@desplega.ai/agent-fs 0.7.5 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cli.js +116 -71
- package/dist/fuse-bin.manifest.json +3 -3
- package/package.json +10 -9
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 ey=Object.create;var{getPrototypeOf:Ey,defineProperty:so,getOwnPropertyNames:fy}=Object;var uy=Object.prototype.hasOwnProperty;function Ty(n){return this[n]}var Ay,Ny,yn=(n,t,o)=>{var i=n!=null&&typeof n==="object";if(i){var e=t?Ay??=new WeakMap:Ny??=new WeakMap,E=e.get(n);if(E)return E}o=n!=null?ey(Ey(n)):{};let f=t||!n||!n.__esModule?so(o,"default",{value:n,enumerable:!0}):o;for(let T of fy(n))if(!uy.call(f,T))so(f,T,{get:Ty.bind(n,T),enumerable:!0});if(i)e.set(n,f);return f};var En=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var yy=(n)=>n;function Ry(n,t){this[n]=yy.bind(null,t)}var Nt=(n,t)=>{for(var o in t)so(n,o,{get:t[o],enumerable:!0,configurable:!0,set:Ry.bind(t,o)})};var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ft=import.meta.require;import{Database as _y}from"bun:sqlite";import{platform as wy}from"os";import{existsSync as ry}from"fs";function Ly(){if(eE)return;if(eE=!0,wy()!=="darwin")return;let n=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite3/lib/libsqlite3.dylib"];for(let t of n)if(ry(t)){try{_y.setCustomSQLite(t)}catch{}return}console.warn(`Warning: Could not find Homebrew SQLite. Extension loading may fail on macOS.
|
|
4
|
+
Install with: brew install sqlite`)}var eE=!1;var EE=R(()=>{Ly()});import{mkdirSync as Uy,readFileSync as Dy,writeFileSync as ao,existsSync as uE}from"fs";import{join as To}from"path";function Sy(){let n=process.env.AGENT_FS_HOME??To(process.env.HOME??"/tmp",".agent-fs");if(n.startsWith("~/"))return To(process.env.HOME??"/tmp",n.slice(2));return n}function k(){return Sy()}function un(){return To(k(),"config.json")}function dn(){return To(k(),"agent-fs.db")}function Oy(){let n=k();if(!uE(n))Uy(n,{recursive:!0})}function ly(n,t){let o={...n};for(let i of Object.keys(t))if(t[i]&&typeof t[i]==="object"&&!Array.isArray(t[i]))o[i]={...n[i],...t[i]};else if(t[i]!==void 0)o[i]=t[i];return o}function fE(n){let t=process.env;if(t.AWS_ENDPOINT_URL_S3||t.S3_ENDPOINT)n.s3.endpoint=t.AWS_ENDPOINT_URL_S3||t.S3_ENDPOINT;if(t.AWS_ACCESS_KEY_ID||t.S3_ACCESS_KEY_ID)n.s3.accessKeyId=t.AWS_ACCESS_KEY_ID||t.S3_ACCESS_KEY_ID;if(t.AWS_SECRET_ACCESS_KEY||t.S3_SECRET_ACCESS_KEY)n.s3.secretAccessKey=t.AWS_SECRET_ACCESS_KEY||t.S3_SECRET_ACCESS_KEY;if(t.BUCKET_NAME||t.S3_BUCKET)n.s3.bucket=t.BUCKET_NAME||t.S3_BUCKET;if(t.AWS_REGION||t.S3_REGION)n.s3.region=t.AWS_REGION||t.S3_REGION;if(t.S3_PROVIDER)n.s3.provider=t.S3_PROVIDER;if(t.S3_PUBLIC_ENDPOINT)n.s3.publicEndpoint=t.S3_PUBLIC_ENDPOINT;if(t.SERVER_PORT||t.PORT)n.server.port=parseInt(t.SERVER_PORT||t.PORT,10);if(t.SERVER_HOST||t.HOST)n.server.host=t.SERVER_HOST||t.HOST;if(t.EMBEDDING_PROVIDER)n.embedding.provider=t.EMBEDDING_PROVIDER;if(t.EMBEDDING_MODEL)n.embedding.model=t.EMBEDDING_MODEL;if(t.EMBEDDING_API_KEY)n.embedding.apiKey=t.EMBEDDING_API_KEY;if(t.AGENT_FS_RATE_LIMIT){if(!n.server.rateLimit)n.server.rateLimit={requestsPerMinute:1200};n.server.rateLimit.requestsPerMinute=parseInt(t.AGENT_FS_RATE_LIMIT,10)}if(t.AGENT_FS_APP_URL)n.appUrl=t.AGENT_FS_APP_URL;return n}function G(){Oy();let n=un();if(!uE(n))return ao(n,JSON.stringify(co,null,2)),fE(structuredClone(co));let t=Dy(n,"utf-8"),o=JSON.parse(t);return fE(ly(co,o))}function TE(n,t){let o=G();o[n]=t,ao(un(),JSON.stringify(o,null,2))}function I(n,t){let o=G(),i=n.split("."),e=o;for(let E=0;E<i.length-1;E++)e=e[i[E]];e[i[i.length-1]]=t,ao(un(),JSON.stringify(o,null,2))}var co;var Ht=R(()=>{co={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={};Nt(u,{users:()=>Zt,orgs:()=>Qt,orgMembers:()=>gy,files:()=>Xy,fileVersions:()=>Cy,events:()=>Yy,drives:()=>Ao,driveMembers:()=>Iy,contentChunks:()=>My,comments:()=>Py});import{sqliteTable as $n,text as D,integer as Z,primaryKey as ni,uniqueIndex as $y}from"drizzle-orm/sqlite-core";var Zt,Qt,gy,Ao,Iy,Xy,Cy,Py,Yy,My;var AE=R(()=>{Zt=$n("users",{id:D("id").primaryKey(),email:D("email").notNull().unique(),apiKeyHash:D("api_key_hash").notNull(),createdAt:Z("created_at",{mode:"timestamp"}).notNull()}),Qt=$n("orgs",{id:D("id").primaryKey(),name:D("name").notNull(),isPersonal:Z("is_personal",{mode:"boolean"}).notNull().default(!1),createdAt:Z("created_at",{mode:"timestamp"}).notNull()}),gy=$n("org_members",{orgId:D("org_id").notNull().references(()=>Qt.id),userId:D("user_id").notNull().references(()=>Zt.id),role:D("role",{enum:["viewer","editor","admin"]}).notNull()},(n)=>({pk:ni({columns:[n.orgId,n.userId]})})),Ao=$n("drives",{id:D("id").primaryKey(),orgId:D("org_id").notNull().references(()=>Qt.id),name:D("name").notNull(),isDefault:Z("is_default",{mode:"boolean"}).notNull().default(!1),createdAt:Z("created_at",{mode:"timestamp"}).notNull()}),Iy=$n("drive_members",{driveId:D("drive_id").notNull().references(()=>Ao.id),userId:D("user_id").notNull().references(()=>Zt.id),role:D("role",{enum:["viewer","editor","admin"]}).notNull()},(n)=>({pk:ni({columns:[n.driveId,n.userId]})})),Xy=$n("files",{path:D("path").notNull(),driveId:D("drive_id").notNull().references(()=>Ao.id),size:Z("size").notNull(),contentType:D("content_type"),author:D("author").notNull(),currentVersionId:D("current_version_id"),createdAt:Z("created_at",{mode:"timestamp"}).notNull(),modifiedAt:Z("modified_at",{mode:"timestamp"}).notNull(),isDeleted:Z("is_deleted",{mode:"boolean"}).notNull().default(!1),embeddingStatus:D("embedding_status",{enum:["pending","indexed","failed"]}).default("pending")},(n)=>({pk:ni({columns:[n.path,n.driveId]})})),Cy=$n("file_versions",{id:Z("id").primaryKey({autoIncrement:!0}),path:D("path").notNull(),driveId:D("drive_id").notNull(),version:Z("version").notNull(),s3VersionId:D("s3_version_id").notNull(),author:D("author").notNull(),operation:D("operation",{enum:["write","edit","append","delete","revert"]}).notNull(),message:D("message"),diffSummary:D("diff_summary"),size:Z("size"),etag:D("etag"),contentHash:D("content_hash"),createdAt:Z("created_at",{mode:"timestamp"}).notNull()},(n)=>({pathDriveVersionUq:$y("file_versions_path_drive_version_uq").on(n.path,n.driveId,n.version)})),Py=$n("comments",{id:D("id").primaryKey(),parentId:D("parent_id"),orgId:D("org_id").notNull().references(()=>Qt.id),driveId:D("drive_id").notNull().references(()=>Ao.id),path:D("path").notNull(),lineStart:Z("line_start"),lineEnd:Z("line_end"),quotedContent:D("quoted_content"),fileVersionId:Z("file_version_id"),body:D("body").notNull(),author:D("author").notNull().references(()=>Zt.id),resolved:Z("resolved",{mode:"boolean"}).notNull().default(!1),resolvedBy:D("resolved_by"),resolvedAt:Z("resolved_at",{mode:"timestamp"}),createdAt:Z("created_at",{mode:"timestamp"}).notNull(),updatedAt:Z("updated_at",{mode:"timestamp"}).notNull(),isDeleted:Z("is_deleted",{mode:"boolean"}).notNull().default(!1)}),Yy=$n("events",{id:D("id").primaryKey(),orgId:D("org_id").notNull().references(()=>Qt.id),type:D("type").notNull(),resourceType:D("resource_type").notNull(),resourceId:D("resource_id").notNull(),actor:D("actor").notNull().references(()=>Zt.id),target:D("target"),status:D("status",{enum:["created","ack","deleted"]}).notNull().default("created"),metadata:D("metadata"),createdAt:Z("created_at",{mode:"timestamp"}).notNull()}),My=$n("content_chunks",{id:Z("id").primaryKey({autoIncrement:!0}),filePath:D("file_path").notNull(),driveId:D("drive_id").notNull(),chunkIndex:Z("chunk_index").notNull(),content:D("content").notNull(),charOffset:Z("char_offset").notNull(),tokenCount:Z("token_count").notNull()})});var NE=`
|
|
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
|
+
`,yE=`
|
|
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,99 +131,100 @@ 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 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 sl}from"bun:sqlite";import{drizzle as ql}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 tA(t){pe.load(t)}function St(t){let n=t??Ht(),o=al(n);if(!cl(o))xl(o,{recursive:!0});let i=new sl(n);return tA(i),i.exec("PRAGMA journal_mode=WAL;"),i.exec("PRAGMA foreign_keys=ON;"),i.exec(Ve),i.exec(We),Ke(i),ql(i,{schema:u})}var G=N(()=>{He();wn();Be()});var Ho=q((iA)=>{var he=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,nA),nA=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,oA=(t)=>t.split("/").map(he).join("/");iA.escapeUri=he;iA.escapeUriPath=oA});var je=q((uA)=>{var Zo=Ho();function EA(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("&")}uA.buildQueryString=EA});function ke(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?de.buildQueryString(o):"";if(E&&E[0]!=="?")E=`?${E}`;let f="";if(t.username!=null||t.password!=null){let l=t.username??"",A=t.password??"";f=`${l}:${A}@`}let T="";if(t.fragment)T=`#${t.fragment}`;return`${i}//${f}${r}${e}${E}${T}`}var de;var me=N(()=>{de=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(RA(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!NA(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},TA,lA,AA,NA=(t)=>TA.test(t)&&!lA.test(t)&&!AA.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 be=N(()=>{TA=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,lA=/(\d+\.){3}\d+/,AA=/\.\./});var se=N(()=>{be()});var qe=(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 Ln=q((gA)=>{class st 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,st.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 st{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Qo.prototype)}}class Jo extends st{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Jo.prototype)}}var _A=(...t)=>async()=>{if(t.length===0)throw new st("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},wA=(t)=>()=>Promise.resolve(t),yA=(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}};gA.CredentialsProviderError=Qo;gA.ProviderError=st;gA.TokenProviderError=Jo;gA.chain=_A;gA.fromStatic=wA;gA.memoize=yA});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=N(()=>{ce=ot(Ln(),1)});import{homedir as $A}from"os";import{sep as XA}from"path";var Bo,CA=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},qt=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:o,HOMEDRIVE:i=`C:${XA}`}=process.env;if(t)return t;if(n)return n;if(o)return`${i}${o}`;let e=CA();if(!Bo[e])Bo[e]=$A();return Bo[e]};var Dn=N(()=>{Bo={}});var tr=(t)=>t.profile||process.env.AWS_PROFILE||"default";var nr=()=>{};var In=q((GA)=>{GA.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(GA.HttpAuthLocation||(GA.HttpAuthLocation={}));GA.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(GA.HttpApiKeyAuthLocation||(GA.HttpApiKeyAuthLocation={}));GA.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(GA.EndpointURLScheme||(GA.EndpointURLScheme={}));GA.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(GA.AlgorithmId||(GA.AlgorithmId={}));var PA=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>GA.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>GA.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(o){n.push(o)},checksumAlgorithms(){return n}}},FA=(t)=>{let n={};return t.checksumAlgorithms().forEach((o)=>{n[o.algorithmId()]=o.checksumConstructor()}),n},MA=(t)=>{return PA(t)},vA=(t)=>{return FA(t)};GA.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(GA.FieldPosition||(GA.FieldPosition={}));var YA="__smithy_context";GA.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(GA.IniSectionType||(GA.IniSectionType={}));GA.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"})(GA.RequestHandlerProtocol||(GA.RequestHandlerProtocol={}));GA.SMITHY_CONTEXT_KEY=YA;GA.getDefaultClientConfiguration=MA;GA.resolveDefaultRuntimeConfig=vA});var At=".";var ko,or=(t)=>Object.entries(t).filter(([n])=>{let o=n.indexOf(At);if(o===-1)return!1;return Object.values(ko.IniSectionType).includes(n.substring(0,o))}).reduce((n,[o,i])=>{let e=o.indexOf(At),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=N(()=>{ko=ot(In(),1)});import{join as JA}from"path";var BA="AWS_CONFIG_FILE",er=()=>process.env[BA]||JA(qt(),".aws","config");var rr=N(()=>{Dn()});import{join as VA}from"path";var WA="AWS_SHARED_CREDENTIALS_FILE",Er=()=>process.env[WA]||VA(qt(),".aws","credentials");var ur=N(()=>{Dn()});var fr,KA,pA,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=KA.exec(f);if(T){let[,l,,A]=T;if(Object.values(fr.IniSectionType).includes(l))o=[l,A].join(At)}else o=f;if(pA.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 A=i?[i,T].join(At):T;n[o][A]=l}}}}return n};var Tr=N(()=>{fr=ot(In(),1),KA=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,pA=["__proto__","profile __proto__"]});import{readFile as hA}from"fs/promises";var zo,lr,bo=(t,n)=>{if(lr[t]!==void 0)return lr[t];if(!zo[t]||n?.ignoreCache)zo[t]=hA(t,"utf8");return zo[t]};var Ar=N(()=>{zo={},lr={}});import{join as Nr}from"path";var Rr=()=>({}),_r=async(t={})=>{let{filepath:n=Er(),configFilepath:o=er()}=t,i=qt(),e="~/",r=n;if(n.startsWith("~/"))r=Nr(i,n.slice(2));let E=o;if(o.startsWith("~/"))E=Nr(i,o.slice(2));let f=await Promise.all([bo(E,{ignoreCache:t.ignoreCache}).then(mo).then(or).catch(Rr),bo(r,{ignoreCache:t.ignoreCache}).then(mo).catch(Rr)]);return{configFile:f[0],credentialsFile:f[1]}};var wr=N(()=>{ir();rr();ur();Dn();Tr();Ar()});var yr=()=>{};var gr=()=>{};var Lr=()=>{};var so=N(()=>{Dn();nr();wr();yr();gr();Lr()});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 A=t(T,n==="config"?e:r);if(A===void 0)throw Error();return A}catch(l){throw new Dr.CredentialsProviderError(l.message||`Not found in config files w/ profile [${i}]: ${pn(t.toString())}`,{logger:o.logger})}};var Ir=N(()=>{so();Dr=ot(Ln(),1)});var Ur,jA=(t)=>typeof t==="function",Sr=(t)=>jA(t)?async()=>await t():Ur.fromStatic(t);var $r=N(()=>{Ur=ot(Ln(),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=N(()=>{ae();Ir();$r();hn=ot(Ln(),1)});var Pr=N(()=>{Cr()});var Fr="AWS_ENDPOINT_URL",Mr="endpoint_url",vr=(t)=>({environmentVariableSelector:(n)=>{let o=t.split(" ").map((r)=>r.toUpperCase()),i=n[[Fr,...o].join("_")];if(i)return i;let e=n[Fr];if(e)return e;return},configFileSelector:(n,o)=>{if(o&&n.services){let e=o[["services",n.services].join(At)];if(e){let r=t.split(" ").map((f)=>f.toLowerCase()),E=e[[r.join("_"),Mr].join(At)];if(E)return E}}let i=n[Mr];if(i)return i;return},default:void 0});var Yr=N(()=>{so()});var Gr=async(t)=>Xr(vr(t??""))();var Hr=N(()=>{Pr();Yr()});var Zr=q((kA)=>{function dA(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}kA.parseQueryString=dA});var Jr=q((bA)=>{var zA=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=zA.parseQueryString(r);return{hostname:n,port:i?parseInt(i):void 0,protocol:e,path:o,query:E}};bA.parseUrl=Qr});var qo,Br=(t)=>{if(typeof t==="object"){if("url"in t){let n=qo.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 qo.parseUrl(t)};var co=N(()=>{qo=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 qA(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},qA=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 qe(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=N(()=>{se();Hr();co()});var Kr=N(()=>{Wr();co()});var hr=q((aA)=>{var pr=In(),cA=(t)=>t[pr.SMITHY_CONTEXT_KEY]||(t[pr.SMITHY_CONTEXT_KEY]={}),xA=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};aA.getSmithyContext=cA;aA.normalizeProvider=xA});var jr=()=>{};var xo=q((uN)=>{var oN=In(),iN=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,o){t.httpHandler?.updateHttpClientConfig(n,o)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},eN=(t)=>{return{httpHandler:t.httpHandler()}};class dr{name;kind;values;constructor({name:t,kind:n=oN.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 kr{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=rN(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 rN(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 EN(t){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(t)}uN.Field=dr;uN.Fields=kr;uN.HttpRequest=jn;uN.HttpResponse=mr;uN.getHttpHandlerExtensionConfiguration=iN;uN.isValidHostname=EN;uN.resolveHttpHandlerRuntimeConfig=eN});var zr=()=>{};var br=()=>{};var sr;var qr=N(()=>{sr={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var cr=N(()=>{zr();qr();br()});var hL;var xr=N(()=>{cr();hL={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:sr.name}});var ar=()=>{};var tE=()=>{};var nE=N(()=>{Kr();jr();xr();ar();tE()});var oE=()=>{};var iE=()=>{};var eE=()=>{};var rE=()=>{};var uE=q((gN)=>{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 wN(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 yN(t){let n="";for(let o=0;o<t.byteLength;o++)n+=EE[t[o]];return n}gN.fromHex=wN;gN.toHex=yN});var ti=q((IN)=>{var ON=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]";IN.isArrayBuffer=ON});var fE=q((CN)=>{var SN=ti(),ni=Vn("buffer"),$N=(t,n=0,o=t.byteLength-n)=>{if(!SN.isArrayBuffer(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return ni.Buffer.from(t,n,o)},XN=(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)};CN.fromArrayBuffer=$N;CN.fromString=XN});var AE=q((YN)=>{var TE=fE(),lE=(t)=>{let n=TE.fromString(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},MN=(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)},vN=(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")};YN.fromUtf8=lE;YN.toUint8Array=MN;YN.toUtf8=vN});var Ni=q((kN)=>{var $t=uE(),Zt=AE(),QN=ti(),wE=xo(),NE=hr(),dn=Ho(),yE="X-Amz-Algorithm",gE="X-Amz-Credential",ei="X-Amz-Date",LE="X-Amz-SignedHeaders",DE="X-Amz-Expires",ri="X-Amz-Signature",Ei="X-Amz-Security-Token",JN="X-Amz-Region-Set",ui="authorization",fi=ei.toLowerCase(),OE="date",IE=[ui,fi,OE],UE=ri.toLowerCase(),sn="x-amz-content-sha256",SE=Ei.toLowerCase(),BN="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-/,VN=[/^proxy-/i,/^sec-/i],kn="AWS4-HMAC-SHA256",WN="AWS4-ECDSA-P256-SHA256",PE="AWS4-HMAC-SHA256-PAYLOAD",FE="UNSIGNED-PAYLOAD",ME=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 RE(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>ME)delete ct[mn.shift()];let f=`AWS4${n.secretAccessKey}`;for(let T of[o,i,e,Ti])f=await RE(t,f,T);return ct[E]=f},KN=()=>{mn.length=0,Object.keys(ct).forEach((t)=>{delete ct[t]})},RE=(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()===sn)return t[i];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||QN.isArrayBuffer(n)){let i=new o;return i.update(Zt.toUint8Array(n)),$t.toHex(await i.digest())}return FE};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(!pN.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let A=new Uint8Array(17);return A[0]=9,A.set($t.fromHex(t.value.replace(/\-/g,"")),1),A}}}var pN=/^[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=dn.escapeUri(i);n.push(e);let r=t[i];if(typeof r==="string")o[e]=`${e}=${dn.escapeUri(r)}`;else if(Array.isArray(r))o[e]=r.slice(0).reduce((E,f)=>E.concat([`${e}=${dn.escapeUri(f)}`]),[]).sort().join("&")}return n.sort().map((i)=>o[i]).filter((i)=>i).join("&")},hN=(t)=>jN(t).toISOString().replace(/\.\d{3}Z$/,"Z"),jN=(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 Ai{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=NE.normalizeProvider(o),this.credentialProvider=NE.normalizeProvider(n)}createCanonicalRequest(t,n,o){let i=Object.keys(n).sort();return`${t.method}
|
|
135
|
-
${this.getCanonicalPath(
|
|
136
|
-
${
|
|
137
|
-
${i.map((e)=>`${e}:${
|
|
134
|
+
`;function RE(n){if(!n.prepare("PRAGMA table_info(file_versions)").all().some((i)=>i.name==="content_hash"))n.exec("ALTER TABLE file_versions ADD COLUMN content_hash TEXT");n.exec("CREATE UNIQUE INDEX IF NOT EXISTS file_versions_path_drive_version_uq ON file_versions(path, drive_id, version)"),n.exec("INSERT OR IGNORE INTO drive_members (drive_id, user_id, role) SELECT d.id, om.user_id, 'admin' FROM drives d JOIN org_members om ON om.org_id = d.org_id AND om.role = 'admin' WHERE NOT EXISTS (SELECT 1 FROM drive_members dm WHERE dm.drive_id = d.id)")}import{Database as Gy}from"bun:sqlite";import{drizzle as Fy}from"drizzle-orm/bun-sqlite";import*as _E from"sqlite-vec";import{existsSync as Hy,mkdirSync as Zy}from"fs";import{dirname as Qy}from"path";function Jy(n){_E.load(n)}function Wn(n){let t=n??dn(),o=Qy(t);if(!Hy(o))Zy(o,{recursive:!0});let i=new Gy(t);return Jy(i),i.exec("PRAGMA journal_mode=WAL;"),i.exec("PRAGMA foreign_keys=ON;"),i.exec(NE),i.exec(yE),RE(i),Fy(i,{schema:u})}var J=R(()=>{EE();Ht();AE()});var ti=En((Vy)=>{var wE=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,By),By=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,Wy=(n)=>n.split("/").map(wE).join("/");Vy.escapeUri=wE;Vy.escapeUriPath=Wy});var rE=En((ky)=>{var oi=ti();function jy(n){let t=[];for(let o of Object.keys(n).sort()){let i=n[o];if(o=oi.escapeUri(o),Array.isArray(i))for(let e=0,E=i.length;e<E;e++)t.push(`${o}=${oi.escapeUri(i[e])}`);else{let e=o;if(i||typeof i==="string")e+=`=${oi.escapeUri(i)}`;t.push(e)}}return t.join("&")}ky.buildQueryString=jy});function UE(n){let{port:t,query:o}=n,{protocol:i,path:e,hostname:E}=n;if(i&&i.slice(-1)!==":")i+=":";if(t)E+=`:${t}`;if(e&&e.charAt(0)!=="/")e=`/${e}`;let f=o?LE.buildQueryString(o):"";if(f&&f[0]!=="?")f=`?${f}`;let T="";if(n.username!=null||n.password!=null){let N=n.username??"",y=n.password??"";T=`${N}:${y}@`}let A="";if(n.fragment)A=`#${n.fragment}`;return`${i}//${T}${E}${e}${f}${A}`}var LE;var DE=R(()=>{LE=yn(rE(),1)});var SE=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(dy(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!by(t)||t.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)n.ForcePathStyle=!0;if(n.DisableMultiRegionAccessPoints)n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0;return n},zy,py,qy,by=(n)=>zy.test(n)&&!py.test(n)&&!qy.test(n),dy=(n)=>{let[t,o,i,,,e]=n.split(":"),E=t==="arn"&&n.split(":").length>=6,f=Boolean(E&&o&&i&&e);if(E&&!f)throw Error(`Invalid ARN: ${n} was an invalid ARN.`);return f};var OE=R(()=>{zy=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,py=/(\d+\.){3}\d+/,qy=/\.\./});var lE=R(()=>{OE()});var $E=(n,t,o,i=!1)=>{let e=async()=>{let E;if(i)E=o.clientContextParams?.[n]??o[n]??o[t];else E=o[n]??o[t];if(typeof E==="function")return E();return E};if(n==="credentialScope"||t==="CredentialScope")return async()=>{let E=typeof o.credentials==="function"?await o.credentials():o.credentials;return E?.credentialScope??E?.CredentialScope};if(n==="accountId"||t==="AccountId")return async()=>{let E=typeof o.credentials==="function"?await o.credentials():o.credentials;return E?.accountId??E?.AccountId};if(n==="endpoint"||t==="endpoint")return async()=>{if(o.isCustomEndpoint===!1)return;let E=await e();if(E&&typeof E==="object"){if("url"in E)return E.url.href;if("hostname"in E){let{protocol:f,hostname:T,port:A,path:N}=E;return`${f}//${T}${A?":"+A:""}${N}`}}return E};return e};var Jt=En((cy)=>{class yt extends Error{name="ProviderError";tryNextLink;constructor(n,t=!0){let o,i=!0;if(typeof t==="boolean")o=void 0,i=t;else if(t!=null&&typeof t==="object")o=t.logger,i=t.tryNextLink??!0;super(n);this.tryNextLink=i,Object.setPrototypeOf(this,yt.prototype),o?.debug?.(`@smithy/property-provider ${i?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class ii extends yt{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ii.prototype)}}class ei extends yt{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ei.prototype)}}var my=(...n)=>async()=>{if(n.length===0)throw new yt("No providers in chain");let t;for(let o of n)try{return await o()}catch(i){if(t=i,i?.tryNextLink)continue;throw i}throw t},xy=(n)=>()=>Promise.resolve(n),sy=(n,t,o)=>{let i,e,E,f=!1,T=async()=>{if(!e)e=n();try{i=await e,E=!0,f=!1}finally{e=void 0}return i};if(t===void 0)return async(A)=>{if(!E||A?.forceRefresh)i=await T();return i};return async(A)=>{if(!E||A?.forceRefresh)i=await T();if(f)return i;if(o&&!o(i))return f=!0,i;if(t(i))return await T(),i;return i}};cy.CredentialsProviderError=ii;cy.ProviderError=yt;cy.TokenProviderError=ei;cy.chain=my;cy.fromStatic=xy;cy.memoize=sy});function No(n){try{let t=new Set(Array.from(n.match(/([A-Z_]){3,}/g)??[]));return t.delete("CONFIG"),t.delete("CONFIG_PREFIX_SEPARATOR"),t.delete("ENV"),[...t].join(", ")}catch(t){return n}}var gE,IE=(n,t)=>async()=>{try{let o=n(process.env,t);if(o===void 0)throw Error();return o}catch(o){throw new gE.CredentialsProviderError(o.message||`Not found in ENV: ${No(n.toString())}`,{logger:t?.logger})}};var XE=R(()=>{gE=yn(Jt(),1)});import{homedir as ER}from"os";import{sep as fR}from"path";var Ei,uR=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Rt=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:o,HOMEDRIVE:i=`C:${fR}`}=process.env;if(n)return n;if(t)return t;if(o)return`${i}${o}`;let e=uR();if(!Ei[e])Ei[e]=ER();return Ei[e]};var Bt=R(()=>{Ei={}});var CE=(n)=>n.profile||process.env.AWS_PROFILE||"default";var PE=()=>{};var Vt=En((_R)=>{_R.HttpAuthLocation=void 0;(function(n){n.HEADER="header",n.QUERY="query"})(_R.HttpAuthLocation||(_R.HttpAuthLocation={}));_R.HttpApiKeyAuthLocation=void 0;(function(n){n.HEADER="header",n.QUERY="query"})(_R.HttpApiKeyAuthLocation||(_R.HttpApiKeyAuthLocation={}));_R.EndpointURLScheme=void 0;(function(n){n.HTTP="http",n.HTTPS="https"})(_R.EndpointURLScheme||(_R.EndpointURLScheme={}));_R.AlgorithmId=void 0;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(_R.AlgorithmId||(_R.AlgorithmId={}));var TR=(n)=>{let t=[];if(n.sha256!==void 0)t.push({algorithmId:()=>_R.AlgorithmId.SHA256,checksumConstructor:()=>n.sha256});if(n.md5!=null)t.push({algorithmId:()=>_R.AlgorithmId.MD5,checksumConstructor:()=>n.md5});return{addChecksumAlgorithm(o){t.push(o)},checksumAlgorithms(){return t}}},AR=(n)=>{let t={};return n.checksumAlgorithms().forEach((o)=>{t[o.algorithmId()]=o.checksumConstructor()}),t},NR=(n)=>{return TR(n)},yR=(n)=>{return AR(n)};_R.FieldPosition=void 0;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(_R.FieldPosition||(_R.FieldPosition={}));var RR="__smithy_context";_R.IniSectionType=void 0;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(_R.IniSectionType||(_R.IniSectionType={}));_R.RequestHandlerProtocol=void 0;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(_R.RequestHandlerProtocol||(_R.RequestHandlerProtocol={}));_R.SMITHY_CONTEXT_KEY=RR;_R.getDefaultClientConfiguration=NR;_R.resolveDefaultRuntimeConfig=yR});var gn=".";var Ri,YE=(n)=>Object.entries(n).filter(([t])=>{let o=t.indexOf(gn);if(o===-1)return!1;return Object.values(Ri.IniSectionType).includes(t.substring(0,o))}).reduce((t,[o,i])=>{let e=o.indexOf(gn),E=o.substring(0,e)===Ri.IniSectionType.PROFILE?o.substring(e+1):o;return t[E]=i,t},{...n.default&&{default:n.default}});var ME=R(()=>{Ri=yn(Vt(),1)});import{join as UR}from"path";var DR="AWS_CONFIG_FILE",GE=()=>process.env[DR]||UR(Rt(),".aws","config");var FE=R(()=>{Bt()});import{join as SR}from"path";var OR="AWS_SHARED_CREDENTIALS_FILE",HE=()=>process.env[OR]||SR(Rt(),".aws","credentials");var ZE=R(()=>{Bt()});var QE,lR,$R,_i=(n)=>{let t={},o,i;for(let e of n.split(/\r?\n/)){let E=e.split(/(^|\s)[;#]/)[0].trim();if(E[0]==="["&&E[E.length-1]==="]"){o=void 0,i=void 0;let T=E.substring(1,E.length-1),A=lR.exec(T);if(A){let[,N,,y]=A;if(Object.values(QE.IniSectionType).includes(N))o=[N,y].join(gn)}else o=T;if($R.includes(T))throw Error(`Found invalid profile name "${T}"`)}else if(o){let T=E.indexOf("=");if(![0,-1].includes(T)){let[A,N]=[E.substring(0,T).trim(),E.substring(T+1).trim()];if(N==="")i=A;else{if(i&&e.trimStart()===e)i=void 0;t[o]=t[o]||{};let y=i?[i,A].join(gn):A;t[o][y]=N}}}}return t};var JE=R(()=>{QE=yn(Vt(),1),lR=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,$R=["__proto__","profile __proto__"]});import{readFile as gR}from"fs/promises";var wi,BE,ri=(n,t)=>{if(BE[n]!==void 0)return BE[n];if(!wi[n]||t?.ignoreCache)wi[n]=gR(n,"utf8");return wi[n]};var WE=R(()=>{wi={},BE={}});import{join as VE}from"path";var KE=()=>({}),vE=async(n={})=>{let{filepath:t=HE(),configFilepath:o=GE()}=n,i=Rt(),e="~/",E=t;if(t.startsWith("~/"))E=VE(i,t.slice(2));let f=o;if(o.startsWith("~/"))f=VE(i,o.slice(2));let T=await Promise.all([ri(f,{ignoreCache:n.ignoreCache}).then(_i).then(YE).catch(KE),ri(E,{ignoreCache:n.ignoreCache}).then(_i).catch(KE)]);return{configFile:T[0],credentialsFile:T[1]}};var jE=R(()=>{ME();FE();ZE();Bt();JE();WE()});var kE=()=>{};var hE=()=>{};var zE=()=>{};var Li=R(()=>{Bt();PE();jE();kE();hE();zE()});var pE,qE=(n,{preferredFile:t="config",...o}={})=>async()=>{let i=CE(o),{configFile:e,credentialsFile:E}=await vE(o),f=E[i]||{},T=e[i]||{},A=t==="config"?{...f,...T}:{...T,...f};try{let y=n(A,t==="config"?e:E);if(y===void 0)throw Error();return y}catch(N){throw new pE.CredentialsProviderError(N.message||`Not found in config files w/ profile [${i}]: ${No(n.toString())}`,{logger:o.logger})}};var bE=R(()=>{Li();pE=yn(Jt(),1)});var dE,IR=(n)=>typeof n==="function",mE=(n)=>IR(n)?async()=>await n():dE.fromStatic(n);var xE=R(()=>{dE=yn(Jt(),1)});var yo,sE=({environmentVariableSelector:n,configFileSelector:t,default:o},i={})=>{let{signingName:e,logger:E}=i;return yo.memoize(yo.chain(IE(n,{signingName:e,logger:E}),qE(t,i),mE(o)))};var cE=R(()=>{XE();bE();xE();yo=yn(Jt(),1)});var aE=R(()=>{cE()});var nf="AWS_ENDPOINT_URL",tf="endpoint_url",of=(n)=>({environmentVariableSelector:(t)=>{let o=n.split(" ").map((E)=>E.toUpperCase()),i=t[[nf,...o].join("_")];if(i)return i;let e=t[nf];if(e)return e;return},configFileSelector:(t,o)=>{if(o&&t.services){let e=o[["services",t.services].join(gn)];if(e){let E=n.split(" ").map((T)=>T.toLowerCase()),f=e[[E.join("_"),tf].join(gn)];if(f)return f}}let i=t[tf];if(i)return i;return},default:void 0});var ef=R(()=>{Li()});var Ef=async(n)=>sE(of(n??""))();var ff=R(()=>{aE();ef()});var uf=En((CR)=>{function XR(n){let t={};if(n=n.replace(/^\?/,""),n)for(let o of n.split("&")){let[i,e=null]=o.split("=");if(i=decodeURIComponent(i),e)e=decodeURIComponent(e);if(!(i in t))t[i]=e;else if(Array.isArray(t[i]))t[i].push(e);else t[i]=[t[i],e]}return t}CR.parseQueryString=XR});var Af=En((MR)=>{var YR=uf(),Tf=(n)=>{if(typeof n==="string")return Tf(new URL(n));let{hostname:t,pathname:o,port:i,protocol:e,search:E}=n,f;if(E)f=YR.parseQueryString(E);return{hostname:t,port:i?parseInt(i):void 0,protocol:e,path:o,query:f}};MR.parseUrl=Tf});var Ui,Nf=(n)=>{if(typeof n==="object"){if("url"in n){let t=Ui.parseUrl(n.url);if(n.headers){t.headers={};for(let[o,i]of Object.entries(n.headers))t.headers[o.toLowerCase()]=i.join(", ")}return t}return n}return Ui.parseUrl(n)};var Di=R(()=>{Ui=yn(Af(),1)});var yf=async(n,t,o,i)=>{if(!o.isCustomEndpoint){let f;if(o.serviceConfiguredEndpoint)f=await o.serviceConfiguredEndpoint();else f=await Ef(o.serviceId);if(f)o.endpoint=()=>Promise.resolve(Nf(f)),o.isCustomEndpoint=!0}let e=await FR(n,t,o);if(typeof o.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let E=o.endpointProvider(e,i);if(o.isCustomEndpoint&&o.endpoint){let f=await o.endpoint();if(f?.headers){E.headers??={};for(let[T,A]of Object.entries(f.headers))E.headers[T]=Array.isArray(A)?A:[A]}}return E},FR=async(n,t,o)=>{let i={},e=t?.getEndpointParameterInstructions?.()||{};for(let[E,f]of Object.entries(e))switch(f.type){case"staticContextParams":i[E]=f.value;break;case"contextParams":i[E]=n[f.name];break;case"clientContextParams":case"builtInParams":i[E]=await $E(f.name,E,o,f.type!=="builtInParams")();break;case"operationContextParams":i[E]=f.get(n);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(e).length===0)Object.assign(i,o);if(String(o.serviceId).toLowerCase()==="s3")await SE(i);return i};var Rf=R(()=>{lE();ff();Di()});var _f=R(()=>{Rf();Di()});var rf=En((QR)=>{var wf=Vt(),HR=(n)=>n[wf.SMITHY_CONTEXT_KEY]||(n[wf.SMITHY_CONTEXT_KEY]={}),ZR=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t};QR.getSmithyContext=HR;QR.normalizeProvider=ZR});var Lf=()=>{};var Si=En((kR)=>{var WR=Vt(),VR=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,o){n.httpHandler?.updateHttpClientConfig(t,o)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},KR=(n)=>{return{httpHandler:n.httpHandler()}};class Uf{name;kind;values;constructor({name:n,kind:t=WR.FieldPosition.HEADER,values:o=[]}){this.name=n,this.kind=t,this.values=o}add(n){this.values.push(n)}set(n){this.values=n}remove(n){this.values=this.values.filter((t)=>t!==n)}toString(){return this.values.map((n)=>n.includes(",")||n.includes(" ")?`"${n}"`:n).join(", ")}get(){return this.values}}class Df{entries={};encoding;constructor({fields:n=[],encoding:t="utf-8"}){n.forEach(this.setField.bind(this)),this.encoding=t}setField(n){this.entries[n.name.toLowerCase()]=n}getField(n){return this.entries[n.toLowerCase()]}removeField(n){delete this.entries[n.toLowerCase()]}getByType(n){return Object.values(this.entries).filter((t)=>t.kind===n)}}class Ro{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(n){this.method=n.method||"GET",this.hostname=n.hostname||"localhost",this.port=n.port,this.query=n.query||{},this.headers=n.headers||{},this.body=n.body,this.protocol=n.protocol?n.protocol.slice(-1)!==":"?`${n.protocol}:`:n.protocol:"https:",this.path=n.path?n.path.charAt(0)!=="/"?`/${n.path}`:n.path:"/",this.username=n.username,this.password=n.password,this.fragment=n.fragment}static clone(n){let t=new Ro({...n,headers:{...n.headers}});if(t.query)t.query=vR(t.query);return t}static isInstance(n){if(!n)return!1;let t=n;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query==="object"&&typeof t.headers==="object"}clone(){return Ro.clone(this)}}function vR(n){return Object.keys(n).reduce((t,o)=>{let i=n[o];return{...t,[o]:Array.isArray(i)?[...i]:i}},{})}class Sf{statusCode;reason;headers;body;constructor(n){this.statusCode=n.statusCode,this.reason=n.reason,this.headers=n.headers||{},this.body=n.body}static isInstance(n){if(!n)return!1;let t=n;return typeof t.statusCode==="number"&&typeof t.headers==="object"}}function jR(n){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(n)}kR.Field=Uf;kR.Fields=Df;kR.HttpRequest=Ro;kR.HttpResponse=Sf;kR.getHttpHandlerExtensionConfiguration=VR;kR.isValidHostname=jR;kR.resolveHttpHandlerRuntimeConfig=KR});var Of=()=>{};var lf=()=>{};var $f;var gf=R(()=>{$f={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var If=R(()=>{Of();gf();lf()});var pS;var Xf=R(()=>{If();pS={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:$f.name}});var Cf=()=>{};var Pf=()=>{};var Yf=R(()=>{_f();Lf();Xf();Cf();Pf()});var Mf=()=>{};var Gf=()=>{};var Ff=()=>{};var Hf=()=>{};var Qf=En((cR)=>{var Zf={},Oi={};for(let n=0;n<256;n++){let t=n.toString(16).toLowerCase();if(t.length===1)t=`0${t}`;Zf[n]=t,Oi[t]=n}function xR(n){if(n.length%2!==0)throw Error("Hex encoded strings must have an even number length");let t=new Uint8Array(n.length/2);for(let o=0;o<n.length;o+=2){let i=n.slice(o,o+2).toLowerCase();if(i in Oi)t[o/2]=Oi[i];else throw Error(`Cannot decode unrecognized sequence ${i} as hexadecimal`)}return t}function sR(n){let t="";for(let o=0;o<n.byteLength;o++)t+=Zf[n[o]];return t}cR.fromHex=xR;cR.toHex=sR});var li=En((o_)=>{var t_=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]";o_.isArrayBuffer=t_});var Jf=En((u_)=>{var e_=li(),$i=Ft("buffer"),E_=(n,t=0,o=n.byteLength-t)=>{if(!e_.isArrayBuffer(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return $i.Buffer.from(n,t,o)},f_=(n,t)=>{if(typeof n!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof n} (${n})`);return t?$i.Buffer.from(n,t):$i.Buffer.from(n)};u_.fromArrayBuffer=E_;u_.fromString=f_});var Vf=En((R_)=>{var Bf=Jf(),Wf=(n)=>{let t=Bf.fromString(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},N_=(n)=>{if(typeof n==="string")return Wf(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(n)},y_=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Bf.fromArrayBuffer(n.buffer,n.byteOffset,n.byteLength).toString("utf8")};R_.fromUtf8=Wf;R_.toUint8Array=N_;R_.toUtf8=y_});var Zi=En((C_)=>{var Vn=Qf(),mn=Vf(),L_=li(),kf=Si(),Kf=rf(),_o=ti(),hf="X-Amz-Algorithm",zf="X-Amz-Credential",Xi="X-Amz-Date",pf="X-Amz-SignedHeaders",qf="X-Amz-Expires",Ci="X-Amz-Signature",Pi="X-Amz-Security-Token",U_="X-Amz-Region-Set",Yi="authorization",Mi=Xi.toLowerCase(),bf="date",df=[Yi,Mi,bf],mf=Ci.toLowerCase(),Do="x-amz-content-sha256",xf=Pi.toLowerCase(),D_="host",sf={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},cf=/^proxy-/,af=/^sec-/,S_=[/^proxy-/i,/^sec-/i],wo="AWS4-HMAC-SHA256",O_="AWS4-ECDSA-P256-SHA256",nu="AWS4-HMAC-SHA256-PAYLOAD",tu="UNSIGNED-PAYLOAD",ou=50,Gi="aws4_request",iu=604800,_t={},ro=[],Lo=(n,t,o)=>`${n}/${t}/${o}/${Gi}`,eu=async(n,t,o,i,e)=>{let E=await vf(n,t.secretAccessKey,t.accessKeyId),f=`${o}:${i}:${e}:${Vn.toHex(E)}:${t.sessionToken}`;if(f in _t)return _t[f];ro.push(f);while(ro.length>ou)delete _t[ro.shift()];let T=`AWS4${t.secretAccessKey}`;for(let A of[o,i,e,Gi])T=await vf(n,T,A);return _t[f]=T},l_=()=>{ro.length=0,Object.keys(_t).forEach((n)=>{delete _t[n]})},vf=(n,t,o)=>{let i=new n(t);return i.update(mn.toUint8Array(o)),i.digest()},gi=({headers:n},t,o)=>{let i={};for(let e of Object.keys(n).sort()){if(n[e]==null)continue;let E=e.toLowerCase();if(E in sf||t?.has(E)||cf.test(E)||af.test(E)){if(!o||o&&!o.has(E))continue}i[E]=n[e].trim().replace(/\s+/g," ")}return i},Uo=async({headers:n,body:t},o)=>{for(let i of Object.keys(n))if(i.toLowerCase()===Do)return n[i];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof t==="string"||ArrayBuffer.isView(t)||L_.isArrayBuffer(t)){let i=new o;return i.update(mn.toUint8Array(t)),Vn.toHex(await i.digest())}return tu};class Eu{format(n){let t=[];for(let e of Object.keys(n)){let E=mn.fromUtf8(e);t.push(Uint8Array.from([E.byteLength]),E,this.formatHeaderValue(n[e]))}let o=new Uint8Array(t.reduce((e,E)=>e+E.byteLength,0)),i=0;for(let e of t)o.set(e,i),i+=e.byteLength;return o}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?0:1]);case"byte":return Uint8Array.from([2,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,n.value,!1),new Uint8Array(o.buffer);case"long":let i=new Uint8Array(9);return i[0]=5,i.set(n.value.bytes,1),i;case"binary":let e=new DataView(new ArrayBuffer(3+n.value.byteLength));e.setUint8(0,6),e.setUint16(1,n.value.byteLength,!1);let E=new Uint8Array(e.buffer);return E.set(n.value,3),E;case"string":let f=mn.fromUtf8(n.value),T=new DataView(new ArrayBuffer(3+f.byteLength));T.setUint8(0,7),T.setUint16(1,f.byteLength,!1);let A=new Uint8Array(T.buffer);return A.set(f,3),A;case"timestamp":let N=new Uint8Array(9);return N[0]=8,N.set(Fi.fromNumber(n.value.valueOf()).bytes,1),N;case"uuid":if(!$_.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let y=new Uint8Array(17);return y[0]=9,y.set(Vn.fromHex(n.value.replace(/\-/g,"")),1),y}}}var $_=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Fi{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let o=7,i=Math.abs(Math.round(n));o>-1&&i>0;o--,i/=256)t[o]=i;if(n<0)jf(t);return new Fi(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)jf(n);return parseInt(Vn.toHex(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function jf(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}var fu=(n,t)=>{n=n.toLowerCase();for(let o of Object.keys(t))if(n===o.toLowerCase())return!0;return!1},uu=(n,t={})=>{let{headers:o,query:i={}}=kf.HttpRequest.clone(n);for(let e of Object.keys(o)){let E=e.toLowerCase();if(E.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(E)||t.hoistableHeaders?.has(E))i[e]=o[e],delete o[e]}return{...n,headers:o,query:i}},Ii=(n)=>{n=kf.HttpRequest.clone(n);for(let t of Object.keys(n.headers))if(df.indexOf(t.toLowerCase())>-1)delete n.headers[t];return n},Tu=({query:n={}})=>{let t=[],o={};for(let i of Object.keys(n)){if(i.toLowerCase()===mf)continue;let e=_o.escapeUri(i);t.push(e);let E=n[i];if(typeof E==="string")o[e]=`${e}=${_o.escapeUri(E)}`;else if(Array.isArray(E))o[e]=E.slice(0).reduce((f,T)=>f.concat([`${e}=${_o.escapeUri(T)}`]),[]).sort().join("&")}return t.sort().map((i)=>o[i]).filter((i)=>i).join("&")},g_=(n)=>I_(n).toISOString().replace(/\.\d{3}Z$/,"Z"),I_=(n)=>{if(typeof n==="number")return new Date(n*1000);if(typeof n==="string"){if(Number(n))return new Date(Number(n)*1000);return new Date(n)}return n};class Hi{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:n,credentials:t,region:o,service:i,sha256:e,uriEscapePath:E=!0}){this.service=i,this.sha256=e,this.uriEscapePath=E,this.applyChecksum=typeof n==="boolean"?n:!0,this.regionProvider=Kf.normalizeProvider(o),this.credentialProvider=Kf.normalizeProvider(t)}createCanonicalRequest(n,t,o){let i=Object.keys(t).sort();return`${n.method}
|
|
135
|
+
${this.getCanonicalPath(n)}
|
|
136
|
+
${Tu(n)}
|
|
137
|
+
${i.map((e)=>`${e}:${t[e]}`).join(`
|
|
138
138
|
`)}
|
|
139
139
|
|
|
140
140
|
${i.join(";")}
|
|
141
|
-
${o}`}async createStringToSign(t,
|
|
142
|
-
${t}
|
|
141
|
+
${o}`}async createStringToSign(n,t,o,i){let e=new this.sha256;e.update(mn.toUint8Array(o));let E=await e.digest();return`${i}
|
|
143
142
|
${n}
|
|
144
|
-
${
|
|
145
|
-
`);return this.signString(L,{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:A}=this.formatDate(n),R=zn(A,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(sn,T.headers)&&this.applyChecksum)T.headers[sn]=w;let L=oi(T,i,o),O=await this.getSignature(l,R,this.getSigningKey(E,f,A,r),this.createCanonicalRequest(T,L,w));return T.headers[ui]=`${kn} Credential=${E.accessKeyId}/${R}, SignedHeaders=${this.getCanonicalHeaderList(L)}, Signature=${O}`,T}async getSignature(t,n,o,i){let e=await this.createStringToSign(t,n,i,kn),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 dN={SignatureV4a:null};kN.ALGORITHM_IDENTIFIER=kn;kN.ALGORITHM_IDENTIFIER_V4A=WN;kN.ALGORITHM_QUERY_PARAM=yE;kN.ALWAYS_UNSIGNABLE_HEADERS=$E;kN.AMZ_DATE_HEADER=fi;kN.AMZ_DATE_QUERY_PARAM=ei;kN.AUTH_HEADER=ui;kN.CREDENTIAL_QUERY_PARAM=gE;kN.DATE_HEADER=OE;kN.EVENT_ALGORITHM_IDENTIFIER=PE;kN.EXPIRES_QUERY_PARAM=DE;kN.GENERATED_HEADERS=IE;kN.HOST_HEADER=BN;kN.KEY_TYPE_IDENTIFIER=Ti;kN.MAX_CACHE_SIZE=ME;kN.MAX_PRESIGNED_TTL=vE;kN.PROXY_HEADER_PATTERN=XE;kN.REGION_SET_PARAM=JN;kN.SEC_HEADER_PATTERN=CE;kN.SHA256_HEADER=sn;kN.SIGNATURE_HEADER=UE;kN.SIGNATURE_QUERY_PARAM=ri;kN.SIGNED_HEADERS_QUERY_PARAM=LE;kN.SignatureV4=JE;kN.SignatureV4Base=Ai;kN.TOKEN_HEADER=SE;kN.TOKEN_QUERY_PARAM=Ei;kN.UNSIGNABLE_PATTERNS=VN;kN.UNSIGNED_PAYLOAD=FE;kN.clearCredentialCache=KN;kN.createScope=zn;kN.getCanonicalHeaders=oi;kN.getCanonicalQuery=QE;kN.getPayloadHash=bn;kN.getSigningKey=YE;kN.hasHeader=HE;kN.moveHeadersToQuery=ZE;kN.prepareRequest=ii;kN.signatureV4aContainer=dN});var qn="X-Amz-S3session-Token",Ri;var BE=N(()=>{Ri=qn.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=N(()=>{BE();KE=ot(Ni(),1);cn=class cn extends KE.SignatureV4{async signWithCredentials(t,n,o){let i=VE(n);t.headers[Ri]=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[Ri],t.headers[qn]=n.sessionToken,t.query=t.query??{},t.query[qn]=n.sessionToken,WE(this,i),this.presign(t,o)}}});var hE=N(()=>{pE()});var jE=()=>{};var dE=()=>{};var kE=()=>{};var mE=N(()=>{oE();iE();eE();rE();hE();jE();dE();kE()});var Un;var _i=N(()=>{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=N(()=>{mE();_i();wi=ot(Ni(),1)});var bE=N(()=>{zE();_i()});var sE="UNSIGNED-PAYLOAD",qE="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[qE]=sE;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 gi=N(()=>{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=(R,w)=>async(L)=>{let{request:O}=L;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:A}=l;return ke(A)};var aE=N(()=>{me();nE();gi();cE=ot(xo(),1)});var tu=N(()=>{aE();gi()});import{S3Client as nu,PutObjectCommand as YR,GetObjectCommand as ou,DeleteObjectCommand as GR,CopyObjectCommand as HR,ListObjectsV2Command as ZR,HeadObjectCommand as QR,ListObjectVersionsCommand as JR,GetBucketVersioningCommand as BR,PutBucketVersioningCommand as VR}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 YR({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 GR({Bucket:this.bucket,Key:t}))}async copyObject(t,n){let o=await this.client.send(new HR({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 ZR({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 QR({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 JR({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 BR({Bucket:this.bucket}))).Status==="Enabled"}catch{return!1}}async enableVersioning(){try{return await this.client.send(new VR({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=N(()=>{tu()});var eu=N(()=>{iu()});var Nt,M,it,et,Sn,c;var m=N(()=>{Nt=class Nt 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}}}};M=class M extends Nt{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 Nt{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 Nt{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 Nt{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 Nt{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 WR}from"drizzle-orm";function $n(t){return KR[t]??"admin"}function Rt(t,n,o){return t.select().from(u.driveMembers).where(WR(ru(u.driveMembers.driveId,o),ru(u.driveMembers.userId,n))).get()?.role??null}function Xn(t,n){let o=Rt(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,KR;var an=N(()=>{G();m();Eu={viewer:0,editor:1,admin:2},KR={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 pR,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:pR`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=N(()=>{G();m()});function K(t){let n=t.split(".").pop()?.toLowerCase()??"";return hR[n]??"application/octet-stream"}function jR(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 dR(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function Pt(t,n){let o=dR(t);if(o===null)return null;if(jR(n))return o;if(n==="application/octet-stream"&&kR(t))return o;return null}function kR(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 hR;var rt=N(()=>{hR={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 Li(t){return t.$client}function wt(t,n){let o=Li(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){Li(t).prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(n.path,n.driveId)}function oo(t,n){let o=Li(t),i,e;if(n.pathPrefix)i=`
|
|
143
|
+
${t}
|
|
144
|
+
${Vn.toHex(E)}`}getCanonicalPath({path:n}){if(this.uriEscapePath){let t=[];for(let e of n.split("/")){if(e?.length===0)continue;if(e===".")continue;if(e==="..")t.pop();else t.push(e)}let o=`${n?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&n?.endsWith("/")?"/":""}`;return _o.escapeUri(o).replace(/%2F/g,"/")}return n}validateResolvedCredentials(n){if(typeof n!=="object"||typeof n.accessKeyId!=="string"||typeof n.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(n){let t=g_(n).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(n){return Object.keys(n).sort().join(";")}}class Au extends Hi{headerFormatter=new Eu;constructor({applyChecksum:n,credentials:t,region:o,service:i,sha256:e,uriEscapePath:E=!0}){super({applyChecksum:n,credentials:t,region:o,service:i,sha256:e,uriEscapePath:E})}async presign(n,t={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:e,unhoistableHeaders:E,signableHeaders:f,hoistableHeaders:T,signingRegion:A,signingService:N}=t,y=await this.credentialProvider();this.validateResolvedCredentials(y);let _=A??await this.regionProvider(),{longDate:r,shortDate:L}=this.formatDate(o);if(i>iu)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let S=Lo(L,_,N??this.service),U=uu(Ii(n),{unhoistableHeaders:E,hoistableHeaders:T});if(y.sessionToken)U.query[Pi]=y.sessionToken;U.query[hf]=wo,U.query[zf]=`${y.accessKeyId}/${S}`,U.query[Xi]=r,U.query[qf]=i.toString(10);let g=gi(U,e,f);return U.query[pf]=this.getCanonicalHeaderList(g),U.query[Ci]=await this.getSignature(r,S,this.getSigningKey(y,_,L,N),this.createCanonicalRequest(U,g,await Uo(n,this.sha256))),U}async sign(n,t){if(typeof n==="string")return this.signString(n,t);else if(n.headers&&n.payload)return this.signEvent(n,t);else if(n.message)return this.signMessage(n,t);else return this.signRequest(n,t)}async signEvent({headers:n,payload:t},{signingDate:o=new Date,priorSignature:i,signingRegion:e,signingService:E}){let f=e??await this.regionProvider(),{shortDate:T,longDate:A}=this.formatDate(o),N=Lo(T,f,E??this.service),y=await Uo({headers:{},body:t},this.sha256),_=new this.sha256;_.update(n);let r=Vn.toHex(await _.digest()),L=[nu,A,N,i,r,y].join(`
|
|
145
|
+
`);return this.signString(L,{signingDate:o,signingRegion:f,signingService:E})}async signMessage(n,{signingDate:t=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(n.message.headers),payload:n.message.body},{signingDate:t,signingRegion:o,signingService:i,priorSignature:n.priorSignature}).then((E)=>{return{message:n.message,signature:E}})}async signString(n,{signingDate:t=new Date,signingRegion:o,signingService:i}={}){let e=await this.credentialProvider();this.validateResolvedCredentials(e);let E=o??await this.regionProvider(),{shortDate:f}=this.formatDate(t),T=new this.sha256(await this.getSigningKey(e,E,f,i));return T.update(mn.toUint8Array(n)),Vn.toHex(await T.digest())}async signRequest(n,{signingDate:t=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:e,signingService:E}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let T=e??await this.regionProvider(),A=Ii(n),{longDate:N,shortDate:y}=this.formatDate(t),_=Lo(y,T,E??this.service);if(A.headers[Mi]=N,f.sessionToken)A.headers[xf]=f.sessionToken;let r=await Uo(A,this.sha256);if(!fu(Do,A.headers)&&this.applyChecksum)A.headers[Do]=r;let L=gi(A,i,o),S=await this.getSignature(N,_,this.getSigningKey(f,T,y,E),this.createCanonicalRequest(A,L,r));return A.headers[Yi]=`${wo} Credential=${f.accessKeyId}/${_}, SignedHeaders=${this.getCanonicalHeaderList(L)}, Signature=${S}`,A}async getSignature(n,t,o,i){let e=await this.createStringToSign(n,t,i,wo),E=new this.sha256(await o);return E.update(mn.toUint8Array(e)),Vn.toHex(await E.digest())}getSigningKey(n,t,o,i){return eu(this.sha256,n,o,t,i||this.service)}}var X_={SignatureV4a:null};C_.ALGORITHM_IDENTIFIER=wo;C_.ALGORITHM_IDENTIFIER_V4A=O_;C_.ALGORITHM_QUERY_PARAM=hf;C_.ALWAYS_UNSIGNABLE_HEADERS=sf;C_.AMZ_DATE_HEADER=Mi;C_.AMZ_DATE_QUERY_PARAM=Xi;C_.AUTH_HEADER=Yi;C_.CREDENTIAL_QUERY_PARAM=zf;C_.DATE_HEADER=bf;C_.EVENT_ALGORITHM_IDENTIFIER=nu;C_.EXPIRES_QUERY_PARAM=qf;C_.GENERATED_HEADERS=df;C_.HOST_HEADER=D_;C_.KEY_TYPE_IDENTIFIER=Gi;C_.MAX_CACHE_SIZE=ou;C_.MAX_PRESIGNED_TTL=iu;C_.PROXY_HEADER_PATTERN=cf;C_.REGION_SET_PARAM=U_;C_.SEC_HEADER_PATTERN=af;C_.SHA256_HEADER=Do;C_.SIGNATURE_HEADER=mf;C_.SIGNATURE_QUERY_PARAM=Ci;C_.SIGNED_HEADERS_QUERY_PARAM=pf;C_.SignatureV4=Au;C_.SignatureV4Base=Hi;C_.TOKEN_HEADER=xf;C_.TOKEN_QUERY_PARAM=Pi;C_.UNSIGNABLE_PATTERNS=S_;C_.UNSIGNED_PAYLOAD=tu;C_.clearCredentialCache=l_;C_.createScope=Lo;C_.getCanonicalHeaders=gi;C_.getCanonicalQuery=Tu;C_.getPayloadHash=Uo;C_.getSigningKey=eu;C_.hasHeader=fu;C_.moveHeadersToQuery=uu;C_.prepareRequest=Ii;C_.signatureV4aContainer=X_});var So="X-Amz-S3session-Token",Qi;var Nu=R(()=>{Qi=So.toLowerCase()});function yu(n){return{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,expiration:n.expiration}}function Ru(n,t){let o=setTimeout(()=>{throw Error("SignatureV4S3Express credential override was created but not called.")},10),i=n.credentialProvider,e=()=>{return clearTimeout(o),n.credentialProvider=i,Promise.resolve(t)};n.credentialProvider=e}var _u,Oo;var wu=R(()=>{Nu();_u=yn(Zi(),1);Oo=class Oo extends _u.SignatureV4{async signWithCredentials(n,t,o){let i=yu(t);n.headers[Qi]=t.sessionToken;let e=this;return Ru(e,i),e.signRequest(n,o??{})}async presignWithCredentials(n,t,o){let i=yu(t);return delete n.headers[Qi],n.headers[So]=t.sessionToken,n.query=n.query??{},n.query[So]=t.sessionToken,Ru(this,i),this.presign(n,o)}}});var ru=R(()=>{wu()});var Lu=()=>{};var Uu=()=>{};var Du=()=>{};var Su=R(()=>{Mf();Gf();Ff();Hf();ru();Lu();Uu();Du()});var Kt;var Ji=R(()=>{Kt={CrtSignerV4:null}});class Wi{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Kt.CrtSignerV4==="function")return"crt";else if(typeof Bi.signatureV4aContainer.SignatureV4a==="function")return"js";return"none"}constructor(n){this.sigv4Signer=new Oo(n),this.signerOptions=n}async sign(n,t={}){if(t.signingRegion==="*")return this.getSigv4aSigner().sign(n,t);return this.sigv4Signer.sign(n,t)}async signWithCredentials(n,t,o={}){if(o.signingRegion==="*"){let i=this.getSigv4aSigner(),e=Kt.CrtSignerV4;if(e&&i instanceof e)return i.signWithCredentials(n,t,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(n,t,o)}async presign(n,t={}){if(t.signingRegion==="*"){let o=this.getSigv4aSigner(),i=Kt.CrtSignerV4;if(i&&o instanceof i)return o.presign(n,t);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(n,t)}async presignWithCredentials(n,t,o={}){if(o.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(n,t,o)}getSigv4aSigner(){if(!this.sigv4aSigner){let n=Kt.CrtSignerV4,t=Bi.signatureV4aContainer.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!n&&!t)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(n&&typeof n==="function")this.sigv4aSigner=new n({...this.signerOptions,signingAlgorithm:1});else if(t&&typeof t==="function")this.sigv4aSigner=new t({...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(!t||typeof t!=="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 t({...this.signerOptions})}}return this.sigv4aSigner}}var Bi;var Ou=R(()=>{Su();Ji();Bi=yn(Zi(),1)});var lu=R(()=>{Ou();Ji()});var $u="UNSIGNED-PAYLOAD",gu="X-Amz-Content-Sha256";class lo{signer;constructor(n){let t={service:n.signingName||n.service||"s3",uriEscapePath:n.uriEscapePath||!1,applyChecksum:n.applyChecksum||!1,...n};this.signer=new Wi(t)}presign(n,{unsignableHeaders:t=new Set,hoistableHeaders:o=new Set,unhoistableHeaders:i=new Set,...e}={}){return this.prepareRequest(n,{unsignableHeaders:t,unhoistableHeaders:i,hoistableHeaders:o}),this.signer.presign(n,{expiresIn:900,unsignableHeaders:t,unhoistableHeaders:i,...e})}presignWithCredentials(n,t,{unsignableHeaders:o=new Set,hoistableHeaders:i=new Set,unhoistableHeaders:e=new Set,...E}={}){return this.prepareRequest(n,{unsignableHeaders:o,unhoistableHeaders:e,hoistableHeaders:i}),this.signer.presignWithCredentials(n,t,{expiresIn:900,unsignableHeaders:o,unhoistableHeaders:e,...E})}prepareRequest(n,{unsignableHeaders:t=new Set,unhoistableHeaders:o=new Set,hoistableHeaders:i=new Set}={}){t.add("content-type"),Object.keys(n.headers).map((T)=>T.toLowerCase()).filter((T)=>T.startsWith("x-amz-server-side-encryption")).forEach((T)=>{if(!i.has(T))o.add(T)}),n.headers[gu]=$u;let e=n.headers.host,E=n.port,f=`${n.hostname}${n.port!=null?":"+E:""}`;if(!e||e===n.hostname&&n.port!=null)n.headers.host=f}}var Vi=R(()=>{lu()});var Iu,Xu=async(n,t,o={})=>{let i,e;if(typeof n.config.endpointProvider==="function"){let r=(await yf(t.input,t.constructor,n.config)).properties?.authSchemes?.[0];if(r?.name==="sigv4a")e=r?.signingRegionSet?.join(",");else e=r?.signingRegion;i=new lo({...n.config,signingName:r?.signingName,region:async()=>e})}else i=new lo(n.config);let E=(_,r)=>async(L)=>{let{request:S}=L;if(!Iu.HttpRequest.isInstance(S))throw Error("Request to be presigned is not an valid HTTP request.");delete S.headers["amz-sdk-invocation-id"],delete S.headers["amz-sdk-request"],delete S.headers["x-amz-user-agent"];let U,g={...o,signingRegion:o.signingRegion??r.signing_region??e,signingService:o.signingService??r.signing_service};if(r.s3ExpressIdentity)U=await i.presignWithCredentials(S,r.s3ExpressIdentity,g);else U=await i.presign(S,g);return{response:{},output:{$metadata:{httpStatusCode:200},presigned:U}}},f="presignInterceptMiddleware",T=n.middlewareStack.clone();T.addRelativeTo(E,{name:f,relation:"before",toMiddleware:"awsAuthMiddleware",override:!0});let A=t.resolveMiddleware(T,n.config,{}),{output:N}=await A({input:t.input}),{presigned:y}=N;return UE(y)};var Cu=R(()=>{DE();Yf();Vi();Iu=yn(Si(),1)});var Pu=R(()=>{Cu();Vi()});import{S3Client as Yu,PutObjectCommand as Rw,GetObjectCommand as Mu,DeleteObjectCommand as _w,CopyObjectCommand as ww,ListObjectsV2Command as rw,HeadObjectCommand as Lw,ListObjectVersionsCommand as Uw,GetBucketVersioningCommand as Dw,PutBucketVersioningCommand as Sw}from"@aws-sdk/client-s3";class Kn{client;presignClient;bucket;versioningEnabled=!1;constructor(n){this.bucket=n.bucket;let t={accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey};this.client=new Yu({region:n.region,endpoint:n.endpoint,credentials:t,forcePathStyle:!0}),this.presignClient=new Yu({region:n.region,endpoint:n.publicEndpoint??n.endpoint,credentials:t,forcePathStyle:!0}),this.versioningEnabled=n.versioningEnabled??!1}async putObject(n,t,o,i){let e=await this.client.send(new Rw({Bucket:this.bucket,Key:n,Body:typeof t==="string"?Buffer.from(t):t,Metadata:o,...i&&{ContentType:i}}));return{etag:e.ETag,versionId:e.VersionId}}async getObject(n,t,o){let i=await this.client.send(new Mu({Bucket:this.bucket,Key:n,...t&&{VersionId:t}}),{abortSignal:o?.abortSignal});return{body:await i.Body.transformToByteArray(),contentType:i.ContentType,size:i.ContentLength,versionId:i.VersionId,etag:i.ETag}}async deleteObject(n){await this.client.send(new _w({Bucket:this.bucket,Key:n}))}async copyObject(n,t){let o=await this.client.send(new ww({Bucket:this.bucket,CopySource:`${this.bucket}/${n}`,Key:t}));return{etag:o.CopyObjectResult?.ETag,versionId:o.VersionId}}async listObjects(n,t){let o=await this.client.send(new rw({Bucket:this.bucket,Prefix:n,...t?.delimiter&&{Delimiter:t.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(n){let t=await this.client.send(new Lw({Bucket:this.bucket,Key:n}));return{contentType:t.ContentType,size:t.ContentLength??0,lastModified:t.LastModified,etag:t.ETag,versionId:t.VersionId}}async listObjectVersions(n){return((await this.client.send(new Uw({Bucket:this.bucket,Prefix:n}))).Versions??[]).filter((o)=>o.Key===n).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 Dw({Bucket:this.bucket}))).Status==="Enabled"}catch{return!1}}async enableVersioning(){try{return await this.client.send(new Sw({Bucket:this.bucket,VersioningConfiguration:{Status:"Enabled"}})),this.versioningEnabled=!0,!0}catch{return!1}}async getPresignedUrl(n,t=86400,o){let i=new Mu({Bucket:this.bucket,Key:n,...o&&{ResponseContentType:o}});return Xu(this.presignClient,i,{expiresIn:t})}}var Gu=R(()=>{Pu()});var Fu=R(()=>{Gu()});var In,X,d,Rn,vt,F;var m=R(()=>{In=class In extends Error{code;suggestion;constructor(n,t,o){super(t);this.name=this.constructor.name,this.code=n,this.suggestion=o}toJSON(){return{error:this.code,message:this.message,...this.suggestion&&{suggestion:this.suggestion}}}};X=class X extends In{path;constructor(n,t){super("NOT_FOUND",n,t?.suggestion);this.path=t?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};d=class d extends In{requiredRole;yourRole;constructor(n,t){super("PERMISSION_DENIED",n,t?.suggestion);this.requiredRole=t?.requiredRole,this.yourRole=t?.yourRole}toJSON(){return{...super.toJSON(),...this.requiredRole&&{required_role:this.requiredRole},...this.yourRole&&{your_role:this.yourRole}}}};Rn=class Rn extends In{path;constructor(n,t){super("EDIT_CONFLICT",n,t?.suggestion);this.path=t?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};vt=class vt extends In{path;constructor(n,t){super("INDEXING_IN_PROGRESS",n,t?.suggestion??"Try again in a moment");this.path=t?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};F=class F extends In{field;constructor(n,t){super("VALIDATION_ERROR",n,t?.suggestion);this.field=t?.field}toJSON(){return{...super.toJSON(),...this.field&&{field:this.field}}}}});import{eq as wt,and as Hu}from"drizzle-orm";function jt(n){return Ow[n]??"admin"}function kt(n,t){if(!n)return!1;return rt[n]>=rt[t]}function xn(n,t,o){return n.select().from(u.orgMembers).where(Hu(wt(u.orgMembers.orgId,o),wt(u.orgMembers.userId,t))).get()?.role??null}function _n(n,t,o){return n.select().from(u.driveMembers).where(Hu(wt(u.driveMembers.driveId,o),wt(u.driveMembers.userId,t))).get()?.role??null}function Lt(n,t){let o=_n(n,t.userId,t.driveId);if(!o)throw new d("You do not have access to this drive",{requiredRole:t.requiredRole,yourRole:"none",suggestion:"Request access from the drive admin"});if(rt[o]<rt[t.requiredRole])throw new d(`This operation requires '${t.requiredRole}' role, but you have '${o}'`,{requiredRole:t.requiredRole,yourRole:o,suggestion:t.requiredRole==="editor"?"Ask a drive admin to upgrade your role to editor":"Ask a drive admin to upgrade your role"});return o}function ht(n,t){Lt(n,t)}function zt(n,t){let o=xn(n,t.userId,t.orgId);if(!o)throw new d("You do not have access to this organization",{requiredRole:t.requiredRole,yourRole:"none",suggestion:"Request access from an org admin"});if(rt[o]<rt[t.requiredRole])throw new d(`This operation requires '${t.requiredRole}' role in the org, but you have '${o}'`,{requiredRole:t.requiredRole,yourRole:o,suggestion:"Ask an org admin to upgrade your role"});return o}function Fn(n,t){let o=n.select().from(u.drives).where(wt(u.drives.id,t.driveId)).get();if(!o)throw new X(`Drive not found: ${t.driveId}`);let i=_n(n,t.userId,t.driveId);if(i==="admin")return i;let e=xn(n,t.userId,o.orgId);if(e==="admin")return e;throw new d("This operation requires drive admin or org admin role",{requiredRole:"admin",yourRole:i??e??"none",suggestion:"Ask a drive or org admin to perform this operation"})}function Hn(n,t){let o=n.select().from(u.drives).where(wt(u.drives.id,t.driveId)).get();if(!o||o.orgId!==t.orgId)throw new X(`Drive not found in org: ${t.driveId}`,{suggestion:"Check the driveId belongs to the org you are addressing"});return{id:o.id,orgId:o.orgId,name:o.name,isDefault:o.isDefault}}var rt,Ow;var pt=R(()=>{J();m();rt={viewer:0,editor:1,admin:2},Ow={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",sql:"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 Zn(n){let t=n;if(!t.startsWith("/"))t="/"+t;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function vn(n){let t=n;if(!t.startsWith("/"))t="/"+t;if(!t.endsWith("/"))t+="/";return t}function Zu(n){return n.startsWith("/")?n.slice(1):n}import{eq as Xn,and as qt,sql as lw,desc as Qu}from"drizzle-orm";function $(n,t,o){let i=Zu(o);return`${n}/drives/${t}/${i}`}async function $o(n,t){return(n.db.select({maxVersion:lw`MAX(version)`}).from(u.fileVersions).where(qt(Xn(u.fileVersions.path,t),Xn(u.fileVersions.driveId,n.driveId))).get()?.maxVersion??0)+1}function Ut(n,t){let o=n.db.select({version:u.fileVersions.version,contentHash:u.fileVersions.contentHash,etag:u.fileVersions.etag,createdAt:u.fileVersions.createdAt}).from(u.fileVersions).where(qt(Xn(u.fileVersions.path,t),Xn(u.fileVersions.driveId,n.driveId))).orderBy(Qu(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 x(n,t,o){let e=await $o(n,t)-1;if(o!==void 0&&e!==o)throw new Rn(`Expected version ${o} but file is at version ${e}`,{path:t,suggestion:"Re-read the file to get the current version and retry"});return e}async function go(n,t){return n.db.select({contentHash:u.fileVersions.contentHash}).from(u.fileVersions).where(qt(Xn(u.fileVersions.path,t),Xn(u.fileVersions.driveId,n.driveId))).orderBy(Qu(u.fileVersions.version)).limit(1).get()?.contentHash??null}async function p(n,t){let o=await $o(n,t.path),i=new Date;try{n.db.transaction((e)=>{e.insert(u.fileVersions).values({path:t.path,driveId:n.driveId,version:o,s3VersionId:t.s3VersionId,author:n.userId,operation:t.operation,message:t.message??null,diffSummary:t.diffSummary??null,size:t.size??null,etag:t.etag??null,contentHash:t.contentHash??null,createdAt:i}).run();let E=e.select().from(u.files).where(qt(Xn(u.files.path,t.path),Xn(u.files.driveId,n.driveId))).get();if(E)e.update(u.files).set({size:t.size??E.size,contentType:t.contentType??E.contentType,author:n.userId,currentVersionId:String(o),modifiedAt:i,isDeleted:t.operation==="delete"}).where(qt(Xn(u.files.path,t.path),Xn(u.files.driveId,n.driveId))).run();else e.insert(u.files).values({path:t.path,driveId:n.driveId,size:t.size??0,contentType:t.contentType??null,author:n.userId,currentVersionId:String(o),createdAt:i,modifiedAt:i,isDeleted:t.operation==="delete"}).run()})}catch(e){let E=String(e?.message??"");if(E.includes("UNIQUE constraint failed")&&E.includes("file_versions"))throw new Rn(`Concurrent write detected for ${t.path}: version ${o} already exists`,{path:t.path,suggestion:"Re-read the file to get the current version and retry the write"});throw e}return o}var j=R(()=>{J();m()});function h(n){let t=n.split(".").pop()?.toLowerCase()??"";return $w[t]??"application/octet-stream"}function gw(n){let t=n.split(";")[0]?.trim().toLowerCase()??"";return t.startsWith("text/")||t==="application/json"||t==="application/x-ndjson"||t==="application/xml"||t==="application/x-yaml"||t==="application/toml"||t==="image/svg+xml"}function Iw(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function jn(n,t){let o=Iw(n);if(o===null)return null;if(gw(t))return o;if(t==="application/octet-stream"&&Xw(n))return o;return null}function Xw(n){if(n.length===0)return!0;let t=0;for(let o of n){if(o===0)return!1;let i=o===9||o===10||o===12||o===13;if(o<32&&!i)t++}return t/n.length<0.01}var $w;var wn=R(()=>{$w={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",tsv:"text/tab-separated-values",xml:"application/xml",json:"application/json",jsonl:"application/x-ndjson",ndjson:"application/x-ndjson",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",parquet:"application/vnd.apache.parquet",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",db:"application/vnd.sqlite3",sqlite:"application/vnd.sqlite3",sqlite3:"application/vnd.sqlite3",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}});function Ki(n){return n.$client}function Cn(n,t){let o=Ki(n);o.prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(t.path,t.driveId),o.prepare("INSERT INTO files_fts(path, content, drive_id) VALUES (?, ?, ?)").run(t.path,t.content,t.driveId)}function Dt(n,t){Ki(n).prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(t.path,t.driveId)}function Io(n,t){let o=Ki(n),i,e;if(t.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 ?
|
|
149
149
|
ORDER BY rank
|
|
150
150
|
LIMIT 50
|
|
151
|
-
`,e=[
|
|
151
|
+
`,e=[t.pattern,t.driveId,t.pathPrefix+"%"];else i=`
|
|
152
152
|
SELECT path, snippet(files_fts, 1, '<b>', '</b>', '...', 32) as snippet, rank
|
|
153
153
|
FROM files_fts
|
|
154
154
|
WHERE content MATCH ? AND drive_id = ?
|
|
155
155
|
ORDER BY rank
|
|
156
156
|
LIMIT 50
|
|
157
|
-
`,e=[
|
|
158
|
-
|
|
159
|
-
`);if(
|
|
160
|
-
`),T
|
|
161
|
-
`),totalLines:
|
|
162
|
-
`),f
|
|
163
|
-
`),totalLines:
|
|
164
|
-
`);for(let
|
|
157
|
+
`,e=[t.pattern,t.driveId];return o.prepare(i).all(...e)}async function Ju(n){if(n.length===0)return[];try{let{RecursiveChunker:t}=await import("chonkie");return(await(await t.create({chunkSize:900})).chunk(n)).map((e)=>({content:e.text,charOffset:e.startIndex??0,tokenCount:e.tokenCount??Math.ceil(e.text.length/4)}))}catch{return Cw(n)}}function Cw(n){let i=[];if(n.length===0)return[];if(n.length<=3600)return[{content:n,charOffset:0,tokenCount:Math.ceil(n.length/4)}];let e=0;while(e<n.length){let E=Math.min(e+3600,n.length),f=n.slice(e,E);if(E<n.length){let T=f.lastIndexOf(`
|
|
158
|
+
|
|
159
|
+
`);if(T>1800)f=f.slice(0,T)}if(i.push({content:f,charOffset:e,tokenCount:Math.ceil(f.length/4)}),e+=f.length-512,e<=i[i.length-1].charOffset)e=i[i.length-1].charOffset+f.length}return i}import{eq as Tn,and as St}from"drizzle-orm";function Pw(n){return n.$client}class Bu{permits;waiting=[];constructor(n){this.permits=n}async acquire(){if(this.permits>0)return this.permits--,()=>this.release();return new Promise((n)=>{this.waiting.push(()=>{this.permits--,n(()=>this.release())})})}release(){this.permits++;let n=this.waiting.shift();if(n)n()}}async function vi(n,t,o){let i=Pw(n),e=n.select({isDeleted:u.files.isDeleted}).from(u.files).where(St(Tn(u.files.path,o.path),Tn(u.files.driveId,o.driveId))).get();if(!e||e.isDeleted)return;try{let E=await Ju(o.content),f=E.map((y)=>y.content),T=await t.embedBatch(f),A=n.select({id:u.contentChunks.id}).from(u.contentChunks).where(St(Tn(u.contentChunks.filePath,o.path),Tn(u.contentChunks.driveId,o.driveId))).all();for(let y of A)i.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(y.id);n.delete(u.contentChunks).where(St(Tn(u.contentChunks.filePath,o.path),Tn(u.contentChunks.driveId,o.driveId))).run();let N=i.prepare("INSERT INTO chunk_vectors(chunk_id, embedding) VALUES (?, ?)");for(let y=0;y<E.length;y++){let _=n.insert(u.contentChunks).values({filePath:o.path,driveId:o.driveId,chunkIndex:y,content:E[y].content,charOffset:E[y].charOffset,tokenCount:E[y].tokenCount}).returning({id:u.contentChunks.id}).get(),r=new Float32Array(T[y]);N.run(_.id,r)}n.update(u.files).set({embeddingStatus:"indexed"}).where(St(Tn(u.files.path,o.path),Tn(u.files.driveId,o.driveId))).run()}catch(E){throw n.update(u.files).set({embeddingStatus:"failed"}).where(St(Tn(u.files.path,o.path),Tn(u.files.driveId,o.driveId))).run(),E}}function Ot(n,t,o){if(!t)return;n.update(u.files).set({embeddingStatus:"pending"}).where(St(Tn(u.files.path,o.path),Tn(u.files.driveId,o.driveId))).run(),Yw.acquire().then(async(i)=>{try{await vi(n,t,o)}catch(e){console.error("Embedding failed",{path:o.path,error:e})}finally{i()}})}var Yw;var bt=R(()=>{J();Yw=new Bu(2)});import{eq as lt,and as ji}from"drizzle-orm";function dt(n,t){Dt(n.db,{path:t,driveId:n.driveId});let o=n.db.select({id:u.contentChunks.id}).from(u.contentChunks).where(ji(lt(u.contentChunks.filePath,t),lt(u.contentChunks.driveId,n.driveId))).all();if(o.length>0){let i=n.db.$client;for(let e of o)i.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(e.id);n.db.delete(u.contentChunks).where(ji(lt(u.contentChunks.filePath,t),lt(u.contentChunks.driveId,n.driveId))).run()}n.db.update(u.files).set({embeddingStatus:null}).where(ji(lt(u.files.path,t),lt(u.files.driveId,n.driveId))).run()}function ki(n,t,o){Cn(n.db,{path:t,driveId:n.driveId,content:o}),Ot(n.db,n.embeddingProvider??null,{path:t,driveId:n.driveId,content:o})}function $t(n,t,o,i){let e=jn(o,i);if(e===null)return dt(n,t),null;return ki(n,t,e),e}var gt=R(()=>{J();bt();wn()});import{createHash as Mw}from"crypto";async function Xo(n,t){let o=new TextEncoder().encode(t.content);return Wu(n,{...t,bytes:o,indexableText:t.content},{maxSize:Gw})}async function Qn(n,t){return Lt(n.db,{userId:n.userId,driveId:n.driveId,requiredRole:"editor"}),Wu(n,t,{maxSize:Fw})}async function Wu(n,t,o){let i=$(n.orgId,n.driveId,t.path),e=t.bytes,E=e.byteLength;if(E>o.maxSize){let y=(o.maxSize/1024/1024).toFixed(0);throw new F(`File size ${(E/1024/1024).toFixed(1)}MB exceeds the ${y}MB limit`,{field:"content",suggestion:"Split large files into smaller chunks"})}let f=Mw("sha256").update(e).digest("hex");if(t.expectedVersion!==void 0){let y=await x(n,t.path,t.expectedVersion);if(y>0){let _=await go(n,t.path);if(_!==null&&_===f)return{version:y,path:t.path,size:E,contentHash:f,deduped:!0}}}let T=h(t.path),A=await n.s3.putObject(i,e,void 0,T),N=await p(n,{path:t.path,s3VersionId:A.versionId??"",operation:"write",message:t.message,size:E,etag:A.etag,contentType:T,contentHash:f});if(t.indexableText!==void 0)ki(n,t.path,t.indexableText);else $t(n,t.path,e,T);return{version:N,path:t.path,size:E,contentHash:f,deduped:!1}}var Gw=10485760,Fw=52428800;var Vu=R(()=>{j();wn();m();pt();gt()});async function Ku(n,t){let o=$(n.orgId,n.driveId,t.path),i;try{let e=await n.s3.getObject(o);i=e.body;let E=e.contentType??h(t.path),f=jn(i,E);if(f===null)throw new F(`File is not readable as text: ${t.path}`,{field:"path",suggestion:"Use `agent-fs download` or `agent-fs signed-url` for binary files"});let T=f.split(`
|
|
160
|
+
`),A=T.length,N=t.offset??0,y=t.limit??Hw,_=T.slice(N,N+y),r=N+y<A;return{content:_.join(`
|
|
161
|
+
`),totalLines:A,truncated:r}}catch(e){if(e?.name==="NoSuchKey"||e?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${t.path}`,{path:t.path});throw e}}var Hw=200;var vu=R(()=>{j();m();wn()});import{createHash as Zw}from"crypto";async function ju(n,t){let o=$(n.orgId,n.driveId,t.path);if(t.expectedVersion!==void 0)await x(n,t.path,t.expectedVersion);let i;try{i=(await n.s3.getObject(o)).body}catch(L){if(L?.name==="NoSuchKey"||L?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${t.path}`,{path:t.path});throw L}let e=new TextDecoder().decode(i),E=e.split(t.old_string).length-1;if(E===0)throw new Rn(`old_string not found in ${t.path}`,{path:t.path,suggestion:"Verify the exact text you want to replace"});if(E>1)throw new Rn(`old_string found ${E} times in ${t.path}, expected exactly 1`,{path:t.path,suggestion:"Provide more surrounding context to make the match unique"});let f=e.replace(t.old_string,t.new_string),T=Buffer.byteLength(f),A=h(t.path),N=Zw("sha256").update(f).digest("hex"),y=await n.s3.putObject(o,f,void 0,A),_=JSON.stringify({old:t.old_string,new:t.new_string}),r=await p(n,{path:t.path,s3VersionId:y.versionId??"",operation:"edit",message:t.message,diffSummary:_,size:T,etag:y.etag,contentType:A,contentHash:N});return Cn(n.db,{path:t.path,driveId:n.driveId,content:f}),Ot(n.db,n.embeddingProvider??null,{path:t.path,driveId:n.driveId,content:f}),{version:r,path:t.path,changes:1}}var ku=R(()=>{j();m();wn();bt()});import{createHash as Qw}from"crypto";async function hu(n,t){let o=$(n.orgId,n.driveId,t.path);if(t.expectedVersion!==void 0)await x(n,t.path,t.expectedVersion);let i="";try{let y=await n.s3.getObject(o);i=new TextDecoder().decode(y.body)}catch(y){if(y?.name==="NoSuchKey"||y?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${t.path}`,{path:t.path});throw y}let e=i+t.content,E=Buffer.byteLength(e),f=h(t.path),T=Qw("sha256").update(e).digest("hex"),A=await n.s3.putObject(o,e,void 0,f),N=await p(n,{path:t.path,s3VersionId:A.versionId??"",operation:"append",message:t.message,size:E,etag:A.etag,contentType:f,contentHash:T});return Cn(n.db,{path:t.path,driveId:n.driveId,content:e}),Ot(n.db,n.embeddingProvider??null,{path:t.path,driveId:n.driveId,content:e}),{version:N,size:E}}var zu=R(()=>{j();m();wn();bt()});import{eq as pu,and as Jw,like as Bw}from"drizzle-orm";async function qu(n,t){let o=vn(t.path??"/"),i=$(n.orgId,n.driveId,o),{objects:e,prefixes:E}=await n.s3.listObjects(i,{delimiter:"/"}),f=n.db.select().from(u.files).where(Jw(pu(u.files.driveId,n.driveId),Bw(u.files.path,o+"%"),pu(u.files.isDeleted,!1))).all(),T=new Map(f.map((N)=>[N.path,N])),A=[];for(let N of E){let y=N.slice(i.length).replace(/\/$/,"");if(y)A.push({name:y,type:"directory",size:0})}for(let N of e){let y=N.key.slice(i.length);if(!y)continue;let _=y.endsWith("/"),r=_?y.slice(0,-1):y;if(_)A.push({name:r,type:"directory",size:0});else{let L=o+r,S=T.get(L);A.push({name:r,type:"file",size:S?.size??N.size,author:S?.author,modifiedAt:S?.modifiedAt??N.lastModified})}}return{entries:A}}var bu=R(()=>{J();j()});import{eq as du,and as Ww}from"drizzle-orm";async function mu(n,t){let o=$(n.orgId,n.driveId,t.path),i;try{i=await n.s3.headObject(o)}catch(E){if(E?.name==="NotFound"||E?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${t.path}`,{path:t.path});throw E}let e=n.db.select().from(u.files).where(Ww(du(u.files.path,t.path),du(u.files.driveId,n.driveId))).get();return{path:t.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 xu=R(()=>{J();j();m()});import{eq as It,and as hi}from"drizzle-orm";async function su(n,t){let o=$(n.orgId,n.driveId,t.path);if(t.expectedVersion!==void 0)await x(n,t.path,t.expectedVersion);await n.s3.deleteObject(o),await p(n,{path:t.path,s3VersionId:"",operation:"delete"}),Dt(n.db,{path:t.path,driveId:n.driveId});let i=n.db.select({id:u.contentChunks.id}).from(u.contentChunks).where(hi(It(u.contentChunks.filePath,t.path),It(u.contentChunks.driveId,n.driveId))).all();if(i.length>0){let e=n.db.$client;for(let E of i)e.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(E.id);n.db.delete(u.contentChunks).where(hi(It(u.contentChunks.filePath,t.path),It(u.contentChunks.driveId,n.driveId))).run()}return n.db.update(u.comments).set({isDeleted:!0,updatedAt:new Date}).where(hi(It(u.comments.path,t.path),It(u.comments.driveId,n.driveId))).run(),{path:t.path,deleted:!0}}var cu=R(()=>{J();j()});import{eq as au,and as Vw}from"drizzle-orm";import{createHash as Kw}from"crypto";async function nT(n,t){let o=$(n.orgId,n.driveId,t.from),i=$(n.orgId,n.driveId,t.to);if(t.expectedVersion!==void 0)await x(n,t.from,t.expectedVersion);let e=await n.s3.copyObject(o,i),E=await n.s3.headObject(i),f=await n.s3.getObject(i),T=Kw("sha256").update(f.body).digest("hex"),A=E.contentType??f.contentType??h(t.to),N=await p(n,{path:t.to,s3VersionId:e.versionId??"",operation:"write",message:t.message??`Moved from ${t.from}`,size:E.size,etag:e.etag,contentType:A,contentHash:T});await n.s3.deleteObject(o),await p(n,{path:t.from,s3VersionId:"",operation:"delete",message:`Moved to ${t.to}`}),Dt(n.db,{path:t.from,driveId:n.driveId});let y=jn(f.body,A);if(y===null)dt(n,t.to);else Cn(n.db,{path:t.to,driveId:n.driveId,content:y}),n.db.update(u.contentChunks).set({filePath:t.to}).where(Vw(au(u.contentChunks.filePath,t.from),au(u.contentChunks.driveId,n.driveId))).run();return{from:t.from,to:t.to,version:N}}var tT=R(()=>{j();J();wn();gt()});import{createHash as vw}from"crypto";async function oT(n,t){let o=$(n.orgId,n.driveId,t.from),i=$(n.orgId,n.driveId,t.to);if(t.expectedVersion!==void 0)await x(n,t.to,t.expectedVersion);let e=await n.s3.copyObject(o,i),E=await n.s3.headObject(i),f=await n.s3.getObject(i),T=vw("sha256").update(f.body).digest("hex"),A=E.contentType??f.contentType??h(t.to),N=await p(n,{path:t.to,s3VersionId:e.versionId??"",operation:"write",message:`Copied from ${t.from}`,size:E.size,etag:e.etag,contentType:A,contentHash:T});return $t(n,t.to,f.body,A),{from:t.from,to:t.to,version:N}}var iT=R(()=>{j();wn();gt()});async function eT(n,t){let o=$(n.orgId,n.driveId,t.path),i=t.lines??jw,e;try{e=(await n.s3.getObject(o)).body}catch(_){if(_?.name==="NoSuchKey"||_?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${t.path}`,{path:t.path});throw _}let f=new TextDecoder().decode(e).split(`
|
|
162
|
+
`),T=f.length,A=Math.max(0,T-i),N=f.slice(A),y=A>0;return{content:N.join(`
|
|
163
|
+
`),totalLines:T,truncated:y}}var jw=20;var ET=R(()=>{j();m()});import{eq as fT,and as kw,desc as hw}from"drizzle-orm";async function uT(n,t){let o=t.limit??50;return{versions:n.db.select().from(u.fileVersions).where(kw(fT(u.fileVersions.path,t.path),fT(u.fileVersions.driveId,n.driveId))).orderBy(hw(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 TT=R(()=>{J()});import{eq as Xt,and as AT}from"drizzle-orm";import{structuredPatch as zw}from"diff";async function NT(n,t){let o=n.db.select().from(u.fileVersions).where(AT(Xt(u.fileVersions.path,t.path),Xt(u.fileVersions.driveId,n.driveId),Xt(u.fileVersions.version,t.v1))).get(),i=n.db.select().from(u.fileVersions).where(AT(Xt(u.fileVersions.path,t.path),Xt(u.fileVersions.driveId,n.driveId),Xt(u.fileVersions.version,t.v2))).get();if(!o||!i)throw new X(`Version ${!o?t.v1:t.v2} not found for ${t.path}`,{path:t.path});if(o.s3VersionId&&i.s3VersionId){let E=$(n.orgId,n.driveId,t.path);try{let[f,T]=await Promise.all([n.s3.getObject(E,o.s3VersionId),n.s3.getObject(E,i.s3VersionId)]),A=new TextDecoder().decode(f.body),N=new TextDecoder().decode(T.body),y=zw(t.path,t.path,A,N),_=[];for(let r of y.hunks)for(let L of r.lines){let S=L.startsWith("+")?"add":L.startsWith("-")?"remove":"context";_.push({type:S,content:L.slice(1)})}return{changes:_}}catch(f){console.warn(`[diff] S3 content fetch failed for ${t.path}, falling back to diffSummary:`,f)}}let e=[];if(i.diffSummary)try{let E=JSON.parse(i.diffSummary);if(E.old)e.push({type:"remove",content:E.old});if(E.new)e.push({type:"add",content:E.new})}catch{e.push({type:"context",content:i.diffSummary})}return{changes:e}}var yT=R(()=>{J();j();m()});import{eq as zi,and as pw}from"drizzle-orm";import{createHash as qw}from"crypto";async function RT(n,t){if(t.expectedVersion!==void 0)await x(n,t.path,t.expectedVersion);let o=n.db.select().from(u.fileVersions).where(pw(zi(u.fileVersions.path,t.path),zi(u.fileVersions.driveId,n.driveId),zi(u.fileVersions.version,t.version))).get();if(!o)throw new X(`Version ${t.version} not found for ${t.path}`,{path:t.path});if(!o.s3VersionId)throw new In("VERSIONING_REQUIRED","S3 versioning required for revert","Enable S3 versioning on the bucket");let i=$(n.orgId,n.driveId,t.path),e=await n.s3.getObject(i,o.s3VersionId),E=h(t.path),f=await n.s3.putObject(i,e.body,void 0,E),T=e.body.length,A=qw("sha256").update(e.body).digest("hex"),N=await p(n,{path:t.path,s3VersionId:f.versionId??"",operation:"revert",message:`Reverted to version ${t.version}`,size:T,etag:f.etag,contentType:E,contentHash:A});return $t(n,t.path,e.body,E),{version:N,revertedTo:t.version}}var _T=R(()=>{J();j();m();wn();gt()});import{eq as pi,and as wT,desc as bw,gte as dw,like as mw}from"drizzle-orm";async function rT(n,t){let o=t.limit??50,i=n.db.select().from(u.fileVersions).where(pi(u.fileVersions.driveId,n.driveId)).$dynamic();if(t.path)i=i.where(wT(pi(u.fileVersions.driveId,n.driveId),mw(u.fileVersions.path,t.path+"%")));if(t.since)i=i.where(wT(pi(u.fileVersions.driveId,n.driveId),dw(u.fileVersions.createdAt,t.since)));return{entries:i.orderBy(bw(u.fileVersions.createdAt)).limit(o).all().map((E)=>({path:E.path,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 LT=R(()=>{J()});async function UT(n,t){let o=new RegExp(t.pattern),i=vn(t.path),E=n.db.$client.prepare("SELECT path, content FROM files_fts WHERE drive_id = ? AND path LIKE ?").all(n.driveId,i+"%"),f=[];for(let T of E){let A=T.content.split(`
|
|
164
|
+
`);for(let N=0;N<A.length;N++)if(o.test(A[N]))f.push({path:T.path,lineNumber:N+1,content:A[N]})}return{matches:f}}var DT=()=>{};async function ST(n,t){let i=Io(n.db,{pattern:t.pattern,driveId:n.driveId,pathPrefix:t.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 "${t.pattern}". Try 'search' for semantic/fuzzy matching.`};return{matches:i}}var OT=()=>{};import{eq as qi,and as xw}from"drizzle-orm";async function lT(n,t){let o=n.embeddingProvider;if(!o)return{results:[],hint:"No embedding provider configured. Set OPENAI_API_KEY or enable local embeddings to use semantic search."};let i=t.limit??10,e=await o.embed(t.query),E=new Float32Array(e),T=n.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(
|
|
168
|
+
LIMIT ?`).all(E,i*2);if(T.length===0)return{results:[]};let A=[],N=new Set;for(let y of T){let _=n.db.select().from(u.contentChunks).where(qi(u.contentChunks.id,y.chunk_id)).get();if(!_)continue;if(_.driveId!==n.driveId)continue;if(N.has(_.filePath))continue;N.add(_.filePath);let r=n.db.select().from(u.files).where(xw(qi(u.files.path,_.filePath),qi(u.files.driveId,n.driveId))).get();if(A.push({path:_.filePath,score:1/(1+y.distance),snippet:_.content.slice(0,200),author:r?.author,modifiedAt:r?.modifiedAt}),A.length>=i)break}return{results:A}}var $T=R(()=>{J()});import{eq as bi,and as sw}from"drizzle-orm";async function gT(n,t){let o=t.limit??10,i=n.embeddingProvider,[e,E]=await Promise.all([i?cw(n,t.query,o*3):[],aw(n,t.query,o*3)]);if(e.length===0&&E.length===0)return{results:[],hint:i?`No results found for "${t.query}".`:"No embedding provider configured. Set OPENAI_API_KEY, GEMINI_API_KEY, or enable local embeddings for semantic search. Showing keyword results only."};let f=60,T=new Map;for(let N=0;N<e.length;N++){let y=e[N],_=1/(f+N+1),r=T.get(y.path);if(r)r.score+=_;else T.set(y.path,{score:_,snippet:y.snippet,author:y.author,modifiedAt:y.modifiedAt})}for(let N=0;N<E.length;N++){let y=E[N],_=1/(f+N+1),r=T.get(y.path);if(r){if(r.score+=_,y.snippet)r.snippet=y.snippet}else T.set(y.path,{score:_,snippet:y.snippet})}return{results:Array.from(T.entries()).sort(([,N],[,y])=>y.score-N.score).slice(0,o).map(([N,y])=>({path:N,score:y.score,snippet:y.snippet,author:y.author,modifiedAt:y.modifiedAt})),hint:!i?"Results are keyword-only. Enable embeddings for better semantic matching.":void 0}}async function cw(n,t,o){let e=await n.embeddingProvider.embed(t),E=new Float32Array(e),T=n.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=[],l=new Set;for(let A of f){let R=t.db.select().from(u.contentChunks).where(Ci(u.contentChunks.id,A.chunk_id)).get();if(!R||R.driveId!==t.driveId)continue;if(l.has(R.filePath))continue;l.add(R.filePath);let w=t.db.select().from(u.files).where(g_(Ci(u.files.path,R.filePath),Ci(u.files.driveId,t.driveId))).get();T.push({path:R.filePath,snippet:R.content.slice(0,200),author:w?.author,modifiedAt:w?.modifiedAt})}return T}function D_(t,n,o){let i=n.split(/\s+/).filter(Boolean).map((e)=>`"${e}"`).join(" OR ");if(!i)return[];try{return oo(t.db,{pattern:i,driveId:t.driveId}).slice(0,o).map((r)=>({path:r.path,snippet:r.snippet}))}catch{return[]}}var xu=N(()=>{G()});import{eq as eo,and as O_,or as I_,isNull as U_}from"drizzle-orm";async function au(t,n){let o=[eo(u.files.driveId,t.driveId),eo(u.files.isDeleted,!1),I_(eo(u.files.embeddingStatus,"failed"),U_(u.files.embeddingStatus),eo(u.files.embeddingStatus,"pending"))];if(n.path){let{like:T}=await import("drizzle-orm"),l=n.path.endsWith("/")?n.path:n.path+"/";o.push(T(u.files.path,l+"%"))}let i=t.db.select({path:u.files.path}).from(u.files).where(O_(...o)).all(),e=0,r=0,E=0,f=3;for(let T=0;T<i.length;T+=f){let l=i.slice(T,T+f),A=await Promise.allSettled(l.map(async(R)=>{let w=I(t.orgId,t.driveId,R.path),L=await t.s3.getObject(w),O=L.contentType??K(R.path),D=Pt(L.body,O);if(D===null)return Mn(t,R.path),"skipped";if(wt(t.db,{path:R.path,driveId:t.driveId,content:D}),t.embeddingProvider)return await Di(t.db,t.embeddingProvider,{path:R.path,driveId:t.driveId,content:D}),"reindexed";return"skipped"}));for(let R of A)if(R.status==="fulfilled")if(R.value==="reindexed")e++;else E++;else console.error("Reindex failed:",R.reason),r++}return{reindexed:e,failed:r,skipped:E}}var tf=N(()=>{G();W();Fn();rn();rt()});import{eq as nf,and as S_,like as $_}from"drizzle-orm";async function of(t,n){let o=Ct(n.path??"/"),i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(S_(nf(u.files.driveId,t.driveId),$_(u.files.path,o+"%"),nf(u.files.isDeleted,!1))).all(),E=new Map(r.map((T)=>[T.path,T])),f=[];for(let T of e){let l=T.key.slice(i.length);if(!l)continue;let A=l.split("/").filter(Boolean);if(A.length===0)continue;if(n.depth!==void 0&&A.length>n.depth)continue;let R=f;for(let w=0;w<A.length;w++){let L=A[w],O=w===A.length-1,D=!O||l.endsWith("/");if(D&&!O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C);if(!C.children)C.children=[];R=C.children}else if(D&&O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C)}else{let C=o+A.slice(0,w+1).join("/"),Z=E.get(C),_n={name:L,type:"file",size:Z?.size??T.size};if(Z?.author)_n.author=Z.author;if(Z?.modifiedAt??T.lastModified)_n.modifiedAt=Z?.modifiedAt??T.lastModified;R.push(_n)}}}return{tree:f}}var ef=N(()=>{G();W()});import{eq as rf,and as X_,like as C_}from"drizzle-orm";function P_(t){let n="",o=0;while(o<t.length){let i=t[o];if(i==="*")if(t[o+1]==="*"){if(n+=".*",o+=2,t[o]==="/")o++}else n+="[^/]*",o++;else if(i==="?")n+="[^/]",o++;else if(".+^${}()|[]\\".includes(i))n+="\\"+i,o++;else n+=i,o++}return new RegExp("^"+n+"$")}async function Ef(t,n){let o=n.path?Ct(n.path):"/",i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(X_(rf(u.files.driveId,t.driveId),C_(u.files.path,o+"%"),rf(u.files.isDeleted,!1))).all(),E=new Map(r.map((l)=>[l.path,l])),f=P_(n.pattern),T=[];for(let l of e){let A=l.key.slice(i.length);if(!A||A.endsWith("/"))continue;if(f.test(A)){let R=o+A,w=E.get(R);T.push({path:R,size:w?.size??l.size,modifiedAt:w?.modifiedAt??l.lastModified})}}return{matches:T}}var uf=N(()=>{G();W()});async function ff(t,n){let o=Cn(n.path),i=I(t.orgId,t.driveId,o),e=n.expiresIn??86400;try{await t.s3.headObject(i)}catch(f){if(f?.name==="NotFound"||f?.name==="NoSuchKey"||f?.$metadata?.httpStatusCode===404)throw new M(`File not found: ${o}`,{path:o});throw f}let r=K(o);return{url:await t.s3.getPresignedUrl(i,e,r!=="application/octet-stream"?r:void 0),path:o,expiresIn:e,expiresAt:new Date(Date.now()+e*1000).toISOString()}}var Tf=N(()=>{W();m();rt()});function Pi(t,n,o,i){let e=i.startsWith("/")?i.slice(1):i;return`${t}/file/~/${n}/${o}/${e}`}import{eq as F,and as yt,sql as Fi,desc as lf}from"drizzle-orm";function Mi(t,n){t.db.insert(u.events).values({id:crypto.randomUUID(),orgId:t.orgId,type:n.type,resourceType:n.resourceType,resourceId:n.resourceId,actor:t.userId,target:n.target??null,status:"created",metadata:n.metadata?JSON.stringify(n.metadata):null,createdAt:new Date}).run()}function ro(t){return{id:t.id,parentId:t.parentId??void 0,path:t.path,lineStart:t.lineStart??void 0,lineEnd:t.lineEnd??void 0,quotedContent:t.quotedContent??void 0,body:t.body,author:t.author,resolved:t.resolved??!1,resolvedBy:t.resolvedBy??void 0,resolvedAt:t.resolvedAt??void 0,fileVersionId:t.fileVersionId??void 0,replyCount:t.replyCount??0,createdAt:t.createdAt,updatedAt:t.updatedAt}}async function Eo(t,n){let o=new Date,i=crypto.randomUUID(),e=n.path;if(n.parentId){let E=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.parentId),F(u.comments.isDeleted,!1))).get();if(!E)throw new M("Parent comment not found",{suggestion:"Check that the parent comment ID is correct and not deleted"});if(E.parentId)throw new c("Cannot reply to a reply \u2014 only root comments accept replies",{suggestion:"Reply to the root comment instead"});if(!e)e=E.path}if(!e)throw new c("path is required for root comments",{field:"path"});let r=t.db.select({id:u.fileVersions.id}).from(u.fileVersions).where(yt(F(u.fileVersions.path,e),F(u.fileVersions.driveId,t.driveId))).orderBy(lf(u.fileVersions.id)).limit(1).get();return t.db.insert(u.comments).values({id:i,parentId:n.parentId??null,orgId:t.orgId,driveId:t.driveId,path:e,lineStart:n.lineStart??null,lineEnd:n.lineEnd??null,quotedContent:n.quotedContent??null,fileVersionId:r?.id??null,body:n.body,author:t.userId,resolved:!1,createdAt:o,updatedAt:o,isDeleted:!1}).run(),Mi(t,{type:"comment_created",resourceType:"comment",resourceId:i,metadata:{path:e,parentId:n.parentId}}),{id:i,path:e,body:n.body,parentId:n.parentId,lineStart:n.lineStart,lineEnd:n.lineEnd,author:t.userId,createdAt:o}}async function uo(t,n){let o=[F(u.comments.driveId,t.driveId),F(u.comments.isDeleted,!1)];if(n.path)o.push(F(u.comments.path,n.path));if(n.parentId)o.push(F(u.comments.parentId,n.parentId));else if(n.parentId===void 0&&!n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`),o.push(F(u.comments.resolved,!1));else if(n.parentId===void 0&&n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`);if(n.orgId)o.push(F(u.comments.orgId,n.orgId));let i=n.limit??50,e=n.offset??0;return{comments:t.db.select().from(u.comments).where(yt(...o)).orderBy(lf(u.comments.createdAt)).limit(i).offset(e).all().map((f)=>{let l=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,f.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((A)=>ro({...A,replyCount:0}));return{...ro({...f,replyCount:l.length}),replies:l}})}}async function fo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=t.db.select({count:Fi`count(*)`}).from(u.comments).where(yt(F(u.comments.parentId,o.id),F(u.comments.isDeleted,!1))).get(),e=ro({...o,replyCount:i?.count??0}),E=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,n.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((f)=>ro({...f,replyCount:0}));return{comment:e,replies:E}}async function To(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only edit your own comments",{suggestion:"Only the comment author can update it"});let i=new Date;return t.db.update(u.comments).set({body:n.body,updatedAt:i}).where(F(u.comments.id,n.id)).run(),{id:n.id,body:n.body,updatedAt:i}}async function lo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only delete your own comments",{suggestion:"Only the comment author can delete it"});let i=new Date;if(t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.id,n.id)).run(),!o.parentId)t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.parentId,n.id)).run();return Mi(t,{type:"comment_deleted",resourceType:"comment",resourceId:n.id}),{deleted:!0}}async function Ao(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.parentId)throw new c("Cannot resolve a reply \u2014 only root comments can be resolved",{suggestion:"Resolve the parent comment instead"});let i=new Date,e=n.resolved?i:null,r=n.resolved?t.userId:null;return t.db.update(u.comments).set({resolved:n.resolved,resolvedBy:r,resolvedAt:e,updatedAt:i}).where(F(u.comments.id,n.id)).run(),Mi(t,{type:n.resolved?"comment_resolved":"comment_reopened",resourceType:"comment",resourceId:n.id}),{id:n.id,resolved:n.resolved,resolvedBy:r??void 0,resolvedAt:e??void 0}}var Af=N(()=>{G();m()});import{z as _}from"zod";async function d(t,n,o,i){let e=vi[n];if(!e)throw Error(`Unknown operation: ${n}`);if(!i?.skipAuth){let f=$n(n);Xn(t.db,{userId:t.userId,driveId:t.driveId,requiredRole:f})}let r=e.schema.parse(o),E=await e.handler(t,r);if(t.appUrl&&E&&typeof E==="object"){if("path"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.path);else if("to"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.to)}return E}function fn(){return Object.keys(vi)}function Ft(t){return vi[t]}var vi;var Yi=N(()=>{an();Nu();_u();yu();Lu();Iu();$u();Cu();Mu();Yu();Hu();Ju();Wu();pu();du();mu();bu();qu();xu();tf();ef();uf();Tf();Af();vi={write:{description:"Write or overwrite a file. Creates the file if it doesn't exist, or creates a new version. Use expectedVersion for optimistic concurrency. Returns { version, path, size }.",handler:io,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cat:{description:"Read file content with optional pagination via offset/limit. Returns { content, totalLines, truncated }.",handler:Ru,schema:_.object({path:_.string(),offset:_.number().int().min(0).optional(),limit:_.number().int().min(1).optional()})},edit:{description:"Replace a specific string in a file (surgical find-and-replace). Captures the edit intent as a diff summary in version history. Returns { version, path, changes }.",handler:wu,schema:_.object({path:_.string(),old_string:_.string(),new_string:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},append:{description:"Append content to the end of an existing file. Creates a new version. Returns { version, size }.",handler:gu,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},ls:{description:"List immediate children of a directory. Returns { entries } where each entry has name, type (file/directory), size, author, modifiedAt.",handler:Ou,schema:_.object({path:_.string().optional()})},stat:{description:"Get file metadata without reading content. Returns path, size, contentType, author, currentVersion, createdAt, modifiedAt, isDeleted, embeddingStatus.",handler:Su,schema:_.object({path:_.string()})},rm:{description:"Delete a file. Removes from S3, cleans up FTS5 index and vector embeddings. Returns { path, deleted }.",handler:Xu,schema:_.object({path:_.string(),expectedVersion:_.number().int().optional()})},mv:{description:"Move or rename a file. Preserves version history at the new path. Returns { from, to, version }.",handler:Fu,schema:_.object({from:_.string(),to:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cp:{description:"Copy a file using server-side S3 copy. Creates a new version at the destination. Returns { from, to, version }.",handler:vu,schema:_.object({from:_.string(),to:_.string(),expectedVersion:_.number().int().optional()})},tail:{description:"Read the last N lines of a file (default 20). Returns { content, totalLines, truncated }.",handler:Gu,schema:_.object({path:_.string(),lines:_.number().int().min(1).optional()})},log:{description:"Show version history for a file. Returns { versions } with version number, author, timestamp, operation type, message, and diff summary.",handler:Qu,schema:_.object({path:_.string(),limit:_.number().int().min(1).optional()})},diff:{description:"Show the diff between two versions of a file. Specify v1 and v2 version numbers. Returns { changes } as add/remove/context hunks.",handler:Vu,schema:_.object({path:_.string(),v1:_.number().int(),v2:_.number().int()})},revert:{description:"Revert a file to a previous version. Creates a new version with the old content. Returns { version, revertedTo }.",handler:Ku,schema:_.object({path:_.string(),version:_.number().int(),expectedVersion:_.number().int().optional()})},recent:{description:"Show recent activity across the drive. Optionally filter by path prefix and time window (since). Returns { entries } with path and version details.",handler:ju,schema:_.object({path:_.string().optional(),since:_.coerce.date().optional(),limit:_.number().int().min(1).optional()})},grep:{description:"Search file content using regex pattern within a specific path. Returns matching lines with line numbers. Searches the FTS5 index, not S3 directly.",handler:ku,schema:_.object({pattern:_.string(),path:_.string()})},fts:{description:"Full-text search across all file content using FTS5 tokens. Different from grep (regex) and search (semantic). Returns { matches } with path, snippet, and rank.",handler:zu,schema:_.object({pattern:_.string(),path:_.string().optional()})},search:{description:"Hybrid search combining semantic (vector) and keyword (FTS5) matching. Best for natural language queries. Degrades to keyword-only without an embedding provider.",handler:cu,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},"vec-search":{description:"Vector-only semantic search using embeddings. Returns results ranked by cosine similarity. Requires an embedding provider (OPENAI_API_KEY, GEMINI_API_KEY, or local).",handler:su,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},reindex:{description:"Re-index files with failed or missing FTS5/embedding entries. Optionally scope to a path prefix. Use after bulk writes or provider changes.",handler:au,schema:_.object({path:_.string().optional()})},tree:{description:"Recursively list all files and directories. Use depth to limit recursion. Returns a nested tree structure with name, type, size, and children.",handler:of,schema:_.object({path:_.string().optional(),depth:_.number().int().min(1).optional()})},glob:{description:"Find files by name pattern. Use `*.md` for root-level files only, `**/*.md` for recursive matching across all subdirectories. Supports `*` (any chars except /), `?` (single char), `**` (any path depth). Optionally scope to a path prefix. Returns { matches } with path, size, and modifiedAt.",handler:Ef,schema:_.object({pattern:_.string(),path:_.string().optional()})},"signed-url":{description:"Generate a temporary presigned URL for direct file download. Default expiry is 24 hours (86400 seconds). The URL requires no authentication. Returns { url, path, expiresIn, expiresAt }.",handler:ff,schema:_.object({path:_.string(),expiresIn:_.number().int().min(60).max(604800).optional()})},"comment-add":{description:"Add a comment to a file. Supports line ranges and threading via parentId. Replies auto-resolve path from parent. Returns { id, path, body, author, createdAt }.",handler:Eo,schema:_.object({path:_.string().optional(),body:_.string(),parentId:_.string().optional(),lineStart:_.number().int().optional(),lineEnd:_.number().int().optional(),quotedContent:_.string().optional()})},"comment-list":{description:"List comments on a file. Filter by path, resolved state, or parentId. Defaults to unresolved root comments. Returns { comments } with inline replies.",handler:uo,schema:_.object({path:_.string().optional(),parentId:_.string().optional(),resolved:_.boolean().optional(),orgId:_.string().optional(),limit:_.number().int().min(1).optional(),offset:_.number().int().min(0).optional()})},"comment-get":{description:"Get a single comment by ID with all its replies. Returns { comment, replies }.",handler:fo,schema:_.object({id:_.string()})},"comment-update":{description:"Update a comment's body. Only the original author can update. Returns { id, body, updatedAt }.",handler:To,schema:_.object({id:_.string(),body:_.string()})},"comment-delete":{description:"Soft-delete a comment. Only the original author can delete. Deleting a root comment also soft-deletes its replies. Returns { deleted }.",handler:lo,schema:_.object({id:_.string()})},"comment-resolve":{description:"Resolve or reopen a root comment. Set resolved=true to resolve, resolved=false to reopen. Only root comments can be resolved. Returns { id, resolved, resolvedBy, resolvedAt }.",handler:Ao,schema:_.object({id:_.string(),resolved:_.boolean()})}}});import{eq as z,and as No}from"drizzle-orm";function Qt(t,n){let o=crypto.randomUUID(),i=new Date;return t.insert(u.drives).values({id:o,orgId:n.orgId,name:n.name,isDefault:n.isDefault??!1,createdAt:i}).run(),{id:o,name:n.name}}function vn(t,n){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().map((o)=>({id:o.id,name:o.name,isDefault:o.isDefault}))}function Ot(t,n,o){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().filter((e)=>{let r=t.select({userId:u.driveMembers.userId}).from(u.driveMembers).where(z(u.driveMembers.driveId,e.id)).all();if(r.length===0)return!0;return r.some((E)=>E.userId===o)}).map((e)=>({id:e.id,name:e.name,isDefault:e.isDefault}))}function Gi(t,n){let o=t.select().from(u.drives).where(z(u.drives.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,orgId:o.orgId,isDefault:o.isDefault}}function Jt(t,n){return t.select({userId:u.driveMembers.userId,email:u.users.email,role:u.driveMembers.role}).from(u.driveMembers).innerJoin(u.users,z(u.driveMembers.userId,u.users.id)).where(z(u.driveMembers.driveId,n)).all()}function Bt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.update(u.driveMembers).set({role:n.role}).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Vt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.delete(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Hi(t,n){t.insert(u.driveMembers).values({driveId:n.driveId,userId:n.userId,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Zi=N(()=>{G()});import{eq as Q,and as Wt,sql as Nf}from"drizzle-orm";function Kt(t,n){let o=crypto.randomUUID(),i=new Date;t.insert(u.orgs).values({id:o,name:n.name,isPersonal:n.isPersonal??!1,createdAt:i}).run(),t.insert(u.orgMembers).values({orgId:o,userId:n.userId,role:"admin"}).run();let e=Qt(t,{orgId:o,name:"default",isDefault:!0});return t.insert(u.driveMembers).values({driveId:e.id,userId:n.userId,role:"admin"}).run(),{id:o,name:n.name}}function p(t,n){return t.select({orgId:u.orgMembers.orgId,role:u.orgMembers.role,name:u.orgs.name,isPersonal:u.orgs.isPersonal}).from(u.orgMembers).innerJoin(u.orgs,Q(u.orgMembers.orgId,u.orgs.id)).where(Q(u.orgMembers.userId,n)).all().map((i)=>({id:i.orgId,name:i.name,role:i.role,isPersonal:i.isPersonal}))}function Yn(t,n){let o=t.select().from(u.orgs).where(Q(u.orgs.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,isPersonal:o.isPersonal}}function pt(t,n){return t.select({userId:u.orgMembers.userId,email:u.users.email,role:u.orgMembers.role}).from(u.orgMembers).innerJoin(u.users,Q(u.orgMembers.userId,u.users.id)).where(Q(u.orgMembers.orgId,n)).all()}function ht(t,n){let o=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!o)throw Error("Member not found in org");if(o.role==="admin"&&n.role!=="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}t.update(u.orgMembers).set({role:n.role}).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function jt(t,n){if(t.select({isPersonal:u.orgs.isPersonal}).from(u.orgs).where(Q(u.orgs.id,n.orgId)).get()?.isPersonal)throw Error("Cannot remove members from a personal org");let i=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!i)throw Error("Member not found in org");if(i.role==="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}let e=t.select({id:u.drives.id}).from(u.drives).where(Q(u.drives.orgId,n.orgId)).all();for(let r of e)t.delete(u.driveMembers).where(Wt(Q(u.driveMembers.driveId,r.id),Q(u.driveMembers.userId,n.userId))).run();t.delete(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function dt(t,n){let o=t.select().from(u.users).where(Q(u.users.email,n.email)).get();if(!o)throw Error(`User with email ${n.email} not found`);t.insert(u.orgMembers).values({orgId:n.orgId,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.orgMembers.orgId,u.orgMembers.userId],set:{role:n.role}}).run();let i=t.select().from(u.drives).where(Q(u.drives.orgId,n.orgId)).get();if(i)t.insert(u.driveMembers).values({driveId:i.id,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Qi=N(()=>{G();Zi()});import{eq as Rf}from"drizzle-orm";function _f(t){let n=new Bun.CryptoHasher("sha256");return n.update(t),n.digest("hex")}function F_(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`af_${Array.from(t,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function M_(){return crypto.randomUUID()}function Et(t,n){let o=M_(),i=F_(),e=_f(i),r=new Date;return t.insert(u.users).values({id:o,email:n.email,apiKeyHash:e,createdAt:r}).run(),Kt(t,{name:n.email.split("@")[0],userId:o,isPersonal:!0}),{user:{id:o,email:n.email},apiKey:i}}function ut(t,n){let o=_f(n),i=t.select().from(u.users).where(Rf(u.users.apiKeyHash,o)).get();if(!i)return null;return{id:i.id,email:i.email}}function Tn(t,n){let o=t.select().from(u.users).where(Rf(u.users.email,n)).get();if(!o)return null;return{id:o.id,email:o.email}}var Ji=N(()=>{G();Qi()});import{eq as Mt,and as Bi}from"drizzle-orm";function b(t,n){if(n.driveId){let r=t.select().from(u.drives).where(Mt(u.drives.id,n.driveId)).get();if(!r)throw Error(`Drive not found: ${n.driveId}`);let E=Rt(t,n.userId,n.driveId);if(!E)throw Error("You do not have access to this drive");return{orgId:r.orgId,driveId:n.driveId,role:E}}if(n.orgId){let r=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,n.orgId),Mt(u.drives.isDefault,!0))).get();if(!r)throw Error(`No default drive for org: ${n.orgId}`);let E=Rt(t,n.userId,r.id);if(!E)throw Error("You do not have access to this drive");return{orgId:n.orgId,driveId:r.id,role:E}}let o=t.select({orgId:u.orgMembers.orgId}).from(u.orgMembers).innerJoin(u.orgs,Mt(u.orgMembers.orgId,u.orgs.id)).where(Bi(Mt(u.orgMembers.userId,n.userId),Mt(u.orgs.isPersonal,!0))).get();if(!o)throw Error("No personal org found for user");let i=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,o.orgId),Mt(u.drives.isDefault,!0))).get();if(!i)throw Error("No default drive found");let e=Rt(t,n.userId,i.id);if(!e)throw Error("You do not have access to your default drive");return{orgId:o.orgId,driveId:i.id,role:e}}var wf=N(()=>{G();an()});function Gn(t){let n=P();if(n.auth.apiKey){if(ut(t,n.auth.apiKey))return{apiKey:n.auth.apiKey}}console.error("[agent-fs] No local user found, creating one...");let o=Et(t,{email:"local@agent-fs.local"});return U("auth.apiKey",o.apiKey),console.error("[agent-fs] Local user created automatically."),{apiKey:o.apiKey}}var yf=N(()=>{wn();Ji()});var gf=N(()=>{Ji();Qi();Zi();an();wf();yf()});var Df;var Lf=N(()=>{Df={name:"agent-fs",version:"0.7.5",private:!0,workspaces:["packages/*"],scripts:{typecheck:"tsc --build",test:"bun test packages/*/src/","test:coverage":"bun test --coverage packages/*/src/",build:"cd packages/cli && bun run build:npm","install-local":"bun run build && cd packages/cli && bun link","uninstall-local":"bun remove -g @desplega.ai/agent-fs && rm -f ~/.bun/bin/agent-fs","deploy:fly":"fly deploy -a agent-fs-taras"},devDependencies:{"bun-types":"^1.2.0",typescript:"^5.7.0",yaml:"^2.8.2","zod-to-json-schema":"^3.25.1"},overrides:{chromadb:"npm:empty-npm-package@1.0.0","chromadb-default-embed":"npm:empty-npm-package@1.0.0","@xenova/transformers":"npm:empty-npm-package@1.0.0","tree-sitter-wasms":"npm:empty-npm-package@1.0.0","web-tree-sitter":"npm:empty-npm-package@1.0.0","cohere-ai":"npm:empty-npm-package@1.0.0",voyageai:"npm:empty-npm-package@1.0.0",ollama:"npm:empty-npm-package@1.0.0"}}});var s;var Vi=N(()=>{Lf();s=Df.version});var If={};bt(If,{LocalEmbeddingProvider:()=>Of});import{join as Y_}from"path";import{mkdirSync as G_,existsSync as H_}from"fs";class Of{name="local";dimensions=768;llama=null;model=null;embeddingContext=null;initPromise=null;async init(){if(this.embeddingContext)return;if(this.initPromise)return this.initPromise;return this.initPromise=this._doInit(),this.initPromise}async _doInit(){let{getLlama:t,resolveModelFile:n}=await import("node-llama-cpp");this.llama=await t();let o=Y_(V(),"models");if(!H_(o))G_(o,{recursive:!0});console.error("[agent-fs] Resolving local embedding model...");let i=await n(Z_,o);console.error("[agent-fs] Model ready:",i),this.model=await this.llama.loadModel({modelPath:i}),this.embeddingContext=await this.model.createEmbeddingContext()}async embed(t){await this.init();let n=await this.embeddingContext.getEmbeddingFor(t);return Array.from(n.vector)}async embedBatch(t){await this.init();let n=[];for(let o of t){let i=await this.embeddingContext.getEmbeddingFor(o);n.push(Array.from(i.vector))}return n}async dispose(){if(this.embeddingContext)await this.embeddingContext.dispose(),this.embeddingContext=null;if(this.model)await this.model.dispose(),this.model=null;this.initPromise=null}}var Z_="hf:nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0";var Uf=N(()=>{wn()});var Wi={};bt(Wi,{OpenAIEmbeddingProvider:()=>Sf});import Q_ from"openai";class Sf{name="openai";dimensions=768;client;constructor(t){this.client=new Q_({apiKey:t})}async embed(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data[0].embedding}async embedBatch(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data.sort((o,i)=>o.index-i.index).map((o)=>o.embedding)}}var Ki=()=>{};var pi={};bt(pi,{GeminiEmbeddingProvider:()=>$f});import{GoogleGenAI as J_}from"@google/genai";class $f{name="gemini";dimensions=768;client;constructor(t){this.client=new J_({apiKey:t})}async embed(t){return(await this.client.models.embedContent({model:"gemini-embedding-001",contents:t,config:{outputDimensionality:768}})).embeddings[0].values}async embedBatch(t){let n=[];for(let o of t){let i=await this.client.models.embedContent({model:"gemini-embedding-001",contents:o,config:{outputDimensionality:768}});n.push(i.embeddings[0].values)}return n}}var hi=()=>{};async function Xf(t){switch(t.provider){case"local":{let{LocalEmbeddingProvider:n}=await Promise.resolve().then(() => (Uf(),If));return new n}case"openai":{if(!t.apiKey)throw Error("OpenAI API key required. Set embedding.apiKey in config.");let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(t.apiKey)}case"gemini":{if(!t.apiKey)throw Error("Gemini API key required. Set embedding.apiKey in config.");let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(t.apiKey)}default:throw Error(`Unknown embedding provider: ${t.provider}`)}}async function ln(t){if(process.env.OPENAI_API_KEY)try{let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(process.env.OPENAI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load OpenAI provider:",n)}if(process.env.GEMINI_API_KEY)try{let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(process.env.GEMINI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load Gemini provider:",n)}if(t?.provider&&t.provider!=="local"&&t.apiKey)try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to create embedding provider from config:",n)}if(t?.provider==="local")try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to load local embedding provider:",n)}return null}var Pf,Cf,Ff=(t)=>typeof t==="string"?{...Cf,name:t}:{...Cf,...t};var Ro=N(()=>{Pf=Symbol("Let zodToJsonSchema decide on which parser to use"),Cf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var Mf=(t)=>{let n=Ff(t),o=n.name!==void 0?[...n.basePath,n.definitionPath,n.name]:n.basePath;return{...n,flags:{hasReferencedOpenAiAnyType:!1},currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(n.definitions).map(([i,e])=>[e._def,{def:e._def,path:[...n.basePath,n.definitionPath,i],jsonSchema:void 0}]))}};var ji=N(()=>{Ro()});function di(t,n,o,i){if(!i?.errorMessages)return;if(o)t.errorMessage={...t.errorMessage,[n]:o}}function X(t,n,o,i,e){t[n]=o,di(t,n,i,e)}var _o=(t,n)=>{let o=0;for(;o<t.length&&o<n.length;o++)if(t[o]!==n[o])break;return[(t.length-o).toString(),...n.slice(o)].join("/")};function H(t){if(t.target!=="openAi")return{};let n=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?_o(n,t.currentPath):n.join("/")}}var tt=()=>{};import{ZodFirstPartyTypeKind as B_}from"zod/v3";function vf(t,n){let o={type:"array"};if(t.type?._def&&t.type?._def?.typeName!==B_.ZodAny)o.items=g(t.type._def,{...n,currentPath:[...n.currentPath,"items"]});if(t.minLength)X(o,"minItems",t.minLength.value,t.minLength.message,n);if(t.maxLength)X(o,"maxItems",t.maxLength.value,t.maxLength.message,n);if(t.exactLength)X(o,"minItems",t.exactLength.value,t.exactLength.message,n),X(o,"maxItems",t.exactLength.value,t.exactLength.message,n);return o}var ki=N(()=>{B()});function Yf(t,n){let o={type:"integer",format:"int64"};if(!t.checks)return o;for(let i of t.checks)switch(i.kind){case"min":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"minimum",i.value,i.message,n);else X(o,"exclusiveMinimum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMinimum=!0;X(o,"minimum",i.value,i.message,n)}break;case"max":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"maximum",i.value,i.message,n);else X(o,"exclusiveMaximum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMaximum=!0;X(o,"maximum",i.value,i.message,n)}break;case"multipleOf":X(o,"multipleOf",i.value,i.message,n);break}return o}var mi=()=>{};function Gf(){return{type:"boolean"}}function wo(t,n){return g(t.type._def,n)}var yo=N(()=>{B()});var Hf=(t,n)=>{return g(t.innerType._def,n)};var zi=N(()=>{B()});function bi(t,n,o){let i=o??n.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((e,r)=>bi(t,n,e))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return V_(t,n)}}var V_=(t,n)=>{let o={type:"integer",format:"unix-time"};if(n.target==="openApi3")return o;for(let i of t.checks)switch(i.kind){case"min":X(o,"minimum",i.value,i.message,n);break;case"max":X(o,"maximum",i.value,i.message,n);break}return o};var si=()=>{};function Zf(t,n){return{...g(t.innerType._def,n),default:t.defaultValue()}}var qi=N(()=>{B()});function Qf(t,n){return n.effectStrategy==="input"?g(t.schema._def,n):H(n)}var ci=N(()=>{B();tt()});function Jf(t){return{type:"string",enum:Array.from(t.values)}}function Bf(t,n){let o=[g(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),g(t.right._def,{...n,currentPath:[...n.currentPath,"allOf","1"]})].filter((r)=>!!r),i=n.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,e=[];return o.forEach((r)=>{if(W_(r)){if(e.push(...r.allOf),r.unevaluatedProperties===void 0)i=void 0}else{let E=r;if("additionalProperties"in r&&r.additionalProperties===!1){let{additionalProperties:f,...T}=r;E=T}else i=void 0;e.push(E)}}),e.length?{allOf:e,...i}:void 0}var W_=(t)=>{if("type"in t&&t.type==="string")return!1;return"allOf"in t};var xi=N(()=>{B()});function Vf(t,n){let o=typeof t.value;if(o!=="bigint"&&o!=="number"&&o!=="boolean"&&o!=="string")return{type:Array.isArray(t.value)?"array":"object"};if(n.target==="openApi3")return{type:o==="bigint"?"integer":o,enum:[t.value]};return{type:o==="bigint"?"integer":o,const:t.value}}function go(t,n){let o={type:"string"};if(t.checks)for(let i of t.checks)switch(i.kind){case"min":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n);break;case"max":X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"email":switch(n.emailStrategy){case"format:email":Tt(o,"email",i.message,n);break;case"format:idn-email":Tt(o,"idn-email",i.message,n);break;case"pattern:zod":k(o,ft.email,i.message,n);break}break;case"url":Tt(o,"uri",i.message,n);break;case"uuid":Tt(o,"uuid",i.message,n);break;case"regex":k(o,i.regex,i.message,n);break;case"cuid":k(o,ft.cuid,i.message,n);break;case"cuid2":k(o,ft.cuid2,i.message,n);break;case"startsWith":k(o,RegExp(`^${te(i.value,n)}`),i.message,n);break;case"endsWith":k(o,RegExp(`${te(i.value,n)}$`),i.message,n);break;case"datetime":Tt(o,"date-time",i.message,n);break;case"date":Tt(o,"date",i.message,n);break;case"time":Tt(o,"time",i.message,n);break;case"duration":Tt(o,"duration",i.message,n);break;case"length":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n),X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"includes":{k(o,RegExp(te(i.value,n)),i.message,n);break}case"ip":{if(i.version!=="v6")Tt(o,"ipv4",i.message,n);if(i.version!=="v4")Tt(o,"ipv6",i.message,n);break}case"base64url":k(o,ft.base64url,i.message,n);break;case"jwt":k(o,ft.jwt,i.message,n);break;case"cidr":{if(i.version!=="v6")k(o,ft.ipv4Cidr,i.message,n);if(i.version!=="v4")k(o,ft.ipv6Cidr,i.message,n);break}case"emoji":k(o,ft.emoji(),i.message,n);break;case"ulid":{k(o,ft.ulid,i.message,n);break}case"base64":{switch(n.base64Strategy){case"format:binary":{Tt(o,"binary",i.message,n);break}case"contentEncoding:base64":{X(o,"contentEncoding","base64",i.message,n);break}case"pattern:zod":{k(o,ft.base64,i.message,n);break}}break}case"nanoid":k(o,ft.nanoid,i.message,n);case"toLowerCase":case"toUpperCase":case"trim":break;default:((e)=>{})(i)}return o}function te(t,n){return n.patternStrategy==="escape"?p_(t):t}function p_(t){let n="";for(let o=0;o<t.length;o++){if(!K_.has(t[o]))n+="\\";n+=t[o]}return n}function Tt(t,n,o,i){if(t.format||t.anyOf?.some((e)=>e.format)){if(!t.anyOf)t.anyOf=[];if(t.format){if(t.anyOf.push({format:t.format,...t.errorMessage&&i.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage){if(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.anyOf.push({format:n,...o&&i.errorMessages&&{errorMessage:{format:o}}})}else X(t,"format",n,o,i)}function k(t,n,o,i){if(t.pattern||t.allOf?.some((e)=>e.pattern)){if(!t.allOf)t.allOf=[];if(t.pattern){if(t.allOf.push({pattern:t.pattern,...t.errorMessage&&i.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage){if(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.allOf.push({pattern:Wf(n,i),...o&&i.errorMessages&&{errorMessage:{pattern:o}}})}else X(t,"pattern",Wf(n,i),o,i)}function Wf(t,n){if(!n.applyRegexFlags||!t.flags)return t.source;let o={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},i=o.i?t.source.toLowerCase():t.source,e="",r=!1,E=!1,f=!1;for(let T=0;T<i.length;T++){if(r){e+=i[T],r=!1;continue}if(o.i){if(E){if(i[T].match(/[a-z]/)){if(f)e+=i[T],e+=`${i[T-2]}-${i[T]}`.toUpperCase(),f=!1;else if(i[T+1]==="-"&&i[T+2]?.match(/[a-z]/))e+=i[T],f=!0;else e+=`${i[T]}${i[T].toUpperCase()}`;continue}}else if(i[T].match(/[a-z]/)){e+=`[${i[T]}${i[T].toUpperCase()}]`;continue}}if(o.m){if(i[T]==="^"){e+=`(^|(?<=[\r
|
|
173
|
-
]))`;continue}else if(i[
|
|
174
|
-
]))`;continue}}if(o.s&&i[
|
|
175
|
-
`:`[${i[
|
|
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 Lo=N(()=>{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]:g(t.valueType._def,{...n,currentPath:[...n.currentPath,"properties",e]})??H(n)}),{}),additionalProperties:n.rejectedAdditionalProperties};let o={type:"object",additionalProperties:g(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}=go(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=N(()=>{B();Lo();yo();tt()});function Kf(t,n){if(n.mapStrategy==="record")return Do(t,n);let o=g(t.keyType._def,{...n,currentPath:[...n.currentPath,"items","items","0"]})||H(n),i=g(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=N(()=>{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=N(()=>{tt()});function jf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function kf(t,n){if(n.target==="openApi3")return df(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 df(t,n)}var Zn,df=(t,n)=>{let o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,e)=>g(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=N(()=>{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=g(t.innerType._def,{...n,currentPath:[...n.currentPath]});if(i&&"$ref"in i)return{allOf:[i],nullable:!0};return i&&{...i,nullable:!0}}let o=g(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}var ie=N(()=>{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",di(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 A=g(T._def,{...n,currentPath:[...n.currentPath,"properties",f],propertyPath:[...n.currentPath,"properties",f]});if(A===void 0)continue;if(i.properties[f]=A,!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 g(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=N(()=>{B()});var sf=(t,n)=>{if(n.currentPath.toString()===n.propertyPath?.toString())return g(t.innerType._def,n);let o=g(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","1"]});return o?{anyOf:[{not:H(n)},o]}:H(n)};var Ee=N(()=>{B();tt()});var qf=(t,n)=>{if(n.pipeStrategy==="input")return g(t.in._def,n);else if(n.pipeStrategy==="output")return g(t.out._def,n);let o=g(t.in._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),i=g(t.out._def,{...n,currentPath:[...n.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,i].filter((e)=>e!==void 0)}};var ue=N(()=>{B()});function cf(t,n){return g(t.type._def,n)}var fe=N(()=>{B()});function xf(t,n){let i={type:"array",uniqueItems:!0,items:g(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=N(()=>{B()});function af(t,n){if(t.rest)return{type:"array",minItems:t.items.length,items:t.items.map((o,i)=>g(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[]),additionalItems:g(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)=>g(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[])}}var le=N(()=>{B()});function tT(t){return{not:H(t)}}var Ae=N(()=>{tt()});function nT(t){return H(t)}var Ne=N(()=>{tt()});var oT=(t,n)=>{return g(t.innerType._def,n)};var Re=N(()=>{B()});import{ZodFirstPartyTypeKind as $}from"zod/v3";var iT=(t,n,o)=>{switch(n){case $.ZodString:return go(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 kf(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 sf(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 qf(t,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return((i)=>{return})(n)}};var _e=N(()=>{tt();ki();mi();yo();zi();si();qi();ci();xi();ne();oe();ie();ee();re();Ee();ue();fe();Oo();Te();Lo();le();Ae();Io();Ne();Re()});function g(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=d_(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"?g(r(),n):r;if(E)k_(t,n,E);if(n.postProcess){let f=n.postProcess(E,t,n);return e.jsonSchema=E,f}return e.jsonSchema=E,E}var d_=(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}}},k_=(t,n,o)=>{if(t.description){if(o.description=t.description,n.markdownDescription)o.markdownDescription=t.description}return o};var B=N(()=>{Ro();_e();tt()});var eT=()=>{};var we=(t,n)=>{let o=Mf(n),i=typeof n==="object"&&n.definitions?Object.entries(n.definitions).reduce((T,[l,A])=>({...T,[l]:g(A._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=g(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=N(()=>{B();ji();tt()});var rT=N(()=>{ye();Ro();ji();B();eT();tt();ki();mi();yo();zi();si();qi();ci();xi();ne();oe();ie();ee();re();Ee();ue();fe();Re();Oo();Te();Lo();le();Ae();Io();Ne();_e();ye()});function Uo(){let t=fn(),n={},o={};for(let e of t){let r=Ft(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:s,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=N(()=>{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:()=>dt,getUserDriveRole:()=>Rt,getUserByEmail:()=>Tn,getUserByApiKey:()=>ut,getS3Key:()=>I,getRequiredRole:()=>$n,getRegisteredOps:()=>fn,getOrg:()=>Yn,getOpDefinition:()=>Ft,getNextVersion:()=>to,getHome:()=>V,getHeadVersionRow:()=>xt,getHeadContentHash:()=>no,getDrive:()=>Gi,getDbPath:()=>Ht,getConfigPath:()=>x,getConfig:()=>P,generateOpenAPISpec:()=>Uo,ensureLocalUser:()=>Gn,dispatchOp:()=>d,createVersion:()=>h,createUser:()=>Et,createOrg:()=>Kt,createEmbeddingProviderFromEnv:()=>ln,createDrive:()=>Qt,createDatabase:()=>St,commentUpdate:()=>To,commentResolve:()=>Ao,commentList:()=>uo,commentGet:()=>fo,commentDelete:()=>lo,commentAdd:()=>Eo,checkPermission:()=>Xn,assertExpectedVersion:()=>j,ValidationError:()=>c,VERSION:()=>s,PermissionDeniedError:()=>it,NotFoundError:()=>M,IndexingInProgressError:()=>Sn,EditConflictError:()=>et,AgentS3Client:()=>Xt,AgentFSError:()=>Nt});var Y=N(()=>{G();wn();eu();m();Yi();W();gf();Vi();ET()});var $o={};bt($o,{stopDaemon:()=>Uw,startDaemon:()=>Iw,daemonStatus:()=>Sw});import{spawn as gw}from"child_process";import{readFileSync as Oe,writeFileSync as Lw,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 RT(){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=RT();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=gw(process.execPath,[i,"server"],{detached:!0,stdio:["ignore",o,o]});if(e.unref(),e.pid)Lw(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=RT();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=N(()=>{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,Fe,fy;var KT=N(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:s});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)}Fe=new ny({name:"agent-fs",version:s},{capabilities:{tools:{}}});Fe.setRequestHandler(ry,async()=>{return await Pe.listTools()});Fe.setRequestHandler(Ey,async(t)=>{return await Pe.callTool(t.params)});fy=new oy;await Fe.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=Ft(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 d(f,i,r);return{content:[{type:"text",text:JSON.stringify(T,null,2)}]}})}}var jT=N(()=>{Y()});import{McpServer as ly}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Yt}from"zod";function dT(t){let{db:n,s3:o,embeddingProvider:i,appUrl:e}=t,r=new ly({name:"agent-fs",version:s}),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,A=b(n,{userId:l.id});return{db:n,s3:o,orgId:A.orgId,driveId:A.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:s};try{let A=E(T),R=await d(A,"ls",{path:"/"},{skipAuth:!0});l.database={ok:!0,rootEntries:R.entries?.length??0}}catch(A){l.database={ok:!1,error:A.message}}try{await o.listObjects("",{delimiter:"/"}),l.s3={ok:!0}}catch(A){l.s3={ok:!1,error:A.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),A=l.userId,w=p(n,A).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:Rt(n,A,Z.id)}))}}),L=T.authInfo?.extra?.user?.email,O={userId:A,...L?{email:L}:{},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),A=f.driveId?Jt(n,f.driveId):pt(n,l.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: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 dt(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(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: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 A=Tn(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,role:f.role});else ht(n,{orgId:l.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: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 A=Tn(n,f.email);if(!A)throw Error(`User with email ${f.email} not found`);if(f.driveId)Vt(n,{driveId:f.driveId,userId:A.id});else jt(n,{orgId:l.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 kT=N(()=>{Y();jT()});function mT(t){return async(n,o)=>{let i=new URL(n.req.url).pathname;if(Ay.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 Ay;var zT=N(()=>{Y();Ay=["/auth/register","/health"]});function Ny(t){if(t instanceof M)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=Ny(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 sT=N(()=>{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],A=Math.ceil((l+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 Ry}from"hono";function qT(t){let n=new Ry;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=N(()=>{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,...A}=T;if(!l)return r.json({error:"VALIDATION_ERROR",message:"op is required in request body"},400);let R=A.driveId||A.drive_id;delete A.driveId,delete A.drive_id;let w=b(t,{userId:E.id,orgId:f,driveId:R}),L={db:t,s3:n,orgId:w.orgId,driveId:w.driveId,userId:E.id,embeddingProvider:o,appUrl:i},O=await d(L,l,A);return r.json(O)}),e}var aT=N(()=>{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 dt(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=N(()=>{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=N(()=>{Y()});import{Hono as gy}from"hono";function el(t,n,o=null,i){let e=new gy;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}),R=new URL(r.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!R)return r.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let w=Cn(decodeURIComponent(R[1])),L=I(l.orgId,l.driveId,w);try{let O=await n.getObject(L),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 A=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 L=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,""),Fo=Number(Ul);if(!Number.isInteger(Fo)||Fo<0)return r.json({error:"VALIDATION_ERROR",message:`If-Match must be a non-negative integer version, got: ${C}`},400);O=Fo}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:A.orgId,driveId:A.driveId,userId:E.id,embeddingProvider:o,appUrl:i},zt=await Dt(Il,{path:L,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=N(()=>{Y()});import{Hono as Ly}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 Ly,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:s})),i.all("/mcp",async(f)=>{let T=f.get("user"),l=new Oy({sessionIdGenerator:void 0,enableJsonResponse:!0});return await dT({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",qT(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=N(()=>{Y();kT();zT();sT();cT();aT();nl();il();rl()});function gt(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 gt(409,"EDIT_CONFLICT",o);if(n==="NotFoundError")return gt(404,"NOT_FOUND",o);if(n==="PermissionDeniedError")return gt(403,"PERMISSION_DENIED",o);if(n==="ValidationError")return gt(415,"VALIDATION",o);if(n==="IndexingInProgressError")return gt(503,"INDEXING_IN_PROGRESS",o);if(/no.*api.*key|no.*user/i.test(o))return gt(401,"AUTH_MISSING",o);return gt(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 gt(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 d(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 d(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 d(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,A=l.subarray(0,Math.min(E,l.length)),R=await Dt(f,{path:r,bytes:A});return{open_write:{version:R.version,content_hash:R.contentHash??"",deduped:R.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 d(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 d(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 d(E,"ls",{path:r}))?.entries?.length>0)return gt(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 gt(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=N(()=>{Y()});import{unlinkSync as Al,existsSync as $y,chmodSync as Xy}from"fs";import{Packr as Cy,Unpackr as Py}from"msgpackr";function Nl(t,n){if($y(t))try{Al(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{Al(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>Fy){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=My.pack(e),E=Buffer.alloc(4);E.writeUInt32BE(r.length,0),t.write(Buffer.concat([E,r]))}var Fy=67108864,My,vy;var Rl=N(()=>{ll();My=new Cy({useRecords:!1}),vy=new Py({useRecords:!1})});var Qy={};import{join as Hy}from"path";function gl(){if(console.log("Shutting down..."),Me.stop(),ve)ve.stop();process.exit(0)}var Nn,wl,yl,Ye=null,Zy,Me,_l,ve=null;var Ll=N(async()=>{Y();fl();Rl();Nn=P(),wl=St(),yl=new Xt(Nn.s3);try{Ye=await ln(Nn.embedding)}catch(t){console.warn("Embedding provider unavailable, semantic search disabled:",t)}Zy=ul(wl,yl,Ye),Me=Bun.serve({fetch:Zy.fetch,port:Nn.server.port,hostname:Nn.server.host});console.log(`agent-fs daemon running on http://${Me.hostname}:${Me.port}`);_l=Hy(V(),"agent-fs.sock");try{ve=Nl(_l,{db:wl,s3:yl,embeddingProvider:Ye,appUrl:Nn.appUrl,resolveApiKey:()=>Nn.auth?.apiKey??null}),console.log(`agent-fs IPC listening on ${_l}`)}catch(t){console.warn("IPC listener unavailable:",t)}process.on("SIGTERM",gl);process.on("SIGINT",gl)});Y();import{Command as Jy}from"commander";Y();class ge{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(`${
|
|
179
|
-
Suggestion: ${
|
|
180
|
-
Suggestion: ${
|
|
181
|
-
`)}function
|
|
182
|
-
`);if(o.length>0&&o[o.length-1]==="")o.pop();let i=
|
|
183
|
-
`)}function
|
|
184
|
-
`)}function
|
|
172
|
+
LIMIT ?`).all(E,o),A=[],N=new Set;for(let y of T){let _=n.db.select().from(u.contentChunks).where(bi(u.contentChunks.id,y.chunk_id)).get();if(!_||_.driveId!==n.driveId)continue;if(N.has(_.filePath))continue;N.add(_.filePath);let r=n.db.select().from(u.files).where(sw(bi(u.files.path,_.filePath),bi(u.files.driveId,n.driveId))).get();A.push({path:_.filePath,snippet:_.content.slice(0,200),author:r?.author,modifiedAt:r?.modifiedAt})}return A}function aw(n,t,o){let i=t.split(/\s+/).filter(Boolean).map((e)=>`"${e}"`).join(" OR ");if(!i)return[];try{return Io(n.db,{pattern:i,driveId:n.driveId}).slice(0,o).map((E)=>({path:E.path,snippet:E.snippet}))}catch{return[]}}var IT=R(()=>{J()});import{eq as Co,and as nr,or as tr,isNull as or}from"drizzle-orm";async function XT(n,t){let o=[Co(u.files.driveId,n.driveId),Co(u.files.isDeleted,!1),tr(Co(u.files.embeddingStatus,"failed"),or(u.files.embeddingStatus),Co(u.files.embeddingStatus,"pending"))];if(t.path){let{like:A}=await import("drizzle-orm"),N=t.path.endsWith("/")?t.path:t.path+"/";o.push(A(u.files.path,N+"%"))}let i=n.db.select({path:u.files.path}).from(u.files).where(nr(...o)).all(),e=0,E=0,f=0,T=3;for(let A=0;A<i.length;A+=T){let N=i.slice(A,A+T),y=await Promise.allSettled(N.map(async(_)=>{let r=$(n.orgId,n.driveId,_.path),L=await n.s3.getObject(r),S=L.contentType??h(_.path),U=jn(L.body,S);if(U===null)return dt(n,_.path),"skipped";if(Cn(n.db,{path:_.path,driveId:n.driveId,content:U}),n.embeddingProvider)return await vi(n.db,n.embeddingProvider,{path:_.path,driveId:n.driveId,content:U}),"reindexed";return"skipped"}));for(let _ of y)if(_.status==="fulfilled")if(_.value==="reindexed")e++;else f++;else console.error("Reindex failed:",_.reason),E++}return{reindexed:e,failed:E,skipped:f}}var CT=R(()=>{J();j();bt();gt();wn()});import{eq as PT,and as ir,like as er}from"drizzle-orm";async function YT(n,t){let o=vn(t.path??"/"),i=$(n.orgId,n.driveId,o),{objects:e}=await n.s3.listObjects(i),E=n.db.select().from(u.files).where(ir(PT(u.files.driveId,n.driveId),er(u.files.path,o+"%"),PT(u.files.isDeleted,!1))).all(),f=new Map(E.map((A)=>[A.path,A])),T=[];for(let A of e){let N=A.key.slice(i.length);if(!N)continue;let y=N.split("/").filter(Boolean);if(y.length===0)continue;if(t.depth!==void 0&&y.length>t.depth)continue;let _=T;for(let r=0;r<y.length;r++){let L=y[r],S=r===y.length-1,U=!S||N.endsWith("/");if(U&&!S){let g=_.find((K)=>K.name===L&&K.type==="directory");if(!g)g={name:L,type:"directory",children:[]},_.push(g);if(!g.children)g.children=[];_=g.children}else if(U&&S){let g=_.find((K)=>K.name===L&&K.type==="directory");if(!g)g={name:L,type:"directory",children:[]},_.push(g)}else{let g=o+y.slice(0,r+1).join("/"),K=f.get(g),bn={name:L,type:"file",size:K?.size??A.size};if(K?.author)bn.author=K.author;if(K?.modifiedAt??A.lastModified)bn.modifiedAt=K?.modifiedAt??A.lastModified;_.push(bn)}}}return{tree:T}}var MT=R(()=>{J();j()});import{eq as GT,and as Er,like as fr}from"drizzle-orm";function ur(n){let t="",o=0;while(o<n.length){let i=n[o];if(i==="*")if(n[o+1]==="*"){if(t+=".*",o+=2,n[o]==="/")o++}else t+="[^/]*",o++;else if(i==="?")t+="[^/]",o++;else if(".+^${}()|[]\\".includes(i))t+="\\"+i,o++;else t+=i,o++}return new RegExp("^"+t+"$")}async function FT(n,t){let o=t.path?vn(t.path):"/",i=$(n.orgId,n.driveId,o),{objects:e}=await n.s3.listObjects(i),E=n.db.select().from(u.files).where(Er(GT(u.files.driveId,n.driveId),fr(u.files.path,o+"%"),GT(u.files.isDeleted,!1))).all(),f=new Map(E.map((N)=>[N.path,N])),T=ur(t.pattern),A=[];for(let N of e){let y=N.key.slice(i.length);if(!y||y.endsWith("/"))continue;if(T.test(y)){let _=o+y,r=f.get(_);A.push({path:_,size:r?.size??N.size,modifiedAt:r?.modifiedAt??N.lastModified})}}return{matches:A}}var HT=R(()=>{J();j()});import{mkdtemp as Tr,rm as ZT,writeFile as Ar}from"fs/promises";import{tmpdir as Nr}from"os";import{join as mi}from"path";import{eq as di,and as yr}from"drizzle-orm";function QT(n){let o=(n.toLowerCase().split("/").pop()??"").split(".");if(o.length<2)return null;let i=!1,e=o.pop();if(e==="gz"&&o.length>=2)i=!0,e=o.pop();let E=_r[e];if(!E)return null;if(i&&!WT.has(E))return null;return{format:E,gzip:i}}function JT(n,t){let o=process.env[n];if(!o)return t;let i=parseInt(o,10);return Number.isFinite(i)&&i>0?i:t}function Lr(){let n=process.env.AGENT_FS_SQL_MEMORY_LIMIT?.trim();if(n&&/^[0-9]+(\.[0-9]+)?\s*(B|KB|MB|GB|TB|KiB|MiB|GiB)?$/i.test(n))return n;return"512MB"}function rn(n){return`'${n.replace(/'/g,"''")}'`}function fn(n){return`"${n.replace(/"/g,'""')}"`}function Ur(n,t){switch(n){case"csv":return`read_csv(${rn(t)})`;case"tsv":return`read_csv(${rn(t)}, delim=E'\\t')`;case"parquet":return`read_parquet(${rn(t)})`;case"json":case"ndjson":return`read_json_auto(${rn(t)})`;case"xlsx":return`read_xlsx(${rn(t)})`;default:throw new F(`Format ${n} is not file-readable`)}}function Sr(n,t){return/\.gz$/i.test(n)&&WT.has(t)}function BT(n,t){return n.db.select({path:u.files.path,size:u.files.size}).from(u.files).where(yr(di(u.files.driveId,n.driveId),di(u.files.path,t),di(u.files.isDeleted,!1))).get()??null}function Or(n,t){let o=[],i=new Set;for(let[f,T]of Object.entries(t.tables??{})){if(!Dr.test(f))throw new F(`Invalid table name: ${f}`,{field:"tables",suggestion:"Table names must match [A-Za-z_][A-Za-z0-9_]*"});if(i.has(f.toLowerCase()))throw new F(`Duplicate table name: ${f}`,{field:"tables"});i.add(f.toLowerCase());let A=Zn(typeof T==="string"?T:T.path),N=typeof T==="string"?void 0:T.format,y=QT(A),_=N??y?.format;if(!_)throw new F(`Cannot infer format for ${A}`,{field:"tables",suggestion:'Pass an explicit format: { path, format: "csv" | "tsv" | "parquet" | "xlsx" | "json" | "ndjson" | "sqlite" | "duckdb" }'});let r=BT(n,A);if(!r)throw new X(`File not found: ${A}`,{path:A});o.push({table:f,path:A,format:_,gzip:Sr(A,_),size:r.size})}let e=new Set,E=1;for(let f of t.query.matchAll(VT)){let T=f[3],A=QT(T);if(!A||!wr.has(A.format))continue;let N=Zn(T);if(e.has(N))continue;e.add(N);let y=BT(n,N);if(!y)continue;let _=`doc_${E++}`;while(i.has(_))_=`doc_${E++}`;i.add(_),o.push({table:_,path:N,format:A.format,gzip:A.gzip,autoBound:!0,size:y.size})}return o}function mt(n){if(n===null||n===void 0)return null;let t=typeof n;if(t==="bigint"){let i=n;return i>=BigInt(Number.MIN_SAFE_INTEGER)&&i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i.toString()}if(t==="number"||t==="string"||t==="boolean")return n;if(n instanceof Uint8Array)return`<blob ${n.byteLength} bytes>`;let o=n;if(typeof o.toDouble==="function")return o.toDouble();if(o.bytes instanceof Uint8Array)return`<blob ${o.bytes.byteLength} bytes>`;if(Array.isArray(o.items))return o.items.map(mt);if(Array.isArray(o.entries))return o.entries.map((i)=>({key:mt(i.key),value:mt(i.value)}));if(o.entries&&typeof o.entries==="object"){let i={};for(let[e,E]of Object.entries(o.entries))i[e]=mt(E);return i}return String(n)}function lr(n,t,o){if(t)return new F(`Query timed out after ${o}ms`,{suggestion:"Simplify the query or reduce the amount of data it scans"});let i=n instanceof Error?n.message:String(n);if(/disabled by configuration|has been locked|external access/i.test(i))return new F(i,{suggestion:"Queries can only access bound documents. Reference documents by drive path (e.g. FROM '/data/sales.csv') or bind them via `tables` \u2014 and check the path exists with `ls`."});return new F(i)}async function KT(n,t){let o=Date.now(),i=t.maxRows??Rr,e=JT("AGENT_FS_SQL_TIMEOUT_MS",30000),E=JT("AGENT_FS_SQL_MAX_FILE_BYTES",268435456),f=Or(n,t);for(let g of f)if(g.size>E)throw new F(`File too large for SQL: ${g.path} (${g.size} bytes, limit ${E})`,{suggestion:"Raise AGENT_FS_SQL_MAX_FILE_BYTES on the server if needed"});let{DuckDBInstance:T}=await import("@duckdb/node-api"),A=null,N=null,y=null,_=null,r=null,L=!1,S=new AbortController;r=setTimeout(()=>{L=!0,S.abort();for(let g of[y,_])try{g?.interrupt()}catch{}},e);let U=()=>{if(L)throw new F(`Query timed out after ${e}ms`,{suggestion:"Reduce the amount of data the query loads or scans"})};try{if(f.length>0){A=await Tr(mi(Nr(),"agent-fs-sql-"));for(let l=0;l<f.length;l++){let H=f[l],nn=rr[H.format]+(H.gzip?".gz":""),tn=mi(A,`t${l}${nn}`);try{let q=await n.s3.getObject($(n.orgId,n.driveId,H.path),void 0,{abortSignal:S.signal});await Ar(tn,q.body)}catch(q){U();let fo=q;if(fo?.name==="NoSuchKey"||fo?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${H.path}`,{path:H.path});throw q}H.localFile=tn,U()}}if(N=await T.create(":memory:"),y=await N.connect(),await y.run(`SET memory_limit=${rn(Lr())}`),f.some((l)=>l.format==="xlsx"))await y.run("INSTALL excel"),await y.run("LOAD excel");let g=f.filter((l)=>l.format==="sqlite"),K=new Map;if(g.length>0&&A)K=await $r(T,g,A,U,(l)=>{_=l});U();for(let l of f)try{if(l.format==="sqlite"){await y.run(`CREATE SCHEMA ${fn(l.table)}`);for(let{table:H,parquetFile:nn}of K.get(l.table)??[])await y.run(`CREATE TABLE ${fn(l.table)}.${fn(H)} AS SELECT * FROM read_parquet(${rn(nn)})`)}else if(l.format==="duckdb"){let H=`src_${l.table}`;await y.run(`ATTACH ${rn(l.localFile)} AS ${fn(H)} (READ_ONLY)`);let tn=(await y.runAndReadAll(`SELECT table_name FROM duckdb_tables() WHERE database_name = ${rn(H)} AND schema_name = 'main'`)).getRowObjectsJson().map((q)=>String(q.table_name));if(tn.length===0)throw new F(`No tables found in ${l.path}`);await y.run(`CREATE SCHEMA ${fn(l.table)}`);for(let q of tn)await y.run(`CREATE TABLE ${fn(l.table)}.${fn(q)} AS SELECT * FROM ${fn(H)}.main.${fn(q)}`);await y.run(`DETACH ${fn(H)}`)}else await y.run(`CREATE TABLE ${fn(l.table)} AS SELECT * FROM ${Ur(l.format,l.localFile)}`)}catch(H){if(H instanceof F)throw H;U();let nn=H instanceof Error?H.message:String(H);throw new F(`Failed to load ${l.path} as ${l.format}: ${nn}`)}if(U(),await y.run("SET enable_external_access=false"),await y.run("SET disabled_filesystems='LocalFileSystem'"),await y.run("SET lock_configuration=true"),A)await ZT(A,{recursive:!0,force:!0}),A=null;let bn=new Map(f.filter((l)=>l.autoBound).map((l)=>[l.path,l.table])),xo=t.query.replace(VT,(l,H,nn,tn)=>{let q=bn.get(Zn(tn));return q?`${H} ${fn(q)}`:l});try{let l=await y.extractStatements(xo);if(l.count===0)throw new F("Query contains no statements",{field:"query"});for(let b=0;b<l.count-1;b++)await(await l.prepare(b)).run();let nn=await(await l.prepare(l.count-1)).runAndReadUntil(i+1),tn=new Map,q=nn.columnNames().map((b)=>{let Gn=tn.get(b)??0;return tn.set(b,Gn+1),Gn===0?b:`${b}_${Gn+1}`}),fo=nn.columnTypes(),ty=q.map((b,Gn)=>({name:b,type:String(fo[Gn]??"UNKNOWN")})),oE=nn.getRows(),oy=oE.length>i||!nn.done,iE=oE.slice(0,i).map((b)=>{let Gn={};for(let uo=0;uo<q.length;uo++)Gn[q[uo]]=mt(b[uo]);return Gn}),iy=f.map((b)=>({table:b.table,path:b.path,format:b.format}));return{columns:ty,rows:iE,rowCount:iE.length,truncated:oy,files:iy,elapsedMs:Date.now()-o}}catch(l){if(l instanceof F)throw l;throw lr(l,L,e)}}finally{if(r)clearTimeout(r);try{y?.closeSync()}catch{}try{N?.closeSync()}catch{}if(A)await ZT(A,{recursive:!0,force:!0}).catch(()=>{})}}async function $r(n,t,o,i,e){let E=new Map,f=await n.create(":memory:"),T=await f.connect();e(T);try{await T.run("INSTALL sqlite"),await T.run("LOAD sqlite");for(let A=0;A<t.length;A++){let N=t[A];try{i(),await T.run(`ATTACH ${rn(N.localFile)} AS src (TYPE sqlite, READ_ONLY)`);let _=(await T.runAndReadAll("SELECT table_name FROM duckdb_tables() WHERE database_name = 'src'")).getRowObjectsJson().map((L)=>String(L.table_name));if(_.length===0)throw new F(`No tables found in ${N.path}`);let r=[];for(let L=0;L<_.length;L++){i();let S=mi(o,`sq_${A}_${L}.parquet`);await T.run(`COPY (SELECT * FROM src.${fn(_[L])}) TO ${rn(S)} (FORMAT parquet)`),r.push({table:_[L],parquetFile:S})}E.set(N.table,r),await T.run("DETACH src")}catch(y){if(y instanceof F)throw y;i();let _=y instanceof Error?y.message:String(y);throw new F(`Failed to load ${N.path} as sqlite: ${_}`)}}}finally{e(null);try{T.closeSync()}catch{}try{f.closeSync()}catch{}}return E}var Rr=1000,_r,wr,WT,rr,Dr,VT;var vT=R(()=>{J();j();m();_r={csv:"csv",tsv:"tsv",tab:"tsv",parquet:"parquet",xlsx:"xlsx",json:"json",jsonl:"ndjson",ndjson:"ndjson",db:"sqlite",sqlite:"sqlite",sqlite3:"sqlite",duckdb:"duckdb"},wr=new Set(["csv","tsv","parquet","xlsx","json","ndjson"]),WT=new Set(["csv","tsv","json","ndjson"]),rr={csv:".csv",tsv:".tsv",parquet:".parquet",xlsx:".xlsx",json:".json",ndjson:".ndjson",sqlite:".db",duckdb:".duckdb"};Dr=/^[A-Za-z_][A-Za-z0-9_]*$/,VT=/\b(from|join)\s+(['"])([^'"]+\.[A-Za-z0-9]+(?:\.gz)?)\2/gi});async function jT(n,t){let o=Zn(t.path),i=$(n.orgId,n.driveId,o),e=t.expiresIn??86400;try{await n.s3.headObject(i)}catch(T){if(T?.name==="NotFound"||T?.name==="NoSuchKey"||T?.$metadata?.httpStatusCode===404)throw new X(`File not found: ${o}`,{path:o});throw T}let E=h(o);return{url:await n.s3.getPresignedUrl(i,e,E!=="application/octet-stream"?E:void 0),path:o,expiresIn:e,expiresAt:new Date(Date.now()+e*1000).toISOString()}}var kT=R(()=>{j();m();wn()});function xi(n,t,o,i){let e=i.startsWith("/")?i.slice(1):i;return`${n}/file/~/${t}/${o}/${e}`}import{eq as P,and as Pn,sql as si,desc as hT}from"drizzle-orm";function ci(n,t){n.db.insert(u.events).values({id:crypto.randomUUID(),orgId:n.orgId,type:t.type,resourceType:t.resourceType,resourceId:t.resourceId,actor:n.userId,target:t.target??null,status:"created",metadata:t.metadata?JSON.stringify(t.metadata):null,createdAt:new Date}).run()}function xt(n,t){return n.db.select().from(u.comments).where(Pn(P(u.comments.id,t),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId),P(u.comments.isDeleted,!1))).get()}function Po(n){return{id:n.id,parentId:n.parentId??void 0,path:n.path,lineStart:n.lineStart??void 0,lineEnd:n.lineEnd??void 0,quotedContent:n.quotedContent??void 0,body:n.body,author:n.author,resolved:n.resolved??!1,resolvedBy:n.resolvedBy??void 0,resolvedAt:n.resolvedAt??void 0,fileVersionId:n.fileVersionId??void 0,replyCount:n.replyCount??0,createdAt:n.createdAt,updatedAt:n.updatedAt}}async function Yo(n,t){let o=new Date,i=crypto.randomUUID(),e=t.path;if(t.parentId){let f=xt(n,t.parentId);if(!f)throw new X("Parent comment not found",{suggestion:"Check that the parent comment ID is correct and not deleted"});if(f.parentId)throw new F("Cannot reply to a reply \u2014 only root comments accept replies",{suggestion:"Reply to the root comment instead"});if(!e)e=f.path}if(!e)throw new F("path is required for root comments",{field:"path"});let E=n.db.select({id:u.fileVersions.id}).from(u.fileVersions).where(Pn(P(u.fileVersions.path,e),P(u.fileVersions.driveId,n.driveId))).orderBy(hT(u.fileVersions.id)).limit(1).get();return n.db.insert(u.comments).values({id:i,parentId:t.parentId??null,orgId:n.orgId,driveId:n.driveId,path:e,lineStart:t.lineStart??null,lineEnd:t.lineEnd??null,quotedContent:t.quotedContent??null,fileVersionId:E?.id??null,body:t.body,author:n.userId,resolved:!1,createdAt:o,updatedAt:o,isDeleted:!1}).run(),ci(n,{type:"comment_created",resourceType:"comment",resourceId:i,metadata:{path:e,parentId:t.parentId}}),{id:i,path:e,body:t.body,parentId:t.parentId,lineStart:t.lineStart,lineEnd:t.lineEnd,author:n.userId,createdAt:o}}async function Mo(n,t){let o=[P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId),P(u.comments.isDeleted,!1)];if(t.path)o.push(P(u.comments.path,t.path));if(t.parentId)o.push(P(u.comments.parentId,t.parentId));else if(t.parentId===void 0&&!t.resolved)o.push(si`${u.comments.parentId} IS NULL`),o.push(P(u.comments.resolved,!1));else if(t.parentId===void 0&&t.resolved)o.push(si`${u.comments.parentId} IS NULL`);if(t.orgId)o.push(P(u.comments.orgId,t.orgId));let i=t.limit??50,e=t.offset??0;return{comments:n.db.select().from(u.comments).where(Pn(...o)).orderBy(hT(u.comments.createdAt)).limit(i).offset(e).all().map((T)=>{let N=n.db.select().from(u.comments).where(Pn(P(u.comments.parentId,T.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId),P(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((y)=>Po({...y,replyCount:0}));return{...Po({...T,replyCount:N.length}),replies:N}})}}async function Go(n,t){let o=xt(n,t.id);if(!o)throw new X("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=n.db.select({count:si`count(*)`}).from(u.comments).where(Pn(P(u.comments.parentId,o.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId),P(u.comments.isDeleted,!1))).get(),e=Po({...o,replyCount:i?.count??0}),f=n.db.select().from(u.comments).where(Pn(P(u.comments.parentId,t.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId),P(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((T)=>Po({...T,replyCount:0}));return{comment:e,replies:f}}async function Fo(n,t){let o=xt(n,t.id);if(!o)throw new X("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==n.userId)throw new d("You can only edit your own comments",{suggestion:"Only the comment author can update it"});let i=new Date;return n.db.update(u.comments).set({body:t.body,updatedAt:i}).where(Pn(P(u.comments.id,t.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId))).run(),{id:t.id,body:t.body,updatedAt:i}}async function Ho(n,t){let o=xt(n,t.id);if(!o)throw new X("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==n.userId)throw new d("You can only delete your own comments",{suggestion:"Only the comment author can delete it"});let i=new Date;if(n.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(Pn(P(u.comments.id,t.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId))).run(),!o.parentId)n.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(Pn(P(u.comments.parentId,t.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId))).run();return ci(n,{type:"comment_deleted",resourceType:"comment",resourceId:t.id}),{deleted:!0}}async function Zo(n,t){let o=xt(n,t.id);if(!o)throw new X("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.parentId)throw new F("Cannot resolve a reply \u2014 only root comments can be resolved",{suggestion:"Resolve the parent comment instead"});let i=new Date,e=t.resolved?i:null,E=t.resolved?n.userId:null;return n.db.update(u.comments).set({resolved:t.resolved,resolvedBy:E,resolvedAt:e,updatedAt:i}).where(Pn(P(u.comments.id,t.id),P(u.comments.orgId,n.orgId),P(u.comments.driveId,n.driveId))).run(),ci(n,{type:t.resolved?"comment_resolved":"comment_reopened",resourceType:"comment",resourceId:t.id}),{id:t.id,resolved:t.resolved,resolvedBy:E??void 0,resolvedAt:e??void 0}}var zT=R(()=>{J();m()});import{z as w}from"zod";async function s(n,t,o,i){let e=ai[t];if(!e)throw Error(`Unknown operation: ${t}`);if(!i?.skipAuth){let T=jt(t);ht(n.db,{userId:n.userId,driveId:n.driveId,requiredRole:T})}let E=e.schema.parse(o),f=await e.handler(n,E);if(n.appUrl&&f&&typeof f==="object"){if("path"in f)f.appUrl=xi(n.appUrl,n.orgId,n.driveId,f.path);else if("to"in f)f.appUrl=xi(n.appUrl,n.orgId,n.driveId,f.to)}return f}function Ct(){return Object.keys(ai)}function Yn(n){return ai[n]}var ai;var ne=R(()=>{pt();Vu();vu();ku();zu();bu();xu();cu();tT();iT();ET();TT();yT();_T();LT();DT();OT();$T();IT();CT();MT();HT();vT();kT();zT();ai={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:Xo,schema:w.object({path:w.string(),content:w.string(),message:w.string().optional(),expectedVersion:w.number().int().optional()})},cat:{description:"Read file content with optional pagination via offset/limit. Returns { content, totalLines, truncated }.",handler:Ku,schema:w.object({path:w.string(),offset:w.number().int().min(0).optional(),limit:w.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:ju,schema:w.object({path:w.string(),old_string:w.string(),new_string:w.string(),message:w.string().optional(),expectedVersion:w.number().int().optional()})},append:{description:"Append content to the end of an existing file. Creates a new version. Returns { version, size }.",handler:hu,schema:w.object({path:w.string(),content:w.string(),message:w.string().optional(),expectedVersion:w.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:qu,schema:w.object({path:w.string().optional()})},stat:{description:"Get file metadata without reading content. Returns path, size, contentType, author, currentVersion, createdAt, modifiedAt, isDeleted, embeddingStatus.",handler:mu,schema:w.object({path:w.string()})},rm:{description:"Delete a file. Removes from S3, cleans up FTS5 index and vector embeddings. Returns { path, deleted }.",handler:su,schema:w.object({path:w.string(),expectedVersion:w.number().int().optional()})},mv:{description:"Move or rename a file. Preserves version history at the new path. Returns { from, to, version }.",handler:nT,schema:w.object({from:w.string(),to:w.string(),message:w.string().optional(),expectedVersion:w.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:oT,schema:w.object({from:w.string(),to:w.string(),expectedVersion:w.number().int().optional()})},tail:{description:"Read the last N lines of a file (default 20). Returns { content, totalLines, truncated }.",handler:eT,schema:w.object({path:w.string(),lines:w.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:uT,schema:w.object({path:w.string(),limit:w.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:NT,schema:w.object({path:w.string(),v1:w.number().int(),v2:w.number().int()})},revert:{description:"Revert a file to a previous version. Creates a new version with the old content. Returns { version, revertedTo }.",handler:RT,schema:w.object({path:w.string(),version:w.number().int(),expectedVersion:w.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:rT,schema:w.object({path:w.string().optional(),since:w.coerce.date().optional(),limit:w.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:UT,schema:w.object({pattern:w.string(),path:w.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:ST,schema:w.object({pattern:w.string(),path:w.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:gT,schema:w.object({query:w.string(),limit:w.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:lT,schema:w.object({query:w.string(),limit:w.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:XT,schema:w.object({path:w.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:YT,schema:w.object({path:w.string().optional(),depth:w.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:FT,schema:w.object({pattern:w.string(),path:w.string().optional()})},sql:{description:"Run a DuckDB SQL query over documents stored in the drive. Reference documents directly by path string literal (e.g. SELECT * FROM '/data/sales.csv') or bind them as named tables via `tables` ({ name: path } or { name: { path, format } } to override format detection). Supports csv, tsv, parquet, xlsx, json, ndjson/jsonl (each also .gz except parquet/xlsx), sqlite (.db/.sqlite/.sqlite3, tables exposed as name.tablename), and .duckdb files. Queries run sandboxed: no filesystem or network access beyond the bound documents. Returns { columns, rows, rowCount, truncated, files, elapsedMs }.",handler:KT,schema:w.object({query:w.string(),tables:w.record(w.union([w.string(),w.object({path:w.string(),format:w.enum(["csv","tsv","parquet","xlsx","json","ndjson","sqlite","duckdb"]).optional()})])).optional(),maxRows:w.number().int().min(1).max(1e4).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:jT,schema:w.object({path:w.string(),expiresIn:w.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:Yo,schema:w.object({path:w.string().optional(),body:w.string(),parentId:w.string().optional(),lineStart:w.number().int().optional(),lineEnd:w.number().int().optional(),quotedContent:w.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:Mo,schema:w.object({path:w.string().optional(),parentId:w.string().optional(),resolved:w.boolean().optional(),orgId:w.string().optional(),limit:w.number().int().min(1).optional(),offset:w.number().int().min(0).optional()})},"comment-get":{description:"Get a single comment by ID with all its replies. Returns { comment, replies }.",handler:Go,schema:w.object({id:w.string()})},"comment-update":{description:"Update a comment's body. Only the original author can update. Returns { id, body, updatedAt }.",handler:Fo,schema:w.object({id:w.string(),body:w.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:Ho,schema:w.object({id:w.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:Zo,schema:w.object({id:w.string(),resolved:w.boolean()})}}});import{eq as c,and as st}from"drizzle-orm";function sn(n,t){let o=crypto.randomUUID(),i=new Date;if(n.insert(u.drives).values({id:o,orgId:t.orgId,name:t.name,isDefault:t.isDefault??!1,createdAt:i}).run(),t.creatorUserId)n.insert(u.driveMembers).values({driveId:o,userId:t.creatorUserId,role:"admin"}).run();return{id:o,name:t.name}}function te(n,t){return n.select().from(u.drives).where(c(u.drives.orgId,t)).all().map((o)=>({id:o.id,name:o.name,isDefault:o.isDefault}))}function Ln(n,t,o){return n.select({id:u.drives.id,name:u.drives.name,isDefault:u.drives.isDefault}).from(u.drives).innerJoin(u.driveMembers,c(u.driveMembers.driveId,u.drives.id)).where(st(c(u.drives.orgId,t),c(u.driveMembers.userId,o))).all().map((i)=>({id:i.id,name:i.name,isDefault:i.isDefault}))}function oe(n,t){let o=n.select().from(u.drives).where(c(u.drives.id,t)).get();if(!o)return null;return{id:o.id,name:o.name,orgId:o.orgId,isDefault:o.isDefault}}function cn(n,t){return n.select({userId:u.driveMembers.userId,email:u.users.email,role:u.driveMembers.role}).from(u.driveMembers).innerJoin(u.users,c(u.driveMembers.userId,u.users.id)).where(c(u.driveMembers.driveId,t)).all()}function an(n,t){if(!n.select({role:u.driveMembers.role}).from(u.driveMembers).where(st(c(u.driveMembers.driveId,t.driveId),c(u.driveMembers.userId,t.userId))).get())throw Error("Member not found in drive");n.update(u.driveMembers).set({role:t.role}).where(st(c(u.driveMembers.driveId,t.driveId),c(u.driveMembers.userId,t.userId))).run()}function nt(n,t){if(!n.select({role:u.driveMembers.role}).from(u.driveMembers).where(st(c(u.driveMembers.driveId,t.driveId),c(u.driveMembers.userId,t.userId))).get())throw Error("Member not found in drive");n.delete(u.driveMembers).where(st(c(u.driveMembers.driveId,t.driveId),c(u.driveMembers.userId,t.userId))).run()}function ie(n,t){n.insert(u.driveMembers).values({driveId:t.driveId,userId:t.userId,role:t.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:t.role}}).run()}var ee=R(()=>{J()});import{eq as B,and as kn,sql as pT}from"drizzle-orm";function tt(n,t){let o=crypto.randomUUID(),i=new Date;return n.insert(u.orgs).values({id:o,name:t.name,isPersonal:t.isPersonal??!1,createdAt:i}).run(),n.insert(u.orgMembers).values({orgId:o,userId:t.userId,role:"admin"}).run(),sn(n,{orgId:o,name:"default",isDefault:!0,creatorUserId:t.userId}),{id:o,name:t.name}}function z(n,t){return n.select({orgId:u.orgMembers.orgId,role:u.orgMembers.role,name:u.orgs.name,isPersonal:u.orgs.isPersonal}).from(u.orgMembers).innerJoin(u.orgs,B(u.orgMembers.orgId,u.orgs.id)).where(B(u.orgMembers.userId,t)).all().map((i)=>({id:i.orgId,name:i.name,role:i.role,isPersonal:i.isPersonal}))}function ct(n,t){let o=n.select().from(u.orgs).where(B(u.orgs.id,t)).get();if(!o)return null;return{id:o.id,name:o.name,isPersonal:o.isPersonal}}function ot(n,t){return n.select({userId:u.orgMembers.userId,email:u.users.email,role:u.orgMembers.role}).from(u.orgMembers).innerJoin(u.users,B(u.orgMembers.userId,u.users.id)).where(B(u.orgMembers.orgId,t)).all()}function it(n,t){let o=n.select({role:u.orgMembers.role}).from(u.orgMembers).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.userId,t.userId))).get();if(!o)throw Error("Member not found in org");if(o.role==="admin"&&t.role!=="admin"){if(n.select({count:pT`count(*)`}).from(u.orgMembers).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}n.update(u.orgMembers).set({role:t.role}).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.userId,t.userId))).run()}function et(n,t){if(n.select({isPersonal:u.orgs.isPersonal}).from(u.orgs).where(B(u.orgs.id,t.orgId)).get()?.isPersonal)throw Error("Cannot remove members from a personal org");let i=n.select({role:u.orgMembers.role}).from(u.orgMembers).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.userId,t.userId))).get();if(!i)throw Error("Member not found in org");if(i.role==="admin"){if(n.select({count:pT`count(*)`}).from(u.orgMembers).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}let e=n.select({id:u.drives.id}).from(u.drives).where(B(u.drives.orgId,t.orgId)).all();for(let E of e)n.delete(u.driveMembers).where(kn(B(u.driveMembers.driveId,E.id),B(u.driveMembers.userId,t.userId))).run();n.delete(u.orgMembers).where(kn(B(u.orgMembers.orgId,t.orgId),B(u.orgMembers.userId,t.userId))).run()}function Et(n,t){let o=n.select().from(u.users).where(B(u.users.email,t.email)).get();if(!o)throw Error(`User with email ${t.email} not found`);n.insert(u.orgMembers).values({orgId:t.orgId,userId:o.id,role:t.role}).onConflictDoUpdate({target:[u.orgMembers.orgId,u.orgMembers.userId],set:{role:t.role}}).run();let i=n.select().from(u.drives).where(kn(B(u.drives.orgId,t.orgId),B(u.drives.isDefault,!0))).get();if(i)n.insert(u.driveMembers).values({driveId:i.id,userId:o.id,role:t.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:t.role}}).run()}var Ee=R(()=>{J();ee()});import{eq as qT}from"drizzle-orm";function bT(n){let t=new Bun.CryptoHasher("sha256");return t.update(n),t.digest("hex")}function gr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),`af_${Array.from(n,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function Ir(){return crypto.randomUUID()}function Un(n,t){let o=Ir(),i=gr(),e=bT(i),E=new Date;return n.insert(u.users).values({id:o,email:t.email,apiKeyHash:e,createdAt:E}).run(),tt(n,{name:t.email.split("@")[0],userId:o,isPersonal:!0}),{user:{id:o,email:t.email},apiKey:i}}function Dn(n,t){let o=bT(t),i=n.select().from(u.users).where(qT(u.users.apiKeyHash,o)).get();if(!i)return null;return{id:i.id,email:i.email}}function Pt(n,t){let o=n.select().from(u.users).where(qT(u.users.email,t)).get();if(!o)return null;return{id:o.id,email:o.email}}var fe=R(()=>{J();Ee()});import{eq as hn,and as ue}from"drizzle-orm";function on(n,t){if(t.driveId){let E=n.select().from(u.drives).where(hn(u.drives.id,t.driveId)).get();if(!E||t.orgId&&E.orgId!==t.orgId)throw new X(`Drive not found: ${t.driveId}`,{suggestion:t.orgId?"Check the driveId belongs to the org you are addressing":void 0});let f=_n(n,t.userId,t.driveId);if(!f)throw new X(`Drive not found: ${t.driveId}`,{suggestion:t.orgId?"Check the driveId belongs to the org you are addressing":void 0});return{orgId:E.orgId,driveId:t.driveId,role:f}}if(t.orgId){let E=n.select().from(u.drives).where(ue(hn(u.drives.orgId,t.orgId),hn(u.drives.isDefault,!0))).get();if(!E)throw new X(`No default drive for org: ${t.orgId}`);let f=_n(n,t.userId,E.id);if(!f)throw new X(`No default drive for org: ${t.orgId}`);return{orgId:t.orgId,driveId:E.id,role:f}}let o=n.select({orgId:u.orgMembers.orgId}).from(u.orgMembers).innerJoin(u.orgs,hn(u.orgMembers.orgId,u.orgs.id)).where(ue(hn(u.orgMembers.userId,t.userId),hn(u.orgs.isPersonal,!0))).get();if(!o)throw Error("No personal org found for user");let i=n.select().from(u.drives).where(ue(hn(u.drives.orgId,o.orgId),hn(u.drives.isDefault,!0))).get();if(!i)throw Error("No default drive found");let e=_n(n,t.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 dT=R(()=>{J();m();pt()});function at(n){let t=G();if(t.auth.apiKey){if(Dn(n,t.auth.apiKey))return{apiKey:t.auth.apiKey}}console.error("[agent-fs] No local user found, creating one...");let o=Un(n,{email:"local@agent-fs.local"});return I("auth.apiKey",o.apiKey),console.error("[agent-fs] Local user created automatically."),{apiKey:o.apiKey}}var mT=R(()=>{Ht();fe()});var xT=R(()=>{fe();Ee();ee();pt();dT();mT()});var cT;var sT=R(()=>{cT={name:"agent-fs",version:"0.9.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:{"@duckdb/node-api":"1.5.3-r.3","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 en;var Te=R(()=>{sT();en=cT.version});var nA={};Nt(nA,{LocalEmbeddingProvider:()=>aT});import{join as Cr}from"path";import{mkdirSync as Pr,existsSync as Yr}from"fs";class aT{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:n,resolveModelFile:t}=await import("node-llama-cpp");this.llama=await n();let o=Cr(k(),"models");if(!Yr(o))Pr(o,{recursive:!0});console.error("[agent-fs] Resolving local embedding model...");let i=await t(Mr,o);console.error("[agent-fs] Model ready:",i),this.model=await this.llama.loadModel({modelPath:i}),this.embeddingContext=await this.model.createEmbeddingContext()}async embed(n){await this.init();let t=await this.embeddingContext.getEmbeddingFor(n);return Array.from(t.vector)}async embedBatch(n){await this.init();let t=[];for(let o of n){let i=await this.embeddingContext.getEmbeddingFor(o);t.push(Array.from(i.vector))}return t}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 Mr="hf:nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0";var tA=R(()=>{Ht()});var Ae={};Nt(Ae,{OpenAIEmbeddingProvider:()=>oA});import Gr from"openai";class oA{name="openai";dimensions=768;client;constructor(n){this.client=new Gr({apiKey:n})}async embed(n){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:n,dimensions:768})).data[0].embedding}async embedBatch(n){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:n,dimensions:768})).data.sort((o,i)=>o.index-i.index).map((o)=>o.embedding)}}var Ne=()=>{};var ye={};Nt(ye,{GeminiEmbeddingProvider:()=>iA});import{GoogleGenAI as Fr}from"@google/genai";class iA{name="gemini";dimensions=768;client;constructor(n){this.client=new Fr({apiKey:n})}async embed(n){return(await this.client.models.embedContent({model:"gemini-embedding-001",contents:n,config:{outputDimensionality:768}})).embeddings[0].values}async embedBatch(n){let t=[];for(let o of n){let i=await this.client.models.embedContent({model:"gemini-embedding-001",contents:o,config:{outputDimensionality:768}});t.push(i.embeddings[0].values)}return t}}var Re=()=>{};async function eA(n){switch(n.provider){case"local":{let{LocalEmbeddingProvider:t}=await Promise.resolve().then(() => (tA(),nA));return new t}case"openai":{if(!n.apiKey)throw Error("OpenAI API key required. Set embedding.apiKey in config.");let{OpenAIEmbeddingProvider:t}=await Promise.resolve().then(() => (Ne(),Ae));return new t(n.apiKey)}case"gemini":{if(!n.apiKey)throw Error("Gemini API key required. Set embedding.apiKey in config.");let{GeminiEmbeddingProvider:t}=await Promise.resolve().then(() => (Re(),ye));return new t(n.apiKey)}default:throw Error(`Unknown embedding provider: ${n.provider}`)}}async function Yt(n){if(process.env.OPENAI_API_KEY)try{let{OpenAIEmbeddingProvider:t}=await Promise.resolve().then(() => (Ne(),Ae));return new t(process.env.OPENAI_API_KEY)}catch(t){console.error("[agent-fs] Failed to load OpenAI provider:",t)}if(process.env.GEMINI_API_KEY)try{let{GeminiEmbeddingProvider:t}=await Promise.resolve().then(() => (Re(),ye));return new t(process.env.GEMINI_API_KEY)}catch(t){console.error("[agent-fs] Failed to load Gemini provider:",t)}if(n?.provider&&n.provider!=="local"&&n.apiKey)try{return await eA(n)}catch(t){console.error("[agent-fs] Failed to create embedding provider from config:",t)}if(n?.provider==="local")try{return await eA(n)}catch(t){console.error("[agent-fs] Failed to load local embedding provider:",t)}return null}var fA,EA,uA=(n)=>typeof n==="string"?{...EA,name:n}:{...EA,...n};var Qo=R(()=>{fA=Symbol("Let zodToJsonSchema decide on which parser to use"),EA={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 TA=(n)=>{let t=uA(n),o=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([i,e])=>[e._def,{def:e._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}};var _e=R(()=>{Qo()});function we(n,t,o,i){if(!i?.errorMessages)return;if(o)n.errorMessage={...n.errorMessage,[t]:o}}function M(n,t,o,i,e){n[t]=o,we(n,t,i,e)}var Jo=(n,t)=>{let o=0;for(;o<n.length&&o<t.length;o++)if(n[o]!==t[o])break;return[(n.length-o).toString(),...t.slice(o)].join("/")};function W(n){if(n.target!=="openAi")return{};let t=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?Jo(t,n.currentPath):t.join("/")}}var An=()=>{};import{ZodFirstPartyTypeKind as Hr}from"zod/v3";function AA(n,t){let o={type:"array"};if(n.type?._def&&n.type?._def?.typeName!==Hr.ZodAny)o.items=O(n.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(n.minLength)M(o,"minItems",n.minLength.value,n.minLength.message,t);if(n.maxLength)M(o,"maxItems",n.maxLength.value,n.maxLength.message,t);if(n.exactLength)M(o,"minItems",n.exactLength.value,n.exactLength.message,t),M(o,"maxItems",n.exactLength.value,n.exactLength.message,t);return o}var re=R(()=>{v()});function NA(n,t){let o={type:"integer",format:"int64"};if(!n.checks)return o;for(let i of n.checks)switch(i.kind){case"min":if(t.target==="jsonSchema7")if(i.inclusive)M(o,"minimum",i.value,i.message,t);else M(o,"exclusiveMinimum",i.value,i.message,t);else{if(!i.inclusive)o.exclusiveMinimum=!0;M(o,"minimum",i.value,i.message,t)}break;case"max":if(t.target==="jsonSchema7")if(i.inclusive)M(o,"maximum",i.value,i.message,t);else M(o,"exclusiveMaximum",i.value,i.message,t);else{if(!i.inclusive)o.exclusiveMaximum=!0;M(o,"maximum",i.value,i.message,t)}break;case"multipleOf":M(o,"multipleOf",i.value,i.message,t);break}return o}var Le=()=>{};function yA(){return{type:"boolean"}}function Bo(n,t){return O(n.type._def,t)}var Wo=R(()=>{v()});var RA=(n,t)=>{return O(n.innerType._def,t)};var Ue=R(()=>{v()});function De(n,t,o){let i=o??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((e,E)=>De(n,t,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 Zr(n,t)}}var Zr=(n,t)=>{let o={type:"integer",format:"unix-time"};if(t.target==="openApi3")return o;for(let i of n.checks)switch(i.kind){case"min":M(o,"minimum",i.value,i.message,t);break;case"max":M(o,"maximum",i.value,i.message,t);break}return o};var Se=()=>{};function _A(n,t){return{...O(n.innerType._def,t),default:n.defaultValue()}}var Oe=R(()=>{v()});function wA(n,t){return t.effectStrategy==="input"?O(n.schema._def,t):W(t)}var le=R(()=>{v();An()});function rA(n){return{type:"string",enum:Array.from(n.values)}}function LA(n,t){let o=[O(n.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),O(n.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((E)=>!!E),i=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,e=[];return o.forEach((E)=>{if(Qr(E)){if(e.push(...E.allOf),E.unevaluatedProperties===void 0)i=void 0}else{let f=E;if("additionalProperties"in E&&E.additionalProperties===!1){let{additionalProperties:T,...A}=E;f=A}else i=void 0;e.push(f)}}),e.length?{allOf:e,...i}:void 0}var Qr=(n)=>{if("type"in n&&n.type==="string")return!1;return"allOf"in n};var $e=R(()=>{v()});function UA(n,t){let o=typeof n.value;if(o!=="bigint"&&o!=="number"&&o!=="boolean"&&o!=="string")return{type:Array.isArray(n.value)?"array":"object"};if(t.target==="openApi3")return{type:o==="bigint"?"integer":o,enum:[n.value]};return{type:o==="bigint"?"integer":o,const:n.value}}function Vo(n,t){let o={type:"string"};if(n.checks)for(let i of n.checks)switch(i.kind){case"min":M(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,t);break;case"max":M(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":On(o,"email",i.message,t);break;case"format:idn-email":On(o,"idn-email",i.message,t);break;case"pattern:zod":a(o,Sn.email,i.message,t);break}break;case"url":On(o,"uri",i.message,t);break;case"uuid":On(o,"uuid",i.message,t);break;case"regex":a(o,i.regex,i.message,t);break;case"cuid":a(o,Sn.cuid,i.message,t);break;case"cuid2":a(o,Sn.cuid2,i.message,t);break;case"startsWith":a(o,RegExp(`^${Ie(i.value,t)}`),i.message,t);break;case"endsWith":a(o,RegExp(`${Ie(i.value,t)}$`),i.message,t);break;case"datetime":On(o,"date-time",i.message,t);break;case"date":On(o,"date",i.message,t);break;case"time":On(o,"time",i.message,t);break;case"duration":On(o,"duration",i.message,t);break;case"length":M(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,t),M(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,t);break;case"includes":{a(o,RegExp(Ie(i.value,t)),i.message,t);break}case"ip":{if(i.version!=="v6")On(o,"ipv4",i.message,t);if(i.version!=="v4")On(o,"ipv6",i.message,t);break}case"base64url":a(o,Sn.base64url,i.message,t);break;case"jwt":a(o,Sn.jwt,i.message,t);break;case"cidr":{if(i.version!=="v6")a(o,Sn.ipv4Cidr,i.message,t);if(i.version!=="v4")a(o,Sn.ipv6Cidr,i.message,t);break}case"emoji":a(o,Sn.emoji(),i.message,t);break;case"ulid":{a(o,Sn.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{On(o,"binary",i.message,t);break}case"contentEncoding:base64":{M(o,"contentEncoding","base64",i.message,t);break}case"pattern:zod":{a(o,Sn.base64,i.message,t);break}}break}case"nanoid":a(o,Sn.nanoid,i.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((e)=>{})(i)}return o}function Ie(n,t){return t.patternStrategy==="escape"?Br(n):n}function Br(n){let t="";for(let o=0;o<n.length;o++){if(!Jr.has(n[o]))t+="\\";t+=n[o]}return t}function On(n,t,o,i){if(n.format||n.anyOf?.some((e)=>e.format)){if(!n.anyOf)n.anyOf=[];if(n.format){if(n.anyOf.push({format:n.format,...n.errorMessage&&i.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage){if(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0)delete n.errorMessage}}n.anyOf.push({format:t,...o&&i.errorMessages&&{errorMessage:{format:o}}})}else M(n,"format",t,o,i)}function a(n,t,o,i){if(n.pattern||n.allOf?.some((e)=>e.pattern)){if(!n.allOf)n.allOf=[];if(n.pattern){if(n.allOf.push({pattern:n.pattern,...n.errorMessage&&i.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage){if(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0)delete n.errorMessage}}n.allOf.push({pattern:DA(t,i),...o&&i.errorMessages&&{errorMessage:{pattern:o}}})}else M(n,"pattern",DA(t,i),o,i)}function DA(n,t){if(!t.applyRegexFlags||!n.flags)return n.source;let o={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},i=o.i?n.source.toLowerCase():n.source,e="",E=!1,f=!1,T=!1;for(let A=0;A<i.length;A++){if(E){e+=i[A],E=!1;continue}if(o.i){if(f){if(i[A].match(/[a-z]/)){if(T)e+=i[A],e+=`${i[A-2]}-${i[A]}`.toUpperCase(),T=!1;else if(i[A+1]==="-"&&i[A+2]?.match(/[a-z]/))e+=i[A],T=!0;else e+=`${i[A]}${i[A].toUpperCase()}`;continue}}else if(i[A].match(/[a-z]/)){e+=`[${i[A]}${i[A].toUpperCase()}]`;continue}}if(o.m){if(i[A]==="^"){e+=`(^|(?<=[\r
|
|
173
|
+
]))`;continue}else if(i[A]==="$"){e+=`($|(?=[\r
|
|
174
|
+
]))`;continue}}if(o.s&&i[A]==="."){e+=f?`${i[A]}\r
|
|
175
|
+
`:`[${i[A]}\r
|
|
176
|
+
]`;continue}if(e+=i[A],i[A]==="\\")E=!0;else if(f&&i[A]==="]")f=!1;else if(!f&&i[A]==="[")f=!0}try{new RegExp(e)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return e}var ge=void 0,Sn,Jr;var Ko=R(()=>{Sn={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(ge===void 0)ge=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return ge},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-_]*$/};Jr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as no}from"zod/v3";function vo(n,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&n.keyType?._def.typeName===no.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((i,e)=>({...i,[e]:O(n.valueType._def,{...t,currentPath:[...t.currentPath,"properties",e]})??W(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let o={type:"object",additionalProperties:O(n.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return o;if(n.keyType?._def.typeName===no.ZodString&&n.keyType._def.checks?.length){let{type:i,...e}=Vo(n.keyType._def,t);return{...o,propertyNames:e}}else if(n.keyType?._def.typeName===no.ZodEnum)return{...o,propertyNames:{enum:n.keyType._def.values}};else if(n.keyType?._def.typeName===no.ZodBranded&&n.keyType._def.type._def.typeName===no.ZodString&&n.keyType._def.type._def.checks?.length){let{type:i,...e}=Bo(n.keyType._def,t);return{...o,propertyNames:e}}return o}var jo=R(()=>{v();Ko();Wo();An()});function SA(n,t){if(t.mapStrategy==="record")return vo(n,t);let o=O(n.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||W(t),i=O(n.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||W(t);return{type:"array",maxItems:125,items:{type:"array",items:[o,i],minItems:2,maxItems:2}}}var Xe=R(()=>{v();jo();An()});function OA(n){let t=n.values,i=Object.keys(n.values).filter((E)=>{return typeof t[t[E]]!=="number"}).map((E)=>t[E]),e=Array.from(new Set(i.map((E)=>typeof E)));return{type:e.length===1?e[0]==="string"?"string":"number":["string","number"],enum:i}}function lA(n){return n.target==="openAi"?void 0:{not:W({...n,currentPath:[...n.currentPath,"not"]})}}var Ce=R(()=>{An()});function $A(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function IA(n,t){if(t.target==="openApi3")return gA(n,t);let o=n.options instanceof Map?Array.from(n.options.values()):n.options;if(o.every((i)=>(i._def.typeName in to)&&(!i._def.checks||!i._def.checks.length))){let i=o.reduce((e,E)=>{let f=to[E._def.typeName];return f&&!e.includes(f)?[...e,f]: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,E)=>{let f=typeof E._def.value;switch(f){case"string":case"number":case"boolean":return[...e,f];case"bigint":return[...e,"integer"];case"object":if(E._def.value===null)return[...e,"null"];case"symbol":case"undefined":case"function":default:return e}},[]);if(i.length===o.length){let e=i.filter((E,f,T)=>T.indexOf(E)===f);return{type:e.length>1?e:e[0],enum:o.reduce((E,f)=>{return E.includes(f._def.value)?E:[...E,f._def.value]},[])}}}else if(o.every((i)=>i._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((i,e)=>[...i,...e._def.values.filter((E)=>!i.includes(E))],[])};return gA(n,t)}var to,gA=(n,t)=>{let o=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((i,e)=>O(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${e}`]})).filter((i)=>!!i&&(!t.strictUnions||typeof i==="object"&&Object.keys(i).length>0));return o.length?{anyOf:o}:void 0};var ko=R(()=>{v();to={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"}});function XA(n,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length)){if(t.target==="openApi3")return{type:to[n.innerType._def.typeName],nullable:!0};return{type:[to[n.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let i=O(n.innerType._def,{...t,currentPath:[...t.currentPath]});if(i&&"$ref"in i)return{allOf:[i],nullable:!0};return i&&{...i,nullable:!0}}let o=O(n.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}var Pe=R(()=>{v();ko()});function CA(n,t){let o={type:"number"};if(!n.checks)return o;for(let i of n.checks)switch(i.kind){case"int":o.type="integer",we(o,"type",i.message,t);break;case"min":if(t.target==="jsonSchema7")if(i.inclusive)M(o,"minimum",i.value,i.message,t);else M(o,"exclusiveMinimum",i.value,i.message,t);else{if(!i.inclusive)o.exclusiveMinimum=!0;M(o,"minimum",i.value,i.message,t)}break;case"max":if(t.target==="jsonSchema7")if(i.inclusive)M(o,"maximum",i.value,i.message,t);else M(o,"exclusiveMaximum",i.value,i.message,t);else{if(!i.inclusive)o.exclusiveMaximum=!0;M(o,"maximum",i.value,i.message,t)}break;case"multipleOf":M(o,"multipleOf",i.value,i.message,t);break}return o}var Ye=()=>{};function PA(n,t){let o=t.target==="openAi",i={type:"object",properties:{}},e=[],E=n.shape();for(let T in E){let A=E[T];if(A===void 0||A._def===void 0)continue;let N=Vr(A);if(N&&o){if(A._def.typeName==="ZodOptional")A=A._def.innerType;if(!A.isNullable())A=A.nullable();N=!1}let y=O(A._def,{...t,currentPath:[...t.currentPath,"properties",T],propertyPath:[...t.currentPath,"properties",T]});if(y===void 0)continue;if(i.properties[T]=y,!N)e.push(T)}if(e.length)i.required=e;let f=Wr(n,t);if(f!==void 0)i.additionalProperties=f;return i}function Wr(n,t){if(n.catchall._def.typeName!=="ZodNever")return O(n.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Vr(n){try{return n.isOptional()}catch{return!0}}var Me=R(()=>{v()});var YA=(n,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return O(n.innerType._def,t);let o=O(n.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return o?{anyOf:[{not:W(t)},o]}:W(t)};var Ge=R(()=>{v();An()});var MA=(n,t)=>{if(t.pipeStrategy==="input")return O(n.in._def,t);else if(t.pipeStrategy==="output")return O(n.out._def,t);let o=O(n.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=O(n.out._def,{...t,currentPath:[...t.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,i].filter((e)=>e!==void 0)}};var Fe=R(()=>{v()});function GA(n,t){return O(n.type._def,t)}var He=R(()=>{v()});function FA(n,t){let i={type:"array",uniqueItems:!0,items:O(n.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(n.minSize)M(i,"minItems",n.minSize.value,n.minSize.message,t);if(n.maxSize)M(i,"maxItems",n.maxSize.value,n.maxSize.message,t);return i}var Ze=R(()=>{v()});function HA(n,t){if(n.rest)return{type:"array",minItems:n.items.length,items:n.items.map((o,i)=>O(o._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[]),additionalItems:O(n.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((o,i)=>O(o._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[])}}var Qe=R(()=>{v()});function ZA(n){return{not:W(n)}}var Je=R(()=>{An()});function QA(n){return W(n)}var Be=R(()=>{An()});var JA=(n,t)=>{return O(n.innerType._def,t)};var We=R(()=>{v()});import{ZodFirstPartyTypeKind as Y}from"zod/v3";var BA=(n,t,o)=>{switch(t){case Y.ZodString:return Vo(n,o);case Y.ZodNumber:return CA(n,o);case Y.ZodObject:return PA(n,o);case Y.ZodBigInt:return NA(n,o);case Y.ZodBoolean:return yA();case Y.ZodDate:return De(n,o);case Y.ZodUndefined:return ZA(o);case Y.ZodNull:return $A(o);case Y.ZodArray:return AA(n,o);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return IA(n,o);case Y.ZodIntersection:return LA(n,o);case Y.ZodTuple:return HA(n,o);case Y.ZodRecord:return vo(n,o);case Y.ZodLiteral:return UA(n,o);case Y.ZodEnum:return rA(n);case Y.ZodNativeEnum:return OA(n);case Y.ZodNullable:return XA(n,o);case Y.ZodOptional:return YA(n,o);case Y.ZodMap:return SA(n,o);case Y.ZodSet:return FA(n,o);case Y.ZodLazy:return()=>n.getter()._def;case Y.ZodPromise:return GA(n,o);case Y.ZodNaN:case Y.ZodNever:return lA(o);case Y.ZodEffects:return wA(n,o);case Y.ZodAny:return W(o);case Y.ZodUnknown:return QA(o);case Y.ZodDefault:return _A(n,o);case Y.ZodBranded:return Bo(n,o);case Y.ZodReadonly:return JA(n,o);case Y.ZodCatch:return RA(n,o);case Y.ZodPipeline:return MA(n,o);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return((i)=>{return})(t)}};var Ve=R(()=>{An();re();Le();Wo();Ue();Se();Oe();le();$e();Xe();Ce();Pe();Ye();Me();Ge();Fe();He();jo();Ze();Ko();Qe();Je();ko();Be();We()});function O(n,t,o=!1){let i=t.seen.get(n);if(t.override){let T=t.override?.(n,t,i,o);if(T!==fA)return T}if(i&&!o){let T=Kr(i,t);if(T!==void 0)return T}let e={def:n,path:t.currentPath,jsonSchema:void 0};t.seen.set(n,e);let E=BA(n,n.typeName,t),f=typeof E==="function"?O(E(),t):E;if(f)vr(n,t,f);if(t.postProcess){let T=t.postProcess(f,n,t);return e.jsonSchema=f,T}return e.jsonSchema=f,f}var Kr=(n,t)=>{switch(t.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Jo(t.currentPath,n.path)};case"none":case"seen":{if(n.path.length<t.currentPath.length&&n.path.every((o,i)=>t.currentPath[i]===o))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),W(t);return t.$refStrategy==="seen"?W(t):void 0}}},vr=(n,t,o)=>{if(n.description){if(o.description=n.description,t.markdownDescription)o.markdownDescription=n.description}return o};var v=R(()=>{Qo();Ve();An()});var WA=()=>{};var Ke=(n,t)=>{let o=TA(t),i=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((A,[N,y])=>({...A,[N]:O(y._def,{...o,currentPath:[...o.basePath,o.definitionPath,N]},!0)??W(o)}),{}):void 0,e=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,E=O(n._def,e===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,e]},!1)??W(o),f=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(f!==void 0)E.title=f;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 T=e===void 0?i?{...E,[o.definitionPath]:i}:E:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,e].join("/"),[o.definitionPath]:{...i,[e]:E}};if(o.target==="jsonSchema7")T.$schema="http://json-schema.org/draft-07/schema#";else if(o.target==="jsonSchema2019-09"||o.target==="openAi")T.$schema="https://json-schema.org/draft/2019-09/schema#";if(o.target==="openAi"&&(("anyOf"in T)||("oneOf"in T)||("allOf"in T)||("type"in T)&&Array.isArray(T.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return T};var ve=R(()=>{v();_e();An()});var VA=R(()=>{ve();Qo();_e();v();WA();An();re();Le();Wo();Ue();Se();Oe();le();$e();Xe();Ce();Pe();Ye();Me();Ge();Fe();He();We();jo();Ze();Ko();Qe();Je();ko();Be();Ve();ve()});function ho(){let n=Ct(),t={},o={};for(let e of n){let E=Yn(e),f=Ke(E.schema,{target:"openApi3"}),{$schema:T,...A}=f;t[e]=A,o[e]=E.description}let i=n.map((e)=>({type:"object",title:e,description:o[e],required:["op",...t[e].required||[]],properties:{op:{type:"string",const:e},driveId:{type:"string",description:"Target drive ID (optional, uses default drive)"},...t[e].properties||{}},additionalProperties:!1}));return{openapi:"3.1.0",info:{title:"agent-fs API",version:en,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 KA=R(()=>{VA();ne();Te()});var vA={};Nt(vA,{writeRaw:()=>Qn,write:()=>Xo,updateOrgMemberRole:()=>it,updateDriveMemberRole:()=>an,setDriveMember:()=>ie,setConfigValue:()=>I,setConfig:()=>TE,schema:()=>u,roleAtLeast:()=>kt,resolveContext:()=>on,requireOrgRole:()=>zt,requireDriveRole:()=>Lt,requireDriveAdmin:()=>Fn,removeOrgMember:()=>et,removeDriveMember:()=>nt,listUserOrgs:()=>z,listOrgMembers:()=>ot,listDrivesForUser:()=>Ln,listDrives:()=>te,listDriveMembers:()=>cn,inviteToOrg:()=>Et,getUserOrgRole:()=>xn,getUserDriveRole:()=>_n,getUserByEmail:()=>Pt,getUserByApiKey:()=>Dn,getS3Key:()=>$,getRequiredRole:()=>jt,getRegisteredOps:()=>Ct,getOrg:()=>ct,getOpDefinition:()=>Yn,getNextVersion:()=>$o,getHome:()=>k,getHeadVersionRow:()=>Ut,getHeadContentHash:()=>go,getDrive:()=>oe,getDbPath:()=>dn,getConfigPath:()=>un,getConfig:()=>G,generateOpenAPISpec:()=>ho,ensureLocalUser:()=>at,dispatchOp:()=>s,createVersion:()=>p,createUser:()=>Un,createOrg:()=>tt,createEmbeddingProviderFromEnv:()=>Yt,createDrive:()=>sn,createDatabase:()=>Wn,commentUpdate:()=>Fo,commentResolve:()=>Zo,commentList:()=>Mo,commentGet:()=>Go,commentDelete:()=>Ho,commentAdd:()=>Yo,checkPermission:()=>ht,assertExpectedVersion:()=>x,assertDriveInOrg:()=>Hn,ValidationError:()=>F,VERSION:()=>en,PermissionDeniedError:()=>d,NotFoundError:()=>X,IndexingInProgressError:()=>vt,EditConflictError:()=>Rn,AgentS3Client:()=>Kn,AgentFSError:()=>In});var Q=R(()=>{J();Ht();Fu();m();ne();j();xT();Te();KA()});var po={};Nt(po,{stopDaemon:()=>lL,startDaemon:()=>OL,daemonStatus:()=>$L});import{spawn as LL}from"child_process";import{readFileSync as he,writeFileSync as UL,unlinkSync as zo,existsSync as io,openSync as DL}from"fs";import{join as ze}from"path";function pe(){return ze(k(),"agent-fs.pid")}function SL(){return ze(k(),"agent-fs.log")}function bA(){return ze(k(),"agent-fs.sock")}function OL(){let n=pe();if(io(n)){let E=parseInt(he(n,"utf-8").trim());try{process.kill(E,0),console.log(`Daemon already running (PID: ${E})`);return}catch{zo(n);let f=bA();if(io(f))try{zo(f)}catch{}}}let t=SL(),o=DL(t,"a"),i=process.argv[1];if(!i)throw Error("Cannot determine entry script (process.argv[1] is empty). Daemon start aborted.");let e=LL(process.execPath,[i,"server"],{detached:!0,stdio:["ignore",o,o]});if(e.unref(),e.pid)UL(n,String(e.pid)),console.log(`Daemon started (PID: ${e.pid})`),console.log(`Logs: ${t}`)}function lL(){let n=pe();if(!io(n)){console.log("Daemon is not running");return}let t=parseInt(he(n,"utf-8").trim());try{process.kill(t,"SIGTERM"),console.log(`Daemon stopped (PID: ${t})`)}catch{console.log(`Process ${t} not found (already stopped)`)}zo(n);let o=bA();if(io(o))try{zo(o)}catch{}}function $L(){let n=pe();if(!io(n))return{running:!1};let t=parseInt(he(n,"utf-8").trim());try{return process.kill(t,0),{running:!0,pid:t}}catch{return{running:!1}}}var qo=R(()=>{Q()});var yU={};import{Server as iU}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as eU}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as EU}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as fU}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ListToolsRequestSchema as uU,CallToolRequestSchema as TU}from"@modelcontextprotocol/sdk/types.js";var eo,me,ON,AU,xe,se,NU;var lN=R(async()=>{Q();eo=G(),me=process.env.AGENT_FS_API_URL??eo.apiUrl??`http://${eo.server.host}:${eo.server.port}`,ON=process.env.AGENT_FS_API_KEY??eo.apiKey??eo.auth?.apiKey;if(!ON)console.error("Error: No API key. Register with `agent-fs auth register` or set AGENT_FS_API_KEY."),process.exit(1);AU=new fU(new URL(`${me}/mcp`),{requestInit:{headers:{Authorization:`Bearer ${ON}`}}}),xe=new EU({name:"agent-fs-proxy",version:en});try{await xe.connect(AU)}catch(n){console.error(`Cannot connect to agent-fs at ${me}.
|
|
177
|
+
Start a daemon with \`agent-fs daemon start\` or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1)}se=new iU({name:"agent-fs",version:en},{capabilities:{tools:{}}});se.setRequestHandler(uU,async()=>{return await xe.listTools()});se.setRequestHandler(TU,async(n)=>{return await xe.callTool(n.params)});NU=new eU;await se.connect(NU);console.error("[agent-fs] MCP proxy connected to "+me)});import{z as $N}from"zod";function gN(n,t){let o=Ct();for(let i of o){let e=Yn(i);if(!e)continue;n.tool(i,e.description,e.schema instanceof $N.ZodObject?e.schema.shape:{params:$N.any()},async(E,f)=>{let T=t(f),A=await s(T,i,E);return{content:[{type:"text",text:JSON.stringify(A,null,2)}]}})}}var IN=R(()=>{Q()});import{McpServer as RU}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as pn}from"zod";function XN(n){let{db:t,s3:o,embeddingProvider:i,appUrl:e}=n,E=new RU({name:"agent-fs",version:en}),f=(T)=>{let A=T.authInfo;if(!A?.extra?.user)throw Error("No auth context \u2014 MCP must be accessed through the HTTP server");let N=A.extra.user,y=on(t,{userId:N.id});return{db:t,s3:o,orgId:y.orgId,driveId:y.driveId,userId:N.id,embeddingProvider:i,appUrl:e}};return gN(E,f),E.tool("health","Check agent-fs system health: database, S3, embeddings, version.",{},async(T,A)=>{let N={version:en};try{let y=f(A),_=await s(y,"ls",{path:"/"},{skipAuth:!0});N.database={ok:!0,rootEntries:_.entries?.length??0}}catch(y){N.database={ok:!1,error:y.message}}try{await o.listObjects("",{delimiter:"/"}),N.s3={ok:!0}}catch(y){N.s3={ok:!1,error:y.message}}return N.embeddings={configured:!!i},{content:[{type:"text",text:JSON.stringify(N,null,2)}]}}),_U(E,{db:t,getContext:f}),E}function _U(n,t){let{db:o,getContext:i}=t,e=(E,f)=>{if(f)Hn(o,{driveId:f,orgId:E.orgId}),Fn(o,{userId:E.userId,driveId:f});else zt(o,{userId:E.userId,orgId:E.orgId,requiredRole:"admin"})};n.tool("whoami","Get current user identity, org memberships, and drive roles.",{},async(E,f)=>{let T=i(f),A=T.userId,y=z(o,A).map((L)=>{let S=Ln(o,L.id,A);return{orgId:L.id,orgName:L.name,drives:S.map((U)=>({driveId:U.id,driveName:U.name,role:_n(o,A,U.id)}))}}),_=f.authInfo?.extra?.user?.email,r={userId:A,..._?{email:_}:{},activeOrg:T.orgId,activeDrive:T.driveId,memberships:y};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}),n.tool("member-list","List members of the current org (requires org admin), or a specific drive in the current org (requires drive admin or org admin) if driveId is provided.",{driveId:pn.string().optional().describe("Drive ID to list members for. Omit for org members.")},async(E,f)=>{let T=i(f);try{e(T,E.driveId);let A=E.driveId?cn(o,E.driveId):ot(o,T.orgId);return{content:[{type:"text",text:JSON.stringify({members:A},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),n.tool("member-invite","Invite a user to the current org by email (requires org admin). The user must already have an agent-fs account.",{email:pn.string().describe("Email of the user to invite"),role:pn.enum(["viewer","editor","admin"]).describe("Role to assign")},async(E,f)=>{let T=i(f);try{return e(T),Et(o,{orgId:T.orgId,email:E.email,role:E.role}),{content:[{type:"text",text:JSON.stringify({ok:!0,invited:E.email,role:E.role},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),n.tool("member-update-role","Update a member's role in the current org (requires org admin) or a specific drive in the current org (requires drive admin or org admin).",{email:pn.string().describe("Email of the member"),role:pn.enum(["viewer","editor","admin"]).describe("New role"),driveId:pn.string().optional().describe("Drive ID to update role for. Omit for org role.")},async(E,f)=>{let T=i(f);try{e(T,E.driveId);let A=Pt(o,E.email);if(!A)throw Error(`User with email ${E.email} not found`);if(E.driveId)an(o,{driveId:E.driveId,userId:A.id,role:E.role});else it(o,{orgId:T.orgId,userId:A.id,role:E.role});return{content:[{type:"text",text:JSON.stringify({ok:!0,email:E.email,role:E.role},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),n.tool("member-remove","Remove a member from the current org (cascades to all drives; requires org admin) or from a specific drive in the current org only (requires drive admin or org admin).",{email:pn.string().describe("Email of the member to remove"),driveId:pn.string().optional().describe("Drive ID to remove from. Omit to remove from org.")},async(E,f)=>{let T=i(f);try{e(T,E.driveId);let A=Pt(o,E.email);if(!A)throw Error(`User with email ${E.email} not found`);if(E.driveId)nt(o,{driveId:E.driveId,userId:A.id});else et(o,{orgId:T.orgId,userId:A.id});return{content:[{type:"text",text:JSON.stringify({ok:!0,removed:E.email},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}})}var CN=R(()=>{Q();IN()});function PN(n){return async(t,o)=>{let i=new URL(t.req.url).pathname;if(wU.some((T)=>i===T||i.startsWith(T)))return o();let e=t.req.header("Authorization");if(!e?.startsWith("Bearer "))return t.json({error:"UNAUTHORIZED",message:"Missing or invalid Authorization header",suggestion:"Include 'Authorization: Bearer <api_key>' header"},401);let E=e.slice(7),f=Dn(n,E);if(!f)return t.json({error:"UNAUTHORIZED",message:"Invalid API key",suggestion:"Register with POST /auth/register"},401);return t.set("user",f),o()}}var wU;var YN=R(()=>{Q();wU=["/auth/register","/health"]});function rU(n){if(n instanceof X)return 404;if(n instanceof d)return 403;if(n instanceof Rn)return 409;if(n instanceof vt)return 503;if(n instanceof F)return 400;if("code"in n)return 400;return 500}function MN(n,t){let o=rU(n);if("toJSON"in n&&typeof n.toJSON==="function")return t.json(n.toJSON(),o);return t.json({error:"INTERNAL_ERROR",message:n.message},o)}var GN=R(()=>{Q()});function mo(n){let t=new Map;return setInterval(()=>{let o=Date.now()-60000;for(let[i,e]of t){let E=e.filter((f)=>f>o);if(E.length===0)t.delete(i);else t.set(i,E)}},300000).unref(),async(o,i)=>{let e=o.req.header("authorization")??"",E=e.startsWith("Bearer ")?e.slice(7):o.req.header("x-forwarded-for")??"unknown",f=Date.now(),T=f-60000,A=(t.get(E)??[]).filter((N)=>N>T);if(A.length>=n){let N=A[0],y=Math.ceil((N+60000-f)/1000);return o.header("Retry-After",String(y)),o.json({error:"RATE_LIMITED",message:"Too many requests"},429)}A.push(f),t.set(E,A),await i()}}import{Hono as LU}from"hono";function FN(n){let t=new LU;return t.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=Un(n,{email:i}),E=z(n,e.user.id);return o.json({apiKey:e.apiKey,userId:e.user.id,orgId:E[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}}),t.get("/me",(o)=>{let i=o.get("user");try{let e=on(n,{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})}}),t}var HN=R(()=>{Q()});import{Hono as UU}from"hono";function ZN(n,t,o=null,i){let e=new UU;return e.post("/:orgId/ops",async(E)=>{let f=E.get("user"),T=E.req.param("orgId"),A=await E.req.json(),{op:N,...y}=A;if(!N)return E.json({error:"VALIDATION_ERROR",message:"op is required in request body"},400);let _=y.driveId||y.drive_id;delete y.driveId,delete y.drive_id;let r=on(n,{userId:f.id,orgId:T,driveId:_}),L={db:n,s3:t,orgId:r.orgId,driveId:r.driveId,userId:f.id,embeddingProvider:o,appUrl:i},S=await s(L,N,y);return E.json(S)}),e}var QN=R(()=>{Q()});import{Hono as DU}from"hono";function ce(n,t,o){let i=xn(n,t,o);if(!i)throw new X(`Org not found: ${o}`,{suggestion:"Check the org id or ask an org admin for access"});return i}function Eo(n,t,o){let i=ce(n,t,o);if(!kt(i,"admin"))throw new d("This operation requires 'admin' role in the org",{requiredRole:"admin",yourRole:i,suggestion:"Ask an org admin to perform this operation"});return i}function JN(n){let t=new DU;return t.get("/",(o)=>{let i=o.get("user"),e=z(n,i.id);return o.json({orgs:e})}),t.post("/",async(o)=>{let i=o.get("user"),{name:e}=await o.req.json(),E=tt(n,{name:e,userId:i.id});return o.json(E,201)}),t.get("/:orgId",(o)=>{let i=o.get("user"),e=o.req.param("orgId");ce(n,i.id,e);let E=ct(n,e);if(!E)return o.json({error:"NOT_FOUND",message:"Org not found"},404);return o.json(E)}),t.get("/:orgId/drives",(o)=>{let i=o.get("user"),e=o.req.param("orgId");ce(n,i.id,e);let E=Ln(n,e,i.id);return o.json({drives:E})}),t.post("/:orgId/drives",async(o)=>{let i=o.get("user"),e=o.req.param("orgId");Eo(n,i.id,e);let{name:E}=await o.req.json(),f=sn(n,{orgId:e,name:E,creatorUserId:i.id});return o.json(f,201)}),t.post("/:orgId/members/invite",async(o)=>{let i=o.get("user"),e=o.req.param("orgId");Eo(n,i.id,e);let{email:E,role:f}=await o.req.json();return Et(n,{orgId:e,email:E,role:f}),o.json({ok:!0})}),t.get("/:orgId/members",(o)=>{let i=o.get("user"),e=o.req.param("orgId");Eo(n,i.id,e);let E=ot(n,e);return o.json({members:E})}),t.patch("/:orgId/members/:userId",async(o)=>{let i=o.get("user"),e=o.req.param("orgId"),E=o.req.param("userId");Eo(n,i.id,e);let{role:f}=await o.req.json();try{return it(n,{orgId:e,userId:E,role:f}),o.json({ok:!0})}catch(T){return o.json({error:"BAD_REQUEST",message:T.message},400)}}),t.delete("/:orgId/members/:userId",(o)=>{let i=o.get("user"),e=o.req.param("orgId"),E=o.req.param("userId");Eo(n,i.id,e);try{return et(n,{orgId:e,userId:E}),o.json({ok:!0})}catch(f){return o.json({error:"BAD_REQUEST",message:f.message},400)}}),t.get("/:orgId/drives/:driveId/members",(o)=>{let i=o.get("user"),e=o.req.param("orgId"),E=o.req.param("driveId");Hn(n,{driveId:E,orgId:e}),Fn(n,{userId:i.id,driveId:E});let f=cn(n,E);return o.json({members:f})}),t.patch("/:orgId/drives/:driveId/members/:userId",async(o)=>{let i=o.get("user"),e=o.req.param("orgId"),E=o.req.param("driveId"),f=o.req.param("userId");Hn(n,{driveId:E,orgId:e}),Fn(n,{userId:i.id,driveId:E});let{role:T}=await o.req.json();try{return an(n,{driveId:E,userId:f,role:T}),o.json({ok:!0})}catch(A){return o.json({error:"BAD_REQUEST",message:A.message},400)}}),t.delete("/:orgId/drives/:driveId/members/:userId",(o)=>{let i=o.get("user"),e=o.req.param("orgId"),E=o.req.param("driveId"),f=o.req.param("userId");Hn(n,{driveId:E,orgId:e}),Fn(n,{userId:i.id,driveId:E});try{return nt(n,{driveId:E,userId:f}),o.json({ok:!0})}catch(T){return o.json({error:"BAD_REQUEST",message:T.message},400)}}),t}var BN=R(()=>{Q()});import{Hono as SU}from"hono";function WN(){let n=new SU;return n.get("/openapi.json",(t)=>{return t.json(ho())}),n}var VN=R(()=>{Q()});import{Hono as OU}from"hono";function KN(n,t,o=null,i){let e=new OU;return e.get("/:orgId/drives/:driveId/files/:filePath{.+}/raw",async(E)=>{let f=E.get("user"),T=E.req.param("orgId"),A=E.req.param("driveId"),N=on(n,{userId:f.id,orgId:T,driveId:A}),_=new URL(E.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!_)return E.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let r=Zn(decodeURIComponent(_[1])),L=$(N.orgId,N.driveId,r);try{let S=await t.getObject(L),U=S.contentType||"application/octet-stream",g=Ut({db:n,driveId:N.driveId},r),K={"Content-Type":U,"Content-Length":String(S.body.length),"Cache-Control":"private, max-age=60"};if(g){if(K.ETag=`"${g.version}"`,K["X-Agent-FS-Version"]=String(g.version),g.contentHash)K["X-Agent-FS-Content-Hash"]=g.contentHash;if(g.createdAt)K["Last-Modified"]=new Date(g.createdAt).toUTCString()}return new Response(S.body.slice(),{status:200,headers:K})}catch(S){if(S?.name==="NoSuchKey"||S?.$metadata?.httpStatusCode===404)return E.json({error:"NOT_FOUND",message:`File not found: ${r}`},404);throw S}}),e.put("/:orgId/drives/:driveId/files/:filePath{.+}/raw",async(E)=>{let f=E.get("user"),T=E.req.param("orgId"),A=E.req.param("driveId");if((E.req.header("Content-Type")??"").toLowerCase().startsWith("application/json"))return E.json({error:"VALIDATION_ERROR",message:"PUT /raw expects a binary body; use POST /ops with op=write for JSON-encoded content"},415);let y=on(n,{userId:f.id,orgId:T,driveId:A}),r=new URL(E.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!r)return E.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let L=Zn(decodeURIComponent(r[1])),S,U=E.req.header("If-None-Match"),g=E.req.header("If-Match");if(U==="*")S=0;else if(g!==void 0){let nn=g.replace(/^"|"$/g,""),tn=Number(nn);if(!Number.isInteger(tn)||tn<0)return E.json({error:"VALIDATION_ERROR",message:`If-Match must be a non-negative integer version, got: ${g}`},400);S=tn}let K=E.req.header("X-Agent-FS-Message")??void 0,bn=await E.req.arrayBuffer(),xo=new Uint8Array(bn),l={db:n,s3:t,orgId:y.orgId,driveId:y.driveId,userId:f.id,embeddingProvider:o,appUrl:i},H=await Qn(l,{path:L,bytes:xo,message:K,expectedVersion:S});return new Response(JSON.stringify(H),{status:200,headers:{"Content-Type":"application/json",ETag:`"${H.version}"`,"X-Agent-FS-Version":String(H.version),...H.contentHash&&{"X-Agent-FS-Content-Hash":H.contentHash},"X-Agent-FS-Deduped":H.deduped?"1":"0"}})}),e}var vN=R(()=>{Q()});import{Hono as lU}from"hono";import{cors as jN}from"hono/cors";import{bodyLimit as $U}from"hono/body-limit";import{WebStandardStreamableHTTPServerTransport as gU}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";function kN(n,t,o=null){let i=new lU,e=G(),E=e.server?.cors?.origins??["*"];if(E.length===1&&E[0]==="*")i.use("*",jN());else i.use("*",jN({origin:E}));i.use("*",$U({maxSize:52428800})),i.use("*",PN(n));let f=e.server?.rateLimit?.requestsPerMinute??1200;if(f>0)i.use("/orgs/*",mo(f)),i.use("/auth/*",mo(f)),i.use("/mcp",mo(f));return i.onError((T,A)=>MN(T,A)),i.get("/health",(T)=>T.json({ok:!0,version:en})),i.all("/mcp",async(T)=>{let A=T.get("user"),N=new gU({sessionIdGenerator:void 0,enableJsonResponse:!0});return await XN({db:n,s3:t,embeddingProvider:o,appUrl:e.appUrl}).connect(N),N.handleRequest(T.req.raw,{authInfo:{token:T.req.header("Authorization")?.slice(7)??"",clientId:A.id,scopes:[],extra:{user:{id:A.id,email:A.email}}}})}),i.route("/auth",FN(n)),i.route("/orgs",JN(n)),i.route("/orgs",ZN(n,t,o,e.appUrl)),i.route("/docs",WN()),i.route("/orgs",KN(n,t,o,e.appUrl)),i}var hN=R(()=>{Q();CN();YN();GN();HN();QN();BN();VN();vN()});function Mn(n,t,o){return{error:{http_status:n,code:t,message:o}}}function IU(n){let t=String(n?.name??""),o=String(n?.message??n??"unknown error");if(t==="EditConflictError")return Mn(409,"EDIT_CONFLICT",o);if(t==="NotFoundError")return Mn(404,"NOT_FOUND",o);if(t==="PermissionDeniedError")return Mn(403,"PERMISSION_DENIED",o);if(t==="ValidationError")return Mn(415,"VALIDATION",o);if(t==="IndexingInProgressError")return Mn(503,"INDEXING_IN_PROGRESS",o);if(/no.*api.*key|no.*user/i.test(o))return Mn(401,"AUTH_MISSING",o);return Mn(500,"INTERNAL",o)}function Nn(n){let t=n.resolveApiKey();if(!t){let i=Error("daemon has no API key configured");throw i.name="AuthError",i}let o=Dn(n.db,t);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 Bn(n,t,o){try{let E=on(n.db,{userId:t,driveId:o});return{orgId:E.orgId,driveId:E.driveId}}catch{}let i=z(n.db,t);for(let E of i){let T=Ln(n.db,E.id,t).find((A)=>A.name===o);if(T)return{orgId:E.id,driveId:T.id}}let e=Error(`Drive not found: ${o}`);throw e.name="NotFoundError",e}function qn(n,t,o,i){return{db:n.db,s3:n.s3,orgId:o,driveId:i,userId:t.userId,embeddingProvider:n.embeddingProvider,appUrl:n.appUrl}}async function zN(n,t){if(!t||typeof t!=="object")return Mn(400,"VALIDATION","request body must be an object");let o=t;try{return await XU(n,o)}catch(i){return IU(i)}}async function XU(n,t){switch(t.op){case"ping":return"pong";case"hello":return"ok";case"list_drives":{let o=Nn(n),i=z(n.db,o.userId),e=[];for(let E of i){let f=Ln(n.db,E.id,o.userId);for(let T of f)e.push({slug:T.name,id:T.id,org_id:E.id})}return{drives:e}}case"default_drive_slug":{let o=Nn(n),i=z(n.db,o.userId);for(let e of i){let E=Ln(n.db,e.id,o.userId),f=E.find((T)=>T.isDefault)??E[0];if(f)return{default_drive_slug:f.name}}return{default_drive_slug:null}}case"get_attr":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=qn(n,o,i,e);try{let T=await s(f,"stat",{path:E});return{attr:{kind:"File",size:T.size,mtime_unix:Math.floor(new Date(T.modifiedAt).getTime()/1000),version:T.currentVersion??null,content_hash:null}}}catch(T){if(String(T?.name)==="NotFoundError")try{let A=await s(f,"ls",{path:E});if(A&&Array.isArray(A.entries)&&A.entries.length>0)return{attr:{kind:"Dir",size:0,mtime_unix:0,version:null,content_hash:null}}}catch{}throw T}}case"read_dir":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path??"/",f=qn(n,o,i,e);return{dir_entries:((await s(f,"ls",{path:E}))?.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=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=$(i,e,E),T=await n.s3.getObject(f),A=Ut({db:n.db,driveId:e},E);return{open_read:{bytes:T.body,version:A?.version??0,content_hash:A?.contentHash??"",size:T.body.length,mtime_unix:A?.createdAt?Math.floor(new Date(A.createdAt).getTime()/1000):0}}}case"open_write":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=qn(n,o,i,e),T=CU(t.bytes),A=await Qn(f,{path:E,bytes:T,expectedVersion:t.base_version??void 0});return{open_write:{version:A.version,content_hash:A.contentHash??"",deduped:A.deduped??!1}}}case"create_file":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=qn(n,o,i,e),T=await Qn(f,{path:E,bytes:new Uint8Array(0),expectedVersion:0});return{open_write:{version:T.version,content_hash:T.contentHash??"",deduped:T.deduped??!1}}}case"truncate":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=t.size??0,T=qn(n,o,i,e),A=$(i,e,E),N=(await n.s3.getObject(A)).body,y=N.subarray(0,Math.min(f,N.length)),_=await Qn(T,{path:E,bytes:y});return{open_write:{version:_.version,content_hash:_.contentHash??"",deduped:_.deduped??!1}}}case"unlink":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=qn(n,o,i,e);return await s(f,"rm",{path:E}),"ok"}case"rename":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.from_path,f=t.to_path,T=qn(n,o,i,e);return await s(T,"mv",{from:E,to:f}),"ok"}case"mkdir":return Nn(n),"ok";case"rmdir":{let o=Nn(n),{orgId:i,driveId:e}=Bn(n,o.userId,t.drive),E=t.path,f=qn(n,o,i,e);if((await s(f,"ls",{path:E}))?.entries?.length>0)return Mn(409,"VALIDATION","directory not empty");return"ok"}case"record_conflict":return console.warn("[agent-fs ipc] conflict:",JSON.stringify({drive:t.drive,path:t.path,base_version:t.base_version,head_version:t.head_version,bytes:t.bytes})),"ok";case"write_status":return console.warn("[agent-fs ipc] status:",t.line),"ok";default:return Mn(400,"VALIDATION",`unknown op: ${t.op}`)}}function CU(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(Array.isArray(n))return new Uint8Array(n);if(n==null)return new Uint8Array(0);if(typeof n==="string")return new TextEncoder().encode(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return new Uint8Array(n);return new Uint8Array(0)}var pN=R(()=>{Q()});import{unlinkSync as qN,existsSync as PU,chmodSync as YU}from"fs";import{Packr as MU,Unpackr as GU}from"msgpackr";function bN(n,t){if(PU(n))try{qN(n)}catch{}let o=Bun.listen({unix:n,socket:{open(i){i.data={buf:Buffer.alloc(0)}},data(i,e){i.data.buf=Buffer.concat([i.data.buf,e]),QU(i,t).catch((E)=>{console.error("[agent-fs ipc] frame drain failed:",E),i.end()})},close(i){i.data.buf=Buffer.alloc(0)},error(i,e){console.error("[agent-fs ipc] socket error:",e)}}});try{YU(n,384)}catch{}return{socketPath:n,stop:()=>{o.stop(!0);try{qN(n)}catch{}}}}async function QU(n,t){while(!0){let o=n.data;if(o.buf.length<4)return;let i=o.buf.readUInt32BE(0);if(i===0||i>FU){console.error(`[agent-fs ipc] implausible frame length ${i}; closing`),n.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 E;try{E=ZU.unpack(e)}catch(f){console.error("[agent-fs ipc] decode failed:",f),n.end();return}JU(n,t,E)}}async function JU(n,t,o){let i;try{i=await zN(t,o.body)}catch(T){i={Error:{http_status:0,code:null,message:String(T?.message??T)}}}let e={id:o.id,body:i},E=HU.pack(e),f=Buffer.alloc(4);f.writeUInt32BE(E.length,0),n.write(Buffer.concat([f,E]))}var FU=67108864,HU,ZU;var dN=R(()=>{pN();HU=new MU({useRecords:!1}),ZU=new GU({useRecords:!1})});var VU={};import{join as BU}from"path";function cN(){if(console.log("Shutting down..."),ae.stop(),nE)nE.stop();process.exit(0)}var Gt,xN,sN,tE=null,WU,ae,mN,nE=null;var aN=R(async()=>{Q();hN();dN();Gt=G(),xN=Wn(),sN=new Kn(Gt.s3);try{tE=await Yt(Gt.embedding)}catch(n){console.warn("Embedding provider unavailable, semantic search disabled:",n)}WU=kN(xN,sN,tE),ae=Bun.serve({fetch:WU.fetch,port:Gt.server.port,hostname:Gt.server.host});console.log(`agent-fs daemon running on http://${ae.hostname}:${ae.port}`);mN=BU(k(),"agent-fs.sock");try{nE=bN(mN,{db:xN,s3:sN,embeddingProvider:tE,appUrl:Gt.appUrl,resolveApiKey:()=>Gt.auth?.apiKey??null}),console.log(`agent-fs IPC listening on ${mN}`)}catch(n){console.warn("IPC listener unavailable:",n)}process.on("SIGTERM",cN);process.on("SIGINT",cN)});Q();import{Command as KU}from"commander";Q();class je{baseUrl;apiKey;constructor(){let n=G();this.baseUrl=process.env.AGENT_FS_API_URL??n.apiUrl??`http://${n.server.host}:${n.server.port}`,this.apiKey=process.env.AGENT_FS_API_KEY??n.apiKey??n.auth.apiKey}async request(n,t){let o=new Headers(t?.headers);if(this.apiKey)o.set("Authorization",`Bearer ${this.apiKey}`);o.set("Content-Type","application/json");let i;try{i=await fetch(`${this.baseUrl}${n}`,{...t,headers:o})}catch(E){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 E=await i.text().catch(()=>"");throw Error(`Unexpected response from daemon (${i.status}): ${E||"empty"}`)}if(!i.ok){let E=e.message??e.error??"Request failed",f=e.suggestion?`
|
|
178
|
+
Suggestion: ${e.suggestion}`:"";throw Error(`${E}${f}`)}return e}async get(n){return this.request(n)}async post(n,t){return this.request(n,{method:"POST",body:JSON.stringify(t)})}async patch(n,t){return this.request(n,{method:"PATCH",body:JSON.stringify(t)})}async del(n){return this.request(n,{method:"DELETE"})}async callOp(n,t,o){return this.post(`/orgs/${n}/ops`,{op:t,...o})}async getMe(){return this.get("/auth/me")}setApiKey(n){this.apiKey=n}async putRaw(n,t,o,i,e={}){let E=new Headers;if(E.set("Content-Type","application/octet-stream"),this.apiKey)E.set("Authorization",`Bearer ${this.apiKey}`);if(e.ifMatch!==void 0)E.set("If-Match",String(e.ifMatch));if(e.contentHash)E.set("X-Agent-FS-Content-Hash",e.contentHash);if(e.message)E.set("X-Agent-FS-Message",e.message);let f=encodeURI(o.replace(/^\/+/,"")),T=`${this.baseUrl}/orgs/${n}/drives/${t}/files/${f}/raw`,A;try{A=await fetch(T,{method:"PUT",headers:E,body:i})}catch(_){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}let N,y=await A.text();try{N=JSON.parse(y)}catch{throw Error(`Unexpected response from daemon (${A.status}): ${y||"empty"}`)}if(!A.ok){let _=N.message??N.error??"Request failed",r=N.suggestion?`
|
|
179
|
+
Suggestion: ${N.suggestion}`:"";throw Error(`${_}${r}`)}return{version:N.version,path:N.path??o,deduped:Boolean(N.deduped),contentHash:A.headers.get("X-Agent-FS-Content-Hash")??N.contentHash??null,size:N.size??i.length}}async getRaw(n,t,o){let i=new Headers;if(this.apiKey)i.set("Authorization",`Bearer ${this.apiKey}`);let e=encodeURI(o.replace(/^\/+/,"")),E=`${this.baseUrl}/orgs/${n}/drives/${t}/files/${e}/raw`,f;try{f=await fetch(E,{method:"GET",headers:i})}catch(T){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}if(!f.ok){let T,A=await f.text().catch(()=>"");try{T=JSON.parse(A)}catch{throw Error(`Unexpected response from daemon (${f.status}): ${A||"empty"}`)}let N=T.message??T.error??"Request failed",y=T.suggestion?`
|
|
180
|
+
Suggestion: ${T.suggestion}`:"";throw Error(`${N}${y}`)}return{bytes:new Uint8Array(await f.arrayBuffer()),contentType:f.headers.get("Content-Type"),version:jr(f.headers.get("X-Agent-FS-Version")),contentHash:f.headers.get("X-Agent-FS-Content-Hash")}}}function jr(n){if(n===null)return null;let t=Number(n);return Number.isInteger(t)?t:null}Q();import{Command as yL}from"commander";function Mt(n){if(n<1024)return`${n} B`;if(n<1048576)return`${(n/1024).toFixed(1)} KB`;if(n<1073741824)return`${(n/1048576).toFixed(1)} MB`;return`${(n/1073741824).toFixed(1)} GB`}function ut(n){if(!n)return"-";let t=typeof n==="string"?new Date(n):n;if(isNaN(t.getTime()))return String(n);return t.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"Z")}function ft(n,t){return n.length>=t?n:n+" ".repeat(t-n.length)}function ke(n,t){return n.length>=t?n:" ".repeat(t-n.length)+n}function kr(n){let t=n.entries??[];if(t.length===0)return"(empty directory)";let o=Math.max(4,...t.map((T)=>String(T.name).length)),i=Math.max(4,...t.map((T)=>String(T.type).length)),e=Math.max(4,...t.map((T)=>Mt(T.size??0).length)),E=ft("NAME",o)+" "+ft("TYPE",i)+" "+ke("SIZE",e)+" MODIFIED",f=t.map((T)=>ft(T.name,o)+" "+ft(T.type,i)+" "+ke(Mt(T.size??0),e)+" "+ut(T.modifiedAt));return[E,...f].join(`
|
|
181
|
+
`)}function hA(n){let o=(n.content??"").split(`
|
|
182
|
+
`);if(o.length>0&&o[o.length-1]==="")o.pop();let i=n.offset??1,e=String(i+o.length-1).length;return o.map((E,f)=>`${ke(String(i+f),e)} ${E}`).join(`
|
|
183
|
+
`)}function hr(n){let t=[["Path",n.path??"-"],["Size",Mt(n.size??0)],["Content-Type",n.contentType??"-"],["Author",n.author??"-"],["Version",n.currentVersion!=null?String(n.currentVersion):"-"],["Created",ut(n.createdAt)],["Modified",ut(n.modifiedAt)],["Deleted",n.isDeleted?"yes":"no"]];if(n.embeddingStatus)t.push(["Embedding",n.embeddingStatus]);if(n.appUrl)t.push(["App URL",n.appUrl]);let o=Math.max(...t.map(([i])=>i.length));return t.map(([i,e])=>`${ft(i+":",o+1)} ${e}`).join(`
|
|
184
|
+
`)}function zr(n){let t=n.versions??[];if(t.length===0)return"(no version history)";return t.map((o)=>{let i=[`v${o.version} ${ut(o.createdAt)} ${o.author??"-"} [${o.operation}]`];if(o.message)i.push(` ${o.message}`);if(o.diffSummary)i.push(` ${o.diffSummary}`);return i.join(`
|
|
185
185
|
`)}).join(`
|
|
186
186
|
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
189
|
-
`)}function
|
|
190
|
-
${i.snippet}`);if(
|
|
191
|
-
hint: ${
|
|
187
|
+
`)}function pr(n){return`\u2713 wrote ${n.path} (v${n.version}, ${Mt(n.size??0)})`}function qr(n){return`\u2713 edited ${n.path} (v${n.version}, ${n.changes} change${n.changes!==1?"s":""})`}function br(n){return`\u2713 appended (v${n.version}, ${Mt(n.size??0)})`}function dr(n){return n.deleted?`\u2713 deleted ${n.path}`:`(not found: ${n.path})`}function mr(n){return`\u2713 moved ${n.from} -> ${n.to} (v${n.version})`}function xr(n){return`\u2713 copied ${n.from} -> ${n.to} (v${n.version})`}function sr(n){let t=n.tree??[];if(t.length===0)return"(empty)";let o=[];function i(e,E){for(let f=0;f<e.length;f++){let T=e[f],A=f===e.length-1,N=A?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",y=T.type==="directory"?"/":"";if(o.push(`${E}${N}${T.name}${y}`),T.children&&T.children.length>0){let _=E+(A?" ":"\u2502 ");i(T.children,_)}}}return i(t,""),o.join(`
|
|
188
|
+
`)}function cr(n){let t=n.matches??[];if(t.length===0)return"(no matches)";return t.map((o)=>`${o.path}:${o.lineNumber}: ${o.content}`).join(`
|
|
189
|
+
`)}function ar(n){let t=n.matches??[];if(t.length===0)return n.hint?`(no matches) ${n.hint}`:"(no matches)";let o=t.map((i)=>`${i.path} (rank: ${typeof i.rank==="number"?i.rank.toFixed(2):i.rank})
|
|
190
|
+
${i.snippet}`);if(n.hint)o.push(`
|
|
191
|
+
hint: ${n.hint}`);return o.join(`
|
|
192
192
|
|
|
193
|
-
`)}function
|
|
193
|
+
`)}function jA(n){let t=n.results??[];if(t.length===0)return"(no results)";return t.map((o)=>`${o.path} (score: ${typeof o.score==="number"?o.score.toFixed(3):o.score})`+(o.author?` by ${o.author}`:"")+`
|
|
194
194
|
${o.snippet}`).join(`
|
|
195
195
|
|
|
196
|
-
`)}function
|
|
197
|
-
`)}function
|
|
198
|
-
`)}function
|
|
196
|
+
`)}function nL(n){let t=n.matches??[];if(t.length===0)return"(no matches)";return t.map((o)=>`${o.path} ${Mt(o.size??0)} ${ut(o.modifiedAt)}`).join(`
|
|
197
|
+
`)}function tL(n){let t=n.changes??[];if(t.length===0)return"(no changes)";return t.map((o)=>{let i=o.type==="add"?"+":o.type==="remove"?"-":" ",e=o.lineNumber!=null?`${o.lineNumber}: `:"";return`${i} ${e}${o.content}`}).join(`
|
|
198
|
+
`)}function oL(n){return hA(n)}function iL(n){return`\u2713 reverted to v${n.revertedTo} (new version: v${n.version})`}function eL(n){let t=n.entries??[];if(t.length===0)return"(no recent activity)";return t.map((o)=>`${o.path} v${o.version} ${ut(o.createdAt)} ${o.author??"-"} [${o.operation}]`+(o.message?`
|
|
199
199
|
${o.message}`:"")).join(`
|
|
200
200
|
|
|
201
|
-
`)}function
|
|
201
|
+
`)}function EL(n){let t=[];if(t.push(`reindexed: ${n.reindexed??0}`),n.failed)t.push(`failed: ${n.failed}`);if(n.skipped)t.push(`skipped: ${n.skipped}`);return t.join(", ")}var kA=80;function fL(n){let t;if(n===null||n===void 0)t="NULL";else if(typeof n==="object")t=JSON.stringify(n);else t=String(n);return t=t.replace(/\s+/g," "),t.length>kA?t.slice(0,kA-1)+"\u2026":t}function uL(n){let t=n.columns??[],o=n.rows??[],i=[];if(t.length>0){let E=t.map((A)=>String(A.name)),f=o.map((A)=>E.map((N)=>fL(A[N]))),T=E.map((A,N)=>Math.max(A.length,...f.map((y)=>y[N].length)));i.push(E.map((A,N)=>ft(A,T[N])).join(" ")),i.push(T.map((A)=>"-".repeat(A)).join(" "));for(let A of f)i.push(A.map((N,y)=>ft(N,T[y])).join(" "))}let e=`${n.rowCount??o.length} row${o.length!==1?"s":""}`;if(n.elapsedMs!=null)e+=` in ${n.elapsedMs}ms`;if(n.truncated)e+=" (truncated \u2014 raise --max-rows to fetch more)";if(i.length>0)i.push("");return i.push(e),i.join(`
|
|
202
|
+
`)}function TL(n){let t=`${n.url}
|
|
202
203
|
|
|
203
|
-
Expires: ${
|
|
204
|
-
App: ${
|
|
204
|
+
Expires: ${ut(n.expiresAt)} (${n.expiresIn}s)`;if(n.appUrl)t+=`
|
|
205
|
+
App: ${n.appUrl}`;return t}var AL={ls:kr,cat:hA,stat:hr,log:zr,write:pr,edit:qr,append:br,rm:dr,mv:mr,cp:xr,tree:sr,grep:cr,fts:ar,search:jA,"vec-search":jA,glob:nL,diff:tL,tail:oL,revert:iL,recent:eL,reindex:EL,sql:uL,"signed-url":TL};function NL(n,t){let o=AL[n];if(o)return o(t);return JSON.stringify(t,null,2)}function oo(n,t,o){if(o)console.log(JSON.stringify(t,null,2));else console.log(NL(n,t))}var RL={s:1000,m:60000,h:3600000,d:86400000,w:604800000};function _L(n){let t=/^(\d+)\s*([smhdw])$/i.exec(n.trim());if(!t)return n;let o=parseInt(t[1],10),i=RL[t[2].toLowerCase()];return new Date(Date.now()-o*i).toISOString()}var wL=[{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 zA(n,t,o,i){for(let e of wL){let E=Yn(e.name),f=new yL(e.name).description(E?.description??e.name);for(let T of e.args)if(T.required)f.argument(`<${T.name}>`);else f.argument(`[${T.name}]`);for(let T of e.options)f.option(T.flag,T.description);f.action(async(...T)=>{let N={...T[T.length-2]},y=null;for(let _=0;_<e.args.length;_++)if(T[_]!==void 0)N[e.args[_].name]=T[_];if(e.name==="write"){if(N.file&&N.content!==void 0)console.error("Error: use either --file or --content, not both"),process.exit(1);if(N.file)y=new Uint8Array(await Bun.file(N.file).arrayBuffer()),delete N.file;else if(N.content===void 0&&!process.stdin.isTTY)y=new Uint8Array(await Bun.stdin.arrayBuffer())}if(e.name==="append"&&N.content===void 0)if(!process.stdin.isTTY)N.content=await Bun.stdin.text();else console.error("Error: --content required (or pipe content via stdin)"),process.exit(1);if(e.name==="write"&&N.content===void 0&&y===null)console.error("Error: --content or --file required (or pipe content via stdin)"),process.exit(1);if(N["expected-version"]!==void 0)N.expectedVersion=N["expected-version"],delete N["expected-version"];if(N.old!==void 0)N.old_string=N.old,delete N.old;if(N.new!==void 0)N.new_string=N.new,delete N.new;if(e.name==="revert"&&N.to!==void 0)N.version=N.to,delete N.to;if(N["expires-in"]!==void 0)N.expiresIn=N["expires-in"],delete N["expires-in"];for(let _ of["offset","limit","lines","v1","v2","version","expectedVersion","depth","expiresIn"])if(N[_]!==void 0)N[_]=parseInt(N[_]);if(e.name==="recent"&&typeof N.since==="string")N.since=_L(N.since);try{let _=await o(),r=n.opts().drive??G().defaultDrive;if(r)N.driveId=r;if(e.name==="write"&&y!==null){if(!i)throw Error("Cannot resolve drive context for raw upload");let S=await t.putRaw(_,await i(_),N.path,y,{ifMatch:N.expectedVersion,message:N.message});oo(e.name,S,n.opts().json);return}let L=await t.callOp(_,e.name,N);oo(e.name,L,n.opts().json)}catch(_){if(_?.cause?.code==="ECONNREFUSED"||_?.message?.includes("fetch failed"))console.error(`Cannot connect to agent-fs daemon.
|
|
205
206
|
Start with: agent-fs daemon start
|
|
206
|
-
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);console.error(`Error: ${
|
|
207
|
-
API key saved to config.`)}import{Command as
|
|
207
|
+
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);console.error(`Error: ${_.message}`),process.exit(1)}}),n.addCommand(f)}}Q();import{Command as rL}from"commander";function qA(n){let t=new rL("auth").description("Authentication commands");return t.command("register").argument("<email>","Email address").description("Register a new user").action(async(o)=>{try{let i=await n.post("/auth/register",{email:o});pA(i,n)}catch{try{let i=Wn(),e=Un(i,{email:o}),E=z(i,e.user.id);pA({apiKey:e.apiKey,userId:e.user.id,orgId:E[0]?.id},n)}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)}}}),t.command("whoami").description("Show current user info").action(async()=>{try{let o=await n.get("/auth/me");console.log(JSON.stringify(o,null,2))}catch{try{let{getConfig:o,getUserByApiKey:i,createDatabase:e,listUserOrgs:E}=await Promise.resolve().then(() => (Q(),vA)),f=o();if(!f.auth.apiKey)console.error("Not logged in. Run: agent-fs auth register <email>"),process.exit(1);let T=e(),A=i(T,f.auth.apiKey);if(!A)console.error("Invalid API key in config."),process.exit(1);let N=E(T,A.id);console.log(JSON.stringify({...A,orgs:N},null,2))}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}}),t}function pA(n,t){console.log("Registered successfully!"),console.log(`API Key: ${n.apiKey}`),console.log(`User ID: ${n.userId}`),console.log(`Org ID: ${n.orgId}`),I("auth.apiKey",n.apiKey),t.setApiKey(n.apiKey),console.log(`
|
|
208
|
+
API key saved to config.`)}import{Command as gL}from"commander";function dA(){let n=new gL("daemon").description("Daemon lifecycle management");return n.command("start").description("Start the agent-fs daemon").action(async()=>{let{startDaemon:t}=await Promise.resolve().then(() => (qo(),po));t()}),n.command("stop").description("Stop the agent-fs daemon").action(async()=>{let{stopDaemon:t}=await Promise.resolve().then(() => (qo(),po));t()}),n.command("status").description("Check daemon status").action(async()=>{let{daemonStatus:t}=await Promise.resolve().then(() => (qo(),po)),o=t();if(o.running)console.log(`Daemon running (PID: ${o.pid})`);else console.log("Daemon is not running")}),n}Q();import{Command as IL}from"commander";import{existsSync as mA}from"fs";function xA(){let n=new IL("config").description("Configuration management");return n.command("get").argument("<key>","Config key (dot notation, e.g., s3.bucket)").description("Get a config value").action((t)=>{let o=G(),i=t.split("."),e=o;for(let E of i)e=e?.[E];if(e===void 0)console.error(`Key not found: ${t}`),process.exit(1);console.log(typeof e==="object"?JSON.stringify(e,null,2):String(e))}),n.command("set").argument("<key>","Config key").argument("<value>","Config value").description("Set a config value").action((t,o)=>{let i=o;try{i=JSON.parse(o)}catch{}I(t,i),console.log(`Set ${t} = ${JSON.stringify(i)}`)}),n.command("list").description("Show all config").action(()=>{console.log(JSON.stringify(G(),null,2))}),n.command("validate").description("Check that config, database, S3, and embeddings are healthy").action(async()=>{let t=[],o=G(),i=mA(un());t.push({name:"Config file",ok:i,message:i?un():"Not found \u2014 run `agent-fs onboard`"});let E=["endpoint","bucket","accessKeyId","secretAccessKey"].filter((y)=>!o.s3[y]);if(t.push({name:"S3 config",ok:E.length===0,message:E.length===0?`${o.s3.provider} \u2192 ${o.s3.endpoint}/${o.s3.bucket}`:`Missing: ${E.join(", ")}`}),E.length===0)try{await new Kn(o.s3).listObjects(""),t.push({name:"S3 connectivity",ok:!0,message:"Connected"})}catch(y){t.push({name:"S3 connectivity",ok:!1,message:y.message||"Connection failed"})}let f=mA(dn());t.push({name:"Database",ok:f,message:f?dn():"Not found \u2014 run `agent-fs onboard`"}),t.push({name:"Auth",ok:!!o.auth.apiKey,message:o.auth.apiKey?"API key configured":"No API key \u2014 run `agent-fs onboard`"});let T=o.embedding.provider,A=!!o.embedding.apiKey||!!process.env.OPENAI_API_KEY||!!process.env.GEMINI_API_KEY;if(T==="openai"||T==="gemini")if(A)try{let y=await Yt(o.embedding);t.push({name:"Embeddings",ok:!!y,message:y?`${T} ready`:`${T} configured but failed to init`})}catch(y){t.push({name:"Embeddings",ok:!1,message:y.message})}else t.push({name:"Embeddings",ok:!1,message:`${T} selected but no API key`});else t.push({name:"Embeddings",ok:!0,message:"local/disabled (semantic search may be unavailable)"});console.log(`
|
|
208
209
|
agent-fs health check
|
|
209
|
-
`);let
|
|
210
|
-
${
|
|
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
|
|
210
|
+
`);let N=!0;for(let y of t){let _=y.ok?"\u2713":"\u2717";if(console.log(` ${_} ${y.name}: ${y.message}`),!y.ok)N=!1}if(console.log(),N)console.log("All checks passed.");else console.log("Some checks failed. Fix the issues above and re-run."),process.exit(1)}),n}Q();import{Command as XL}from"commander";function sA(n,t){let o=new XL("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 T=await n.get(`/orgs/${e}/drives`);if(i){console.log(JSON.stringify(T,null,2));return}for(let A of T.drives){let N=A.isDefault?" (default)":"";console.log(`${A.id} ${A.name}${N}`)}return}let{orgs:E}=await n.get("/orgs");if(i){let T=[];for(let A of E){let{drives:N}=await n.get(`/orgs/${A.id}/drives`);T.push({orgId:A.id,orgName:A.name,drives:N})}console.log(JSON.stringify(T,null,2));return}if(!E||E.length===0){console.log("(no orgs)");return}let f=G();for(let T of E){let A=[];if(T.isPersonal)A.push("personal");if(f.defaultOrg===T.id)A.push("active");let N=A.length>0?` (${A.join(", ")})`:"";console.log(`
|
|
211
|
+
${T.name} [${T.role}]${N}`);let{drives:y}=await n.get(`/orgs/${T.id}/drives`);for(let _ of y){let r=[];if(_.isDefault)r.push("default");if(f.defaultDrive===_.id)r.push("active");let L=r.length>0?` (${r.join(", ")})`:"";console.log(` ${_.id} ${_.name}${L}`)}}}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 t(),E=await n.post(`/orgs/${e}/drives`,{name:i});console.log(JSON.stringify(E,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=G(),E=await n.getMe(),f=e.defaultOrg??E.defaultOrgId;if(!f)console.error("Error: No org context. Run 'agent-fs auth register' first."),process.exit(1);let{drives:T}=await n.get(`/orgs/${f}/drives`),A;if(e.defaultDrive)A=T.find((y)=>y.id===e.defaultDrive);if(!A)A=T.find((y)=>y.isDefault)??T[0]??null;let N=e.defaultOrg?"config (org switch)":"server default";if(i)console.log(JSON.stringify({orgId:f,drive:A,source:N},null,2));else console.log(`org: ${f}`),console.log(`drive: ${A?.id??"(none)"} ${A?.name??""}`),console.log(`source: ${N}`)}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 n.get("/orgs"),E=null,f=null;for(let T of e){let{drives:A}=await n.get(`/orgs/${T.id}/drives`),N=A.find((y)=>y.id===i);if(N){E=N,f=T;break}}if(!E)console.error(`Error: Drive ${i} not found in any of your orgs.`),process.exit(1);I("defaultOrg",f.id),I("defaultDrive",i),console.log(`Switched to drive: ${E.name} (org: ${f.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",`
|
|
212
|
+
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 E=await t();await n.post(`/orgs/${E}/members/invite`,{email:i,role:e.role}),console.log(`Invited ${i} as ${e.role}`)}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o}Q();import{Command as CL}from"commander";function cA(n){let t=new CL("org").description("Org management");return t.command("list").description("List orgs you belong to").action(async()=>{let o=t.parent?.opts().json;try{let{orgs:i}=await n.get("/orgs");if(o){console.log(JSON.stringify(i,null,2));return}if(!i||i.length===0){console.log("(no orgs)");return}let e=G();for(let E of i){let f=[];if(E.isPersonal)f.push("personal");if(e.defaultOrg===E.id)f.push("active");let T=f.length>0?` (${f.join(", ")})`:"";console.log(`${E.id} ${E.name} [${E.role}]${T}`)}}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),t.command("current").description("Show current org context").action(async()=>{let o=t.parent?.opts().json;try{let i=G(),e=await n.getMe(),E=i.defaultOrg??e.defaultOrgId;if(!E)console.error("Error: No org context. Run 'agent-fs auth register' first."),process.exit(1);let f=await n.get(`/orgs/${E}`),T=i.defaultOrg?"config (org switch)":"server default";if(o)console.log(JSON.stringify({...f,source:T},null,2));else console.log(`${f.id} ${f.name}${f.isPersonal?" (personal)":""}`),console.log(`source: ${T}`)}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),t.command("switch").argument("<orgId>","Org ID to switch to").description("Set default org context").action(async(o)=>{try{let i=await n.get(`/orgs/${o}`);I("defaultOrg",o),I("defaultDrive",void 0),console.log(`Switched to org: ${i.name} (${o})`)}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),t}import{Command as ZL}from"commander";Q();import{Command as PL}from"commander";import{execSync as Tt}from"child_process";import{existsSync as YL}from"fs";function bo(){return new PL("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(t)=>{if(t.remote)console.error(`Remote mode is not yet supported in the onboard wizard.
|
|
212
213
|
To connect to a remote server, configure manually:
|
|
213
|
-
agent-fs config set api.url "`+
|
|
214
|
-
agent-fs config set api.key "<your-api-key>"`),process.exit(1);let o=
|
|
214
|
+
agent-fs config set api.url "`+t.remote+`"
|
|
215
|
+
agent-fs config set api.key "<your-api-key>"`),process.exit(1);let o=un();if(YL(o)){if(G().auth.apiKey&&!t.yes)console.log("Existing configuration found at "+o),console.log(`Re-running onboard will update settings. Use -y to accept defaults.
|
|
215
216
|
`)}console.log(`Setting up agent-fs...
|
|
216
|
-
`);let e=!(
|
|
217
|
+
`);let e=!(t.s3Endpoint||t.s3Bucket||t.s3AccessKey||t.s3SecretKey);if(t.s3Endpoint){if(I("s3.endpoint",t.s3Endpoint),t.s3Bucket)I("s3.bucket",t.s3Bucket);if(t.s3AccessKey)I("s3.accessKeyId",t.s3AccessKey);if(t.s3SecretKey)I("s3.secretAccessKey",t.s3SecretKey);if(t.s3Region)I("s3.region",t.s3Region);I("s3.provider","s3"),console.log("S3 configured from flags.")}else if(e)await GL(!!t.yes);else await FL();let E=t.embeddings??(t.yes?"none":void 0);if(E)ML(E,t);else if(!t.yes)console.log(`
|
|
217
218
|
Embedding provider not specified. Skipping (semantic search disabled).`),console.log("Configure later: agent-fs config set embedding.provider openai");console.log(`
|
|
218
|
-
Initializing database...`);let
|
|
219
|
-
User registered: ${
|
|
220
|
-
User registered: ${
|
|
219
|
+
Initializing database...`);let f=Wn();if(console.log("Database ready."),e||t.yes){let{apiKey:T}=at(f),A=Dn(f,T),N=z(f,A.id);console.log(`
|
|
220
|
+
User registered: ${A.email}`),console.log(`API Key: ${T}`),console.log(`Org ID: ${N[0]?.id}`)}else{let T=await HL();try{let A=Un(f,{email:T}),N=z(f,A.user.id);I("auth.apiKey",A.apiKey),console.log(`
|
|
221
|
+
User registered: ${T}`),console.log(`API Key: ${A.apiKey}`),console.log(`Org ID: ${N[0]?.id}`)}catch(A){if(A.message?.includes("UNIQUE"))console.log(`User ${T} already exists.`);else throw A}}console.log("\nSetup complete! Run `agent-fs daemon start` to begin."),console.log("Or use MCP directly: agent-fs mcp")})}function ML(n,t){switch(n){case"openai":if(I("embedding.provider","openai"),I("embedding.model","text-embedding-3-small"),t.openaiKey)I("embedding.apiKey",t.openaiKey);console.log("Embeddings: OpenAI (text-embedding-3-small)");break;case"gemini":if(I("embedding.provider","gemini"),I("embedding.model","text-embedding-004"),t.geminiKey)I("embedding.apiKey",t.geminiKey);console.log("Embeddings: Google Gemini (text-embedding-004)");break;case"local":I("embedding.provider","local"),console.log("Embeddings: local llama.cpp");break;case"none":I("embedding.provider","local"),I("embedding.model",""),I("embedding.apiKey",""),console.log("Embeddings: disabled (semantic search unavailable)");break;default:console.error(`Unknown embedding provider: ${n}`),console.error("Valid options: openai, gemini, local, none"),process.exit(1)}}async function GL(n){try{Tt("which docker",{stdio:"ignore"}),Tt("docker info",{stdio:"ignore"})}catch{console.error(`Docker is required for local mode (MinIO).
|
|
221
222
|
Install Docker: https://docs.docker.com/get-docker/
|
|
222
|
-
Or use 'agent-fs onboard --s3-endpoint <url>' to configure your own S3 bucket.`),process.exit(1)}let
|
|
223
|
-
Edit with: agent-fs config set s3.endpoint <url>`)}async function
|
|
224
|
-
`),await
|
|
223
|
+
Or use 'agent-fs onboard --s3-endpoint <url>' to configure your own S3 bucket.`),process.exit(1)}let t=Tt("docker ps -a --filter name=agent-fs-minio --format '{{.Names}}'",{encoding:"utf-8"}).trim();if(t==="agent-fs-minio")console.log("Found existing MinIO container (agent-fs-minio).");if(!n){let o=t==="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 E=new TextDecoder().decode(e).trim().toLowerCase();if(E==="n"||E==="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(t==="agent-fs-minio")Tt("docker start agent-fs-minio",{stdio:"inherit"}),console.log("MinIO container started.");else Tt('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{Tt("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=Tt("docker inspect --format='{{.Id}}' agent-fs-minio",{encoding:"utf-8"}).trim();I("minio.containerId",o),I("minio.managed",!0)}catch(o){console.error(`Failed to set up MinIO: ${o.message}`),process.exit(1)}I("s3.provider","minio"),I("s3.endpoint","http://localhost:9000"),I("s3.bucket","agentfs"),I("s3.region","us-east-1"),I("s3.accessKeyId","minioadmin"),I("s3.secretAccessKey","minioadmin"),console.log("MinIO configured.")}async function FL(){let n=G();console.log("Using S3 configuration from ~/.agent-fs/config.json"),console.log(` Provider: ${n.s3.provider}`),console.log(` Endpoint: ${n.s3.endpoint}`),console.log(` Bucket: ${n.s3.bucket}`),console.log(`
|
|
224
|
+
Edit with: agent-fs config set s3.endpoint <url>`)}async function HL(){process.stdout.write("Email for first user: ");let n=Bun.stdin.stream().getReader(),{value:t}=await n.read();return n.releaseLock(),new TextDecoder().decode(t).trim()||"local@agent-fs.local"}function aA(){let n=bo(),t=new ZL("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'.
|
|
225
|
+
`),await n.parseAsync(i.args,{from:"user"})});for(let o of n.options)t.addOption(o);return t}import{Command as QL}from"commander";function nN(n,t){let o=new QL("comment").description("Document comments");async function i(e,E){try{return await n.callOp(await t(),e,E)}catch(f){if(f?.cause?.code==="ECONNREFUSED"||f?.message?.includes("fetch failed"))console.error(`Cannot connect to agent-fs daemon.
|
|
225
226
|
Start with: agent-fs daemon start
|
|
226
|
-
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);throw
|
|
227
|
+
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);throw f}}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,E)=>{try{let f={path:e,body:E.body};if(E.quotedContent)f.quotedContent=E.quotedContent;if(E.line)f.lineStart=parseInt(E.line),f.lineEnd=parseInt(E.line);if(E.lineStart)f.lineStart=parseInt(E.lineStart);if(E.lineEnd)f.lineEnd=parseInt(E.lineEnd);let T=await i("comment-add",f);console.log(JSON.stringify(T,null,2))}catch(f){console.error(`Error: ${f.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,E)=>{try{let f=await i("comment-add",{parentId:e,body:E.body});console.log(JSON.stringify(f,null,2))}catch(f){console.error(`Error: ${f.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,E)=>{try{let f={};if(e)f.path=e;if(E.resolved)f.resolved=!0;if(E.limit)f.limit=parseInt(E.limit);if(E.offset)f.offset=parseInt(E.offset);let T=await i("comment-list",f);console.log(JSON.stringify(T,null,2))}catch(f){console.error(`Error: ${f.message}`),process.exit(1)}}),o.command("get").argument("<id>","Comment ID").description("Get a comment with its replies").action(async(e)=>{try{let E=await i("comment-get",{id:e});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("update").argument("<id>","Comment ID").requiredOption("--body <text>","New comment body").description("Update a comment").action(async(e,E)=>{try{let f=await i("comment-update",{id:e,body:E.body});console.log(JSON.stringify(f,null,2))}catch(f){console.error(`Error: ${f.message}`),process.exit(1)}}),o.command("delete").argument("<id>","Comment ID").description("Delete a comment (soft delete)").action(async(e)=>{try{let E=await i("comment-delete",{id:e});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("resolve").argument("<id>","Comment ID").description("Resolve a comment").action(async(e)=>{try{let E=await i("comment-resolve",{id:e,resolved:!0});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("reopen").argument("<id>","Comment ID").description("Reopen a resolved comment").action(async(e)=>{try{let E=await i("comment-resolve",{id:e,resolved:!1});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o}import{Command as JL}from"commander";function oN(n,t){let o=new JL("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 E=await t(),f=e?`/orgs/${E}/drives/${e}/members`:`/orgs/${E}/members`,{members:T}=await n.get(f);if(i){console.log(JSON.stringify(T,null,2));return}if(!T||T.length===0){console.log("(no members)");return}for(let A of T)console.log(`${A.email} [${A.role}]`)}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").action(async(i,e)=>{try{let E=await t();await n.post(`/orgs/${E}/members/invite`,{email:i,role:e.role}),console.log(`Invited ${i} as ${e.role}`)}catch(E){console.error(`Error: ${E.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 E=o.parent?.opts().drive;try{let f=await t(),T=await tN(n,f,i,E);if(E)await n.patch(`/orgs/${f}/drives/${E}/members/${T}`,{role:e.role});else await n.patch(`/orgs/${f}/members/${T}`,{role:e.role});let A=E?`drive ${E}`:"org";console.log(`Updated ${i} to ${e.role} (${A})`)}catch(f){console.error(`Error: ${f.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 E=await t(),f=await tN(n,E,i,e);if(e)await n.del(`/orgs/${E}/drives/${e}/members/${f}`),console.log(`Removed ${i} from drive ${e}`);else await n.del(`/orgs/${E}/members/${f}`),console.log(`Removed ${i} from org`)}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o}async function tN(n,t,o,i){let e=i?`/orgs/${t}/drives/${i}/members`:`/orgs/${t}/members`,{members:E}=await n.get(e),f=E.find((T)=>T.email===o);if(!f)throw Error(`Member with email ${o} not found`);return f.userId}import{Command as WL}from"commander";var iN=`---
|
|
227
228
|
name: agent-fs
|
|
228
229
|
description: >-
|
|
229
230
|
Use when the user wants to store, retrieve, search, or manage files in agent-fs \u2014
|
|
@@ -234,7 +235,10 @@ description: >-
|
|
|
234
235
|
"update role", file persistence for agents, shared agent filesystem, or any
|
|
235
236
|
mention of the agent-fs CLI. Also use when the user needs to manage drives,
|
|
236
237
|
manage org/drive members, generate presigned URLs, check recent activity, or use
|
|
237
|
-
semantic search across stored files. Also use when the user wants to
|
|
238
|
+
semantic search across stored files. Also use when the user wants to run SQL
|
|
239
|
+
over stored data files ("query this csv", "sql over my files", "duckdb",
|
|
240
|
+
"aggregate the parquet file", "query the sqlite db", "join these spreadsheets").
|
|
241
|
+
Also use when the user wants to mount or
|
|
238
242
|
unmount agent-fs as a Linux FUSE filesystem ("mount agent-fs", "fuse mount",
|
|
239
243
|
"fuse", "remote mount", "sandbox mount", "expose drives as files",
|
|
240
244
|
"use cat/grep/mv on my agent-fs files", "umount the drive", "mount a remote
|
|
@@ -363,6 +367,14 @@ symlinks are unsupported and throw \`EPERM\`.
|
|
|
363
367
|
- \`search\` \u2014 general-purpose search combining keywords and meaning (recommended default)
|
|
364
368
|
- \`vec-search\` \u2014 pure semantic search when you want conceptual matches only
|
|
365
369
|
|
|
370
|
+
### SQL Queries (DuckDB)
|
|
371
|
+
|
|
372
|
+
| Command | Usage | Description |
|
|
373
|
+
|---------|-------|-------------|
|
|
374
|
+
| \`sql\` | \`agent-fs sql <query> [-t name=path[:format]]... [--max-rows <n>]\` | Run DuckDB SQL over stored documents |
|
|
375
|
+
|
|
376
|
+
Supported formats: csv, tsv, parquet, xlsx, json, ndjson/jsonl (each also \`.gz\` except parquet/xlsx), sqlite (\`.db\`/\`.sqlite\`/\`.sqlite3\`), and \`.duckdb\`. Reference file-format documents directly by quoted drive path inside the query, or bind any document to a table name with \`-t\`. SQLite/DuckDB databases require a \`-t\` binding and expose their tables as \`<name>.<table>\`. Append \`:format\` to a binding to query documents with non-standard extensions (e.g. \`-t logs=/raw/data.txt:csv\`). Queries are sandboxed \u2014 no host filesystem or network access. Results cap at \`--max-rows\` (default 1000, max 10000); \`truncated: true\` in JSON output signals more rows exist.
|
|
377
|
+
|
|
366
378
|
### Comments
|
|
367
379
|
|
|
368
380
|
| Command | Usage | Description |
|
|
@@ -395,15 +407,19 @@ symlinks are unsupported and throw \`EPERM\`.
|
|
|
395
407
|
|
|
396
408
|
The \`--drive\` flag is a global option \u2014 place it before the subcommand: \`agent-fs --drive <id> member list\`.
|
|
397
409
|
|
|
410
|
+
Member commands are admin-gated: org-scoped commands require org \`admin\`; drive-scoped commands (\`--drive <id>\`) require drive \`admin\` or admin of the owning org, and the drive must belong to the current org. Non-admins get a permission error; org/drive IDs outside your memberships return "not found".
|
|
411
|
+
|
|
398
412
|
### Drive Management
|
|
399
413
|
|
|
400
414
|
| Command | Usage | Description |
|
|
401
415
|
|---------|-------|-------------|
|
|
402
416
|
| \`drive list\` | \`agent-fs drive list\` | List drives in current org |
|
|
403
|
-
| \`drive create\` | \`agent-fs drive create <name>\` | Create a new drive |
|
|
417
|
+
| \`drive create\` | \`agent-fs drive create <name>\` | Create a new drive (requires org admin) |
|
|
404
418
|
| \`drive current\` | \`agent-fs drive current\` | Show current drive context |
|
|
405
419
|
| \`drive invite\` | \`agent-fs drive invite <email> --role <role>\` | Invite user (viewer/editor/admin) |
|
|
406
420
|
|
|
421
|
+
Drive membership is explicit: \`drive list\` shows only drives you're a member of. Creating a drive automatically grants you admin membership on it; other users must be invited per drive (or via org invite, which grants access to the default drive).
|
|
422
|
+
|
|
407
423
|
### Config & Daemon
|
|
408
424
|
|
|
409
425
|
| Command | Usage | Description |
|
|
@@ -424,6 +440,8 @@ Two topologies are supported:
|
|
|
424
440
|
- **Local mode** (default): helper talks to a local daemon over a Unix socket. Daemon must be running and have an S3 backend configured.
|
|
425
441
|
- **Remote mode** (\`--remote\`): helper talks directly to a remote agent-fs HTTP API. No local daemon required \u2014 ideal for sandboxes (sprite, E2B, Hetzner VMs, GitHub Actions runners) that can reach a hosted agent-fs but can't run the full daemon stack.
|
|
426
442
|
|
|
443
|
+
FUSE writes require the \`editor\` role or better on the drive \u2014 on drives where you're a \`viewer\`, the mount is read-only for file writes (writes fail with \`EACCES\`; check \`<mount>/.agent-fs/errors.ndjson\` for the \`PERMISSION_DENIED\` record).
|
|
444
|
+
|
|
427
445
|
| Command | Usage | Description |
|
|
428
446
|
|---------|-------|-------------|
|
|
429
447
|
| \`mount\` | \`agent-fs mount <path> [--allow-other] [--foreground]\` | Mount drives at \`<path>\` via local daemon (e.g. \`/mnt/agent-fs/<drive>/\`). |
|
|
@@ -465,6 +483,23 @@ agent-fs search "financial performance metrics" --limit 5
|
|
|
465
483
|
agent-fs vec-search "financial performance metrics" --limit 5
|
|
466
484
|
\`\`\`
|
|
467
485
|
|
|
486
|
+
### Query data files with SQL
|
|
487
|
+
|
|
488
|
+
\`\`\`bash
|
|
489
|
+
# Query a CSV directly by path
|
|
490
|
+
agent-fs sql "SELECT category, sum(amount) AS total FROM '/finance/2026.csv' GROUP BY category" --json
|
|
491
|
+
|
|
492
|
+
# Join documents of different formats
|
|
493
|
+
agent-fs sql "SELECT s.name, t.tag FROM sales s JOIN tags t ON s.id = t.id" \\
|
|
494
|
+
-t sales=/data/sales.csv -t tags=/data/tags.parquet
|
|
495
|
+
|
|
496
|
+
# Query a stored SQLite database (tables exposed as app.<table>)
|
|
497
|
+
agent-fs sql "SELECT count(*) FROM app.users" -t app=/backups/app.db
|
|
498
|
+
|
|
499
|
+
# Pipe a query via stdin
|
|
500
|
+
echo "SELECT count(*) FROM '/data/events.ndjson'" | agent-fs sql
|
|
501
|
+
\`\`\`
|
|
502
|
+
|
|
468
503
|
### Review and revert changes
|
|
469
504
|
|
|
470
505
|
\`\`\`bash
|
|
@@ -553,7 +588,7 @@ agent-fs signed-url docs/report.pdf --json
|
|
|
553
588
|
# \u2192 { "url": "https://...", "path": "/docs/report.pdf", "expiresIn": 86400, "expiresAt": "2026-03-20T..." }
|
|
554
589
|
\`\`\`
|
|
555
590
|
|
|
556
|
-
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.
|
|
591
|
+
The presigned URL requires no authentication \u2014 anyone with the link can download the file until it expires. Access is RBAC-checked only at generation time (viewer-or-better on the drive); after that the URL is a bearer secret. Don't log it or paste it anywhere you wouldn't paste a credential, and prefer the shortest workable \`--expires-in\`. 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.
|
|
557
592
|
|
|
558
593
|
**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.
|
|
559
594
|
|
|
@@ -603,15 +638,25 @@ fusermount3 -u ~/mnt
|
|
|
603
638
|
\`\`\`
|
|
604
639
|
|
|
605
640
|
See \`docs/mounting/\` for per-environment guides (sprite, E2B, Hetzner).
|
|
606
|
-
`;function
|
|
641
|
+
`;function eN(){return new WL("docs").description("Show agent-fs documentation and command reference").action(()=>{let n=iN.replace(/^---[\s\S]*?---\n*/,"");console.log(n)})}Q();import{Command as _N}from"commander";import{existsSync as Jn,readFileSync as wN,writeFileSync as zL,unlinkSync as pL,statSync as qL,readdirSync as bL}from"fs";import{dirname as dL,join as zn}from"path";import{fileURLToPath as mL}from"url";import{spawn as AN}from"child_process";import{existsSync as qe}from"fs";import{join as VL}from"path";import{createRequire as KL}from"module";var vL={x64:"@desplega.ai/agent-fs-fuse-linux-x64",arm64:"@desplega.ai/agent-fs-fuse-linux-arm64"};function EN(){let n=process.env.AGENT_FS_FUSE_BIN;if(n){if(!qe(n))throw Error(`AGENT_FS_FUSE_BIN is set to '${n}' but no file exists there. Did you build the helper? Run: cd packages/fuse-helper && cargo build --release`);return{binPath:n,source:"env"}}let t=process.arch,o=vL[t];if(o)try{let E=KL(import.meta.url).resolve(`${o}/package.json`).replace(/[\\/]package\.json$/,""),f=VL(E,"bin","agent-fs-fuse");if(qe(f))return{binPath:f,source:"subpackage"}}catch{}throw Error(`FUSE helper not found.
|
|
607
642
|
`+" \u2022 Linux: `npm install -g @desplega.ai/agent-fs` should have installed "+`\`${o??"agent-fs-fuse-linux-<arch>"}\` automatically.
|
|
608
|
-
`+" \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
|
|
609
|
-
`),e=parseInt(o,10);if(!Number.isFinite(e))return{running:!1};try{process.kill(e,0)}catch{return{running:!1}}let
|
|
610
|
-
`).trim()||void 0;return{running:!0,pid:e,mountpoint:
|
|
611
|
-
${
|
|
612
|
-
`)}function
|
|
643
|
+
`+" \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 fN(n,t){if(!qe(t))return null;let o=process.arch==="x64"?"linux-x64":`linux-${process.arch}`;try{let e=JSON.parse(await Bun.file(t).text()).binaries?.[o];if(!e)return null;let E=e.replace(/^sha256:/,""),f=new Bun.CryptoHasher("sha256");f.update(await Bun.file(n).bytes());let T=f.digest("hex");if(T!==E)return`binary hash mismatch \u2014 expected ${E}, got ${T}`;return null}catch(i){return`manifest verification failed: ${String(i?.message??i)}`}}function uN(n){let{mode:t,mountpoint:o,socket:i,apiUrl:e,apiKey:E,allowOther:f,logFile:T}=n;if(!o)throw Error("buildHelperSpawnArgs: mountpoint is required");if(t==="remote"){if(i)throw Error("Cannot combine --remote with --socket \u2014 they select different transports. "+"Drop --socket to use remote HTTP transport.");if(!e||!E)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||E)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 A=["--mountpoint",o];if(t==="remote")A.push("--api-url",e);else A.push("--socket",i);if(T)A.push("--log-file",T);if(f)A.push("--allow-other");let N={};if(t==="remote")N.AGENT_FS_API_KEY=E;return{argv:A,env:N}}import{existsSync as jL,readFileSync as kL}from"fs";function hL(n){if(!n||!jL(n))return{};try{let t=kL(n,"utf-8");return JSON.parse(t)}catch{return{}}}function TN(n,t,o){let i=hL(t),e=i.apiKey??i.auth?.apiKey,E=n.apiUrl??o.AGENT_FS_API_URL??i.apiUrl,f=n.apiKey??o.AGENT_FS_API_KEY??e;if(!E||!f)return null;let T=n.apiUrl?"flag":o.AGENT_FS_API_URL?"env":"config",A=n.apiKey?"flag":o.AGENT_FS_API_KEY?"env":"config";return{apiUrl:E,apiKey:f,source:{apiUrl:T,apiKey:A}}}function be(){return zn(k(),"mount.pid")}function NN(){return zn(k(),"mount.log")}function xL(){return zn(k(),"agent-fs.sock")}function yN(){let n=(()=>{try{let o=mL(import.meta.url),i=dL(o),e=[zn(i,"fuse-bin.manifest.json"),zn(i,"..","fuse-bin.manifest.json"),zn(i,"..","..","dist","fuse-bin.manifest.json")];for(let E of e)if(Jn(E))return E;return e[0]}catch{return""}})(),t=zn(k(),"fuse-bin.manifest.json");if(n&&Jn(n))return n;if(Jn(t))return t;return n||t}function de(){let n=be();if(!Jn(n))return{running:!1};let t=wN(n,"utf-8").trim(),[o,...i]=t.split(`
|
|
644
|
+
`),e=parseInt(o,10);if(!Number.isFinite(e))return{running:!1};try{process.kill(e,0)}catch{return{running:!1}}let E=i.join(`
|
|
645
|
+
`).trim()||void 0;return{running:!0,pid:e,mountpoint:E}}function RN(n,t){zL(be(),`${n}
|
|
646
|
+
${t}
|
|
647
|
+
`)}function rN(){let n=be();if(Jn(n))try{pL(n)}catch{}}function LN(){let n=new _N("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(t,o)=>{if(!t){n.help();return}await sL(t,o)});return n.command("status").description("Show the current mount's PID and mountpoint").action(async()=>{let t=de();if(!t.running){console.log("Mount is not running");return}if(console.log(`Mount PID: ${t.pid}`),t.mountpoint)console.log(`Mountpoint: ${t.mountpoint}`);let o=t.mountpoint?zn(t.mountpoint,".agent-fs","status"):null;if(o&&Jn(o))try{console.log(`Status: ${wN(o,"utf-8").trim()}`)}catch{}}),n}function UN(){return new _N("umount").description("Unmount a previously-mounted agent-fs FUSE filesystem").argument("<path>","Directory the filesystem is mounted at").action(async(n)=>{await cL(n)})}async function sL(n,t){let o=n;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(!Jn(o))console.error(`Mountpoint does not exist: ${o}`),process.exit(1);try{if(!qL(o).isDirectory())console.error(`Mountpoint is not a directory: ${o}`),process.exit(1)}catch(U){console.error(`Cannot stat mountpoint: ${U.message}`),process.exit(1)}try{if(bL(o).length>0)console.error(`Mountpoint is not empty: ${o}`),process.exit(1)}catch(U){console.error(`Cannot read mountpoint: ${U.message}`),process.exit(1)}let i=de();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(t.remote||t.apiUrl||t.apiKey);if(e&&t.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 E="local",f,T,A;if(e){if(t.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 U=TN({apiUrl:t.apiUrl,apiKey:t.apiKey},un(),{AGENT_FS_API_URL:process.env.AGENT_FS_API_URL,AGENT_FS_API_KEY:process.env.AGENT_FS_API_KEY});if(!U)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);E="remote",f=U.apiUrl,T=U.apiKey}else if(A=t.socket??xL(),!Jn(A))console.error(`Daemon socket not found at ${A}.`),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 N;try{N=EN()}catch(U){console.error(U.message),process.exit(1)}let y=await fN(N.binPath,yN());if(y)console.error(`Refusing to spawn helper: ${y}`),process.exit(1);if(!Jn(yN()))console.error("Warning: no fuse-bin.manifest.json found \u2014 skipping hash verification.");let _;try{_=uN({mode:E,mountpoint:o,socket:A,apiUrl:f,apiKey:T,allowOther:t.allowOther,foreground:t.foreground,logFile:NN()})}catch(U){console.error(U.message),process.exit(1)}let r={...process.env,..._.env};if(t.foreground){let U=AN(N.binPath,_.argv,{stdio:"inherit",env:r});if(U.on("exit",(g)=>{rN(),process.exit(g??0)}),U.pid)RN(U.pid,o);return}let L=AN(N.binPath,_.argv,{detached:!0,stdio:"ignore",env:r});if(L.pid===void 0)console.error("Failed to spawn FUSE helper."),process.exit(1);RN(L.pid,o),L.unref();let S=E==="remote"?`remote: ${f}`:`socket: ${A}`;console.log(`Mount started (PID: ${L.pid}, ${N.source}, ${S})`),console.log(`Mountpoint: ${o}`),console.log(`Logs: ${NN()}`)}async function cL(n){if(process.platform!=="linux")console.error("FUSE umount is Linux-only."),process.exit(1);let t=de();if(t.running&&t.pid!==void 0)try{process.kill(t.pid,"SIGTERM"),console.log(`Sent SIGTERM to mount helper (PID: ${t.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",n]}).exitCode===0){console.log(`Unmounted ${n} (via ${o})`);break}}catch{}rN()}import{Command as aL}from"commander";function DN(n,t,o){let i=new aL("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,E)=>{try{let f=await t(),T=await o(f),A=await n.getRaw(f,T,e);if(E.output){if(await Bun.write(E.output,A.bytes),i.parent?.opts().json)console.log(JSON.stringify({path:e,output:E.output,size:A.bytes.byteLength,contentType:A.contentType,version:A.version,contentHash:A.contentHash},null,2));else console.log(`wrote ${E.output} (${A.bytes.byteLength} bytes)`);return}process.stdout.write(Buffer.from(A.bytes))}catch(f){console.error(`Error: ${f.message}`),process.exit(1)}});return i}Q();import{Command as nU}from"commander";var tU=new Set(["csv","tsv","parquet","xlsx","json","ndjson","sqlite","duckdb"]);function oU(n){let t=n.indexOf("=");if(t<=0)throw Error(`Invalid --table binding: ${n} (expected name=path[:format])`);let o=n.slice(0,t),i=n.slice(t+1),e=i.lastIndexOf(":");if(e>0){let E=i.slice(e+1).toLowerCase();if(tU.has(E))return{name:o,value:{path:i.slice(0,e),format:E}}}return{name:o,value:i}}function SN(n,t,o){return new nU("sql").description(Yn("sql")?.description??"Run a DuckDB SQL query over documents stored in the drive").argument("[query]","SQL query (reads stdin if omitted)").option("-t, --table <name=path[:format]>","Bind a document as a named table (repeatable). Append :format to override detection, e.g. logs=/raw/data.txt:csv",(e,E)=>[...E,e],[]).option("--max-rows <n>","Max rows to return (default: 1000, max: 10000)").addHelpText("after",`
|
|
648
|
+
Examples:
|
|
649
|
+
agent-fs sql "SELECT * FROM '/data/sales.csv' LIMIT 10"
|
|
650
|
+
agent-fs sql "SELECT s.name, t.tag FROM sales s JOIN tags t ON s.id = t.id" \\
|
|
651
|
+
-t sales=/data/sales.csv -t tags=/data/tags.parquet
|
|
652
|
+
agent-fs sql "SELECT * FROM app.users" -t app=/backups/app.db
|
|
653
|
+
agent-fs sql "SELECT sum(a) FROM logs" -t logs=/raw/data.txt:csv
|
|
654
|
+
echo "SELECT count(*) FROM '/data/events.ndjson'" | agent-fs sql
|
|
655
|
+
`).action(async(e,E)=>{let f=e;if(f===void 0){if(!process.stdin.isTTY)f=(await Bun.stdin.text()).trim();if(!f)console.error("Error: query required (as argument or via stdin)"),process.exit(1)}let T={query:f};if(E.table.length>0){let A={};for(let N of E.table)try{let{name:y,value:_}=oU(N);A[y]=_}catch(y){console.error(`Error: ${y.message}`),process.exit(1)}T.tables=A}if(E.maxRows!==void 0)T.maxRows=parseInt(E.maxRows);try{let A=await o(),N=n.opts().drive??G().defaultDrive;if(N)T.driveId=N;let y=await t.callOp(A,"sql",T);oo("sql",y,n.opts().json)}catch(A){if(A?.cause?.code==="ECONNREFUSED"||A?.message?.includes("fetch failed"))console.error(`Cannot connect to agent-fs daemon.
|
|
656
|
+
Start with: agent-fs daemon start
|
|
657
|
+
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);console.error(`Error: ${A.message}`),process.exit(1)}})}var V=new KU;V.name("agent-fs").description("Agent-first filesystem backed by S3").version(en).option("--org <orgId>","Override org context").option("--drive <driveId>","Override drive context").option("--json","Output raw JSON");var ln=new je;async function At(){let n=V.opts().org;if(n)return n;let t=G();if(t.defaultOrg)return t.defaultOrg;try{let o=await ln.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 ny(n){let t=V.opts().drive;if(t)return t;let o=G();if(o.defaultDrive)return o.defaultDrive;let i=n??await At(),e=await ln.getMe();if(e.defaultOrgId===i&&e.defaultDriveId)return e.defaultDriveId;let{drives:E}=await ln.get(`/orgs/${i}/drives`),f=E.find((T)=>T.isDefault)??E[0];if(!f)console.error("Error: No drive context. Use --drive or run 'agent-fs drive create'."),process.exit(1);return f.id}V.addCommand(eN());zA(V,ln,At,ny);V.addCommand(DN(ln,At,ny));V.addCommand(SN(V,ln,At));V.addCommand(qA(ln));V.addCommand(dA());V.addCommand(xA());V.addCommand(sA(ln,At));V.addCommand(cA(ln));V.addCommand(aA());V.addCommand(bo());V.addCommand(nN(ln,At));V.addCommand(oN(ln,At));V.addCommand(LN());V.addCommand(UN());V.command("mcp").description("Start MCP server (stdio)").action(async()=>{await lN().then(() => yU)});V.command("server").description("Run server in foreground (dev mode)").action(async()=>{await aN().then(() => VU)});var vU=`
|
|
613
658
|
Global Options:
|
|
614
659
|
--org <orgId> Override org context
|
|
615
660
|
--drive <driveId> Override drive context
|
|
616
661
|
--json Output raw JSON
|
|
617
|
-
`;for(let
|
|
662
|
+
`;for(let n of V.commands)n.addHelpText("after",vU);V.parse();
|