@rizom/brain 0.2.0-alpha.749 → 0.2.0-alpha.750
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +11 -11
- package/dist/chunks/app-7e5m9g6k.js +5 -0
- package/dist/chunks/{index-sw6zmn97.js → index-18gtvkxj.js} +2 -2
- package/dist/chunks/{index-dz05sh35.js → index-68ge01gj.js} +6 -6
- package/dist/chunks/{index-dz05sh35.js.map → index-68ge01gj.js.map} +6 -6
- package/dist/chunks/{index-k8mhqgy0.js → index-dv5k8aft.js} +3 -3
- package/dist/chunks/{index-k8mhqgy0.js.map → index-dv5k8aft.js.map} +1 -1
- package/dist/chunks/{index-tchhjqm2.js → index-g3c3c3y0.js} +2 -2
- package/dist/chunks/{index-key3y4em.js → index-ppg0xa7k.js} +2 -2
- package/dist/chunks/{index-qfgnh1b2.js → index-q6pcp7gc.js} +4 -4
- package/dist/chunks/{index-qfgnh1b2.js.map → index-q6pcp7gc.js.map} +4 -4
- package/dist/chunks/{package-zw8n5jm7.js → package-6203jv7y.js} +3 -3
- package/dist/chunks/{package-zw8n5jm7.js.map → package-6203jv7y.js.map} +1 -1
- package/dist/entities.js +1 -1
- package/dist/git-broker.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +6 -6
- package/dist/model.js.map +4 -4
- package/dist/services.js +1 -1
- package/dist/testing.js +1 -1
- package/dist/ui/studio-chunks/main-5ndk80hz.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/app-32s4n60w.js +0 -5
- /package/dist/chunks/{app-32s4n60w.js.map → app-7e5m9g6k.js.map} +0 -0
- /package/dist/chunks/{index-sw6zmn97.js.map → index-18gtvkxj.js.map} +0 -0
- /package/dist/chunks/{index-tchhjqm2.js.map → index-g3c3c3y0.js.map} +0 -0
- /package/dist/chunks/{index-key3y4em.js.map → index-ppg0xa7k.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./index-p39p7p8h.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.
|
|
2
|
+
import"./index-p39p7p8h.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.750",r={"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},a={"@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/react":"^19.2.17",typescript:"^7.0.2"},c=["src"],p="./src/index.ts",l="./src/index.ts",o=!0,k={dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},d="module",b="./src/index.ts",w={name:n,license:i,version:t,dependencies:r,devDependencies:a,files:c,main:p,module:l,private:o,scripts:k,type:d,types:b};export{w as default,r as dependencies,a as devDependencies,c as files,i as license,p as main,l as module,n as name,o as private,k as scripts,d as type,b as types,t as version};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
5
|
-
//# sourceMappingURL=package-
|
|
4
|
+
//# debugId=507504FF8748929B64756E2164756E21
|
|
5
|
+
//# sourceMappingURL=package-6203jv7y.js.map
|
package/dist/entities.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-624fhq2j.js";import{Gc as m,de as p,lh as t,ph as x,qh as a,rh as b,sh as c,th as d,uh as g}from"./chunks/index-
|
|
2
|
+
import"./chunks/index-624fhq2j.js";import{Gc as m,de as p,lh as t,ph as x,qh as a,rh as b,sh as c,th as d,uh as g}from"./chunks/index-q6pcp7gc.js";import{Dm as f}from"./chunks/index-9881eck9.js";import"./chunks/index-nwdvz1vw.js";import"./chunks/index-6gqg29bj.js";import{Tx as e}from"./chunks/index-7ne5672k.js";import"./chunks/index-amf6s7a5.js";import"./chunks/index-p39p7p8h.js";export{m as ProjectionJsonObjectSchema,f as defineChannel,t as defineDashboardWidget,x as defineDataSource,a as defineEntity,b as defineEntityAnalyticsReport,c as defineEntityJob,g as defineEntityPackage,d as defineProjection,p as defineProjectionRule,e as z};
|
|
3
3
|
|
|
4
4
|
//# debugId=0FFE4A80C65C5FE664756E2164756E21
|
|
5
5
|
//# sourceMappingURL=entities.js.map
|
package/dist/git-broker.js
CHANGED
|
@@ -328,5 +328,5 @@ ${t}:`]}}function q2e(e){switch(e){case"stop":return"stop";case"length":return"l
|
|
|
328
328
|
*...and ${e.files.length-10} more files*`)}if(e.exists&&e.stats.totalFiles===0)t.push(`
|
|
329
329
|
## Getting Started
|
|
330
330
|
`),t.push("Your sync directory is empty. Entities will be organized as follows:"),t.push("- Base entities: `/<entity-id>.md`"),t.push("- Other types: `/<entity-type>/<entity-id>.md`");return t.join(`
|
|
331
|
-
`)}}class M1{schema=Joe;logger;directorySync;operationStatus;constructor(e,t,n,r){this.logger=e,this.directorySync=n,this.operationStatus=r}async process(e,t,n){this.logger.debug("Processing directory export job",{jobId:t,data:e});let r=Date.now();try{let o=await this.directorySync.exportEntitiesWithProgress(e.entityTypes,n,e.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:t,exported:o.exported,failed:o.failed,duration:Date.now()-r}),await this.operationStatus?.addExportResult(o),o}catch(o){throw this.logger.error("Directory export job failed",{jobId:t,error:o}),await this.operationStatus?.recordIssue({kind:"export",message:de(o,"Directory export failed")}),o}}summarizeDataForLog(e){return{entityTypes:e.entityTypes??"all",batchSize:e.batchSize}}}function wI(e,t,n,r){let o=t.projectionBatch;if(!o)return r();return e.bulkMutations.runDurableBulkMutationChild({source:"directory-sync",operationId:o.operationId,rootJobId:o.rootJobId,childKey:o.childKey,expectedChildren:o.expectedChildren,jobId:n},r)}async function $m(e,t,n,r){let o=t.projectionBatch;if(!o)return;await e.bulkMutations.settleDurableBulkMutationChild({operationId:o.operationId,childKey:o.childKey,jobId:n,outcome:r})}class j1{schema=Woe;logger;directorySync;context;operationStatus;reconciliation;constructor(e,t,n,r,o){this.logger=e,this.context=t,this.directorySync=n,this.operationStatus=r,this.reconciliation=o}async process(e,t,n){return this.logger.debug("Processing directory import job",{jobId:t,data:e}),wI(this.context,e,t,async()=>{await this.refuseUnregisteredEntityTypes(e,t);let r=Date.now();try{let o=await this.directorySync.importEntitiesWithProgress(e.paths,n,e.batchSize??100,e.projectionBatch,e.plan);return this.logger.debug("Directory import job completed",{jobId:t,imported:o.imported,skipped:o.skipped,failed:o.failed,quarantined:o.quarantined,duration:Date.now()-r}),await this.operationStatus?.addImportResult(o),o}catch(o){throw this.logger.error("Directory import job failed",{jobId:t,error:o}),await this.operationStatus?.recordIssue({kind:"import",message:de(o,"Directory import failed")}),o}})}async refuseUnregisteredEntityTypes(e,t){let n=(e.entityTypes??[]).filter((o)=>!this.context.entityService.hasEntityType(o));if(n.length===0)return;let r=`Directory import needs entity types this process does not register: ${n.join(", ")}`;throw this.logger.warn(r,{jobId:t}),await this.reconciliation?.requireFullScan(),await this.operationStatus?.recordIssue({kind:"import",message:r}),Error(r)}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}summarizeDataForLog(e){return{pathCount:e.paths?.length??"all",batchSize:e.batchSize}}}ni();var A5t=300000,P5t=500;async function pVe(e){let t={...e,jobIds:e.jobIds.filter((c)=>c!=="")};if(t.jobIds.length===0)return;let n=t.maxWaitMs??A5t,r=t.pollIntervalMs??P5t;t.logger.debug(`Waiting for ${t.jobIds.length} import jobs to complete`);let o=te.gen(function*(){let c=yield*Wl.currentTimeMillis;yield*te.gen(function*(){let d=(yield*te.tryPromise({try:()=>Promise.all(t.jobIds.map((f)=>t.entityService.getAsyncJobStatus(f))),catch:(f)=>f})).filter((f)=>f&&(f.status==="completed"||f.status==="failed")).length;if(d===t.jobIds.length)return t.logger.debug("All import jobs completed"),!0;if((yield*Wl.currentTimeMillis)-c>n)return t.logger.warn(`Timeout waiting for import jobs (${d}/${t.jobIds.length} completed)`),!0;let m=Math.round(d/t.jobIds.length*100);return yield*te.tryPromise({try:()=>t.reporter.report({progress:50+Math.round(m*0.05),message:`Processing ${d}/${t.jobIds.length} entities`}),catch:(f)=>f}),!1}).pipe(te.repeat({schedule:oa.spaced(r),until:(l)=>l}))}),s=la(o,t.clock),a=await te.runPromiseExit(s);if(Jt.isFailure(a))throw qn.squash(a.cause)}class $1{schema=Goe;logger;getDirectorySync;context;constructor(e,t,n){this.logger=e,this.context=t,this.getDirectorySync=n}async process(e,t,n){let r=Date.now(),o=e.syncDirection??"both",s=this.getDirectorySync();this.logger.info("Starting directory sync job",{jobId:t,operation:e.operation,syncDirection:o});let a={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},c={exported:0,failed:0,errors:[]};if(o!=="export")if(await n.report({progress:10,message:"Scanning directory for changes"}),a=await this.importWithProgress(s,e.paths,n),o==="import")await this.waitForImportJobs(a.jobIds,n),await n.report({progress:100,message:`Import complete: ${a.imported} imported`});else await n.report({progress:50,message:`Imported ${a.imported} entities`}),await this.waitForImportJobs(a.jobIds,n),await n.report({progress:56,message:"Processing complete, starting export"});if(o!=="import"){let l=o==="export"?10:60;await n.report({progress:l,message:"Exporting entities to directory"}),c=await this.exportWithProgress(s,e.entityTypes,n),await n.report({progress:100,message:o==="export"?`Export complete: ${c.exported} exported`:`Sync complete: ${a.imported} imported, ${c.exported} exported`})}let u=Date.now()-r;return this.logger.info("Directory sync job completed",{jobId:t,duration:u,imported:a.imported,exported:c.exported}),{import:a,export:c,duration:u}}async importWithProgress(e,t,n){try{return await e.importEntitiesWithProgress(t,n,10)}catch(r){throw this.logger.error("Import phase failed",{error:r}),r}}async exportWithProgress(e,t,n){try{return await e.exportEntitiesWithProgress(t,n,10)}catch(r){throw this.logger.error("Export phase failed",{error:r}),r}}waitForImportJobs(e,t){return pVe({jobIds:e,entityService:this.context.entityService,reporter:t,logger:this.logger})}summarizeDataForLog(e){return{operation:e.operation,syncDirection:e.syncDirection}}}class N1{schema=Hoe;context;getDirectorySync;getGitSync;reconciliation;operationStatus;constructor(e,t,n,r,o){this.context=e,this.getDirectorySync=t,this.getGitSync=n,this.reconciliation=r,this.operationStatus=o}async process(e,t,n){await n.report({progress:5,message:"Pulling latest content from git"});let r=e.runId?this.operationStatus?.createProgressObserver(e.runId):void 0;r?.();let s=(await this.reconciliation.pullAndQueue({gitSync:this.getGitSync(),directorySync:this.getDirectorySync(),context:this.context,source:e.source,full:e.full,...r?{onGitProgress:r}:{},metadata:{rootJobId:t,interfaceType:e.interfaceType,channelId:e.channelId}})).batch;if(await n.report({progress:35,message:"Scanning pulled content for sync changes"}),!s)return await n.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await n.report({progress:100,message:`Sync queued: ${s.importOperationsCount} import jobs for ${s.totalFiles} files`}),_5t(s)}summarizeDataForLog(e){return{source:e.source,interfaceType:e.interfaceType,channelId:e.channelId}}}function _5t(e){return{gitPulled:!0,batchQueued:!0,batchId:e.batchId,importOperations:e.importOperationsCount,totalFiles:e.totalFiles}}class F1{schema=x1;logger;context;directorySync;constructor(e,t,n){this.logger=e,this.context=t,this.directorySync=n}async process(e,t,n){return wI(this.context,e,t,async()=>{let r=x1.parse(e),o="deletions"in r,s=o?r.deletions:[r];await n.report({progress:0,total:s.length,message:s.length===1?`Deleting ${s[0]?.entityType}:${s[0]?.entityId}`:`Deleting ${s.length} entities`});let a=[];for(let[u,l]of s.entries())a.push(await this.deleteEntity(l,u+1,s.length,n));if(o)return a;let c=a[0];if(!c)throw Error("Directory delete job has no targets");return c})}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}summarizeDataForLog(e){if("deletions"in e)return{deletionCount:e.deletions.length};return{entityId:e.entityId,entityType:e.entityType,filePath:e.filePath}}async deleteEntity(e,t,n,r){this.logger.info("Processing entity deletion for removed file",e);let o=await this.remainingFiles(e);if(o.length>0)return this.logger.info("Kept entity another of its files still holds",{...e,remaining:o}),await this.directorySync.importEntities(o),await r.report({progress:t,total:n,message:`Kept ${e.entityType}:${e.entityId}`}),this.directorySync.completePendingDelete(e.entityType,e.entityId,e.filePath),{deleted:!1,...e};try{let s=await this.directorySync.deleteForRemovedFile(e.entityType,e.entityId),a=s==="deleted";if(a)this.logger.info("Successfully deleted entity for removed file",{entityId:e.entityId,entityType:e.entityType});else if(s==="kept")this.logger.info("Kept an entity that changed since its file was last written",{entityId:e.entityId,entityType:e.entityType});else this.logger.warn("Entity not found in database",{entityId:e.entityId,entityType:e.entityType});return await r.report({progress:t,total:n,message:`Deleted ${e.entityType}:${e.entityId}`}),this.directorySync.completePendingDelete(e.entityType,e.entityId,e.filePath),{deleted:a,...e}}catch(s){throw this.logger.error("Failed to delete entity",{...e,error:s}),s}}async remainingFiles(e){let t=[...new Set([e.filePath,...this.directorySync.fileOps.getEntityDeletePaths(e.entityType,e.entityId)])],n=await Promise.all(t.map((r)=>this.directorySync.fileOps.fileExists(r)));return t.filter((r,o)=>n[o])}}H();var O5t=i.object({projectionBatch:fI.optional()});class U1{schema=O5t;context;directorySync;constructor(e,t){this.context=e,this.directorySync=t}async process(e,t,n){return wI(this.context,e,t,async()=>{await n.report({progress:0,message:"Removing orphaned entities"});let r=await this.directorySync.removeOrphanedEntities(e.projectionBatch);return await n.report({progress:100,message:`Cleanup complete: ${r.deleted} orphans removed`}),r})}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}}import{readFile as D5t}from"fs/promises";async function Is(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}H();var z5t=i.record(i.string(),i.unknown());class B1{schema=Voe;logger;context;fetcher;constructor(e,t,n=Tm){this.logger=t,this.context=e,this.fetcher=n}async process(e,t,n){let{filePath:r,sourceUrl:o,postTitle:s,postSlug:a,customAlt:c}=e;this.logger.debug("Starting image conversion job",{jobId:t,filePath:r,sourceUrl:o,postSlug:a});try{await Is(n,{progress:Ko.INIT,message:`Reading file: ${r}`});let u;try{u=await D5t(r,"utf-8")}catch(h){return this.logger.error("Failed to read file",{filePath:r,error:de(h)}),Zp.failure(h)}let l;try{l=ba(u)}catch(h){return this.logger.warn("Failed to parse markdown",{filePath:r,error:de(h)}),Zp.failure(h)}let d=z5t.safeParse(l.frontmatter),p=d.success?d.data:{};if(p.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await Is(n,{progress:Ko.FETCH,message:"Checking for existing image"});let m=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:o}},limit:1}}),f;if(m[0])f=m[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:o,imageId:f}),await Is(n,{progress:Ko.EXTRACT,message:`Reusing existing image: ${f}`});else{await Is(n,{progress:Ko.PROCESS,message:`Fetching image from ${o}`});let h;try{h=await this.fetcher(o)}catch(E){return this.logger.error("Failed to fetch image",{sourceUrl:o,error:de(E)}),Zp.failure(E)}await Is(n,{progress:Ko.GENERATE,message:"Creating image entity"}),f=`${a}-cover`;let v=`Cover image for ${s}`,S;try{S=await UP(this.context.entityService,{dataUrl:h},{title:v,alt:c??v,sourceUrl:o})}catch(E){return this.logger.error("Fetched image cannot be stored",{sourceUrl:o,error:de(E)}),Zp.failure(E)}await this.context.entityService.createEntity({entity:{id:f,...S.entity},stagedAsset:S.stagedAsset}),this.logger.debug("Created image entity",{imageId:f,sourceUrl:o}),await Is(n,{progress:Ko.EXTRACT,message:`Created image: ${f}`})}await Is(n,{progress:Ko.SAVE,message:"Updating file"});let g={...p};delete g.coverImageUrl,delete g.coverImageAlt,g.coverImageId=f;let y=Sa(g,l.content);try{await Dd(r,y)}catch(h){return this.logger.error("Failed to write file",{filePath:r,error:de(h)}),Zp.failure(h)}return await Is(n,{progress:Ko.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:r,imageId:f,sourceUrl:o}),{success:!0,imageId:f}}catch(u){return this.logger.error("Image conversion job failed",{jobId:t,filePath:r,error:de(u)}),Zp.failure(u)}}summarizeDataForLog(e){return{filePath:e.filePath,sourceUrl:e.sourceUrl,postSlug:e.postSlug}}}import{readFile as M5t}from"fs/promises";class L1{schema=Koe;logger;converter;constructor(e,t,n=Tm){this.logger=t,this.converter=new xO(e.entityService,t,n)}async process(e,t,n){let{filePath:r,postSlug:o}=e;this.logger.debug("Starting inline image conversion job",{jobId:t,filePath:r,postSlug:o});try{await Is(n,{progress:Ko.INIT,message:`Reading file: ${r}`});let s;try{s=await M5t(r,"utf-8")}catch(u){let l=de(u);return this.logger.error("Failed to read file",{filePath:r,error:l}),{success:!1,error:l}}await Is(n,{progress:Ko.FETCH,message:"Detecting inline images"});let a=this.converter.detectInlineImages(s,o);if(a.length===0)return this.logger.debug("No inline images to convert",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:r,count:a.length}),await Is(n,{progress:Ko.PROCESS,message:`Converting ${a.length} images`});let c=await this.converter.convert(s,o);if(!c.converted)return this.logger.debug("No images were converted",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await Is(n,{progress:Ko.SAVE,message:"Writing updated file"});try{await Dd(r,c.content)}catch(u){let l=de(u);return this.logger.error("Failed to write file",{filePath:r,error:l}),{success:!1,error:l}}return await Is(n,{progress:Ko.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:r,convertedCount:c.convertedCount}),{success:!0,convertedCount:c.convertedCount}}catch(s){let a=de(s);return this.logger.error("Inline image conversion job failed",{jobId:t,filePath:r,error:a}),{success:!1,error:a}}}summarizeDataForLog(e){return{filePath:e.filePath,postSlug:e.postSlug}}}function Nm(e,t){let n=t.summarizeDataForLog?.bind(t);return nL({type:e,input:t.schema,...n&&{summarize:n},process:({input:r,jobId:o,progress:s,signal:a})=>t.process(r,o,s,a)})}function fVe(e,t,n,r=()=>t,o,s){let a=(c)=>n.child(c);return[Nm("directory-sync",new $1(a("DirectorySyncJobHandler"),e,r)),Nm("directory-export",new M1(a("DirectoryExportJobHandler"),e,t,o)),Nm("directory-import",new j1(a("DirectoryImportJobHandler"),e,t,o,s)),Nm("directory-delete",new F1(a("DirectoryDeleteJobHandler"),e,t)),Nm("directory-cleanup",new U1(e,t)),Nm("cover-image-convert",new B1(e,a("CoverImageConversionJobHandler"))),Nm("inline-image-convert",new L1(e,a("InlineImageConversionJobHandler")))]}cs();H();var j5t=i.record(i.string(),i.unknown());function mVe(e,t,n,r,o){for(let s of[UE,BE,LE])e.runtime.listen(s,()=>{t()},{mode:"observe"});n.debug("Setup durable entity-export wakeups",{entityTypes:r})}function gVe(e,t,n,r,o){t.setJobQueueCallback(async(s)=>{let a=await r?.startRun("watcher","importing"),c=[{type:s.type,data:j5t.parse(s.data)}],u=$r(),l=async()=>{let p=await e.jobs.enqueueBatch(c,{priority:5,source:"directory-sync-watcher",rootJobId:u,metadata:{operationType:"file_operations",operationTarget:n,pluginId:"directory-sync"}});if(a)await r?.attachBatch(a,p);return p},d=async(p)=>{if(!a)return;await r?.failRun(a,de(p,"Watcher import failed"),"import")};try{return await l()}catch(p){o.retry(l,p,`queue a watched ${s.type}`).then(async(m)=>{if(m.kind!=="succeeded")await d(p)}).catch((m)=>{e.logger.warn("Failed to record a stopped watcher run",{error:m})});return}})}import{readdir as yVe,mkdir as $5t,copyFile as N5t}from"fs/promises";import{join as hVe,resolve as Die}from"path";async function F5t(e,t,n){if(!await co(e))return!0;if((await yVe(e)).filter((s)=>!s.startsWith(".")&&!s.startsWith("_")).length>0)return!1;if(n){let s=await n.getStatus();if(s.isRepo&&s.lastCommit!==void 0)return t.debug("Git repository with history detected - skipping seed content",{path:e}),!1}return!0}async function bVe(e,t){let n=await yVe(e,{withFileTypes:!0});for(let r of n){let o=hVe(e,r.name),s=hVe(t,r.name);if(r.isDirectory()){if(!await co(s))await $5t(s,{recursive:!0});await bVe(o,s)}else await N5t(o,s)}}async function SVe(e,t,n,r){let o=Die(process.cwd(),e);n=n?Die(n):Die(process.cwd(),"seed-content");let s=await F5t(o,t,r);if(s&&await co(n))t.debug("Copying seed content to brain-data directory"),await bVe(n,o),t.debug("Seed content copied successfully");else if(s)t.debug("No seed content directory found, starting with empty brain-data");else t.debug("brain-data directory not empty, skipping seed content")}var xVe="initial-sync";function vVe(e){let{context:t,config:n,logger:r,gitSync:o}=e,s=!1,a=async()=>{if(s)return{initialSyncPending:!1};if(s=!0,n.seedContent){let d=n.syncPath??t.dataDir;if(await SVe(d,r,n.seedContentPath,o),n.strictSeedEntityTypes)await _1(d,t.entityService)}let c;try{c=await U5t(e)}catch(d){return r.error("Initial sync failed",d),await wVe(e),await e.recovery?.onGitRecoveryFailed(d),await t.runtime.messaging.broadcast(wT,{success:!1,error:de(d)}),{initialSyncPending:!0}}let{batchIds:u,runId:l}=c;if(u.length===0)return await t.runtime.messaging.broadcast(wT,{success:!0}),{initialSyncPending:!1};return r.info("Initial sync queued for the worker",{batchIds:u}),L5t(t,u).then(async(d)=>{await B5t(e,l,d),await t.runtime.messaging.broadcast(wT,d)}).catch((d)=>{r.error("Unable to report initial sync completion",d)}),{initialSyncPending:!0}};t.runtime.initialSync(async()=>(r.debug("Plugins registered, queueing initial sync"),a()))}async function U5t(e){let{context:t,getDirectorySync:n,gitSync:r,reconciliation:o,recovery:s,operationStatus:a}=e,c=n(),u=(await a?.getSnapshot())?.activeRun?.batchId,l=await a?.startRun("startup",r?"pulling":"scanning"),d;try{if(r&&o)s?.onGitProgress(),d=(await o.pullAndQueue({gitSync:r,directorySync:c,context:t,source:xVe,full:!0,...s?{onGitProgress:s.onGitProgress}:{}})).batch;else d=await c.queueSyncBatch(t,xVe)}catch(p){if(l)await a?.failRun(l,de(p,"Initial sync failed"),r?"git":"source");throw p}if(await s?.onGitRecoverySucceeded(),l)if(d)await a?.attachBatch(l,d.batchId);else await a?.completeRun(l,"No files to import");return{batchIds:[u,d?.batchId].filter((p)=>p!==void 0),runId:d?l:void 0}}async function B5t(e,t,n){if(n.success){if(t)await e.operationStatus?.completeRun(t,"Startup import completed");return}if(e.logger.error("Initial sync import failed",{error:n.error}),await wVe(e),t)await e.operationStatus?.failRun(t,n.error,"import")}function L5t(e,t){return new Promise((n)=>{let r=new Set(t),o=[],s=(c,u)=>{if(!r.delete(c))return;if(u)o.push(...u.length>0?u:[`Initial sync batch ${c} failed`]);if(r.size>0)return;a(),n(o.length===0?{success:!0}:{success:!1,error:o.join("; ")})},a=e.runtime.listen(Eh,({payload:c})=>{if(c.type==="batch"){if(c.status==="completed")s(c.id,null);if(c.status==="failed")s(c.id,c.batchDetails?.errors??[])}});for(let c of t)e.jobs.getBatchStatus(c).then((u)=>{if(!u)s(c,[`Initial sync batch ${c} was not found`]);else if(u.status==="completed")s(c,null);else if(u.status==="failed")s(c,u.errors)},(u)=>s(c,[de(u)]))})}async function wVe(e){try{await e.reconciliation?.requireFullScan()}catch(t){e.logger.error("Unable to require a full rescan",t)}}var Z5t={guard:(e)=>e(),progress:async()=>{},succeeded:async()=>{},requiresRepository:async()=>{},initialSyncRecovery:()=>{return}};function EVe(e){let{operationStatus:t,interruptedPull:n}=e;if(e.executionOnly||!n)return Z5t;let r=n.id,o=(c,u)=>t.finishInterruptedPull(r,{recovered:c,message:u}),s=(c)=>o(!0,`Recovered interrupted Git handoff during ${c}`),a=(c)=>o(!1,`Interrupted Git handoff recovery failed: ${de(c)}`);return{guard:async(c)=>{try{return await c()}catch(u){throw await a(u),u}},progress:()=>t.markProgress(r),succeeded:s,requiresRepository:()=>o(!1,"Interrupted Git handoff recovery requires a configured repository"),initialSyncRecovery:()=>({onGitProgress:t.createProgressObserver(r),onGitRecoverySucceeded:()=>s("initial sync"),onGitRecoveryFailed:a})}}function TVe(e){let{gitSync:t,directorySync:n,context:r,intervalMinutes:o,logger:s,runtime:a,reconciliation:c,operationStatus:u}=e;if(o<=0)return;let l=o*60*1000,d=async(p)=>{let m=await u?.startRun("periodic","pulling");try{let f=m?u?.createProgressObserver(m):void 0,g=await c.pullAndQueue({gitSync:t,directorySync:n,context:r,source:"periodic-sync",signal:p,...f?{onGitProgress:f}:{}});if(m)await u?.markPhase(m,"scanning");let{files:y,batch:h}=g;if(y.length>0)s.info("Periodic sync: pulled changes",{filesChanged:y.length});if(h){if(s.debug("Periodic sync: queued imports",{importOperations:h.importOperationsCount,totalFiles:h.totalFiles}),m)await u?.attachBatch(m,h.batchId)}else if(m)await u?.completeRun(m,y.length===0?"Remote checked; no changes found":"Remote changes required no imports")}catch(f){if(p.aborted){if(m)await u?.clearRun(m)}else if(s.error("Periodic git sync failed",{error:f}),m)await u?.failRun(m,de(f,"Periodic Git sync failed"))}};a.schedulePeriodic(l,d),s.info("Started periodic git sync",{intervalMinutes:o})}async function IVe(e){try{return await e(),!0}catch(t){if(!(t instanceof jm))throw t;return!1}}async function zie(e){let t=await e.listPendingEntityExports(),n=[],r=!1;for(let a of t){if(e.isPendingRemoteDelete(a.entityType,a.entityId)){n.push(a);continue}if(a.operation==="delete"){let l=await IVe(()=>e.deleteEntityFile(a.entityType,a.entityId));n.push(a),r||=l;continue}let c=await e.getEntity({entityType:a.entityType,id:a.entityId,visibilityScope:on("directory sync drains durable exports across all visibility tiers"),source:!0});if(!c)throw Error(`Durable entity export cannot resolve upsert target ${a.entityType}:${a.entityId} at revision ${a.revision}`);let u=await IVe(()=>e.writeEntity(c));n.push(a),r||=u}let o=!1;if(r&&e.commitAndPush){let a=await e.commitAndPush();if(o=a.pushed,a.checkpoint===null)throw Error("Git export did not return a confirmed checkpoint; durable intents remain pending");if(!e.saveCheckpoint)throw Error("Git export checkpoint persistence is unavailable; durable intents remain pending");await e.saveCheckpoint(a.checkpoint)}let s=await e.acknowledgeEntityExports({intents:n});return{processed:n.length,acknowledged:s,pushed:o}}var q5t=5000,G5t=100;class Mie{queue=new qS;runtime;directorySync;entityService;gitSync;saveCheckpoint;operationStatus;logger;debounceMs;reconciliationIntervalMs;started=!1;constructor(e){this.runtime=e.runtime,this.directorySync=e.directorySync,this.entityService=e.entityService,this.gitSync=e.gitSync,this.saveCheckpoint=e.saveCheckpoint,this.operationStatus=e.operationStatus,this.logger=e.logger,this.debounceMs=e.debounceMs,this.reconciliationIntervalMs=e.reconciliationIntervalMs??q5t}async start(){if(this.started)return;this.started=!0,this.runtime.schedulePeriodic(this.reconciliationIntervalMs,(e)=>this.reconcilePending(e)),await this.reconcilePending()}wake(){this.runtime.scheduleTrailing("durable-entity-export",this.debounceMs,()=>this.attemptDrain())}async settleBeforeCleanup(){try{await this.drain()}catch(e){throw await this.recordFailure(e),this.wake(),e}}async reconcilePending(e){try{if(e?.throwIfAborted(),!await this.entityService.hasPendingEntityExports())return;e?.throwIfAborted(),await this.drain()}catch(t){if(e?.aborted)return;await this.recordFailure(t),this.wake()}}async attemptDrain(){try{await this.drain()}catch(e){await this.recordFailure(e),this.wake()}}async drain(){await this.queue.run(()=>this.drainPass(G5t))}async drainPass(e){let t={listPendingEntityExports:()=>this.entityService.listPendingEntityExports(),getEntity:(s)=>this.entityService.getEntityRaw({...s}),writeEntity:async(s)=>{this.directorySync.suppressWatchPaths(this.directorySync.fileOps.getEntityConvergencePaths(s));try{await this.directorySync.writeEntityFile(s)}catch(a){if(a instanceof jm)this.logger.warn("Entity placement refused",{error:a}),await this.operationStatus?.recordIssue({kind:"placement",path:`${s.entityType}/${s.id}`,message:`Saved but not exported: ${a.message}`});throw a}await this.operationStatus?.clearIssue({kind:"placement",path:`${s.entityType}/${s.id}`})},deleteEntityFile:async(s,a)=>{this.directorySync.suppressWatchPaths(this.directorySync.fileOps.getEntityDeletePaths(s,a)),await this.directorySync.fileOps.deleteEntityFiles(s,a)},isPendingRemoteDelete:(s,a)=>this.directorySync.isPendingDelete(s,a),acknowledgeEntityExports:async(s)=>{for(let a of s.intents)if(a.operation==="delete")await this.operationStatus?.clearIssue({kind:"placement",path:`${a.entityType}/${a.entityId}`});return this.entityService.acknowledgeEntityExports(s)}},n=this.gitSync,r=this.saveCheckpoint,o=n?await zie({...t,commitAndPush:()=>n.commitAndPush(),saveCheckpoint:async(s)=>{if(!r)throw Error("Git export checkpoint persistence is unavailable; durable intents remain pending");await r(s)}}):await zie(t);if(!await this.entityService.hasPendingEntityExports()){await this.operationStatus?.clearIssues(["export","git"]);return}if(o.processed===0)throw Error("Durable entity exports could not make progress");if(e<=1)throw Error("Durable entity exports did not settle");await this.drainPass(e-1)}async recordFailure(e){let t=de(e,"Entity export failed");this.logger.error("Durable entity export failed",{error:e});try{await this.operationStatus?.recordIssue({kind:"export",message:t})}catch(n){this.logger.error("Failed to record durable entity export issue",{error:n})}}}async function jie(e,t={}){let[n]=e;if(n===void 0)throw Error("runProcess needs a command to run");let r=Bun.spawn([...e],{...t.cwd===void 0?{}:{cwd:t.cwd},...t.env===void 0?{}:{env:t.env},...t.stdin===void 0?{}:{stdin:Buffer.from(t.stdin)},stdout:"pipe",stderr:"pipe"}),[o,s,a]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{exitCode:a,stdout:o,stderr:s}}import{cpSync as H5t,existsSync as CVe,mkdirSync as W5t,mkdtempSync as J5t,rmSync as V5t}from"fs";import{tmpdir as K5t}from"os";import{fileURLToPath as Q5t}from"url";import{join as Y5t,resolve as X5t}from"path";async function Bh(e,t){let n=await jie(["git",...t],{cwd:e});if(n.exitCode!==0){let r=n.stderr.trim(),o=n.stdout.trim();throw Error(r||o||`git ${t.join(" ")} failed`)}}function eQt(e){return e.startsWith("file://")}function tQt(e){return Q5t(e)}async function nQt(e,t){return(await jie(["git","--git-dir",e,"show-ref","--verify","--quiet",`refs/heads/${t}`])).exitCode===0}async function kVe(e){if(!e.bootstrapFromSeed)return;if(!e.gitUrl||!eQt(e.gitUrl))return;if(!e.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let t=e.branch??"main",n=tQt(e.gitUrl),r=X5t(e.seedContentPath);if(!CVe(r))throw Error(`Seed content path not found: ${r}`);if(!CVe(n))e.logger.debug("Creating local bare content remote",{remotePath:n,branch:t}),W5t(n,{recursive:!0}),await Bh(process.cwd(),["init","--bare",`--initial-branch=${t}`,n]);if(await nQt(n,t)){e.logger.debug("Content remote already initialized",{remotePath:n,branch:t});return}e.logger.debug("Seeding local content remote",{remotePath:n,seedPath:r,branch:t});let o=J5t(Y5t(K5t(),"directory-sync-seed-"));try{await Bh(o,["init",`--initial-branch=${t}`]),await Bh(o,["config","user.name",e.authorName??"Brain"]),await Bh(o,["config","user.email",e.authorEmail??"brain@localhost"]),H5t(r,o,{recursive:!0,filter:(s)=>!s.split("/").includes(".git")}),await Bh(o,["add","."]),await Bh(o,["commit","-m","seed content remote"]),await Bh(o,["remote","add","origin",e.gitUrl]),await Bh(o,["push","-u","origin",t])}finally{V5t(o,{recursive:!0,force:!0})}}function RVe(e,t,n,r,o){e.runtime.answer(AY,({request:s})=>{let a=JS(s),{relativePath:c,owner:u,writable:l}=WS(s.entityType,s.entityId,a,Uh(e.entityService)),[d,...p]=Jp(s.entityId),m=p.at(-1)??d,f=c.length-a.length,g=m&&c.endsWith(`${m}${a}`)?{start:f-m.length,end:f}:null;return{relativePath:c,leaf:g,owner:u,writable:l}}),e.runtime.answer(PY,async()=>{let s=await t().getStatus(),a=o?.();return{syncPath:s.syncPath,isInitialized:s.exists,watchEnabled:s.watching,lastSync:s.lastSync?.toISOString()??null,totalFiles:s.stats.totalFiles,byEntityType:s.stats.byEntityType,git:await rQt(r?.(),n),...a?{managementUrl:a}:{}}}),n.debug("Registered message handlers")}async function rQt(e,t){if(!e)return null;try{let n=await e.getStatus();return{branch:n.branch,hasChanges:n.hasChanges,ahead:n.ahead,behind:n.behind,lastCommit:n.lastCommit??null,remote:n.remote??null}}catch(n){return t.debug("Git status unavailable for sync:status:request",{error:n}),null}}H();async function Z1(e){let t=await e.operationStatus?.startRun("manual",e.gitSync?"pulling":"scanning");try{if(e.gitSync){let r=await e.context.jobs.enqueue({type:"sync-request",data:{source:e.source,runId:t,interfaceType:e.interfaceType,channelId:e.channelId,...e.full?{full:!0}:{}},...e.toolContext?{toolContext:e.toolContext}:{}});if(t)await e.operationStatus?.attachJob(t,r);return{...t?{runId:t}:{},gitPulled:!0,jobId:r,status:"queued"}}let n=await e.directorySync.queueSyncBatch(e.context,e.source,{interfaceType:e.interfaceType,channelId:e.channelId});if(!n){if(t)await e.operationStatus?.completeRun(t,"No files to sync");return{...t?{runId:t}:{},gitPulled:!1,status:"settled"}}if(t)await e.operationStatus?.attachBatch(t,n.batchId);return{...t?{runId:t}:{},...n,gitPulled:!1,status:"queued"}}catch(n){if(t)await e.operationStatus?.failRun(t,de(n,"Sync request failed"),e.gitSync?"git":"source");throw n}}H();var AVe=i.object({action:i.literal("history"),entityType:i.string().min(1),id:i.string().min(1),sha:i.string().optional(),limit:i.number().int().positive().optional().default(10)});async function PVe(e,t){let n=`${e.entityType}/${e.id}.md`;try{if(e.sha){let o=await t.show(e.sha,n);return Cl({sha:e.sha,entityType:e.entityType,id:e.id,content:o},`Content at ${e.sha.slice(0,7)}`)}let r=await t.log(n,e.limit);if(r.length===0)return Cl({commits:[]},`No history found for ${e.entityType}/${e.id}`);return Cl({commits:r,entityType:e.entityType,id:e.id},`${r.length} version${r.length===1?"":"s"} found`)}catch(r){return Rm(de(r,"History lookup failed"))}}var oQt=i.object({action:i.enum(["sync","status"]).default("sync").describe("Use sync for a refresh request and status for a status check")}),iQt=i.object({action:i.enum(["sync","status","history"]).default("sync").describe("Use sync for git/filesystem sync, status for a status check, and history only for entity history"),full:i.boolean().optional().describe("Sync only; true rescans every file instead of the changes since the last sync, for files an earlier sync skipped"),entityType:i.string().optional().describe("History only; omit for sync and status"),id:i.string().optional().describe("History only; omit for sync and status"),sha:i.string().optional().describe("Optional history revision; omit for sync and status"),limit:i.number().int().positive().optional().default(10).describe("History only; omit for sync and status")}),sQt=i.discriminatedUnion("action",[i.object({action:i.literal("sync")}),i.object({action:i.literal("status")})]),aQt=i.discriminatedUnion("action",[i.object({action:i.literal("sync"),full:i.boolean().optional()}),i.object({action:i.literal("status")}),AVe]);function _Ve(e,t,n,r,o){return[b_("directory","sync",r?"Manage directory and git sync with an action discriminator. For requests such as 'sync with git', immediately call action=sync with no entityType, id, or sha; never ask for those fields because they apply only to action=history. Action=sync queues a git pull plus a scan of the brain's content directory and also handles refresh, pull, backup-to-git, and requests to import files changed in the content directory. A file attached in chat is not in the content directory: save it with system_create with source kind upload, never by syncing. For every sync or git status follow-up after action=sync, including a bare 'what is the status', immediately call action=status with no entity fields; a sync jobId is not a system_job_status batchId. Use action=history to read git version history for a specific entity.":"Manage the brain's content directory sync with an action discriminator. Immediately call action=sync for refresh or content sync requests, and to import files changed in the content directory. A file attached in chat is not in the content directory: save it with system_create with source kind upload, never by syncing. Immediately call action=status for directory sync status follow-ups, including a bare 'what is the status'.",r?iQt:oQt,async(a,c)=>{let u=r?aQt.parse(a):sQt.parse(a);if(u.action==="sync")return cQt({directorySync:e,pluginContext:t,pluginId:n,gitSync:r,operationStatus:o,context:c,full:"full"in u&&u.full===!0});if(u.action==="status")return uQt(e,r);if(!r)return Rm("History is unavailable because git is not configured");return PVe(u,r)},{visibility:"admin",sideEffects:"external",cli:{name:"sync"}})]}async function cQt(e){try{let t=e.context.channelId?`${e.context.interfaceType}:${e.context.channelId}`:`plugin:${e.pluginId}`,n=await Z1({context:e.pluginContext,directorySync:e.directorySync,source:t,interfaceType:e.context.interfaceType,channelId:e.context.channelId,toolContext:e.context,gitSync:e.gitSync,operationStatus:e.operationStatus,full:e.full});if(n.gitPulled)return Cl({jobId:n.jobId,status:n.status,gitPulled:!0,...n.runId?{runId:n.runId}:{}},"Sync queued: git pull and filesystem scan will run in the background");if(n.status==="settled")return Cl({gitPulled:!1,...n.runId?{runId:n.runId}:{}},"No files to sync");return Cl({batchId:n.batchId,importOperations:n.importOperationsCount,totalFiles:n.totalFiles,gitPulled:!1,...n.runId?{runId:n.runId}:{}},`Sync started: ${n.importOperationsCount} import jobs queued for ${n.totalFiles} files`)}catch(t){return Rm(de(t,"Sync failed"))}}async function uQt(e,t){try{let n=await e.getStatus(),r={syncPath:n.syncPath,lastSync:n.lastSync?.toISOString(),watching:n.watching};if(t){let o=await t.getStatus();r.git={isRepo:o.isRepo,branch:o.branch,hasChanges:o.hasChanges,ahead:o.ahead,behind:o.behind,remote:o.remote}}return Cl(r)}catch(n){return Rm(de(n,"Status check failed"))}}cs();H();import{isAbsolute as OVe,relative as lQt}from"path";var MVe=i.enum(["manual","periodic","watcher","save","startup"]),dQt=i.enum(["pulling","scanning","importing","settling"]),pQt=i.enum(["succeeded","attention","failed"]),fQt=i.enum(["quarantined","import","export","placement","git","source"]),jVe=i.object({imported:i.number().int().nonnegative(),skipped:i.number().int().nonnegative(),failed:i.number().int().nonnegative(),quarantined:i.number().int().nonnegative(),exported:i.number().int().nonnegative()}),Nie=i.preprocess((e)=>{if(typeof e!=="object"||e===null||"lastProgressAt"in e||!("startedAt"in e)||typeof e.startedAt!=="string")return e;return{...e,lastProgressAt:e.startedAt}},i.object({id:i.string().min(1),source:MVe,state:dQt,startedAt:i.string().datetime(),lastProgressAt:i.string().datetime(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional(),...jVe.shape})),Fie=i.object({id:i.string().min(1),source:MVe,outcome:pQt,startedAt:i.string().datetime(),completedAt:i.string().datetime(),summary:i.string().min(1).max(240),...jVe.shape}),Uie=i.object({id:i.string().min(1),kind:fQt,path:i.string().min(1).max(300).optional(),message:i.string().min(1).max(400),occurredAt:i.string().datetime()}),mQt=i.object({activeRun:Nie.optional(),recentRuns:i.array(Fie).max(5),issues:i.array(Uie)}),gQt=i.object({gitPulled:i.literal(!0),batchQueued:i.boolean(),batchId:i.string().optional(),importOperations:i.number().int().nonnegative().optional(),totalFiles:i.number().int().nonnegative().optional()}),DVe={imported:0,skipped:0,failed:0,quarantined:0,exported:0},hQt={recentRuns:[],issues:[]},yQt=i.object({lastProgressAt:i.string().datetime()}),bQt="directory-sync.operation-status",SQt="current",xQt="directory-sync.operation-progress",vQt=1000,wQt=30000;class Bie{store;progressStore;jobs;logger;now;inactivityTimeoutMs;staleGraceMs;progressPersistenceIntervalMs;lastProgressPersistence=new Map;syncPath;constructor(e,t,n,r,o={}){this.store=new GS({runtimeState:e,namespace:bQt,key:SQt,schema:mQt,createEmpty:()=>structuredClone(hQt)}),this.progressStore=e.scoped({namespace:xQt,schema:yQt}),this.jobs=t,this.logger=n,this.syncPath=r,this.now=o.now??Date.now,this.inactivityTimeoutMs=o.inactivityTimeoutMs??sD,this.staleGraceMs=o.staleGraceMs??wQt,this.progressPersistenceIntervalMs=o.progressPersistenceIntervalMs??vQt}setSyncPath(e){this.syncPath=e}async initialize(e){if(e?.executionOnly)return;let t=await this.store.snapshot();if(t.activeRun&&!t.activeRun.jobId&&!t.activeRun.batchId){if(t.activeRun.state==="pulling")return this.withEffectiveProgress(t.activeRun);await this.clearRun(t.activeRun.id);return}await this.reconcile();return}startRun(e,t){let n=$r(),r=this.now();return this.mutate((o)=>{if(o.activeRun)return;let s=new Date(r).toISOString();return o.activeRun={id:n,source:e,state:t,startedAt:s,lastProgressAt:s,...DVe},this.lastProgressPersistence.set(n,r),n})}markPhase(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;r.activeRun.state=t,r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}async markProgress(e){let t=this.now(),n=this.lastProgressPersistence.get(e);if(n!==void 0&&t-n<this.progressPersistenceIntervalMs)return;this.lastProgressPersistence.set(e,t),await this.progressStore.set(e,{lastProgressAt:new Date(t).toISOString()})}createProgressObserver(e){return()=>{this.markProgress(e).catch((t)=>{this.logger.debug("Unable to persist directory Git progress",{error:t})})}}attachJob(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;r.activeRun.jobId=t,r.activeRun.state="pulling",r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}attachBatch(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;delete r.activeRun.jobId,r.activeRun.batchId=t,r.activeRun.state="importing",r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}addImportResult(e){let t=this.now();return this.mutate((n)=>{if(n.activeRun)n.activeRun.imported+=e.imported,n.activeRun.skipped+=e.skipped,n.activeRun.failed+=e.failed,n.activeRun.quarantined+=e.quarantined,n.activeRun.lastProgressAt=new Date(t).toISOString(),this.lastProgressPersistence.set(n.activeRun.id,t);let r=[...(e.issues??[]).map((o)=>({kind:"import",path:this.safePath(o.path),message:o.message})),...e.errors.map((o)=>({kind:"import",path:this.safePath(o.path),message:o.error})),...e.quarantinedFiles.map((o)=>({kind:"quarantined",path:this.safePath(o),message:"File was quarantined because it could not be imported"}))];if(r.length===0)n.issues=n.issues.filter((o)=>o.kind!=="import"&&o.kind!=="quarantined");else for(let o of r)this.prependIssue(n,o)})}addExportResult(e){let t=this.now();return this.mutate((n)=>{if(n.activeRun)n.activeRun.exported+=e.exported,n.activeRun.failed+=e.failed,n.activeRun.lastProgressAt=new Date(t).toISOString(),this.lastProgressPersistence.set(n.activeRun.id,t);if(e.errors.length===0){n.issues=n.issues.filter((r)=>r.kind!=="export");return}for(let r of e.errors)this.prependIssue(n,{kind:"export",path:`${r.entityType}/${r.entityId}.md`,message:r.error})})}recordIssue(e){return this.mutate((t)=>this.prependIssue(t,e))}clearIssues(e){return this.mutate((t)=>{t.issues=t.issues.filter((n)=>!e.includes(n.kind))})}clearIssue(e){let t=e.kind==="placement"?e.path:this.safePath(e.path);return this.mutate((n)=>{n.issues=n.issues.filter((r)=>r.id!==`${e.kind}:${t}`)})}completeRun(e,t){return this.finishRun(e,"succeeded",t)}async clearRun(e){await this.mutate((t)=>{if(t.activeRun?.id===e)delete t.activeRun}),await this.clearProgress(e)}async failRun(e,t,n="git"){await this.mutate((r)=>{let o=r.activeRun;if(o?.id!==e)return;let s=EO(t);this.prependRecent(r,o,"failed",s),this.prependIssue(r,{kind:n,message:s}),delete r.activeRun}),await this.clearProgress(e)}async finishInterruptedPull(e,t){await this.mutate((n)=>{let r=n.activeRun;if(r?.id!==e||r.state!=="pulling")return;let o=EO(t.message);this.prependRecent(n,r,t.recovered?"attention":"failed",o),this.prependIssue(n,{kind:"git",message:o}),delete n.activeRun}),await this.clearProgress(e)}recordTerminal(e,t,n,r={}){return this.mutate((o)=>{let s=new Date(this.now()).toISOString();this.prependRecent(o,{id:$r(),source:e,state:"settling",startedAt:s,lastProgressAt:s,...DVe,...r},t,n)})}async reconcile(){let t=(await this.store.snapshot()).activeRun;if(!t)return;try{if(t.jobId){let n=await this.jobs.getStatus(t.jobId);if(!n){await this.failRun(t.id,"The active sync job could not be found after restart","source");return}if(n.status==="pending"||n.status==="processing")return;if(n.status==="failed"){await this.failRun(t.id,n.lastError??"Git-backed sync failed");return}let r=gQt.safeParse(EQt(n.result));if(!r.success){await this.failRun(t.id,"Sync job completed without a readable result","source");return}if(r.data.batchQueued&&r.data.batchId)return await this.attachBatch(t.id,r.data.batchId),await this.reconcile();await this.completeRun(t.id,"Remote checked; no files to import");return}if(t.batchId){let n=await this.jobs.getBatchStatus(t.batchId);if(!n){await this.failRun(t.id,"The active sync batch could not be recovered after restart","source");return}if(n.status==="pending"||n.status==="processing")return;if(n.status==="failed"){await this.failRun(t.id,n.errors.join("; ")||"Directory import batch failed","import");return}await this.completeRun(t.id,`${n.completedOperations} sync operations completed`)}}catch(n){this.logger.debug("Unable to reconcile directory sync operation",{error:n})}}async getSnapshot(){await this.reconcile();let e=await this.store.snapshot();if(e.activeRun)e.activeRun=await this.withEffectiveProgress(e.activeRun);return e}async getOperationalHealth(){let e=await this.store.snapshot();if(e.activeRun?.state!=="pulling")return $ie();let t=await this.withEffectiveProgress(e.activeRun);if(t.jobId){if((await this.jobs.getStatus(t.jobId))?.status!=="processing")return $ie()}let n=Math.max(0,this.now()-Date.parse(t.lastProgressAt)),r=this.inactivityTimeoutMs+this.staleGraceMs;if(n<=r)return $ie();return{status:"degraded",message:`Directory Git pull has made no progress for ${n}ms`,details:{runId:t.id,source:t.source,state:t.state,lastProgressAt:t.lastProgressAt,inactivityMs:n,staleAfterMs:r}}}async finishRun(e,t,n){await this.mutate((r)=>{let o=r.activeRun;if(o?.id!==e)return;let s=o.failed>0||o.quarantined>0?"attention":t;if(this.prependRecent(r,o,s,n),delete r.activeRun,s==="succeeded")r.issues=r.issues.filter((a)=>a.kind!=="git"&&a.kind!=="source")}),await this.clearProgress(e)}mutate(e){return this.store.mutate(e)}prependRecent(e,t,n,r){let o={id:t.id,source:t.source,outcome:n,startedAt:t.startedAt,completedAt:new Date(this.now()).toISOString(),summary:EO(r,240),imported:t.imported,skipped:t.skipped,failed:t.failed,quarantined:t.quarantined,exported:t.exported};e.recentRuns=[o,...e.recentRuns.filter((s)=>s.id!==o.id)].slice(0,5)}prependIssue(e,t){let n=t.path?t.kind==="placement"?t.path:this.safePath(t.path):void 0,r={id:`${t.kind}:${n??EO(t.message,80)}`,kind:t.kind,...n?{path:n}:{},message:EO(t.message),occurredAt:new Date(this.now()).toISOString()},o=[r,...e.issues.filter((a)=>a.id!==r.id)],s=0;e.issues=o.filter((a)=>a.kind==="placement"||s++<8)}async withEffectiveProgress(e){let t=await this.progressStore.get(e.id);if(!t||Date.parse(t.lastProgressAt)<=Date.parse(e.lastProgressAt))return e;return{...e,lastProgressAt:t.lastProgressAt}}async clearProgress(e){this.lastProgressPersistence.delete(e),await this.progressStore.delete(e)}safePath(e){if(!OVe(e))return zVe(e);let t=lQt(this.syncPath,e);if(t.startsWith("..")||OVe(t))return"content file";return zVe(t)}}function $ie(){return{status:"healthy",message:"No stale directory Git pull"}}function EQt(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function zVe(e){return e.replaceAll("\\","/").replace(/^\.\//,"").slice(0,300)||"content file"}function EO(e,t=400){return e.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/(token|password|authorization)=([^\s&]+)/gi,"$1=[redacted]").replace(/\s+/g," ").trim().slice(0,t)||"Directory sync operation failed"}cs();H();ZA();var TQt=i.object({checkpoint:Qg.optional(),entityTypes:i.array(i.string()).optional(),fullScanRequest:i.string().optional()}),IQt="directory-sync.git-reconciliation",CQt="current";function $Ve(e){return async(t)=>{let n=await e.getStatus();if(!n.isRepo)return[];let r=new Set(n.files.map((o)=>o.path));return t.filter((o)=>!r.has(o))}}class Lie{store;constructor(e){this.store=new GS({runtimeState:e,namespace:IQt,key:CQt,schema:TQt,createEmpty:()=>({})})}async getCheckpoint(){return(await this.store.snapshot()).checkpoint}saveCheckpoint(e,t){return this.store.mutate((n)=>{if(n.checkpoint=e,t)n.entityTypes=NVe(t)})}requireFullScan(){return this.store.mutate((e)=>{e.fullScanRequest=$r()})}async pullAndQueue(e){let t=await e.gitSync.pull(e.signal,e.onGitProgress);if(t.conflicts&&t.conflicts.length>0)await e.gitSync.acknowledgePullConflicts(await e.directorySync.recordPullConflicts(t.conflicts));return e.signal?.throwIfAborted(),this.queueCurrentDelta(e)}replayAndQueue(e){return this.queueCurrentDelta(e)}async queueCurrentDelta(e){e.signal?.throwIfAborted();let t=NVe(e.context.entityService.getEntityTypes()),n=await this.store.snapshot(),r=e.entityTypesIncomplete!==!0,o=e.full===!0||r&&(n.fullScanRequest!==void 0||!kQt(n.entityTypes,t)),s=await e.gitSync.getReconciliationDelta(o?void 0:n.checkpoint),a=(l)=>this.store.mutate((d)=>{if(d.checkpoint=l,d.entityTypes=t,r&&s.mode==="full"&&d.fullScanRequest===n.fullScanRequest)delete d.fullScanRequest});if(s.mode==="full"){let l=await e.directorySync.queueSyncBatch(e.context,e.source,e.metadata),d=l!==null;if(d)await a(s.checkpoint);return{mode:s.mode,files:[],deletedFiles:[],batch:l,checkpointAdvanced:d}}let c=s.files.length===0?[]:await e.directorySync.withoutStoredEchoes(s.files);if(c.length===0&&s.deletedFiles.length===0){if(s.files.length>0)e.directorySync.ignorePulledWatchPaths(s.files,$Ve(e.gitSync));return await a(s.checkpoint),{mode:s.mode,files:[],deletedFiles:[],batch:null,checkpointAdvanced:!0}}await e.directorySync.recordPendingPullDeletes(s.deletedFiles);let u=await e.directorySync.queueSyncBatch(e.context,e.source,e.metadata,c,s.deletedFiles);if(u)e.directorySync.ignorePulledWatchPaths(s.files,$Ve(e.gitSync)),await a(s.checkpoint);return{mode:s.mode,files:c,deletedFiles:s.deletedFiles,batch:u,checkpointAdvanced:u!==null}}}function NVe(e){return[...new Set(e)].sort()}function kQt(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])}H();import{basename as RQt}from"path";var UVe=i.object({health:i.enum(["healthy","active","attention"]),directory:i.object({displayPath:i.string().min(1),exists:i.boolean(),watching:i.boolean(),totalFiles:i.number().int().nonnegative(),byEntityType:i.record(i.string(),i.number().int().nonnegative()),lastSettledAt:i.string().datetime().optional()}),git:i.object({branch:i.string().min(1),remoteLabel:i.string().min(1).optional(),hasChanges:i.boolean(),ahead:i.number().int().nonnegative(),behind:i.number().int().nonnegative(),lastCommit:i.string().min(1).optional(),changedFiles:i.array(i.object({path:i.string().min(1),status:i.string().min(1)})),changedFilesTruncated:i.boolean()}).nullable(),automation:i.object({autoSync:i.boolean(),watchIntervalMs:i.number().int().nonnegative(),remoteIntervalMinutes:i.number().nonnegative().optional(),commitDebounceMs:i.number().int().nonnegative().optional(),deleteOnFileRemoval:i.boolean()}),activeRun:Nie.optional(),recentRuns:i.array(Fie),issues:i.array(Uie)}),Zie=O_({name:"sync-now",label:"Sync now",permission:"admin",input:i.object({}),output:i.object({accepted:i.boolean(),status:i.string().min(1),runId:i.string().min(1).optional(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional()})}),AQt=new Map([["M","Modified"],["A","Added"],["D","Deleted"],["R","Renamed"],["C","Copied"],["U","Unmerged"],["??","Untracked"]]);function PQt(e){let t=e.imported+e.skipped+e.failed+e.quarantined;return{type:"progress",id:"active-sync",label:"Directory sync",state:e.state,detail:`${t} files handled \xB7 ${e.exported} exported`,startedAt:e.startedAt,updatedAt:e.lastProgressAt,tone:e.failed>0||e.quarantined>0?"warn":"neutral"}}var FVe=I_({id:"sync",label:"Content sync",permission:"admin",data:UVe,actions:[Zie],refresh:({data:e})=>e.activeRun?1000:void 0,view:({data:e})=>{let t=new Map;for(let u of e.issues){let l=t.get(u.kind);if(l)l.push(u);else t.set(u.kind,[u])}let n=e.activeRun?[PQt(e.activeRun)]:[],r=e.git?[{type:"list",id:"changed-files",presentation:"activity",empty:"No changed files.",items:e.git.changedFiles.map((u,l)=>({id:`changed-${l+1}`,title:u.path,description:AQt.get(u.status)??"Working-tree change",metadata:[`Git status: ${u.status} \xB7 working tree`]}))}]:[],o={type:"key-values",id:"sync-repository-facts",items:[{label:"Health",value:e.health},...e.git?[{label:"Branch",value:e.git.branch},{label:"Remote",value:e.git.remoteLabel??"Not supplied"},...e.git.lastCommit?[{label:"Last commit",value:e.git.lastCommit}]:[],{label:"Commits ahead",value:e.git.ahead},{label:"Commits behind",value:e.git.behind}]:[{label:"Remote",value:"files only"}],{label:"Content files",value:e.directory.totalFiles},{label:"Entity types",value:Object.keys(e.directory.byEntityType).length},{label:"Issues",value:e.issues.length},{label:"Automatic sync",value:e.automation.autoSync},{label:"Watch interval",value:`${e.automation.watchIntervalMs} ms`},{label:"Delete removed files",value:e.automation.deleteOnFileRemoval},...e.automation.remoteIntervalMinutes===void 0?[]:[{label:"Remote interval",value:`${e.automation.remoteIntervalMinutes} min`}],...e.automation.commitDebounceMs===void 0?[]:[{label:"Commit debounce",value:`${e.automation.commitDebounceMs} ms`}]]},s=[...n,{type:"list",id:"recent-runs",presentation:"activity",empty:"No directory sync runs have completed yet.",items:e.recentRuns.map((u)=>({id:u.id,title:`${{manual:"Manual sync",periodic:"Periodic sync",watcher:"Watch sync",save:"Save sync",startup:"Startup sync"}[u.source]} \xB7 ${u.outcome}`,description:u.summary,tone:u.outcome==="succeeded"?"good":u.outcome==="failed"?"error":"warn",metadata:[`Imported: ${u.imported}`,`Exported: ${u.exported}`,`Completed: ${u.completedAt}`]}))},...r],c=[...[...t.entries()].flatMap(([u,l])=>{let d=[...l].sort((f,g)=>Date.parse(g.occurredAt)-Date.parse(f.occurredAt)),p=d[0];if(!p)return[];let m=u==="git"?"Repository sync":u==="export"?"Content export":u==="import"?"Content import":u==="placement"?"Content placement":u==="source"?"Content folder":u;return[{type:"notice",id:`sync-issues-${u}`,title:`${m} needs attention`,text:[`${d.length} recorded ${d.length===1?"issue":"issues"}`,p.path].filter(Boolean).join(" \xB7 "),tone:"warn",details:d.map((f)=>[`Occurred: ${f.occurredAt}`,f.path?`Path: ${f.path}`:void 0,f.message].filter(Boolean).join(`
|
|
331
|
+
`)}}class M1{schema=Joe;logger;directorySync;operationStatus;constructor(e,t,n,r){this.logger=e,this.directorySync=n,this.operationStatus=r}async process(e,t,n){this.logger.debug("Processing directory export job",{jobId:t,data:e});let r=Date.now();try{let o=await this.directorySync.exportEntitiesWithProgress(e.entityTypes,n,e.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:t,exported:o.exported,failed:o.failed,duration:Date.now()-r}),await this.operationStatus?.addExportResult(o),o}catch(o){throw this.logger.error("Directory export job failed",{jobId:t,error:o}),await this.operationStatus?.recordIssue({kind:"export",message:de(o,"Directory export failed")}),o}}summarizeDataForLog(e){return{entityTypes:e.entityTypes??"all",batchSize:e.batchSize}}}function wI(e,t,n,r){let o=t.projectionBatch;if(!o)return r();return e.bulkMutations.runDurableBulkMutationChild({source:"directory-sync",operationId:o.operationId,rootJobId:o.rootJobId,childKey:o.childKey,expectedChildren:o.expectedChildren,jobId:n},r)}async function $m(e,t,n,r){let o=t.projectionBatch;if(!o)return;await e.bulkMutations.settleDurableBulkMutationChild({operationId:o.operationId,childKey:o.childKey,jobId:n,outcome:r})}class j1{schema=Woe;logger;directorySync;context;operationStatus;reconciliation;constructor(e,t,n,r,o){this.logger=e,this.context=t,this.directorySync=n,this.operationStatus=r,this.reconciliation=o}async process(e,t,n){return this.logger.debug("Processing directory import job",{jobId:t,data:e}),wI(this.context,e,t,async()=>{await this.refuseUnregisteredEntityTypes(e,t);let r=Date.now();try{let o=await this.directorySync.importEntitiesWithProgress(e.paths,n,e.batchSize??100,e.projectionBatch,e.plan);return this.logger.debug("Directory import job completed",{jobId:t,imported:o.imported,skipped:o.skipped,failed:o.failed,quarantined:o.quarantined,duration:Date.now()-r}),await this.operationStatus?.addImportResult(o),o}catch(o){throw this.logger.error("Directory import job failed",{jobId:t,error:o}),await this.operationStatus?.recordIssue({kind:"import",message:de(o,"Directory import failed")}),o}})}async refuseUnregisteredEntityTypes(e,t){let n=(e.entityTypes??[]).filter((o)=>!this.context.entityService.hasEntityType(o));if(n.length===0)return;let r=`Directory import needs entity types this process does not register: ${n.join(", ")}`;throw this.logger.warn(r,{jobId:t}),await this.reconciliation?.requireFullScan(),await this.operationStatus?.recordIssue({kind:"import",message:r}),Error(r)}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}summarizeDataForLog(e){return{pathCount:e.paths?.length??"all",batchSize:e.batchSize}}}ni();var A5t=300000,P5t=500;async function pVe(e){let t={...e,jobIds:e.jobIds.filter((c)=>c!=="")};if(t.jobIds.length===0)return;let n=t.maxWaitMs??A5t,r=t.pollIntervalMs??P5t;t.logger.debug(`Waiting for ${t.jobIds.length} import jobs to complete`);let o=te.gen(function*(){let c=yield*Wl.currentTimeMillis;yield*te.gen(function*(){let d=(yield*te.tryPromise({try:()=>Promise.all(t.jobIds.map((f)=>t.entityService.getAsyncJobStatus(f))),catch:(f)=>f})).filter((f)=>f&&(f.status==="completed"||f.status==="failed")).length;if(d===t.jobIds.length)return t.logger.debug("All import jobs completed"),!0;if((yield*Wl.currentTimeMillis)-c>n)return t.logger.warn(`Timeout waiting for import jobs (${d}/${t.jobIds.length} completed)`),!0;let m=Math.round(d/t.jobIds.length*100);return yield*te.tryPromise({try:()=>t.reporter.report({progress:50+Math.round(m*0.05),message:`Processing ${d}/${t.jobIds.length} entities`}),catch:(f)=>f}),!1}).pipe(te.repeat({schedule:oa.spaced(r),until:(l)=>l}))}),s=la(o,t.clock),a=await te.runPromiseExit(s);if(Jt.isFailure(a))throw qn.squash(a.cause)}class $1{schema=Goe;logger;getDirectorySync;context;constructor(e,t,n){this.logger=e,this.context=t,this.getDirectorySync=n}async process(e,t,n){let r=Date.now(),o=e.syncDirection??"both",s=this.getDirectorySync();this.logger.info("Starting directory sync job",{jobId:t,operation:e.operation,syncDirection:o});let a={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},c={exported:0,failed:0,errors:[]};if(o!=="export")if(await n.report({progress:10,message:"Scanning directory for changes"}),a=await this.importWithProgress(s,e.paths,n),o==="import")await this.waitForImportJobs(a.jobIds,n),await n.report({progress:100,message:`Import complete: ${a.imported} imported`});else await n.report({progress:50,message:`Imported ${a.imported} entities`}),await this.waitForImportJobs(a.jobIds,n),await n.report({progress:56,message:"Processing complete, starting export"});if(o!=="import"){let l=o==="export"?10:60;await n.report({progress:l,message:"Exporting entities to directory"}),c=await this.exportWithProgress(s,e.entityTypes,n),await n.report({progress:100,message:o==="export"?`Export complete: ${c.exported} exported`:`Sync complete: ${a.imported} imported, ${c.exported} exported`})}let u=Date.now()-r;return this.logger.info("Directory sync job completed",{jobId:t,duration:u,imported:a.imported,exported:c.exported}),{import:a,export:c,duration:u}}async importWithProgress(e,t,n){try{return await e.importEntitiesWithProgress(t,n,10)}catch(r){throw this.logger.error("Import phase failed",{error:r}),r}}async exportWithProgress(e,t,n){try{return await e.exportEntitiesWithProgress(t,n,10)}catch(r){throw this.logger.error("Export phase failed",{error:r}),r}}waitForImportJobs(e,t){return pVe({jobIds:e,entityService:this.context.entityService,reporter:t,logger:this.logger})}summarizeDataForLog(e){return{operation:e.operation,syncDirection:e.syncDirection}}}class N1{schema=Hoe;context;getDirectorySync;getGitSync;reconciliation;operationStatus;constructor(e,t,n,r,o){this.context=e,this.getDirectorySync=t,this.getGitSync=n,this.reconciliation=r,this.operationStatus=o}async process(e,t,n){await n.report({progress:5,message:"Pulling latest content from git"});let r=e.runId?this.operationStatus?.createProgressObserver(e.runId):void 0;r?.();let s=(await this.reconciliation.pullAndQueue({gitSync:this.getGitSync(),directorySync:this.getDirectorySync(),context:this.context,source:e.source,full:e.full,...r?{onGitProgress:r}:{},metadata:{rootJobId:t,interfaceType:e.interfaceType,channelId:e.channelId}})).batch;if(await n.report({progress:35,message:"Scanning pulled content for sync changes"}),!s)return await n.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await n.report({progress:100,message:`Sync queued: ${s.importOperationsCount} import jobs for ${s.totalFiles} files`}),_5t(s)}summarizeDataForLog(e){return{source:e.source,interfaceType:e.interfaceType,channelId:e.channelId}}}function _5t(e){return{gitPulled:!0,batchQueued:!0,batchId:e.batchId,importOperations:e.importOperationsCount,totalFiles:e.totalFiles}}class F1{schema=x1;logger;context;directorySync;constructor(e,t,n){this.logger=e,this.context=t,this.directorySync=n}async process(e,t,n){return wI(this.context,e,t,async()=>{let r=x1.parse(e),o="deletions"in r,s=o?r.deletions:[r];await n.report({progress:0,total:s.length,message:s.length===1?`Deleting ${s[0]?.entityType}:${s[0]?.entityId}`:`Deleting ${s.length} entities`});let a=[];for(let[u,l]of s.entries())a.push(await this.deleteEntity(l,u+1,s.length,n));if(o)return a;let c=a[0];if(!c)throw Error("Directory delete job has no targets");return c})}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}summarizeDataForLog(e){if("deletions"in e)return{deletionCount:e.deletions.length};return{entityId:e.entityId,entityType:e.entityType,filePath:e.filePath}}async deleteEntity(e,t,n,r){this.logger.info("Processing entity deletion for removed file",e);let o=await this.remainingFiles(e);if(o.length>0)return this.logger.info("Kept entity another of its files still holds",{...e,remaining:o}),await this.directorySync.importEntities(o),await r.report({progress:t,total:n,message:`Kept ${e.entityType}:${e.entityId}`}),this.directorySync.completePendingDelete(e.entityType,e.entityId,e.filePath),{deleted:!1,...e};try{let s=await this.directorySync.deleteForRemovedFile(e.entityType,e.entityId),a=s==="deleted";if(a)this.logger.info("Successfully deleted entity for removed file",{entityId:e.entityId,entityType:e.entityType});else if(s==="kept")this.logger.info("Kept an entity that changed since its file was last written",{entityId:e.entityId,entityType:e.entityType});else this.logger.warn("Entity not found in database",{entityId:e.entityId,entityType:e.entityType});return await r.report({progress:t,total:n,message:`Deleted ${e.entityType}:${e.entityId}`}),this.directorySync.completePendingDelete(e.entityType,e.entityId,e.filePath),{deleted:a,...e}}catch(s){throw this.logger.error("Failed to delete entity",{...e,error:s}),s}}async remainingFiles(e){let t=[...new Set([e.filePath,...this.directorySync.fileOps.getEntityDeletePaths(e.entityType,e.entityId)])],n=await Promise.all(t.map((r)=>this.directorySync.fileOps.fileExists(r)));return t.filter((r,o)=>n[o])}}H();var O5t=i.object({projectionBatch:fI.optional()});class U1{schema=O5t;context;directorySync;constructor(e,t){this.context=e,this.directorySync=t}async process(e,t,n){return wI(this.context,e,t,async()=>{await n.report({progress:0,message:"Removing orphaned entities"});let r=await this.directorySync.removeOrphanedEntities(e.projectionBatch);return await n.report({progress:100,message:`Cleanup complete: ${r.deleted} orphans removed`}),r})}async onTerminalSuccess(e,t){await $m(this.context,e,t,"completed")}async onTerminalError(e,t,n){await $m(this.context,t,n,"failed")}}import{readFile as D5t}from"fs/promises";async function Is(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}H();var z5t=i.record(i.string(),i.unknown());class B1{schema=Voe;logger;context;fetcher;constructor(e,t,n=Tm){this.logger=t,this.context=e,this.fetcher=n}async process(e,t,n){let{filePath:r,sourceUrl:o,postTitle:s,postSlug:a,customAlt:c}=e;this.logger.debug("Starting image conversion job",{jobId:t,filePath:r,sourceUrl:o,postSlug:a});try{await Is(n,{progress:Ko.INIT,message:`Reading file: ${r}`});let u;try{u=await D5t(r,"utf-8")}catch(h){return this.logger.error("Failed to read file",{filePath:r,error:de(h)}),Zp.failure(h)}let l;try{l=ba(u)}catch(h){return this.logger.warn("Failed to parse markdown",{filePath:r,error:de(h)}),Zp.failure(h)}let d=z5t.safeParse(l.frontmatter),p=d.success?d.data:{};if(p.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await Is(n,{progress:Ko.FETCH,message:"Checking for existing image"});let m=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:o}},limit:1}}),f;if(m[0])f=m[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:o,imageId:f}),await Is(n,{progress:Ko.EXTRACT,message:`Reusing existing image: ${f}`});else{await Is(n,{progress:Ko.PROCESS,message:`Fetching image from ${o}`});let h;try{h=await this.fetcher(o)}catch(E){return this.logger.error("Failed to fetch image",{sourceUrl:o,error:de(E)}),Zp.failure(E)}await Is(n,{progress:Ko.GENERATE,message:"Creating image entity"}),f=`${a}-cover`;let v=`Cover image for ${s}`,S;try{S=await UP(this.context.entityService,{dataUrl:h},{title:v,alt:c??v,sourceUrl:o})}catch(E){return this.logger.error("Fetched image cannot be stored",{sourceUrl:o,error:de(E)}),Zp.failure(E)}await this.context.entityService.createEntity({entity:{id:f,...S.entity},stagedAsset:S.stagedAsset}),this.logger.debug("Created image entity",{imageId:f,sourceUrl:o}),await Is(n,{progress:Ko.EXTRACT,message:`Created image: ${f}`})}await Is(n,{progress:Ko.SAVE,message:"Updating file"});let g={...p};delete g.coverImageUrl,delete g.coverImageAlt,g.coverImageId=f;let y=Sa(g,l.content);try{await Dd(r,y)}catch(h){return this.logger.error("Failed to write file",{filePath:r,error:de(h)}),Zp.failure(h)}return await Is(n,{progress:Ko.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:r,imageId:f,sourceUrl:o}),{success:!0,imageId:f}}catch(u){return this.logger.error("Image conversion job failed",{jobId:t,filePath:r,error:de(u)}),Zp.failure(u)}}summarizeDataForLog(e){return{filePath:e.filePath,sourceUrl:e.sourceUrl,postSlug:e.postSlug}}}import{readFile as M5t}from"fs/promises";class L1{schema=Koe;logger;converter;constructor(e,t,n=Tm){this.logger=t,this.converter=new xO(e.entityService,t,n)}async process(e,t,n){let{filePath:r,postSlug:o}=e;this.logger.debug("Starting inline image conversion job",{jobId:t,filePath:r,postSlug:o});try{await Is(n,{progress:Ko.INIT,message:`Reading file: ${r}`});let s;try{s=await M5t(r,"utf-8")}catch(u){let l=de(u);return this.logger.error("Failed to read file",{filePath:r,error:l}),{success:!1,error:l}}await Is(n,{progress:Ko.FETCH,message:"Detecting inline images"});let a=this.converter.detectInlineImages(s,o);if(a.length===0)return this.logger.debug("No inline images to convert",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:r,count:a.length}),await Is(n,{progress:Ko.PROCESS,message:`Converting ${a.length} images`});let c=await this.converter.convert(s,o);if(!c.converted)return this.logger.debug("No images were converted",{filePath:r}),await Is(n,{progress:Ko.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await Is(n,{progress:Ko.SAVE,message:"Writing updated file"});try{await Dd(r,c.content)}catch(u){let l=de(u);return this.logger.error("Failed to write file",{filePath:r,error:l}),{success:!1,error:l}}return await Is(n,{progress:Ko.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:r,convertedCount:c.convertedCount}),{success:!0,convertedCount:c.convertedCount}}catch(s){let a=de(s);return this.logger.error("Inline image conversion job failed",{jobId:t,filePath:r,error:a}),{success:!1,error:a}}}summarizeDataForLog(e){return{filePath:e.filePath,postSlug:e.postSlug}}}function Nm(e,t){let n=t.summarizeDataForLog?.bind(t);return nL({type:e,input:t.schema,...n&&{summarize:n},process:({input:r,jobId:o,progress:s,signal:a})=>t.process(r,o,s,a)})}function fVe(e,t,n,r=()=>t,o,s){let a=(c)=>n.child(c);return[Nm("directory-sync",new $1(a("DirectorySyncJobHandler"),e,r)),Nm("directory-export",new M1(a("DirectoryExportJobHandler"),e,t,o)),Nm("directory-import",new j1(a("DirectoryImportJobHandler"),e,t,o,s)),Nm("directory-delete",new F1(a("DirectoryDeleteJobHandler"),e,t)),Nm("directory-cleanup",new U1(e,t)),Nm("cover-image-convert",new B1(e,a("CoverImageConversionJobHandler"))),Nm("inline-image-convert",new L1(e,a("InlineImageConversionJobHandler")))]}cs();H();var j5t=i.record(i.string(),i.unknown());function mVe(e,t,n,r,o){for(let s of[UE,BE,LE])e.runtime.listen(s,()=>{t()},{mode:"observe"});n.debug("Setup durable entity-export wakeups",{entityTypes:r})}function gVe(e,t,n,r,o){t.setJobQueueCallback(async(s)=>{let a=await r?.startRun("watcher","importing"),c=[{type:s.type,data:j5t.parse(s.data)}],u=$r(),l=async()=>{let p=await e.jobs.enqueueBatch(c,{priority:5,source:"directory-sync-watcher",rootJobId:u,metadata:{operationType:"file_operations",operationTarget:n,pluginId:"directory-sync"}});if(a)await r?.attachBatch(a,p);return p},d=async(p)=>{if(!a)return;await r?.failRun(a,de(p,"Watcher import failed"),"import")};try{return await l()}catch(p){o.retry(l,p,`queue a watched ${s.type}`).then(async(m)=>{if(m.kind!=="succeeded")await d(p)}).catch((m)=>{e.logger.warn("Failed to record a stopped watcher run",{error:m})});return}})}import{readdir as yVe,mkdir as $5t,copyFile as N5t}from"fs/promises";import{join as hVe,resolve as Die}from"path";async function F5t(e,t,n){if(!await co(e))return!0;if((await yVe(e)).filter((s)=>!s.startsWith(".")&&!s.startsWith("_")).length>0)return!1;if(n){let s=await n.getStatus();if(s.isRepo&&s.lastCommit!==void 0)return t.debug("Git repository with history detected - skipping seed content",{path:e}),!1}return!0}async function bVe(e,t){let n=await yVe(e,{withFileTypes:!0});for(let r of n){let o=hVe(e,r.name),s=hVe(t,r.name);if(r.isDirectory()){if(!await co(s))await $5t(s,{recursive:!0});await bVe(o,s)}else await N5t(o,s)}}async function SVe(e,t,n,r){let o=Die(process.cwd(),e);n=n?Die(n):Die(process.cwd(),"seed-content");let s=await F5t(o,t,r);if(s&&await co(n))t.debug("Copying seed content to brain-data directory"),await bVe(n,o),t.debug("Seed content copied successfully");else if(s)t.debug("No seed content directory found, starting with empty brain-data");else t.debug("brain-data directory not empty, skipping seed content")}var xVe="initial-sync";function vVe(e){let{context:t,config:n,logger:r,gitSync:o}=e,s=!1,a=async()=>{if(s)return{initialSyncPending:!1};if(s=!0,n.seedContent){let d=n.syncPath??t.dataDir;if(await SVe(d,r,n.seedContentPath,o),n.strictSeedEntityTypes)await _1(d,t.entityService)}let c;try{c=await U5t(e)}catch(d){return r.error("Initial sync failed",d),await wVe(e),await e.recovery?.onGitRecoveryFailed(d),await t.runtime.messaging.broadcast(wT,{success:!1,error:de(d)}),{initialSyncPending:!0}}let{batchIds:u,runId:l}=c;if(u.length===0)return await t.runtime.messaging.broadcast(wT,{success:!0}),{initialSyncPending:!1};return r.info("Initial sync queued for the worker",{batchIds:u}),L5t(t,u).then(async(d)=>{await B5t(e,l,d),await t.runtime.messaging.broadcast(wT,d)}).catch((d)=>{r.error("Unable to report initial sync completion",d)}),{initialSyncPending:!0}};t.runtime.initialSync(async()=>(r.debug("Plugins registered, queueing initial sync"),a()))}async function U5t(e){let{context:t,getDirectorySync:n,gitSync:r,reconciliation:o,recovery:s,operationStatus:a}=e,c=n(),u=(await a?.getSnapshot())?.activeRun?.batchId,l=await a?.startRun("startup",r?"pulling":"scanning"),d;try{if(r&&o)s?.onGitProgress(),d=(await o.pullAndQueue({gitSync:r,directorySync:c,context:t,source:xVe,full:!0,...s?{onGitProgress:s.onGitProgress}:{}})).batch;else d=await c.queueSyncBatch(t,xVe)}catch(p){if(l)await a?.failRun(l,de(p,"Initial sync failed"),r?"git":"source");throw p}if(await s?.onGitRecoverySucceeded(),l)if(d)await a?.attachBatch(l,d.batchId);else await a?.completeRun(l,"No files to import");return{batchIds:[u,d?.batchId].filter((p)=>p!==void 0),runId:d?l:void 0}}async function B5t(e,t,n){if(n.success){if(t)await e.operationStatus?.completeRun(t,"Startup import completed");return}if(e.logger.error("Initial sync import failed",{error:n.error}),await wVe(e),t)await e.operationStatus?.failRun(t,n.error,"import")}function L5t(e,t){return new Promise((n)=>{let r=new Set(t),o=[],s=(c,u)=>{if(!r.delete(c))return;if(u)o.push(...u.length>0?u:[`Initial sync batch ${c} failed`]);if(r.size>0)return;a(),n(o.length===0?{success:!0}:{success:!1,error:o.join("; ")})},a=e.runtime.listen(Eh,({payload:c})=>{if(c.type==="batch"){if(c.status==="completed")s(c.id,null);if(c.status==="failed")s(c.id,c.batchDetails?.errors??[])}});for(let c of t)e.jobs.getBatchStatus(c).then((u)=>{if(!u)s(c,[`Initial sync batch ${c} was not found`]);else if(u.status==="completed")s(c,null);else if(u.status==="failed")s(c,u.errors)},(u)=>s(c,[de(u)]))})}async function wVe(e){try{await e.reconciliation?.requireFullScan()}catch(t){e.logger.error("Unable to require a full rescan",t)}}var Z5t={guard:(e)=>e(),progress:async()=>{},succeeded:async()=>{},requiresRepository:async()=>{},initialSyncRecovery:()=>{return}};function EVe(e){let{operationStatus:t,interruptedPull:n}=e;if(e.executionOnly||!n)return Z5t;let r=n.id,o=(c,u)=>t.finishInterruptedPull(r,{recovered:c,message:u}),s=(c)=>o(!0,`Recovered interrupted Git handoff during ${c}`),a=(c)=>o(!1,`Interrupted Git handoff recovery failed: ${de(c)}`);return{guard:async(c)=>{try{return await c()}catch(u){throw await a(u),u}},progress:()=>t.markProgress(r),succeeded:s,requiresRepository:()=>o(!1,"Interrupted Git handoff recovery requires a configured repository"),initialSyncRecovery:()=>({onGitProgress:t.createProgressObserver(r),onGitRecoverySucceeded:()=>s("initial sync"),onGitRecoveryFailed:a})}}function TVe(e){let{gitSync:t,directorySync:n,context:r,intervalMinutes:o,logger:s,runtime:a,reconciliation:c,operationStatus:u}=e;if(o<=0)return;let l=o*60*1000,d=async(p)=>{let m=await u?.startRun("periodic","pulling");try{let f=m?u?.createProgressObserver(m):void 0,g=await c.pullAndQueue({gitSync:t,directorySync:n,context:r,source:"periodic-sync",signal:p,...f?{onGitProgress:f}:{}});if(m)await u?.markPhase(m,"scanning");let{files:y,batch:h}=g;if(y.length>0)s.info("Periodic sync: pulled changes",{filesChanged:y.length});if(h){if(s.debug("Periodic sync: queued imports",{importOperations:h.importOperationsCount,totalFiles:h.totalFiles}),m)await u?.attachBatch(m,h.batchId)}else if(m)await u?.completeRun(m,y.length===0?"Remote checked; no changes found":"Remote changes required no imports")}catch(f){if(p.aborted){if(m)await u?.clearRun(m)}else if(s.error("Periodic git sync failed",{error:f}),m)await u?.failRun(m,de(f,"Periodic Git sync failed"))}};a.schedulePeriodic(l,d),s.info("Started periodic git sync",{intervalMinutes:o})}async function IVe(e){try{return await e(),!0}catch(t){if(!(t instanceof jm))throw t;return!1}}async function zie(e){let t=await e.listPendingEntityExports(),n=[],r=!1;for(let a of t){if(e.isPendingRemoteDelete(a.entityType,a.entityId)){n.push(a);continue}if(a.operation==="delete"){let l=await IVe(()=>e.deleteEntityFile(a.entityType,a.entityId));n.push(a),r||=l;continue}let c=await e.getEntity({entityType:a.entityType,id:a.entityId,visibilityScope:on("directory sync drains durable exports across all visibility tiers"),source:!0});if(!c)throw Error(`Durable entity export cannot resolve upsert target ${a.entityType}:${a.entityId} at revision ${a.revision}`);let u=await IVe(()=>e.writeEntity(c));n.push(a),r||=u}let o=!1;if(r&&e.commitAndPush){let a=await e.commitAndPush();if(o=a.pushed,a.checkpoint===null)throw Error("Git export did not return a confirmed checkpoint; durable intents remain pending");if(!e.saveCheckpoint)throw Error("Git export checkpoint persistence is unavailable; durable intents remain pending");await e.saveCheckpoint(a.checkpoint)}let s=await e.acknowledgeEntityExports({intents:n});return{processed:n.length,acknowledged:s,pushed:o}}var q5t=5000,G5t=100;class Mie{queue=new qS;runtime;directorySync;entityService;gitSync;saveCheckpoint;operationStatus;logger;debounceMs;reconciliationIntervalMs;started=!1;constructor(e){this.runtime=e.runtime,this.directorySync=e.directorySync,this.entityService=e.entityService,this.gitSync=e.gitSync,this.saveCheckpoint=e.saveCheckpoint,this.operationStatus=e.operationStatus,this.logger=e.logger,this.debounceMs=e.debounceMs,this.reconciliationIntervalMs=e.reconciliationIntervalMs??q5t}async start(){if(this.started)return;this.started=!0,this.runtime.schedulePeriodic(this.reconciliationIntervalMs,(e)=>this.reconcilePending(e)),await this.reconcilePending()}wake(){this.runtime.scheduleTrailing("durable-entity-export",this.debounceMs,()=>this.attemptDrain())}async settleBeforeCleanup(){try{await this.drain()}catch(e){throw await this.recordFailure(e),this.wake(),e}}async reconcilePending(e){try{if(e?.throwIfAborted(),!await this.entityService.hasPendingEntityExports())return;e?.throwIfAborted(),await this.drain()}catch(t){if(e?.aborted)return;await this.recordFailure(t),this.wake()}}async attemptDrain(){try{await this.drain()}catch(e){await this.recordFailure(e),this.wake()}}async drain(){await this.queue.run(()=>this.drainPass(G5t))}async drainPass(e){let t={listPendingEntityExports:()=>this.entityService.listPendingEntityExports(),getEntity:(s)=>this.entityService.getEntityRaw({...s}),writeEntity:async(s)=>{this.directorySync.suppressWatchPaths(this.directorySync.fileOps.getEntityConvergencePaths(s));try{await this.directorySync.writeEntityFile(s)}catch(a){if(a instanceof jm)this.logger.warn("Entity placement refused",{error:a}),await this.operationStatus?.recordIssue({kind:"placement",path:`${s.entityType}/${s.id}`,message:`Saved but not exported: ${a.message}`});throw a}await this.operationStatus?.clearIssue({kind:"placement",path:`${s.entityType}/${s.id}`})},deleteEntityFile:async(s,a)=>{this.directorySync.suppressWatchPaths(this.directorySync.fileOps.getEntityDeletePaths(s,a)),await this.directorySync.fileOps.deleteEntityFiles(s,a)},isPendingRemoteDelete:(s,a)=>this.directorySync.isPendingDelete(s,a),acknowledgeEntityExports:async(s)=>{for(let a of s.intents)if(a.operation==="delete")await this.operationStatus?.clearIssue({kind:"placement",path:`${a.entityType}/${a.entityId}`});return this.entityService.acknowledgeEntityExports(s)}},n=this.gitSync,r=this.saveCheckpoint,o=n?await zie({...t,commitAndPush:()=>n.commitAndPush(),saveCheckpoint:async(s)=>{if(!r)throw Error("Git export checkpoint persistence is unavailable; durable intents remain pending");await r(s)}}):await zie(t);if(!await this.entityService.hasPendingEntityExports()){await this.operationStatus?.clearIssues(["export","git"]);return}if(o.processed===0)throw Error("Durable entity exports could not make progress");if(e<=1)throw Error("Durable entity exports did not settle");await this.drainPass(e-1)}async recordFailure(e){let t=de(e,"Entity export failed");this.logger.error("Durable entity export failed",{error:e});try{await this.operationStatus?.recordIssue({kind:"export",message:t})}catch(n){this.logger.error("Failed to record durable entity export issue",{error:n})}}}async function jie(e,t={}){let[n]=e;if(n===void 0)throw Error("runProcess needs a command to run");let r=Bun.spawn([...e],{...t.cwd===void 0?{}:{cwd:t.cwd},...t.env===void 0?{}:{env:t.env},...t.stdin===void 0?{}:{stdin:Buffer.from(t.stdin)},stdout:"pipe",stderr:"pipe"}),[o,s,a]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{exitCode:a,stdout:o,stderr:s}}import{cpSync as H5t,existsSync as CVe,mkdirSync as W5t,mkdtempSync as J5t,rmSync as V5t}from"fs";import{tmpdir as K5t}from"os";import{fileURLToPath as Q5t}from"url";import{join as Y5t,resolve as X5t}from"path";async function Bh(e,t){let n=await jie(["git",...t],{cwd:e});if(n.exitCode!==0){let r=n.stderr.trim(),o=n.stdout.trim();throw Error(r||o||`git ${t.join(" ")} failed`)}}function eQt(e){return e.startsWith("file://")}function tQt(e){return Q5t(e)}async function nQt(e,t){return(await jie(["git","--git-dir",e,"show-ref","--verify","--quiet",`refs/heads/${t}`])).exitCode===0}async function kVe(e){if(!e.bootstrapFromSeed)return;if(!e.gitUrl||!eQt(e.gitUrl))return;if(!e.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let t=e.branch??"main",n=tQt(e.gitUrl),r=X5t(e.seedContentPath);if(!CVe(r))throw Error(`Seed content path not found: ${r}`);if(!CVe(n))e.logger.debug("Creating local bare content remote",{remotePath:n,branch:t}),W5t(n,{recursive:!0}),await Bh(process.cwd(),["init","--bare",`--initial-branch=${t}`,n]);if(await nQt(n,t)){e.logger.debug("Content remote already initialized",{remotePath:n,branch:t});return}e.logger.debug("Seeding local content remote",{remotePath:n,seedPath:r,branch:t});let o=J5t(Y5t(K5t(),"directory-sync-seed-"));try{await Bh(o,["init",`--initial-branch=${t}`]),await Bh(o,["config","user.name",e.authorName??"Brain"]),await Bh(o,["config","user.email",e.authorEmail??"brain@localhost"]),H5t(r,o,{recursive:!0,filter:(s)=>!s.split("/").includes(".git")}),await Bh(o,["add","."]),await Bh(o,["commit","-m","seed content remote"]),await Bh(o,["remote","add","origin",e.gitUrl]),await Bh(o,["push","-u","origin",t])}finally{V5t(o,{recursive:!0,force:!0})}}function RVe(e,t,n,r,o){e.runtime.answer(AY,({request:s})=>{let a=JS(s),{relativePath:c,owner:u,writable:l}=WS(s.entityType,s.entityId,a,Uh(e.entityService)),[d,...p]=Jp(s.entityId),m=p.at(-1)??d,f=c.length-a.length,g=m&&c.endsWith(`${m}${a}`)?{start:f-m.length,end:f}:null;return{relativePath:c,leaf:g,owner:u,writable:l}}),e.runtime.answer(PY,async()=>{let s=await t().getStatus(),a=o?.();return{syncPath:s.syncPath,isInitialized:s.exists,watchEnabled:s.watching,lastSync:s.lastSync?.toISOString()??null,totalFiles:s.stats.totalFiles,byEntityType:s.stats.byEntityType,git:await rQt(r?.(),n),...a?{managementUrl:a}:{}}}),n.debug("Registered message handlers")}async function rQt(e,t){if(!e)return null;try{let n=await e.getStatus();return{branch:n.branch,hasChanges:n.hasChanges,ahead:n.ahead,behind:n.behind,lastCommit:n.lastCommit??null,remote:n.remote??null}}catch(n){return t.debug("Git status unavailable for sync:status:request",{error:n}),null}}H();async function Z1(e){let t=await e.operationStatus?.startRun("manual",e.gitSync?"pulling":"scanning");try{if(e.gitSync){let r=await e.context.jobs.enqueue({type:"sync-request",data:{source:e.source,runId:t,interfaceType:e.interfaceType,channelId:e.channelId,...e.full?{full:!0}:{}},...e.toolContext?{toolContext:e.toolContext}:{}});if(t)await e.operationStatus?.attachJob(t,r);return{...t?{runId:t}:{},gitPulled:!0,jobId:r,status:"queued"}}let n=await e.directorySync.queueSyncBatch(e.context,e.source,{interfaceType:e.interfaceType,channelId:e.channelId});if(!n){if(t)await e.operationStatus?.completeRun(t,"No files to sync");return{...t?{runId:t}:{},gitPulled:!1,status:"settled"}}if(t)await e.operationStatus?.attachBatch(t,n.batchId);return{...t?{runId:t}:{},...n,gitPulled:!1,status:"queued"}}catch(n){if(t)await e.operationStatus?.failRun(t,de(n,"Sync request failed"),e.gitSync?"git":"source");throw n}}H();var AVe=i.object({action:i.literal("history"),entityType:i.string().min(1),id:i.string().min(1),sha:i.string().optional(),limit:i.number().int().positive().optional().default(10)});async function PVe(e,t){let n=`${e.entityType}/${e.id}.md`;try{if(e.sha){let o=await t.show(e.sha,n);return Cl({sha:e.sha,entityType:e.entityType,id:e.id,content:o},`Content at ${e.sha.slice(0,7)}`)}let r=await t.log(n,e.limit);if(r.length===0)return Cl({commits:[]},`No history found for ${e.entityType}/${e.id}`);return Cl({commits:r,entityType:e.entityType,id:e.id},`${r.length} version${r.length===1?"":"s"} found`)}catch(r){return Rm(de(r,"History lookup failed"))}}var oQt=i.object({action:i.enum(["sync","status"]).default("sync").describe("Use sync for a refresh request and status for a status check")}),iQt=i.object({action:i.enum(["sync","status","history"]).default("sync").describe("Use sync for git/filesystem sync, status for a status check, and history only for entity history"),full:i.boolean().optional().describe("Sync only; true rescans every file instead of the changes since the last sync, for files an earlier sync skipped"),entityType:i.string().optional().describe("History only; omit for sync and status"),id:i.string().optional().describe("History only; omit for sync and status"),sha:i.string().optional().describe("Optional history revision; omit for sync and status"),limit:i.number().int().positive().optional().default(10).describe("History only; omit for sync and status")}),sQt=i.discriminatedUnion("action",[i.object({action:i.literal("sync")}),i.object({action:i.literal("status")})]),aQt=i.discriminatedUnion("action",[i.object({action:i.literal("sync"),full:i.boolean().optional()}),i.object({action:i.literal("status")}),AVe]);function _Ve(e,t,n,r,o){return[b_("directory","sync",r?"Manage directory and git sync with an action discriminator. For requests such as 'sync with git', immediately call action=sync with no entityType, id, or sha; never ask for those fields because they apply only to action=history. Action=sync queues a git pull plus a scan of the brain's content directory; call it only when the user asks to sync, refresh, pull, or back up the content. A file attached in chat is not in the content directory: save it with system_create with source kind upload, never by syncing. For every sync or git status follow-up after action=sync, including a bare 'what is the status', immediately call action=status with no entity fields; a sync jobId is not a system_job_status batchId. Use action=history to read git version history for a specific entity.":"Manage the brain's content directory sync with an action discriminator. Call action=sync only when the user asks to sync, refresh, or import the content directory itself, such as 'refresh my content from the filesystem'. A file attached in chat is not in the content directory: save it with system_create with source kind upload, never by syncing. Immediately call action=status for directory sync status follow-ups, including a bare 'what is the status'.",r?iQt:oQt,async(a,c)=>{let u=r?aQt.parse(a):sQt.parse(a);if(u.action==="sync")return cQt({directorySync:e,pluginContext:t,pluginId:n,gitSync:r,operationStatus:o,context:c,full:"full"in u&&u.full===!0});if(u.action==="status")return uQt(e,r);if(!r)return Rm("History is unavailable because git is not configured");return PVe(u,r)},{visibility:"admin",sideEffects:"external",cli:{name:"sync"}})]}async function cQt(e){try{let t=e.context.channelId?`${e.context.interfaceType}:${e.context.channelId}`:`plugin:${e.pluginId}`,n=await Z1({context:e.pluginContext,directorySync:e.directorySync,source:t,interfaceType:e.context.interfaceType,channelId:e.context.channelId,toolContext:e.context,gitSync:e.gitSync,operationStatus:e.operationStatus,full:e.full});if(n.gitPulled)return Cl({jobId:n.jobId,status:n.status,gitPulled:!0,...n.runId?{runId:n.runId}:{}},"Sync queued: git pull and filesystem scan will run in the background");if(n.status==="settled")return Cl({gitPulled:!1,...n.runId?{runId:n.runId}:{}},"No files to sync");return Cl({batchId:n.batchId,importOperations:n.importOperationsCount,totalFiles:n.totalFiles,gitPulled:!1,...n.runId?{runId:n.runId}:{}},`Sync started: ${n.importOperationsCount} import jobs queued for ${n.totalFiles} files`)}catch(t){return Rm(de(t,"Sync failed"))}}async function uQt(e,t){try{let n=await e.getStatus(),r={syncPath:n.syncPath,lastSync:n.lastSync?.toISOString(),watching:n.watching};if(!t)r.git={configured:!1};else{let o=await t.getStatus();r.git={isRepo:o.isRepo,branch:o.branch,hasChanges:o.hasChanges,ahead:o.ahead,behind:o.behind,remote:o.remote}}return Cl(r)}catch(n){return Rm(de(n,"Status check failed"))}}cs();H();import{isAbsolute as OVe,relative as lQt}from"path";var MVe=i.enum(["manual","periodic","watcher","save","startup"]),dQt=i.enum(["pulling","scanning","importing","settling"]),pQt=i.enum(["succeeded","attention","failed"]),fQt=i.enum(["quarantined","import","export","placement","git","source"]),jVe=i.object({imported:i.number().int().nonnegative(),skipped:i.number().int().nonnegative(),failed:i.number().int().nonnegative(),quarantined:i.number().int().nonnegative(),exported:i.number().int().nonnegative()}),Nie=i.preprocess((e)=>{if(typeof e!=="object"||e===null||"lastProgressAt"in e||!("startedAt"in e)||typeof e.startedAt!=="string")return e;return{...e,lastProgressAt:e.startedAt}},i.object({id:i.string().min(1),source:MVe,state:dQt,startedAt:i.string().datetime(),lastProgressAt:i.string().datetime(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional(),...jVe.shape})),Fie=i.object({id:i.string().min(1),source:MVe,outcome:pQt,startedAt:i.string().datetime(),completedAt:i.string().datetime(),summary:i.string().min(1).max(240),...jVe.shape}),Uie=i.object({id:i.string().min(1),kind:fQt,path:i.string().min(1).max(300).optional(),message:i.string().min(1).max(400),occurredAt:i.string().datetime()}),mQt=i.object({activeRun:Nie.optional(),recentRuns:i.array(Fie).max(5),issues:i.array(Uie)}),gQt=i.object({gitPulled:i.literal(!0),batchQueued:i.boolean(),batchId:i.string().optional(),importOperations:i.number().int().nonnegative().optional(),totalFiles:i.number().int().nonnegative().optional()}),DVe={imported:0,skipped:0,failed:0,quarantined:0,exported:0},hQt={recentRuns:[],issues:[]},yQt=i.object({lastProgressAt:i.string().datetime()}),bQt="directory-sync.operation-status",SQt="current",xQt="directory-sync.operation-progress",vQt=1000,wQt=30000;class Bie{store;progressStore;jobs;logger;now;inactivityTimeoutMs;staleGraceMs;progressPersistenceIntervalMs;lastProgressPersistence=new Map;syncPath;constructor(e,t,n,r,o={}){this.store=new GS({runtimeState:e,namespace:bQt,key:SQt,schema:mQt,createEmpty:()=>structuredClone(hQt)}),this.progressStore=e.scoped({namespace:xQt,schema:yQt}),this.jobs=t,this.logger=n,this.syncPath=r,this.now=o.now??Date.now,this.inactivityTimeoutMs=o.inactivityTimeoutMs??sD,this.staleGraceMs=o.staleGraceMs??wQt,this.progressPersistenceIntervalMs=o.progressPersistenceIntervalMs??vQt}setSyncPath(e){this.syncPath=e}async initialize(e){if(e?.executionOnly)return;let t=await this.store.snapshot();if(t.activeRun&&!t.activeRun.jobId&&!t.activeRun.batchId){if(t.activeRun.state==="pulling")return this.withEffectiveProgress(t.activeRun);await this.clearRun(t.activeRun.id);return}await this.reconcile();return}startRun(e,t){let n=$r(),r=this.now();return this.mutate((o)=>{if(o.activeRun)return;let s=new Date(r).toISOString();return o.activeRun={id:n,source:e,state:t,startedAt:s,lastProgressAt:s,...DVe},this.lastProgressPersistence.set(n,r),n})}markPhase(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;r.activeRun.state=t,r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}async markProgress(e){let t=this.now(),n=this.lastProgressPersistence.get(e);if(n!==void 0&&t-n<this.progressPersistenceIntervalMs)return;this.lastProgressPersistence.set(e,t),await this.progressStore.set(e,{lastProgressAt:new Date(t).toISOString()})}createProgressObserver(e){return()=>{this.markProgress(e).catch((t)=>{this.logger.debug("Unable to persist directory Git progress",{error:t})})}}attachJob(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;r.activeRun.jobId=t,r.activeRun.state="pulling",r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}attachBatch(e,t){let n=this.now();return this.mutate((r)=>{if(r.activeRun?.id!==e)return;delete r.activeRun.jobId,r.activeRun.batchId=t,r.activeRun.state="importing",r.activeRun.lastProgressAt=new Date(n).toISOString(),this.lastProgressPersistence.set(e,n)})}addImportResult(e){let t=this.now();return this.mutate((n)=>{if(n.activeRun)n.activeRun.imported+=e.imported,n.activeRun.skipped+=e.skipped,n.activeRun.failed+=e.failed,n.activeRun.quarantined+=e.quarantined,n.activeRun.lastProgressAt=new Date(t).toISOString(),this.lastProgressPersistence.set(n.activeRun.id,t);let r=[...(e.issues??[]).map((o)=>({kind:"import",path:this.safePath(o.path),message:o.message})),...e.errors.map((o)=>({kind:"import",path:this.safePath(o.path),message:o.error})),...e.quarantinedFiles.map((o)=>({kind:"quarantined",path:this.safePath(o),message:"File was quarantined because it could not be imported"}))];if(r.length===0)n.issues=n.issues.filter((o)=>o.kind!=="import"&&o.kind!=="quarantined");else for(let o of r)this.prependIssue(n,o)})}addExportResult(e){let t=this.now();return this.mutate((n)=>{if(n.activeRun)n.activeRun.exported+=e.exported,n.activeRun.failed+=e.failed,n.activeRun.lastProgressAt=new Date(t).toISOString(),this.lastProgressPersistence.set(n.activeRun.id,t);if(e.errors.length===0){n.issues=n.issues.filter((r)=>r.kind!=="export");return}for(let r of e.errors)this.prependIssue(n,{kind:"export",path:`${r.entityType}/${r.entityId}.md`,message:r.error})})}recordIssue(e){return this.mutate((t)=>this.prependIssue(t,e))}clearIssues(e){return this.mutate((t)=>{t.issues=t.issues.filter((n)=>!e.includes(n.kind))})}clearIssue(e){let t=e.kind==="placement"?e.path:this.safePath(e.path);return this.mutate((n)=>{n.issues=n.issues.filter((r)=>r.id!==`${e.kind}:${t}`)})}completeRun(e,t){return this.finishRun(e,"succeeded",t)}async clearRun(e){await this.mutate((t)=>{if(t.activeRun?.id===e)delete t.activeRun}),await this.clearProgress(e)}async failRun(e,t,n="git"){await this.mutate((r)=>{let o=r.activeRun;if(o?.id!==e)return;let s=EO(t);this.prependRecent(r,o,"failed",s),this.prependIssue(r,{kind:n,message:s}),delete r.activeRun}),await this.clearProgress(e)}async finishInterruptedPull(e,t){await this.mutate((n)=>{let r=n.activeRun;if(r?.id!==e||r.state!=="pulling")return;let o=EO(t.message);this.prependRecent(n,r,t.recovered?"attention":"failed",o),this.prependIssue(n,{kind:"git",message:o}),delete n.activeRun}),await this.clearProgress(e)}recordTerminal(e,t,n,r={}){return this.mutate((o)=>{let s=new Date(this.now()).toISOString();this.prependRecent(o,{id:$r(),source:e,state:"settling",startedAt:s,lastProgressAt:s,...DVe,...r},t,n)})}async reconcile(){let t=(await this.store.snapshot()).activeRun;if(!t)return;try{if(t.jobId){let n=await this.jobs.getStatus(t.jobId);if(!n){await this.failRun(t.id,"The active sync job could not be found after restart","source");return}if(n.status==="pending"||n.status==="processing")return;if(n.status==="failed"){await this.failRun(t.id,n.lastError??"Git-backed sync failed");return}let r=gQt.safeParse(EQt(n.result));if(!r.success){await this.failRun(t.id,"Sync job completed without a readable result","source");return}if(r.data.batchQueued&&r.data.batchId)return await this.attachBatch(t.id,r.data.batchId),await this.reconcile();await this.completeRun(t.id,"Remote checked; no files to import");return}if(t.batchId){let n=await this.jobs.getBatchStatus(t.batchId);if(!n){await this.failRun(t.id,"The active sync batch could not be recovered after restart","source");return}if(n.status==="pending"||n.status==="processing")return;if(n.status==="failed"){await this.failRun(t.id,n.errors.join("; ")||"Directory import batch failed","import");return}await this.completeRun(t.id,`${n.completedOperations} sync operations completed`)}}catch(n){this.logger.debug("Unable to reconcile directory sync operation",{error:n})}}async getSnapshot(){await this.reconcile();let e=await this.store.snapshot();if(e.activeRun)e.activeRun=await this.withEffectiveProgress(e.activeRun);return e}async getOperationalHealth(){let e=await this.store.snapshot();if(e.activeRun?.state!=="pulling")return $ie();let t=await this.withEffectiveProgress(e.activeRun);if(t.jobId){if((await this.jobs.getStatus(t.jobId))?.status!=="processing")return $ie()}let n=Math.max(0,this.now()-Date.parse(t.lastProgressAt)),r=this.inactivityTimeoutMs+this.staleGraceMs;if(n<=r)return $ie();return{status:"degraded",message:`Directory Git pull has made no progress for ${n}ms`,details:{runId:t.id,source:t.source,state:t.state,lastProgressAt:t.lastProgressAt,inactivityMs:n,staleAfterMs:r}}}async finishRun(e,t,n){await this.mutate((r)=>{let o=r.activeRun;if(o?.id!==e)return;let s=o.failed>0||o.quarantined>0?"attention":t;if(this.prependRecent(r,o,s,n),delete r.activeRun,s==="succeeded")r.issues=r.issues.filter((a)=>a.kind!=="git"&&a.kind!=="source")}),await this.clearProgress(e)}mutate(e){return this.store.mutate(e)}prependRecent(e,t,n,r){let o={id:t.id,source:t.source,outcome:n,startedAt:t.startedAt,completedAt:new Date(this.now()).toISOString(),summary:EO(r,240),imported:t.imported,skipped:t.skipped,failed:t.failed,quarantined:t.quarantined,exported:t.exported};e.recentRuns=[o,...e.recentRuns.filter((s)=>s.id!==o.id)].slice(0,5)}prependIssue(e,t){let n=t.path?t.kind==="placement"?t.path:this.safePath(t.path):void 0,r={id:`${t.kind}:${n??EO(t.message,80)}`,kind:t.kind,...n?{path:n}:{},message:EO(t.message),occurredAt:new Date(this.now()).toISOString()},o=[r,...e.issues.filter((a)=>a.id!==r.id)],s=0;e.issues=o.filter((a)=>a.kind==="placement"||s++<8)}async withEffectiveProgress(e){let t=await this.progressStore.get(e.id);if(!t||Date.parse(t.lastProgressAt)<=Date.parse(e.lastProgressAt))return e;return{...e,lastProgressAt:t.lastProgressAt}}async clearProgress(e){this.lastProgressPersistence.delete(e),await this.progressStore.delete(e)}safePath(e){if(!OVe(e))return zVe(e);let t=lQt(this.syncPath,e);if(t.startsWith("..")||OVe(t))return"content file";return zVe(t)}}function $ie(){return{status:"healthy",message:"No stale directory Git pull"}}function EQt(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function zVe(e){return e.replaceAll("\\","/").replace(/^\.\//,"").slice(0,300)||"content file"}function EO(e,t=400){return e.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/(token|password|authorization)=([^\s&]+)/gi,"$1=[redacted]").replace(/\s+/g," ").trim().slice(0,t)||"Directory sync operation failed"}cs();H();ZA();var TQt=i.object({checkpoint:Qg.optional(),entityTypes:i.array(i.string()).optional(),fullScanRequest:i.string().optional()}),IQt="directory-sync.git-reconciliation",CQt="current";function $Ve(e){return async(t)=>{let n=await e.getStatus();if(!n.isRepo)return[];let r=new Set(n.files.map((o)=>o.path));return t.filter((o)=>!r.has(o))}}class Lie{store;constructor(e){this.store=new GS({runtimeState:e,namespace:IQt,key:CQt,schema:TQt,createEmpty:()=>({})})}async getCheckpoint(){return(await this.store.snapshot()).checkpoint}saveCheckpoint(e,t){return this.store.mutate((n)=>{if(n.checkpoint=e,t)n.entityTypes=NVe(t)})}requireFullScan(){return this.store.mutate((e)=>{e.fullScanRequest=$r()})}async pullAndQueue(e){let t=await e.gitSync.pull(e.signal,e.onGitProgress);if(t.conflicts&&t.conflicts.length>0)await e.gitSync.acknowledgePullConflicts(await e.directorySync.recordPullConflicts(t.conflicts));return e.signal?.throwIfAborted(),this.queueCurrentDelta(e)}replayAndQueue(e){return this.queueCurrentDelta(e)}async queueCurrentDelta(e){e.signal?.throwIfAborted();let t=NVe(e.context.entityService.getEntityTypes()),n=await this.store.snapshot(),r=e.entityTypesIncomplete!==!0,o=e.full===!0||r&&(n.fullScanRequest!==void 0||!kQt(n.entityTypes,t)),s=await e.gitSync.getReconciliationDelta(o?void 0:n.checkpoint),a=(l)=>this.store.mutate((d)=>{if(d.checkpoint=l,d.entityTypes=t,r&&s.mode==="full"&&d.fullScanRequest===n.fullScanRequest)delete d.fullScanRequest});if(s.mode==="full"){let l=await e.directorySync.queueSyncBatch(e.context,e.source,e.metadata),d=l!==null;if(d)await a(s.checkpoint);return{mode:s.mode,files:[],deletedFiles:[],batch:l,checkpointAdvanced:d}}let c=s.files.length===0?[]:await e.directorySync.withoutStoredEchoes(s.files);if(c.length===0&&s.deletedFiles.length===0){if(s.files.length>0)e.directorySync.ignorePulledWatchPaths(s.files,$Ve(e.gitSync));return await a(s.checkpoint),{mode:s.mode,files:[],deletedFiles:[],batch:null,checkpointAdvanced:!0}}await e.directorySync.recordPendingPullDeletes(s.deletedFiles);let u=await e.directorySync.queueSyncBatch(e.context,e.source,e.metadata,c,s.deletedFiles);if(u)e.directorySync.ignorePulledWatchPaths(s.files,$Ve(e.gitSync)),await a(s.checkpoint);return{mode:s.mode,files:c,deletedFiles:s.deletedFiles,batch:u,checkpointAdvanced:u!==null}}}function NVe(e){return[...new Set(e)].sort()}function kQt(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])}H();import{basename as RQt}from"path";var UVe=i.object({health:i.enum(["healthy","active","attention"]),directory:i.object({displayPath:i.string().min(1),exists:i.boolean(),watching:i.boolean(),totalFiles:i.number().int().nonnegative(),byEntityType:i.record(i.string(),i.number().int().nonnegative()),lastSettledAt:i.string().datetime().optional()}),git:i.object({branch:i.string().min(1),remoteLabel:i.string().min(1).optional(),hasChanges:i.boolean(),ahead:i.number().int().nonnegative(),behind:i.number().int().nonnegative(),lastCommit:i.string().min(1).optional(),changedFiles:i.array(i.object({path:i.string().min(1),status:i.string().min(1)})),changedFilesTruncated:i.boolean()}).nullable(),automation:i.object({autoSync:i.boolean(),watchIntervalMs:i.number().int().nonnegative(),remoteIntervalMinutes:i.number().nonnegative().optional(),commitDebounceMs:i.number().int().nonnegative().optional(),deleteOnFileRemoval:i.boolean()}),activeRun:Nie.optional(),recentRuns:i.array(Fie),issues:i.array(Uie)}),Zie=O_({name:"sync-now",label:"Sync now",permission:"admin",input:i.object({}),output:i.object({accepted:i.boolean(),status:i.string().min(1),runId:i.string().min(1).optional(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional()})}),AQt=new Map([["M","Modified"],["A","Added"],["D","Deleted"],["R","Renamed"],["C","Copied"],["U","Unmerged"],["??","Untracked"]]);function PQt(e){let t=e.imported+e.skipped+e.failed+e.quarantined;return{type:"progress",id:"active-sync",label:"Directory sync",state:e.state,detail:`${t} files handled \xB7 ${e.exported} exported`,startedAt:e.startedAt,updatedAt:e.lastProgressAt,tone:e.failed>0||e.quarantined>0?"warn":"neutral"}}var FVe=I_({id:"sync",label:"Content sync",permission:"admin",data:UVe,actions:[Zie],refresh:({data:e})=>e.activeRun?1000:void 0,view:({data:e})=>{let t=new Map;for(let u of e.issues){let l=t.get(u.kind);if(l)l.push(u);else t.set(u.kind,[u])}let n=e.activeRun?[PQt(e.activeRun)]:[],r=e.git?[{type:"list",id:"changed-files",presentation:"activity",empty:"No changed files.",items:e.git.changedFiles.map((u,l)=>({id:`changed-${l+1}`,title:u.path,description:AQt.get(u.status)??"Working-tree change",metadata:[`Git status: ${u.status} \xB7 working tree`]}))}]:[],o={type:"key-values",id:"sync-repository-facts",items:[{label:"Health",value:e.health},...e.git?[{label:"Branch",value:e.git.branch},{label:"Remote",value:e.git.remoteLabel??"Not supplied"},...e.git.lastCommit?[{label:"Last commit",value:e.git.lastCommit}]:[],{label:"Commits ahead",value:e.git.ahead},{label:"Commits behind",value:e.git.behind}]:[{label:"Remote",value:"files only"}],{label:"Content files",value:e.directory.totalFiles},{label:"Entity types",value:Object.keys(e.directory.byEntityType).length},{label:"Issues",value:e.issues.length},{label:"Automatic sync",value:e.automation.autoSync},{label:"Watch interval",value:`${e.automation.watchIntervalMs} ms`},{label:"Delete removed files",value:e.automation.deleteOnFileRemoval},...e.automation.remoteIntervalMinutes===void 0?[]:[{label:"Remote interval",value:`${e.automation.remoteIntervalMinutes} min`}],...e.automation.commitDebounceMs===void 0?[]:[{label:"Commit debounce",value:`${e.automation.commitDebounceMs} ms`}]]},s=[...n,{type:"list",id:"recent-runs",presentation:"activity",empty:"No directory sync runs have completed yet.",items:e.recentRuns.map((u)=>({id:u.id,title:`${{manual:"Manual sync",periodic:"Periodic sync",watcher:"Watch sync",save:"Save sync",startup:"Startup sync"}[u.source]} \xB7 ${u.outcome}`,description:u.summary,tone:u.outcome==="succeeded"?"good":u.outcome==="failed"?"error":"warn",metadata:[`Imported: ${u.imported}`,`Exported: ${u.exported}`,`Completed: ${u.completedAt}`]}))},...r],c=[...[...t.entries()].flatMap(([u,l])=>{let d=[...l].sort((f,g)=>Date.parse(g.occurredAt)-Date.parse(f.occurredAt)),p=d[0];if(!p)return[];let m=u==="git"?"Repository sync":u==="export"?"Content export":u==="import"?"Content import":u==="placement"?"Content placement":u==="source"?"Content folder":u;return[{type:"notice",id:`sync-issues-${u}`,title:`${m} needs attention`,text:[`${d.length} recorded ${d.length===1?"issue":"issues"}`,p.path].filter(Boolean).join(" \xB7 "),tone:"warn",details:d.map((f)=>[`Occurred: ${f.occurredAt}`,f.path?`Path: ${f.path}`:void 0,f.message].filter(Boolean).join(`
|
|
332
332
|
`))}]}),{type:"columns",id:"sync-body",primary:s.map((u)=>u.type==="list"?{type:"card",id:`${u.id}-section`,label:u.id==="recent-runs"?"Recent runs":"Changed files",metadata:[u.id==="recent-runs"?`${u.items.length} retained`:`${u.items.length} ${e.git?.changedFilesTruncated?"shown":"in working tree"}`],blocks:[u,...u.id==="changed-files"&&e.git?.changedFilesTruncated?[{type:"notice",id:"changed-files-remainder",text:`Showing the first ${u.items.length} changed files. Additional working-tree changes are not shown.`}]:[]]}:u),aside:[{type:"card",id:"sync-source-card",label:"Connection",blocks:[{type:"key-values",id:"sync-source",items:[{label:"Folder",value:e.directory.displayPath},{label:"Available",value:e.directory.exists},{label:"Watcher",value:e.directory.watching?"Watching":"Stopped"},...e.directory.lastSettledAt?[{label:"Last settled",value:e.directory.lastSettledAt}]:[]]}]},{type:"card",id:"sync-repository-card",label:"Repository details",presentation:"disclosure",blocks:[o]}]}];return{kicker:"Durability operations",title:"Content sync",primaryAction:{action:Zie,input:{},disabled:Boolean(e.activeRun)},blocks:c}}});class qie{options;registered=!1;constructor(e){this.options=e}async getSnapshot(){let e=await this.options.getDirectorySync().getStatus();this.options.operationStatus.setSyncPath(e.syncPath);let t,n=this.options.getGitSync();if(n)try{if(t=await n.getStatus(),!t.hasChanges&&t.ahead===0&&t.behind===0)await this.options.operationStatus.clearIssues(["git"])}catch(s){await this.options.operationStatus.recordIssue({kind:"git",message:de(s,"Git status unavailable")})}if(!e.exists)await this.options.operationStatus.recordIssue({kind:"source",message:"The configured sync directory is unavailable"});else await this.options.operationStatus.clearIssues(["source"]);let r=await this.options.operationStatus.getSnapshot(),o=r.recentRuns[0]?.completedAt??e.lastSync?.toISOString();return UVe.parse({health:r.activeRun?"active":r.issues.length>0?"attention":"healthy",directory:{displayPath:RQt(e.syncPath)||"brain-data",exists:e.exists,watching:e.watching,totalFiles:e.stats.totalFiles,byEntityType:e.stats.byEntityType,...o?{lastSettledAt:o}:{}},git:t?this.toSafeGitStatus(t):null,automation:{autoSync:this.options.config.autoSync,watchIntervalMs:this.options.config.watchInterval,...n?{remoteIntervalMinutes:this.options.config.syncInterval,commitDebounceMs:this.options.config.commitDebounce}:{},deleteOnFileRemoval:this.options.config.deleteOnFileRemoval},...r.activeRun?{activeRun:r.activeRun}:{},recentRuns:r.recentRuns,issues:r.issues})}async registerStudioWorkspace(){let{studio:e}=this.options.context.runtime;if(!e.isAvailable())return;let t=e.source({definition:FVe,bind:(r)=>FVe.bind(r,{load:()=>this.getSnapshot(),actions:[Zie.bind(r,async({caller:o})=>{if(!o)throw Error("Directory sync requires an authenticated caller");let s={interfaceType:"studio",actor:{kind:"user",userId:o.actor.id},userPermissionLevel:o.permission},a=await Z1({context:this.options.context,directorySync:this.options.getDirectorySync(),source:`studio:${o.actor.id}`,interfaceType:"studio",toolContext:s,gitSync:this.options.getGitSync(),operationStatus:this.options.operationStatus});return{accepted:a.status==="queued",status:a.status,...a.runId?{runId:a.runId}:{},...a.gitPulled?{jobId:a.jobId}:{},...!a.gitPulled&&a.status==="queued"?{batchId:a.batchId}:{}}})]})}),n=await e.register(t);return this.registered=n!==void 0,n}async unregisterStudioWorkspace(){if(!this.registered)return;await this.options.context.runtime.studio.unregister(`${this.options.context.pluginId}:sync`),this.registered=!1}toSafeGitStatus(e){let t=e.files.slice(0,20).map((r)=>({path:_Qt(r.path),status:r.status.trim()||"changed"})),n=OQt(this.options.config);return{branch:e.branch,...n?{remoteLabel:n}:{},hasChanges:e.hasChanges,ahead:e.ahead,behind:e.behind,...e.lastCommit?{lastCommit:e.lastCommit}:{},changedFiles:t,changedFilesTruncated:e.files.length>t.length}}}function _Qt(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/"))return"content file";return t.slice(0,300)||"content file"}function OQt(e){if(e.git?.repo)return e.git.repo;let t=e.git?.gitUrl;if(!t)return;if(t.startsWith("file:"))return"local remote";try{let n=new URL(t),r=n.pathname.replace(/^\//,"").replace(/\.git$/,"");return r?`${n.hostname}/${r}`:n.hostname}catch{let n=/^(?:[^@]+@)?([^:]+):(.+?)(?:\.git)?$/.exec(t);if(!n?.[1]||!n[2])return"configured remote";return`${n[1]}/${n[2].replace(/\.git$/,"")}`}}ni();class Gie{resourceScope;scheduleScope;periodicScope;delayScope;scheduleFibers;periodicFibers;delayedFibers;clock;activeOperations=new Set;activeFailures=[];nextPeriodicId=0;closePromise=null;closed=!1;constructor(e={}){this.resourceScope=te.runSync(ln.make()),this.scheduleScope=te.runSync(ln.make()),this.periodicScope=te.runSync(ln.make()),this.delayScope=te.runSync(ln.make()),this.scheduleFibers=te.runSync(ln.provide(Cg.make(),this.scheduleScope)),this.periodicFibers=te.runSync(ln.provide(ua.make(),this.periodicScope)),this.delayedFibers=te.runSync(ln.provide(ua.make(),this.delayScope)),this.clock=e.clock}async acquire(e,t){if(this.closed)throw Error("Directory sync runtime is closed");let n=te.acquireRelease(te.promise(e),(o)=>te.promise(()=>t(o))),r=await te.runPromiseExit(ln.provide(n,this.resourceScope));if(Jt.isFailure(r))throw qn.squash(r.cause);return r.value}schedulePeriodic(e,t){if(this.closed)return;if(!Number.isFinite(e)||e<=0)throw Error("Periodic interval must be a positive finite number");let n=this.nextPeriodicId++,r=()=>{if(this.closed||ua.hasUnsafe(this.periodicFibers,n))return;let a=te.tryPromise({try:t,catch:(c)=>c}).pipe(te.catch((c)=>te.sync(()=>{this.activeFailures.push(c)})));ua.setUnsafe(this.periodicFibers,n,te.runFork(a),{onlyIfMissing:!0})},o=te.sleep(e).pipe(te.andThen(te.sync(r)),te.forever),s=la(o,this.clock);Cg.addUnsafe(this.scheduleFibers,te.runFork(s))}scheduleTrailing(e,t,n){if(this.closed)return;let r=te.sleep(t).pipe(te.andThen(te.sync(()=>{this.trackActive(n)}))),o=la(r,this.clock),s=te.runFork(o);ua.setUnsafe(this.delayedFibers,e,s)}close(){return this.closed=!0,this.closePromise??=this.closeRuntime(),this.closePromise}trackActive(e){if(this.closed)return;let t;try{t=e()}catch(r){t=Promise.reject(r)}let n=t.catch((r)=>{this.activeFailures.push(r)}).finally(()=>{this.activeOperations.delete(n)});this.activeOperations.add(n)}async closeRuntime(){let e=[],t=async(n)=>{try{await n()}catch(r){e.push(r)}};await t(()=>this.closeScope(this.scheduleScope)),await t(()=>this.closeScope(this.periodicScope)),await t(()=>this.closeScope(this.delayScope)),await t(()=>this.closeScope(this.resourceScope));while(this.activeOperations.size>0)await Promise.all([...this.activeOperations]);if(e.push(...this.activeFailures),e.length>0)throw e[0]}async closeScope(e){let t=await te.runPromiseExit(ln.close(e,Jt.void));if(Jt.isFailure(t))throw qn.squash(t.cause)}}function BVe(e){return{initialize:()=>e().initialize(),initializeDirectory:()=>e().initializeDirectory(),setJobQueueCallback:(t)=>e().setJobQueueCallback(t),sync:()=>e().sync(),processEntityExport:(t)=>e().processEntityExport(t),recordPullConflicts:(t)=>e().recordPullConflicts(t),deleteForRemovedFile:(t,n)=>e().deleteForRemovedFile(t,n),exportEntities:(t)=>e().exportEntities(t),importEntitiesWithProgress:(t,n,r,o,s)=>e().importEntitiesWithProgress(t,n,r,o,s),exportEntitiesWithProgress:(t,n,r)=>e().exportEntitiesWithProgress(t,n,r),importEntities:(t)=>e().importEntities(t),removeOrphanedEntities:(t)=>e().removeOrphanedEntities(t),get fileOps(){return e().fileOps},get shouldDeleteOnFileRemoval(){return e().shouldDeleteOnFileRemoval},getAllMarkdownFiles:()=>e().getAllMarkdownFiles(),ensureDirectoryStructure:()=>e().ensureDirectoryStructure(),getStatus:()=>e().getStatus(),queueSyncBatch:(t,n,r,o,s)=>e().queueSyncBatch(t,n,r,o,s),startWatching:()=>e().startWatching(),stopWatching:()=>e().stopWatching(),suppressWatchPaths:(t)=>e().suppressWatchPaths(t),ignorePulledWatchPaths:(t,n)=>e().ignorePulledWatchPaths(t,n),withoutStoredEchoes:(t)=>e().withoutStoredEchoes(t),recordPendingPullDeletes:(t)=>e().recordPendingPullDeletes(t),isPendingDelete:(t,n)=>e().isPendingDelete(t,n),completePendingDelete:(t,n,r)=>e().completePendingDelete(t,n,r),setWatchCallback:(t)=>e().setWatchCallback(t)}}function LVe(e){return{initialize:()=>e().initialize(),hasRemote:()=>e().hasRemote(),getStatus:()=>e().getStatus(),hasLocalChanges:()=>e().hasLocalChanges(),commit:(t)=>e().commit(t),commitAndPush:()=>e().commitAndPush(),push:(t)=>e().push(t),pull:(t)=>e().pull(t),acknowledgePullConflicts:(t)=>e().acknowledgePullConflicts(t),getReconciliationDelta:(t)=>e().getReconciliationDelta(t),cleanup:()=>e().cleanup(),log:(t,n)=>e().log(t,n),show:(t,n)=>e().show(t,n)}}function ZVe(e){if(e.gitConfigured){if(!e.gitBrokerCheckout)throw Error("Git sync is configured but the broker checkout path is unavailable");return e.gitBrokerCheckout}return e.configuredSyncPath??e.dataDir}class q1{config;context;logger;syncRequestJob;directorySync;gitSync;operationStatus;gitReconciliation;workspaceProvider;studioWorkspaceUrl;runtime=new Gie;directorySyncFacade=BVe(()=>this.requireDirectorySync());gitSyncFacade=LVe(()=>this.requireGitSync());runtimeScheduler={scheduleTrailing:(e,t,n)=>{this.runtime.scheduleTrailing(e,t,n)}};watcherOwned=!1;gitBackgroundStarted=!1;entityExportDispatcher;pendingDeletes=new vO;constructor(e,t){this.config=e,this.context=t,this.logger=t.logger}getContext(){return this.context}requireDirectorySync(){if(!this.directorySync)throw Error("DirectorySync service not initialized");return this.directorySync}requireGitSync(){if(!this.gitSync)throw Error("GitSync service not initialized");return this.gitSync}requireEntityExportDispatcher(){if(!this.entityExportDispatcher)throw Error("Durable entity-export dispatcher is unavailable");return this.entityExportDispatcher}createEntityExportDispatcher(e,t,n,r){return new Mie({runtime:t,directorySync:n,entityService:e.entityService,gitSync:r,...r?{saveCheckpoint:(o)=>this.requireGitReconciliation().saveCheckpoint(o)}:{},operationStatus:this.operationStatus,logger:this.logger.child("EntityExportDispatcher"),debounceMs:this.config.commitDebounce})}bindCleanupAdmission(e,t,n){if(n){t.setCleanupAdmission(()=>n.settleBeforeCleanup());return}t.setCleanupAdmission(async()=>{if(await e.entityService.hasPendingEntityExports())throw Error("Directory cleanup blocked by pending durable entity exports")})}requireOperationStatus(){if(!this.operationStatus)throw Error("Directory sync operation status not initialized");return this.operationStatus}requireGitReconciliation(){if(!this.gitReconciliation)throw Error("Git reconciliation service not initialized");return this.gitReconciliation}hasGitSync(){return this.gitSync!==void 0}common;async registerCommon(){this.common=await this.registerCommonParts(this.context)}async registerRoles(){let e=this.context,t=this.common;if(!t)throw Error("Directory sync registered out of order");let{syncPath:n,recovery:r}=t;if(this.isGitConfigured())await this.registerGit(e,n,r);else await r.requiresRepository();if(e.executionOnly)this.bindCleanupAdmission(e,this.requireDirectorySync());else this.registerServingRole(e,r)}async registerCommonParts(e){e.runtime.template("status",{name:"status",description:"Directory synchronization status",schema:gE,basePrompt:"",formatter:new z1,requiredPermission:"admin"});let t=ZVe({configuredSyncPath:this.config.syncPath,dataDir:e.dataDir,gitConfigured:this.isGitConfigured(),gitBrokerCheckout:e.gitBrokerCheckout});this.directorySync=this.createDirectorySync(e,t);try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:t})}catch(r){throw this.logger.error("Failed to initialize directory",r),r}this.operationStatus=new Bie(e.runtimeState,e.jobs,this.logger.child("OperationStatus"),t);let n=EVe({operationStatus:this.operationStatus,interruptedPull:await this.operationStatus.initialize({executionOnly:e.executionOnly}),executionOnly:e.executionOnly});if(this.registerOperationalHealth(e),this.gitReconciliation=new Lie(e.runtimeState),!e.executionOnly&&this.config.autoSync)gVe(e,this.directorySync,t,this.operationStatus,await this.runtime.acquire(async()=>new NE({logger:this.logger}),(r)=>r.dispose()));if(this.config.git&&!this.isGitConfigured())this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(this.isGitConfigured())this.syncRequestJob=Nm("sync-request",new N1(e,()=>this.requireDirectorySync(),()=>this.requireGitSync(),this.requireGitReconciliation(),this.operationStatus));return{syncPath:t,recovery:n}}registerOperationalHealth(e){if(e.executionOnly)return;e.runtime.operationalHealth("git-progress",()=>this.requireOperationStatus().getOperationalHealth());let t=e.gitBrokerSocket;if(!this.isGitConfigured()||t===void 0)return;e.runtime.operationalHealth("git-broker",Oie({probe:_ie(t)}))}async registerGit(e,t,n){let r=await n.guard(async()=>{if(!e.executionOnly)await this.bootstrapContentRemote();let o=await this.connectToGitBroker(t,this.requireDirectorySync());if(this.gitSync=o,!e.executionOnly)await this.reconcileInheritedWork(e,o,this.requireDirectorySync());return await o.initialize(),o});if(this.logger.info("Git integration enabled",{repo:this.config.git?.repo}),!e.executionOnly&&!this.config.initialSync)await this.replayAtStartup(e,r,n)}replayAtStartup(e,t,n){return n.guard(async()=>{await n.progress(),await this.requireGitReconciliation().replayAndQueue({gitSync:t,directorySync:this.requireDirectorySync(),context:e,source:"startup-replay",entityTypesIncomplete:!0}),await n.succeeded("startup")})}registerServingRole(e,t){let n=this.createEntityExportDispatcher(e,this.runtime,this.requireDirectorySync(),this.gitSync);if(this.entityExportDispatcher=n,this.bindCleanupAdmission(e,this.requireDirectorySync(),n),mVe(e,()=>this.requireEntityExportDispatcher().wake(),this.logger,this.config.entityTypes,this.operationStatus),this.config.initialSync)vVe({context:e,getDirectorySync:()=>this.requireDirectorySync(),config:this.config,logger:this.logger,gitSync:this.gitSync?this.gitSyncFacade:void 0,reconciliation:this.gitSync?this.requireGitReconciliation():void 0,recovery:this.gitSync?t.initialSyncRecovery():void 0,operationStatus:this.operationStatus});this.workspaceProvider=new qie({context:e,config:this.config,getDirectorySync:()=>this.requireDirectorySync(),getGitSync:()=>this.gitSync,operationStatus:this.requireOperationStatus()}),RVe(e,()=>this.requireDirectorySync(),this.logger,()=>this.gitSync,()=>this.studioWorkspaceUrl)}assertConflictsCanBeKept(){if(this.getContext().entityService.getEntityTypes().includes(Lp))return;throw Error(`directory-sync needs the "${Lp}" entity type to keep edits that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)}async ready(){if(this.config.seedContent&&this.config.strictSeedEntityTypes){let e=this.getContext();await _1(this.config.syncPath??e.dataDir,e.entityService)}await this.requireEntityExportDispatcher().start(),await this.startBackgroundWork(),this.studioWorkspaceUrl=await this.workspaceProvider?.registerStudioWorkspace()}tools(){return _Ve(this.directorySyncFacade,this.getContext(),this.context.pluginId,this.gitSync?this.gitSyncFacade:void 0,this.operationStatus)}async shutdown(){await this.workspaceProvider?.unregisterStudioWorkspace(),await this.stopGeneration(this.runtime,this.directorySync,this.gitSync),this.watcherOwned=!1,this.gitBackgroundStarted=!1,this.entityExportDispatcher=void 0}getDirectorySync(){return this.directorySync}createDirectorySync(e,t){return new D1({syncPath:t,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,maxImportFileBytes:this.config.maxImportFileBytes,maxAssetImportBytes:this.config.maxAssetImportBytes,entityService:e.entityService,logger:e.logger,conflicts:{base:OWe(e.runtimeState),record:async(r)=>(await e.runtime.messaging.request(bY,r)).status==="answered"}},this.pendingDeletes)}isGitConfigured(){return this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0)}async bootstrapContentRemote(){let e=this.config.git;if(!e)return;await kVe({gitUrl:e.gitUrl,branch:e.branch,seedContentPath:this.config.seedContentPath,bootstrapFromSeed:e.bootstrapFromSeed,authorName:e.authorName,authorEmail:e.authorEmail,logger:this.logger.child("ContentRemoteBootstrap")})}async connectToGitBroker(e,t){let n=this.config.git;if(!n)throw Error("Git configuration is unavailable");let r={},o=this.getContext().executionOnly?void 0:dVe({logger:this.logger.child("GitOwner"),scheduler:this.runtimeScheduler,replay:lVe({client:()=>r.gitSync,replay:async(a)=>{await this.requireGitReconciliation().replayAndQueue({gitSync:a,directorySync:t,context:this.getContext(),source:"broker-replacement-replay"})}})}),s=await h_e({socketPath:this.getContext().gitBrokerSocket,checkoutPath:e,branch:n.branch,remoteUrl:aD({logger:this.logger,dataDir:e,repo:n.repo,gitUrl:n.gitUrl}),logger:this.logger.child("GitSync"),...o?{onOwnerUnavailable:()=>{o("pending replacement")}}:{}});return r.gitSync=s,s}async reconcileInheritedWork(e,t,n){if(await t.admitsMutations())return;this.logger.warn("Git owner is holding mutations; reconciling inherited work"),await this.requireGitReconciliation().replayAndQueue({gitSync:t,directorySync:n,context:e,source:"inherited-work-replay",entityTypesIncomplete:!0}),await t.openAdmission()}async startBackgroundWork(){let e=this.requireDirectorySync();if(this.config.autoSync&&!this.watcherOwned)await this.runtime.acquire(()=>e.startWatching(),()=>e.stopWatching()),this.watcherOwned=!0;let t=this.gitSync;if(!t||this.gitBackgroundStarted)return;let n=this.getContext();if(this.config.autoSync)TVe({gitSync:t,directorySync:e,context:n,intervalMinutes:this.config.syncInterval,logger:this.logger.child("GitPeriodicSync"),runtime:this.runtime,reconciliation:this.requireGitReconciliation(),operationStatus:this.operationStatus});this.gitBackgroundStarted=!0}async stopGeneration(e,t,n){let r=[];try{await e.close()}catch(o){r.push(o)}try{await t?.stopWatching()}catch(o){r.push(o)}try{await n?.cleanup()}catch(o){r.push(o)}if(r.length>0)throw r[0]}jobHandlers(){return[...fVe(this.context,this.directorySyncFacade,this.logger,()=>this.requireDirectorySync(),this.requireOperationStatus(),this.requireGitReconciliation()),...this.syncRequestJob?[this.syncRequestJob]:[]]}}function Hie(e={}){let t=sL({id:"directory-sync",config:vS,setup:async(n)=>{let r=eL(n),o=new q1(n.config,PWe(r));await o.registerCommon(),r.registering(()=>o.registerRoles()),r.registered(()=>o.assertConflictsCanBeKept()),r.ready(()=>o.ready()),n.lifecycle.onCleanup(()=>o.shutdown());let s={sync:o};return e.onSetup?.(s),s}});return D_(oL(t,({state:n})=>n.sync.jobHandlers()),({state:n})=>n.sync.tools())}var kyr=Hie();var qVe="./brain-data";var Byr=i.object({syncPath:i.string().optional(),git:i.object({repo:i.string().optional(),gitUrl:i.string().optional()}).optional()});async function GVe(e,t,n={}){let r=n.processImpl??process,o=n.startHost??eee,s=r.env[SE];if(!s)return{success:!1,message:`${SE} is unset; the Git broker is started by the Brain supervisor, not directly`,exitCode:1};let a=await o({socketPath:s,runtimeDir:xE(e),cwd:e,dataDir:qVe,pluginConfig:kU(t.plugins?.["directory-sync"]??{},r.env),logger:po.getInstance()}).then((c)=>({broker:c,error:void 0}),(c)=>({broker:void 0,error:c}));if(!a.broker)return{success:!1,message:`Git broker failed to start: ${de(a.error)}`,exitCode:1};return r.send?.({type:"broker-ready"}),await new Promise((c)=>{r.on("SIGTERM",c),r.on("SIGINT",c)}),await a.broker.stop(),{success:!0}}po.setProcessRole("git-broker");var MQt=po.getInstance(),jQt=i.object({plugins:i.object({"directory-sync":i.unknown().optional()}).optional()}),HVe=process.cwd(),TO=await Promise.resolve().then(()=>GVe(HVe,jQt.parse(hZ(DQt(zQt(HVe,"brain.yaml"),"utf8"))))).catch((e)=>({success:!1,message:`Git broker failed: ${de(e)}`,exitCode:1}));if(!TO.success&&TO.message)MQt.error(TO.message);process.exit(TO.success?0:TO.exitCode??1);
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sa as d,Ta as t}from"./chunks/index-
|
|
2
|
+
import{Sa as d,Ta as t}from"./chunks/index-g3c3c3y0.js";import{Rg as a}from"./chunks/index-q6pcp7gc.js";import"./chunks/index-9881eck9.js";import"./chunks/index-nwdvz1vw.js";import"./chunks/index-6gqg29bj.js";import"./chunks/index-7ne5672k.js";import"./chunks/index-amf6s7a5.js";import"./chunks/index-p39p7p8h.js";function s(e,i){let o=new Set,n=new Set;for(let r of e){if(!t(r))throw Error(`${i} contains a value that was not returned by use()`);if(o.has(r.definition))throw Error(`${i} contains duplicate plugin definition "${r.definition.id}"; include each configured definition only once`);if(n.has(r.definition.id))throw Error(`${i} contains duplicate local plugin id "${r.definition.id}"; give each package definition a unique local id before composing it`);o.add(r.definition),n.add(r.definition.id)}}function l(e){a(e.id,"Bundle id"),s(e.members,`Bundle "${e.id}"`);for(let i of e.config??[])if(!t(i.member))throw Error(`Bundle "${e.id}" config contains a value that was not returned by use()`);for(let i of e.permissions??[])if(!t(i.member))throw Error(`Bundle "${e.id}" permissions contains a value that was not returned by use()`);for(let i of e.evalDisable??[])if(!t(i))throw Error(`Bundle "${e.id}" evalDisable contains a value that was not returned by use()`);return Object.freeze({...e,members:Object.freeze([...e.members]),...e.config?{config:Object.freeze([...e.config])}:{},...e.permissions?{permissions:Object.freeze([...e.permissions])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}function u(e){if(!e.name.trim())throw Error("Brain name must not be empty");if(e.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");s(e.plugins,`Brain "${e.name}"`);let i=new Set(e.plugins),o=new Set;for(let n of e.bundles??[]){if(o.has(n.id))throw Error(`Brain "${e.name}" has duplicate bundle "${n.id}"`);o.add(n.id);for(let r of n.members)if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" references a plugin outside its catalog`);for(let r of n.config??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" config references a plugin outside its catalog`);for(let r of n.permissions??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" permissions reference a plugin outside its catalog`);for(let r of n.evalDisable??[])if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" evalDisable references a plugin outside its catalog`)}for(let n of e.evalDisable??[])if(!i.has(n))throw Error(`Brain "${e.name}" evalDisable references a plugin outside its catalog`);return Object.freeze({...e,plugins:Object.freeze([...e.plugins]),...e.bundles?{bundles:Object.freeze([...e.bundles])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}export{u as defineBrain,l as defineBundle,d as use};
|
|
3
3
|
|
|
4
4
|
//# debugId=A3D30437D98ACAD364756E2164756E21
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/dist/interfaces.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-x8e40qwv.js";import{Pi as t,Qi as x,Ri as a,Si as b,Ti as c,Ui as d,xh as p}from"./chunks/index-
|
|
2
|
+
import"./chunks/index-x8e40qwv.js";import{Pi as t,Qi as x,Ri as a,Si as b,Ti as c,Ui as d,xh as p}from"./chunks/index-q6pcp7gc.js";import{co as m,pm as f}from"./chunks/index-9881eck9.js";import"./chunks/index-nwdvz1vw.js";import"./chunks/index-6gqg29bj.js";import{Tx as e}from"./chunks/index-7ne5672k.js";import"./chunks/index-amf6s7a5.js";import"./chunks/index-p39p7p8h.js";export{f as SdkError,m as UserPermissionLevelSchema,p as defineAccountSettings,a as defineDaemon,b as defineInterface,c as defineMessageInterface,d as defineMessageInterfacePackage,x as defineRoute,t as protocol,e as z};
|
|
3
3
|
|
|
4
4
|
//# debugId=F7A9CF8BBCBC0DDE64756E2164756E21
|
|
5
5
|
//# sourceMappingURL=interfaces.js.map
|