@rizom/brain 0.2.0-alpha.740 → 0.2.0-alpha.741
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 +6 -6
- package/dist/chunks/{app-tkmn9eak.js → app-f6yszdd3.js} +2 -2
- package/dist/chunks/{index-8n7a0qnc.js → index-gk97fevd.js} +2 -2
- package/dist/chunks/{index-fw3pb5r1.js → index-kgb6mq4z.js} +3 -3
- package/dist/chunks/{index-fw3pb5r1.js.map → index-kgb6mq4z.js.map} +1 -1
- package/dist/chunks/{package-4t6r1d0z.js → package-szn9kp3r.js} +3 -3
- package/dist/chunks/{package-4t6r1d0z.js.map → package-szn9kp3r.js.map} +1 -1
- package/dist/git-broker.js +1 -1
- package/dist/model.js +6 -6
- package/dist/model.js.map +4 -4
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-tkmn9eak.js.map → app-f6yszdd3.js.map} +0 -0
- /package/dist/chunks/{index-8n7a0qnc.js.map → index-gk97fevd.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B as a}from"./index-
|
|
2
|
+
import{B as a}from"./index-gk97fevd.js";import"./index-4mffgwx9.js";import"./index-whfdx63h.js";import"./index-1092p6rf.js";import"./index-z5wmjvhz.js";import"./index-zpjmcztt.js";import"./index-5ype4xpz.js";import"./index-qj469kc9.js";import"./index-kxp92js5.js";import"./index-hz5a2ea5.js";import"./index-cmt5v1dy.js";export{a as App};
|
|
3
3
|
|
|
4
4
|
//# debugId=B0224EA8233B0C3764756E2164756E21
|
|
5
|
-
//# sourceMappingURL=app-
|
|
5
|
+
//# sourceMappingURL=app-f6yszdd3.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{L as p}from"./index-4mffgwx9.js";import{Da as m,Ia as d,La as v,Ma as S}from"./index-whfdx63h.js";import{Qg as h}from"./index-z5wmjvhz.js";import{oo as n,qo as a}from"./index-5ype4xpz.js";import{Js as f,Xv as s,Ys as l}from"./index-qj469kc9.js";import{Sx as g}from"./index-cmt5v1dy.js";async function u(i){let[{default:e},{default:t}]=await Promise.all([import("./index-fvndhkj1.js"),import("./package-
|
|
2
|
+
import{L as p}from"./index-4mffgwx9.js";import{Da as m,Ia as d,La as v,Ma as S}from"./index-whfdx63h.js";import{Qg as h}from"./index-z5wmjvhz.js";import{oo as n,qo as a}from"./index-5ype4xpz.js";import{Js as f,Xv as s,Ys as l}from"./index-qj469kc9.js";import{Sx as g}from"./index-cmt5v1dy.js";async function u(i){let[{default:e},{default:t}]=await Promise.all([import("./index-fvndhkj1.js"),import("./package-szn9kp3r.js")]);return h(e,i??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(i,e){return new c(v(i),e)}constructor(i,e){if(this.config=i,this.hasCLI=process.argv.slice(2).includes("--cli"),e)this.shell=e}async migrate(){let i=a.getInstance();await new d(i).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(i,e){this.shell=m.createFresh(S(this.config,i),void 0,{...e?.processRole&&{processRole:e.processRole},...e?.peerChannel&&{peerChannel:e.peerChannel}})}wantsCLI(i){return this.hasCLI||i?.cli===!0}async registerCLIInterface(i){if(!this.wantsCLI(i))return;let e=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))e.registerPlugin(t)}async initialize(i,e){if(!this.shell){if(!e?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(i,e)}if(await this.registerCLIInterface(e),this.stopPromise)return;await this.getShell().initialize(i)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){if(await this.closeSignalScope(),this.migrationPromise)await this.migrationPromise.catch(()=>{return});await this.shell?.shutdown()}async run(i){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(i),r=a.createFresh({level:t,context:this.config.name,useStderr:o});if(o)a.getInstance().setUseStderr(!0);r.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,i),this.stopPromise)return;await this.start(),i?.onRuntimeReady?.(),r.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(C){r.error(`\u274C Failed to start ${this.config.name}:`,C),process.exit(1)}}static async run(i,e,t){await c.create(i,e).run(t)}setupSignalHandlers(){if(this.signalScope)return;let i=s.runSync(l.make()),e=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],e),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(i,s.sync(()=>{r(),o()}))),this.signalScope=i}requestGracefulShutdown(i){if(this.signalShutdownFiber)return;let e=a.getInstance();e.info(`
|
|
3
3
|
Received ${i}, shutting down gracefully...`);let t=s.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(s.match({onFailure:(o)=>{e.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=s.runFork(t)}async closeSignalScope(){let i=this.signalScope;if(this.signalScope=null,i)await s.runPromise(l.close(i,f.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
4
4
|
export{c as B};
|
|
5
5
|
|
|
6
6
|
//# debugId=8B97E0F24A75770464756E2164756E21
|
|
7
|
-
//# sourceMappingURL=index-
|
|
7
|
+
//# sourceMappingURL=index-gk97fevd.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jx as t}from"./index-kxp92js5.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.
|
|
2
|
+
import{Jx as t}from"./index-kxp92js5.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.741",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/client":"^2.3.1","@modelcontextprotocol/server":"^2.3.1","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20","@types/react":"^19.2.17",postcss:"^8.5.29",react:"^19.2.7","react-dom":"^19.2.7",tailwindcss:"^4.3.1",yaml:"^2.9.0",zod:"^4.2.0"},devDependencies:{"@brains/a2a":"workspace:*","@brains/action-board":"workspace:*","@brains/action-items":"workspace:*","@brains/admin":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/ai-evaluation":"workspace:*","@brains/ai-service":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/ask-content":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/book":"workspace:*","@brains/build-tools":"workspace:*","@brains/chat":"workspace:*","@brains/contact":"workspace:*","@brains/content-formatters":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/core":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/deploy-support":"workspace:*","@brains/directory-sync":"workspace:*","@brains/doc":"workspace:*","@brains/document":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email":"workspace:*","@brains/email-workflows":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/faq":"workspace:*","@brains/form":"workspace:*","@brains/forms":"workspace:*","@brains/guide":"workspace:*","@brains/http-host":"workspace:*","@brains/image":"workspace:*","@brains/image-plugin":"workspace:*","@brains/knowledge-map":"workspace:*","@brains/link":"workspace:*","@brains/linkedin-import":"workspace:*","@brains/mcp":"workspace:*","@brains/mcp-service":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/oauth-broker":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/onboarding":"workspace:*","@brains/operation-context":"workspace:*","@brains/playbooks":"workspace:*","@brains/plugins":"workspace:*","@brains/portfolio":"workspace:*","@brains/profile":"workspace:*","@brains/prompt":"workspace:*","@brains/quiz":"workspace:*","@brains/refined-note":"workspace:*","@brains/sdk":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/site-organization":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/studio":"workspace:*","@brains/style-guide":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/typescript-config":"workspace:*","@brains/unified-inbox":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/webdav":"workspace:*","@brains/wishlist":"workspace:*","@libsql/client":"^0.17.4","@manypkg/get-packages":"^3.1.0","@rizom/theme-default":"workspace:*","@types/bun":"^1.4.0","@types/react-dom":"^19.0.3",rolldown:"^1.0.0","rolldown-plugin-dts":"^0.27.4",typescript:"^7.0.2"},engines:{bun:">=1.4.0"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./chat":{types:"./dist/chat.d.ts",import:"./dist/chat.js"},"./cli":"./dist/brain.js","./model":{types:"./dist/model.d.ts",import:"./dist/model.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","react-devtools-core":"^7.0.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/studio",eval:"bun run build && brain-eval","eval:headless":"bun run eval --suite headless","eval:personal":"bun run eval --suite personal","eval:professional":"bun run eval --suite professional","eval:team":"bun run eval --suite team","eval:git":"bun run eval --suite professional --tags requires-supervised-git --mcp-basic --url http://localhost:8080 --token $MCP_AUTH_TOKEN",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts","start:minimal":"sh scripts/start-test-app.sh minimal","start:unified-inbox":"sh scripts/start-test-app.sh unified-inbox","start:personal":"sh scripts/start-test-app.sh personal","start:publishing":"sh scripts/start-test-app.sh publishing","start:team":"sh scripts/start-test-app.sh team",test:"bun test --parallel=4 --path-ignore-patterns='**/{boot-smoke,served-surface,canonical-eval-suites,public-plugin-api,public-authoring-golden,public-authoring-docs,public-chat-contract,package-metadata}.test.ts'","test:boot-smoke":"bun run build && bun run test:boot-smoke:prebuilt","test:boot-smoke:prebuilt":"bun test test/boot-smoke.test.ts test/served-surface.test.ts","test:evals":"bun test test/canonical-eval-suites.test.ts","test:surface":"bun test test/public-plugin-api.test.ts test/public-authoring-golden.test.ts test/public-authoring-docs.test.ts test/public-chat-contract.test.ts test/package-metadata.test.ts && bun run test:boot-smoke:prebuilt","test:packed:compat":"bun scripts/run-packed-compatibility.ts",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.model.json"},type:"module"};import{existsSync as d,readFileSync as b}from"fs";import{dirname as u,join as a}from"path";var k=t.looseObject({name:t.string().min(1),version:t.string().min(1),dependencies:t.record(t.string(),t.string()).optional(),peerDependencies:t.record(t.string(),t.string()).optional()});class r extends Error{constructor(e,s,i){super(i?`Package "${e.name}@${e.version}" requires @rizom/brain "${i}", but "${s}" is installed; install a compatible Brain version or update the peer range only after testing that release`:`Package "${e.name}@${e.version}" must declare a @rizom/brain peer dependency; add the tested range under peerDependencies in its package.json`);this.name="PackagePeerCompatibilityError"}}function o(e){let s=u(e);return s===e?[e]:[e,...o(s)]}function m(e,s){return Object.freeze({name:e.name,version:e.version,dependencies:Object.freeze({...e.dependencies??{}}),peerDependencies:Object.freeze({...e.peerDependencies??{}}),directory:s})}function v(e){let s=o(e).find((p)=>d(a(p,"package.json")));if(s===void 0)throw Error(`No package.json at or above "${e}"; run from the package's own directory`);let i=a(s,"package.json"),c=JSON.parse(b(i,"utf8")),n=k.safeParse(c);if(!n.success)throw Error(`"${i}" must declare non-empty name and version fields`);return m(n.data,s)}function j(e,s){let i=e.peerDependencies["@rizom/brain"];if(!i||!Bun.semver.satisfies(s,i))throw new r(e,s,i)}
|
|
3
3
|
export{v as M,j as N,g as O};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
6
|
-
//# sourceMappingURL=index-
|
|
5
|
+
//# debugId=3E453C9F5286833964756E2164756E21
|
|
6
|
+
//# sourceMappingURL=index-kgb6mq4z.js.map
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"@brains/utils/zod\";\n\nconst packageManifestSchema = z.looseObject({\n name: z.string().min(1),\n version: z.string().min(1),\n dependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n});\n\nexport interface InstalledPackageManifest {\n readonly name: string;\n readonly version: string;\n readonly dependencies: Readonly<Record<string, string>>;\n readonly peerDependencies: Readonly<Record<string, string>>;\n readonly directory: string;\n}\n\nexport class PackagePeerCompatibilityError extends Error {\n constructor(\n packageMetadata: InstalledPackageManifest,\n brainVersion: string,\n peerRange: string | undefined,\n ) {\n super(\n peerRange\n ? `Package \"${packageMetadata.name}@${packageMetadata.version}\" requires @rizom/brain \"${peerRange}\", but \"${brainVersion}\" is installed; install a compatible Brain version or update the peer range only after testing that release`\n : `Package \"${packageMetadata.name}@${packageMetadata.version}\" must declare a @rizom/brain peer dependency; add the tested range under peerDependencies in its package.json`,\n );\n this.name = \"PackagePeerCompatibilityError\";\n }\n}\n\nfunction matchesPackageRef(packageRef: string, packageName: string): boolean {\n return packageRef === packageName || packageRef.startsWith(`${packageName}/`);\n}\n\nfunction ancestorDirectories(directory: string): string[] {\n const parent = dirname(directory);\n return parent === directory\n ? [directory]\n : [directory, ...ancestorDirectories(parent)];\n}\n\nfunction installedManifest(\n manifest: z.output<typeof packageManifestSchema>,\n directory: string,\n): InstalledPackageManifest {\n return Object.freeze({\n name: manifest.name,\n version: manifest.version,\n dependencies: Object.freeze({ ...(manifest.dependencies ?? {}) }),\n peerDependencies: Object.freeze({ ...(manifest.peerDependencies ?? {}) }),\n directory,\n });\n}\n\n/**\n * The package a directory belongs to: the nearest `package.json` at or above\n * it, the way an installed module's package is found.\n */\nexport function findPackageManifest(\n fromDirectory: string,\n): InstalledPackageManifest {\n const directory = ancestorDirectories(fromDirectory).find((candidate) =>\n existsSync(join(candidate, \"package.json\")),\n );\n if (directory === undefined) {\n throw new Error(\n `No package.json at or above \"${fromDirectory}\"; run from the package's own directory`,\n );\n }\n const manifestPath = join(directory, \"package.json\");\n const rawManifest: unknown = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n const parsed = packageManifestSchema.safeParse(rawManifest);\n if (!parsed.success) {\n throw new Error(\n `\"${manifestPath}\" must declare non-empty name and version fields`,\n );\n }\n return installedManifest(parsed.data, directory);\n}\n\nexport function resolveInstalledPackageManifest(\n packageRef: string,\n fromDirectory: string,\n): InstalledPackageManifest {\n let resolved: string;\n try {\n resolved = Bun.resolveSync(packageRef, fromDirectory);\n } catch (error) {\n throw new Error(\n `Could not resolve installed package \"${packageRef}\" from \"${fromDirectory}\"; install it in the Brain application or correct the package reference`,\n { cause: error },\n );\n }\n\n for (const directory of ancestorDirectories(dirname(resolved))) {\n const manifestPath = join(directory, \"package.json\");\n if (!existsSync(manifestPath)) continue;\n\n const rawManifest: unknown = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n const parsed = packageManifestSchema.safeParse(rawManifest);\n if (parsed.success && matchesPackageRef(packageRef, parsed.data.name)) {\n return installedManifest(parsed.data, directory);\n }\n }\n\n throw new Error(\n `Resolved package \"${packageRef}\" from \"${fromDirectory}\" but could not find valid package metadata; ensure its package.json declares matching non-empty name and version fields`,\n );\n}\n\n/** A package runs only on a Brain its `@rizom/brain` peer range admits. */\nexport function assertBrainPeerCompatibility(\n packageMetadata: InstalledPackageManifest,\n brainVersion: string,\n): void {\n const peerRange = packageMetadata.peerDependencies[\"@rizom/brain\"];\n if (!peerRange || !Bun.semver.satisfies(brainVersion, peerRange)) {\n throw new PackagePeerCompatibilityError(\n packageMetadata,\n brainVersion,\n peerRange,\n );\n }\n}\n\nexport function resolveBrainDefinitionDependencies(\n brainPackageRef: string,\n fromDirectory: string,\n): InstalledPackageManifest[] {\n const brain = resolveInstalledPackageManifest(brainPackageRef, fromDirectory);\n if (brain.name === \"@rizom/brain\") return [];\n\n const runtime = resolveInstalledPackageManifest(\n \"@rizom/brain\",\n fromDirectory,\n );\n assertBrainPeerCompatibility(brain, runtime.version);\n\n const definitionDependencies = Object.keys(brain.dependencies)\n .map((dependency) =>\n resolveInstalledPackageManifest(dependency, brain.directory),\n )\n .filter(\n (dependency) => dependency.peerDependencies[\"@rizom/brain\"] !== undefined,\n );\n for (const dependency of definitionDependencies) {\n assertBrainPeerCompatibility(dependency, runtime.version);\n }\n return definitionDependencies;\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";mjNAAA,qBAAS,kBAAY,WACrB,kBAAS,UAAS,aAGlB,IAAM,EAAwB,EAAE,YAAY,CAC1C,KAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EACtB,QAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EACzB,aAAc,EAAE,OAAO,EAAE,OAAO,EAAG,EAAE,OAAO,CAAC,EAAE,SAAS,EACxD,iBAAkB,EAAE,OAAO,EAAE,OAAO,EAAG,EAAE,OAAO,CAAC,EAAE,SAAS,CAC9D,CAAC,EAUM,MAAM,UAAsC,KAAM,CACvD,WAAW,CACT,EACA,EACA,EACA,CACA,MACE,EACI,YAAY,EAAgB,QAAQ,EAAgB,mCAAmC,YAAoB,+GAC3G,YAAY,EAAgB,QAAQ,EAAgB,uHAC1D,EACA,KAAK,KAAO,gCAEhB,CAMA,SAAS,CAAmB,CAAC,EAA6B,CACxD,IAAM,EAAS,EAAQ,CAAS,EAChC,OAAO,IAAW,EACd,CAAC,CAAS,EACV,CAAC,EAAW,GAAG,EAAoB,CAAM,CAAC,EAGhD,SAAS,CAAiB,CACxB,EACA,EAC0B,CAC1B,OAAO,OAAO,OAAO,CACnB,KAAM,EAAS,KACf,QAAS,EAAS,QAClB,aAAc,OAAO,OAAO,IAAM,EAAS,cAAgB,CAAC,CAAG,CAAC,EAChE,iBAAkB,OAAO,OAAO,IAAM,EAAS,kBAAoB,CAAC,CAAG,CAAC,EACxE,WACF,CAAC,EAOI,SAAS,CAAmB,CACjC,EAC0B,CAC1B,IAAM,EAAY,EAAoB,CAAa,EAAE,KAAK,CAAC,IACzD,EAAW,EAAK,EAAW,cAAc,CAAC,CAC5C,EACA,GAAI,IAAc,OAChB,MAAU,MACR,gCAAgC,0CAClC,EAEF,IAAM,EAAe,EAAK,EAAW,cAAc,EAC7C,EAAuB,KAAK,MAAM,EAAa,EAAc,MAAM,CAAC,EACpE,EAAS,EAAsB,UAAU,CAAW,EAC1D,GAAI,CAAC,EAAO,QACV,MAAU,MACR,IAAI,mDACN,EAEF,OAAO,EAAkB,EAAO,KAAM,CAAS,EAkC1C,SAAS,CAA4B,CAC1C,EACA,EACM,CACN,IAAM,EAAY,EAAgB,iBAAiB,gBACnD,GAAI,CAAC,GAAa,CAAC,IAAI,OAAO,UAAU,EAAc,CAAS,EAC7D,MAAM,IAAI,EACR,EACA,EACA,CACF",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "3E453C9F5286833964756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./index-cmt5v1dy.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.
|
|
2
|
+
import"./index-cmt5v1dy.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.741",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=541B7D224697376B64756E2164756E21
|
|
5
|
+
//# sourceMappingURL=package-szn9kp3r.js.map
|
package/dist/git-broker.js
CHANGED
|
@@ -327,5 +327,5 @@ ${t}:`]}}function x2e(e){switch(e){case"stop":return"stop";case"length":return"l
|
|
|
327
327
|
*...and ${e.files.length-10} more files*`)}if(e.exists&&e.stats.totalFiles===0)t.push(`
|
|
328
328
|
## Getting Started
|
|
329
329
|
`),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(`
|
|
330
|
-
`)}}class A1{schema=Uoe;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 vI(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 jm(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 P1{schema=Foe;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}),vI(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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(this.context,t,n,"failed")}summarizeDataForLog(e){return{pathCount:e.paths?.length??"all",batchSize:e.batchSize}}}ei();var L3t=300000,Z3t=500;async function FJe(e){let t={...e,jobIds:e.jobIds.filter((c)=>c!=="")};if(t.jobIds.length===0)return;let n=t.maxWaitMs??L3t,r=t.pollIntervalMs??Z3t;t.logger.debug(`Waiting for ${t.jobIds.length} import jobs to complete`);let o=te.gen(function*(){let c=yield*Hl.currentTimeMillis;yield*te.gen(function*(){let d=(yield*te.tryPromise({try:()=>Promise.all(t.jobIds.map((m)=>t.entityService.getAsyncJobStatus(m))),catch:(m)=>m})).filter((m)=>m&&(m.status==="completed"||m.status==="failed")).length;if(d===t.jobIds.length)return t.logger.debug("All import jobs completed"),!0;if((yield*Hl.currentTimeMillis)-c>n)return t.logger.warn(`Timeout waiting for import jobs (${d}/${t.jobIds.length} completed)`),!0;let f=Math.round(d/t.jobIds.length*100);return yield*te.tryPromise({try:()=>t.reporter.report({progress:50+Math.round(f*0.05),message:`Processing ${d}/${t.jobIds.length} entities`}),catch:(m)=>m}),!1}).pipe(te.repeat({schedule:ra.spaced(r),until:(l)=>l}))}),s=ua(o,t.clock),a=await te.runPromiseExit(s);if(Jt.isFailure(a))throw qn.squash(a.cause)}class _1{schema=$oe;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 FJe({jobIds:e,entityService:this.context.entityService,reporter:t,logger:this.logger})}summarizeDataForLog(e){return{operation:e.operation,syncDirection:e.syncDirection}}}class O1{schema=Noe;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`}),q3t(s)}summarizeDataForLog(e){return{source:e.source,interfaceType:e.interfaceType,channelId:e.channelId}}}function q3t(e){return{gitPulled:!0,batchQueued:!0,batchId:e.batchId,importOperations:e.importOperationsCount,totalFiles:e.totalFiles}}class D1{schema=g1;logger;context;directorySync;constructor(e,t,n){this.logger=e,this.context=t,this.directorySync=n}async process(e,t,n){return vI(this.context,e,t,async()=>{let r=g1.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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(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.context.entityService.deleteEntity({entityType:e.entityType,id:e.entityId,options:{persistenceOrigin:"directory-sync"}});if(s)this.logger.info("Successfully deleted entity for removed file",{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:s,...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])}}W();var G3t=i.object({projectionBatch:pI.optional()});class z1{schema=G3t;context;directorySync;constructor(e,t){this.context=e,this.directorySync=t}async process(e,t,n){return vI(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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(this.context,t,n,"failed")}}import{readFile as W3t}from"fs/promises";async function Es(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}W();var H3t=i.record(i.string(),i.unknown());class M1{schema=Boe;logger;context;fetcher;constructor(e,t,n=wm){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 Es(n,{progress:Vo.INIT,message:`Reading file: ${r}`});let u;try{u=await W3t(r,"utf-8")}catch(h){return this.logger.error("Failed to read file",{filePath:r,error:de(h)}),Bp.failure(h)}let l;try{l=ya(u)}catch(h){return this.logger.warn("Failed to parse markdown",{filePath:r,error:de(h)}),Bp.failure(h)}let d=H3t.safeParse(l.frontmatter),p=d.success?d.data:{};if(p.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:r}),await Es(n,{progress:Vo.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await Es(n,{progress:Vo.FETCH,message:"Checking for existing image"});let f=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:o}},limit:1}}),m;if(f[0])m=f[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:o,imageId:m}),await Es(n,{progress:Vo.EXTRACT,message:`Reusing existing image: ${m}`});else{await Es(n,{progress:Vo.PROCESS,message:`Fetching image from ${o}`});let h;try{h=await this.fetcher(o)}catch(T){return this.logger.error("Failed to fetch image",{sourceUrl:o,error:de(T)}),Bp.failure(T)}await Es(n,{progress:Vo.GENERATE,message:"Creating image entity"}),m=`${a}-cover`;let v=`Cover image for ${s}`,S;try{S=await $P(this.context.entityService,{dataUrl:h},{title:v,alt:c??v,sourceUrl:o})}catch(T){return this.logger.error("Fetched image cannot be stored",{sourceUrl:o,error:de(T)}),Bp.failure(T)}await this.context.entityService.createEntity({entity:{id:m,...S.entity},stagedAsset:S.stagedAsset}),this.logger.debug("Created image entity",{imageId:m,sourceUrl:o}),await Es(n,{progress:Vo.EXTRACT,message:`Created image: ${m}`})}await Es(n,{progress:Vo.SAVE,message:"Updating file"});let g={...p};delete g.coverImageUrl,delete g.coverImageAlt,g.coverImageId=m;let y=ba(g,l.content);try{await Em(r,y)}catch(h){return this.logger.error("Failed to write file",{filePath:r,error:de(h)}),Bp.failure(h)}return await Es(n,{progress:Vo.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:r,imageId:m,sourceUrl:o}),{success:!0,imageId:m}}catch(u){return this.logger.error("Image conversion job failed",{jobId:t,filePath:r,error:de(u)}),Bp.failure(u)}}summarizeDataForLog(e){return{filePath:e.filePath,sourceUrl:e.sourceUrl,postSlug:e.postSlug}}}import{readFile as J3t}from"fs/promises";class j1{schema=Loe;logger;converter;constructor(e,t,n=wm){this.logger=t,this.converter=new hO(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 Es(n,{progress:Vo.INIT,message:`Reading file: ${r}`});let s;try{s=await J3t(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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await Es(n,{progress:Vo.SAVE,message:"Writing updated file"});try{await Em(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 Es(n,{progress:Vo.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 $m(e,t){let n=t.summarizeDataForLog?.bind(t);return QB({type:e,input:t.schema,...n&&{summarize:n},process:({input:r,jobId:o,progress:s,signal:a})=>t.process(r,o,s,a)})}function UJe(e,t,n,r=()=>t,o,s){let a=(c)=>n.child(c);return[$m("directory-sync",new _1(a("DirectorySyncJobHandler"),e,r)),$m("directory-export",new A1(a("DirectoryExportJobHandler"),e,t,o)),$m("directory-import",new P1(a("DirectoryImportJobHandler"),e,t,o,s)),$m("directory-delete",new D1(a("DirectoryDeleteJobHandler"),e,t)),$m("directory-cleanup",new z1(e,t)),$m("cover-image-convert",new M1(e,a("CoverImageConversionJobHandler"))),$m("inline-image-convert",new j1(e,a("InlineImageConversionJobHandler")))]}is();W();var V3t=i.record(i.string(),i.unknown());function BJe(e,t,n,r,o){for(let s of[FE,UE,BE])e.runtime.listen(s,()=>{t()},{mode:"observe"});n.debug("Setup durable entity-export wakeups",{entityTypes:r})}function LJe(e,t,n,r,o){t.setJobQueueCallback(async(s)=>{let a=await r?.startRun("watcher","importing"),c=[{type:s.type,data:V3t.parse(s.data)}],u=jr(),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(f)=>{if(f.kind!=="succeeded")await d(p)}).catch((f)=>{e.logger.warn("Failed to record a stopped watcher run",{error:f})});return}})}import{readdir as qJe,mkdir as K3t,copyFile as Q3t}from"fs/promises";import{join as ZJe,resolve as Tie}from"path";async function Y3t(e,t,n){if(!await ao(e))return!0;if((await qJe(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 GJe(e,t){let n=await qJe(e,{withFileTypes:!0});for(let r of n){let o=ZJe(e,r.name),s=ZJe(t,r.name);if(r.isDirectory()){if(!await ao(s))await K3t(s,{recursive:!0});await GJe(o,s)}else await Q3t(o,s)}}async function WJe(e,t,n,r){let o=Tie(process.cwd(),e);n=n?Tie(n):Tie(process.cwd(),"seed-content");let s=await Y3t(o,t,r);if(s&&await ao(n))t.debug("Copying seed content to brain-data directory"),await GJe(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 HJe="initial-sync";function JJe(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 WJe(d,r,n.seedContentPath,o),n.strictSeedEntityTypes)await I1(d,t.entityService)}let c;try{c=await X3t(e)}catch(d){return r.error("Initial sync failed",d),await VJe(e),await e.recovery?.onGitRecoveryFailed(d),await t.runtime.messaging.broadcast(vT,{success:!1,error:de(d)}),{initialSyncPending:!0}}let{batchIds:u,runId:l}=c;if(u.length===0)return await t.runtime.messaging.broadcast(vT,{success:!0}),{initialSyncPending:!1};return r.info("Initial sync queued for the worker",{batchIds:u}),t5t(t,u).then(async(d)=>{await e5t(e,l,d),await t.runtime.messaging.broadcast(vT,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 X3t(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:HJe,full:!0,...s?{onGitProgress:s.onGitProgress}:{}})).batch;else d=await c.queueSyncBatch(t,HJe)}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 e5t(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 VJe(e),t)await e.operationStatus?.failRun(t,n.error,"import")}function t5t(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(wh,({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 VJe(e){try{await e.reconciliation?.requireFullScan()}catch(t){e.logger.error("Unable to require a full rescan",t)}}var n5t={guard:(e)=>e(),progress:async()=>{},succeeded:async()=>{},requiresRepository:async()=>{},initialSyncRecovery:()=>{return}};function KJe(e){let{operationStatus:t,interruptedPull:n}=e;if(e.executionOnly||!n)return n5t;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 QJe(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 f=await u?.startRun("periodic","pulling");try{let m=f?u?.createProgressObserver(f):void 0,g=await c.pullAndQueue({gitSync:t,directorySync:n,context:r,source:"periodic-sync",signal:p,...m?{onGitProgress:m}:{}});if(f)await u?.markPhase(f,"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}),f)await u?.attachBatch(f,h.batchId)}else if(f)await u?.completeRun(f,y.length===0?"Remote checked; no changes found":"Remote changes required no imports")}catch(m){if(p.aborted){if(f)await u?.clearRun(f)}else if(s.error("Periodic git sync failed",{error:m}),f)await u?.failRun(f,de(m,"Periodic Git sync failed"))}};a.schedulePeriodic(l,d),s.info("Started periodic git sync",{intervalMinutes:o})}async function YJe(e){try{return await e(),!0}catch(t){if(!(t instanceof Mm))throw t;return!1}}async function Iie(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 YJe(()=>e.deleteEntityFile(a.entityType,a.entityId));n.push(a),r||=l;continue}let c=await e.getEntity({entityType:a.entityType,id:a.entityId,visibilityScope:xn("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 YJe(()=>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 r5t=5000,o5t=100;class kie{queue=new ZS;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??r5t}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(o5t))}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.fileOps.writeEntity(s)}catch(a){if(a instanceof Mm)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 Iie({...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 Iie(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 Cie(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 i5t,existsSync as XJe,mkdirSync as s5t,mkdtempSync as a5t,rmSync as c5t}from"fs";import{tmpdir as u5t}from"os";import{fileURLToPath as l5t}from"url";import{join as d5t,resolve as p5t}from"path";async function Uh(e,t){let n=await Cie(["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 f5t(e){return e.startsWith("file://")}function m5t(e){return l5t(e)}async function g5t(e,t){return(await Cie(["git","--git-dir",e,"show-ref","--verify","--quiet",`refs/heads/${t}`])).exitCode===0}async function eVe(e){if(!e.bootstrapFromSeed)return;if(!e.gitUrl||!f5t(e.gitUrl))return;if(!e.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let t=e.branch??"main",n=m5t(e.gitUrl),r=p5t(e.seedContentPath);if(!XJe(r))throw Error(`Seed content path not found: ${r}`);if(!XJe(n))e.logger.debug("Creating local bare content remote",{remotePath:n,branch:t}),s5t(n,{recursive:!0}),await Uh(process.cwd(),["init","--bare",`--initial-branch=${t}`,n]);if(await g5t(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=a5t(d5t(u5t(),"directory-sync-seed-"));try{await Uh(o,["init",`--initial-branch=${t}`]),await Uh(o,["config","user.name",e.authorName??"Brain"]),await Uh(o,["config","user.email",e.authorEmail??"brain@localhost"]),i5t(r,o,{recursive:!0,filter:(s)=>!s.split("/").includes(".git")}),await Uh(o,["add","."]),await Uh(o,["commit","-m","seed content remote"]),await Uh(o,["remote","add","origin",e.gitUrl]),await Uh(o,["push","-u","origin",t])}finally{c5t(o,{recursive:!0,force:!0})}}function tVe(e,t,n,r,o){e.runtime.answer(wY,({request:s})=>{let a=HS(s),{relativePath:c,owner:u,writable:l}=WS(s.entityType,s.entityId,a,Fh(e.entityService)),[d,...p]=Wp(s.entityId),f=p.at(-1)??d,m=c.length-a.length,g=f&&c.endsWith(`${f}${a}`)?{start:m-f.length,end:m}:null;return{relativePath:c,leaf:g,owner:u,writable:l}}),e.runtime.answer(EY,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 h5t(r?.(),n),...a?{managementUrl:a}:{}}}),n.debug("Registered message handlers")}async function h5t(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}}W();async function $1(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}}W();var nVe=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 rVe(e,t){let n=`${e.entityType}/${e.id}.md`;try{if(e.sha){let o=await t.show(e.sha,n);return Il({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 Il({commits:[]},`No history found for ${e.entityType}/${e.id}`);return Il({commits:r,entityType:e.entityType,id:e.id},`${r.length} version${r.length===1?"":"s"} found`)}catch(r){return Cm(de(r,"History lookup failed"))}}var y5t=i.object({action:i.enum(["sync","status"]).default("sync").describe("Use sync for a refresh request and status for a status check")}),b5t=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")}),S5t=i.discriminatedUnion("action",[i.object({action:i.literal("sync")}),i.object({action:i.literal("status")})]),x5t=i.discriminatedUnion("action",[i.object({action:i.literal("sync"),full:i.boolean().optional()}),i.object({action:i.literal("status")}),nVe]);function oVe(e,t,n,r,o){return[m_("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 filesystem scan when git is configured and also handles refresh, pull, backup-to-git, and filesystem import requests. 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 directory sync with an action discriminator. Immediately call action=sync for refresh, filesystem import, or content sync requests. Immediately call action=status for directory sync status follow-ups, including a bare 'what is the status'.",r?b5t:y5t,async(a,c)=>{let u=r?x5t.parse(a):S5t.parse(a);if(u.action==="sync")return v5t({directorySync:e,pluginContext:t,pluginId:n,gitSync:r,operationStatus:o,context:c,full:"full"in u&&u.full===!0});if(u.action==="status")return w5t(e,r);if(!r)return Cm("History is unavailable because git is not configured");return rVe(u,r)},{visibility:"admin",sideEffects:"external",cli:{name:"sync"}})]}async function v5t(e){try{let t=e.context.channelId?`${e.context.interfaceType}:${e.context.channelId}`:`plugin:${e.pluginId}`,n=await $1({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 Il({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 Il({gitPulled:!1,...n.runId?{runId:n.runId}:{}},"No files to sync");return Il({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 Cm(de(t,"Sync failed"))}}async function w5t(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 Il(r)}catch(n){return Cm(de(n,"Status check failed"))}}is();W();import{isAbsolute as iVe,relative as E5t}from"path";var cVe=i.enum(["manual","periodic","watcher","save","startup"]),T5t=i.enum(["pulling","scanning","importing","settling"]),I5t=i.enum(["succeeded","attention","failed"]),k5t=i.enum(["quarantined","import","export","placement","git","source"]),uVe=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()}),Aie=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:cVe,state:T5t,startedAt:i.string().datetime(),lastProgressAt:i.string().datetime(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional(),...uVe.shape})),Pie=i.object({id:i.string().min(1),source:cVe,outcome:I5t,startedAt:i.string().datetime(),completedAt:i.string().datetime(),summary:i.string().min(1).max(240),...uVe.shape}),_ie=i.object({id:i.string().min(1),kind:k5t,path:i.string().min(1).max(300).optional(),message:i.string().min(1).max(400),occurredAt:i.string().datetime()}),C5t=i.object({activeRun:Aie.optional(),recentRuns:i.array(Pie).max(5),issues:i.array(_ie)}),R5t=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()}),sVe={imported:0,skipped:0,failed:0,quarantined:0,exported:0},A5t={recentRuns:[],issues:[]},P5t=i.object({lastProgressAt:i.string().datetime()}),_5t="directory-sync.operation-status",O5t="current",D5t="directory-sync.operation-progress",z5t=1000,M5t=30000;class Oie{store;progressStore;jobs;logger;now;inactivityTimeoutMs;staleGraceMs;progressPersistenceIntervalMs;lastProgressPersistence=new Map;syncPath;constructor(e,t,n,r,o={}){this.store=new qS({runtimeState:e,namespace:_5t,key:O5t,schema:C5t,createEmpty:()=>structuredClone(A5t)}),this.progressStore=e.scoped({namespace:D5t,schema:P5t}),this.jobs=t,this.logger=n,this.syncPath=r,this.now=o.now??Date.now,this.inactivityTimeoutMs=o.inactivityTimeoutMs??nD,this.staleGraceMs=o.staleGraceMs??M5t,this.progressPersistenceIntervalMs=o.progressPersistenceIntervalMs??z5t}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=jr(),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,...sVe},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=SO(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=SO(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:jr(),source:e,state:"settling",startedAt:s,lastProgressAt:s,...sVe,...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=R5t.safeParse(j5t(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 Rie();let t=await this.withEffectiveProgress(e.activeRun);if(t.jobId){if((await this.jobs.getStatus(t.jobId))?.status!=="processing")return Rie()}let n=Math.max(0,this.now()-Date.parse(t.lastProgressAt)),r=this.inactivityTimeoutMs+this.staleGraceMs;if(n<=r)return Rie();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:SO(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??SO(t.message,80)}`,kind:t.kind,...n?{path:n}:{},message:SO(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(!iVe(e))return aVe(e);let t=E5t(this.syncPath,e);if(t.startsWith("..")||iVe(t))return"content file";return aVe(t)}}function Rie(){return{status:"healthy",message:"No stale directory Git pull"}}function j5t(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function aVe(e){return e.replaceAll("\\","/").replace(/^\.\//,"").slice(0,300)||"content file"}function SO(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"}is();W();GN();var $5t=i.object({checkpoint:Kg.optional(),entityTypes:i.array(i.string()).optional(),fullScanRequest:i.string().optional()}),N5t="directory-sync.git-reconciliation",F5t="current";function lVe(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 Die{store;constructor(e){this.store=new qS({runtimeState:e,namespace:N5t,key:F5t,schema:$5t,createEmpty:()=>({})})}async getCheckpoint(){return(await this.store.snapshot()).checkpoint}saveCheckpoint(e,t){return this.store.mutate((n)=>{if(n.checkpoint=e,t)n.entityTypes=dVe(t)})}requireFullScan(){return this.store.mutate((e)=>{e.fullScanRequest=jr()})}async pullAndQueue(e){return await e.gitSync.pull(e.signal,e.onGitProgress),e.signal?.throwIfAborted(),this.queueCurrentDelta(e)}replayAndQueue(e){return this.queueCurrentDelta(e)}async queueCurrentDelta(e){e.signal?.throwIfAborted();let t=dVe(e.context.entityService.getEntityTypes()),n=await this.store.snapshot(),r=e.entityTypesIncomplete!==!0,o=e.full===!0||r&&(n.fullScanRequest!==void 0||!U5t(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,lVe(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,lVe(e.gitSync)),await a(s.checkpoint);return{mode:s.mode,files:c,deletedFiles:s.deletedFiles,batch:u,checkpointAdvanced:u!==null}}}function dVe(e){return[...new Set(e)].sort()}function U5t(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])}W();import{basename as B5t}from"path";var fVe=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:Aie.optional(),recentRuns:i.array(Pie),issues:i.array(_ie)}),zie=R_({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()})}),L5t=new Map([["M","Modified"],["A","Added"],["D","Deleted"],["R","Renamed"],["C","Copied"],["U","Unmerged"],["??","Untracked"]]);function Z5t(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 pVe=v_({id:"sync",label:"Content sync",permission:"admin",data:fVe,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?[Z5t(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:L5t.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((m,g)=>Date.parse(g.occurredAt)-Date.parse(m.occurredAt)),p=d[0];if(!p)return[];let f=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:`${f} needs attention`,text:[`${d.length} recorded ${d.length===1?"issue":"issues"}`,p.path].filter(Boolean).join(" \xB7 "),tone:"warn",details:d.map((m)=>[`Occurred: ${m.occurredAt}`,m.path?`Path: ${m.path}`:void 0,m.message].filter(Boolean).join(`
|
|
330
|
+
`)}}class A1{schema=Uoe;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 vI(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 jm(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 P1{schema=Foe;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}),vI(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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(this.context,t,n,"failed")}summarizeDataForLog(e){return{pathCount:e.paths?.length??"all",batchSize:e.batchSize}}}ei();var L3t=300000,Z3t=500;async function FJe(e){let t={...e,jobIds:e.jobIds.filter((c)=>c!=="")};if(t.jobIds.length===0)return;let n=t.maxWaitMs??L3t,r=t.pollIntervalMs??Z3t;t.logger.debug(`Waiting for ${t.jobIds.length} import jobs to complete`);let o=te.gen(function*(){let c=yield*Hl.currentTimeMillis;yield*te.gen(function*(){let d=(yield*te.tryPromise({try:()=>Promise.all(t.jobIds.map((m)=>t.entityService.getAsyncJobStatus(m))),catch:(m)=>m})).filter((m)=>m&&(m.status==="completed"||m.status==="failed")).length;if(d===t.jobIds.length)return t.logger.debug("All import jobs completed"),!0;if((yield*Hl.currentTimeMillis)-c>n)return t.logger.warn(`Timeout waiting for import jobs (${d}/${t.jobIds.length} completed)`),!0;let f=Math.round(d/t.jobIds.length*100);return yield*te.tryPromise({try:()=>t.reporter.report({progress:50+Math.round(f*0.05),message:`Processing ${d}/${t.jobIds.length} entities`}),catch:(m)=>m}),!1}).pipe(te.repeat({schedule:ra.spaced(r),until:(l)=>l}))}),s=ua(o,t.clock),a=await te.runPromiseExit(s);if(Jt.isFailure(a))throw qn.squash(a.cause)}class _1{schema=$oe;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 FJe({jobIds:e,entityService:this.context.entityService,reporter:t,logger:this.logger})}summarizeDataForLog(e){return{operation:e.operation,syncDirection:e.syncDirection}}}class O1{schema=Noe;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`}),q3t(s)}summarizeDataForLog(e){return{source:e.source,interfaceType:e.interfaceType,channelId:e.channelId}}}function q3t(e){return{gitPulled:!0,batchQueued:!0,batchId:e.batchId,importOperations:e.importOperationsCount,totalFiles:e.totalFiles}}class D1{schema=g1;logger;context;directorySync;constructor(e,t,n){this.logger=e,this.context=t,this.directorySync=n}async process(e,t,n){return vI(this.context,e,t,async()=>{let r=g1.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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(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.context.entityService.deleteEntity({entityType:e.entityType,id:e.entityId,options:{persistenceOrigin:"directory-sync"}});if(s)this.logger.info("Successfully deleted entity for removed file",{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:s,...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])}}W();var G3t=i.object({projectionBatch:pI.optional()});class z1{schema=G3t;context;directorySync;constructor(e,t){this.context=e,this.directorySync=t}async process(e,t,n){return vI(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 jm(this.context,e,t,"completed")}async onTerminalError(e,t,n){await jm(this.context,t,n,"failed")}}import{readFile as W3t}from"fs/promises";async function Es(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}W();var H3t=i.record(i.string(),i.unknown());class M1{schema=Boe;logger;context;fetcher;constructor(e,t,n=wm){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 Es(n,{progress:Vo.INIT,message:`Reading file: ${r}`});let u;try{u=await W3t(r,"utf-8")}catch(h){return this.logger.error("Failed to read file",{filePath:r,error:de(h)}),Bp.failure(h)}let l;try{l=ya(u)}catch(h){return this.logger.warn("Failed to parse markdown",{filePath:r,error:de(h)}),Bp.failure(h)}let d=H3t.safeParse(l.frontmatter),p=d.success?d.data:{};if(p.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:r}),await Es(n,{progress:Vo.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await Es(n,{progress:Vo.FETCH,message:"Checking for existing image"});let f=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:o}},limit:1}}),m;if(f[0])m=f[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:o,imageId:m}),await Es(n,{progress:Vo.EXTRACT,message:`Reusing existing image: ${m}`});else{await Es(n,{progress:Vo.PROCESS,message:`Fetching image from ${o}`});let h;try{h=await this.fetcher(o)}catch(T){return this.logger.error("Failed to fetch image",{sourceUrl:o,error:de(T)}),Bp.failure(T)}await Es(n,{progress:Vo.GENERATE,message:"Creating image entity"}),m=`${a}-cover`;let v=`Cover image for ${s}`,S;try{S=await $P(this.context.entityService,{dataUrl:h},{title:v,alt:c??v,sourceUrl:o})}catch(T){return this.logger.error("Fetched image cannot be stored",{sourceUrl:o,error:de(T)}),Bp.failure(T)}await this.context.entityService.createEntity({entity:{id:m,...S.entity},stagedAsset:S.stagedAsset}),this.logger.debug("Created image entity",{imageId:m,sourceUrl:o}),await Es(n,{progress:Vo.EXTRACT,message:`Created image: ${m}`})}await Es(n,{progress:Vo.SAVE,message:"Updating file"});let g={...p};delete g.coverImageUrl,delete g.coverImageAlt,g.coverImageId=m;let y=ba(g,l.content);try{await Em(r,y)}catch(h){return this.logger.error("Failed to write file",{filePath:r,error:de(h)}),Bp.failure(h)}return await Es(n,{progress:Vo.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:r,imageId:m,sourceUrl:o}),{success:!0,imageId:m}}catch(u){return this.logger.error("Image conversion job failed",{jobId:t,filePath:r,error:de(u)}),Bp.failure(u)}}summarizeDataForLog(e){return{filePath:e.filePath,sourceUrl:e.sourceUrl,postSlug:e.postSlug}}}import{readFile as J3t}from"fs/promises";class j1{schema=Loe;logger;converter;constructor(e,t,n=wm){this.logger=t,this.converter=new hO(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 Es(n,{progress:Vo.INIT,message:`Reading file: ${r}`});let s;try{s=await J3t(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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.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 Es(n,{progress:Vo.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await Es(n,{progress:Vo.SAVE,message:"Writing updated file"});try{await Em(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 Es(n,{progress:Vo.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 $m(e,t){let n=t.summarizeDataForLog?.bind(t);return QB({type:e,input:t.schema,...n&&{summarize:n},process:({input:r,jobId:o,progress:s,signal:a})=>t.process(r,o,s,a)})}function UJe(e,t,n,r=()=>t,o,s){let a=(c)=>n.child(c);return[$m("directory-sync",new _1(a("DirectorySyncJobHandler"),e,r)),$m("directory-export",new A1(a("DirectoryExportJobHandler"),e,t,o)),$m("directory-import",new P1(a("DirectoryImportJobHandler"),e,t,o,s)),$m("directory-delete",new D1(a("DirectoryDeleteJobHandler"),e,t)),$m("directory-cleanup",new z1(e,t)),$m("cover-image-convert",new M1(e,a("CoverImageConversionJobHandler"))),$m("inline-image-convert",new j1(e,a("InlineImageConversionJobHandler")))]}is();W();var V3t=i.record(i.string(),i.unknown());function BJe(e,t,n,r,o){for(let s of[FE,UE,BE])e.runtime.listen(s,()=>{t()},{mode:"observe"});n.debug("Setup durable entity-export wakeups",{entityTypes:r})}function LJe(e,t,n,r,o){t.setJobQueueCallback(async(s)=>{let a=await r?.startRun("watcher","importing"),c=[{type:s.type,data:V3t.parse(s.data)}],u=jr(),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(f)=>{if(f.kind!=="succeeded")await d(p)}).catch((f)=>{e.logger.warn("Failed to record a stopped watcher run",{error:f})});return}})}import{readdir as qJe,mkdir as K3t,copyFile as Q3t}from"fs/promises";import{join as ZJe,resolve as Tie}from"path";async function Y3t(e,t,n){if(!await ao(e))return!0;if((await qJe(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 GJe(e,t){let n=await qJe(e,{withFileTypes:!0});for(let r of n){let o=ZJe(e,r.name),s=ZJe(t,r.name);if(r.isDirectory()){if(!await ao(s))await K3t(s,{recursive:!0});await GJe(o,s)}else await Q3t(o,s)}}async function WJe(e,t,n,r){let o=Tie(process.cwd(),e);n=n?Tie(n):Tie(process.cwd(),"seed-content");let s=await Y3t(o,t,r);if(s&&await ao(n))t.debug("Copying seed content to brain-data directory"),await GJe(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 HJe="initial-sync";function JJe(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 WJe(d,r,n.seedContentPath,o),n.strictSeedEntityTypes)await I1(d,t.entityService)}let c;try{c=await X3t(e)}catch(d){return r.error("Initial sync failed",d),await VJe(e),await e.recovery?.onGitRecoveryFailed(d),await t.runtime.messaging.broadcast(vT,{success:!1,error:de(d)}),{initialSyncPending:!0}}let{batchIds:u,runId:l}=c;if(u.length===0)return await t.runtime.messaging.broadcast(vT,{success:!0}),{initialSyncPending:!1};return r.info("Initial sync queued for the worker",{batchIds:u}),t5t(t,u).then(async(d)=>{await e5t(e,l,d),await t.runtime.messaging.broadcast(vT,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 X3t(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:HJe,full:!0,...s?{onGitProgress:s.onGitProgress}:{}})).batch;else d=await c.queueSyncBatch(t,HJe)}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 e5t(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 VJe(e),t)await e.operationStatus?.failRun(t,n.error,"import")}function t5t(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(wh,({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 VJe(e){try{await e.reconciliation?.requireFullScan()}catch(t){e.logger.error("Unable to require a full rescan",t)}}var n5t={guard:(e)=>e(),progress:async()=>{},succeeded:async()=>{},requiresRepository:async()=>{},initialSyncRecovery:()=>{return}};function KJe(e){let{operationStatus:t,interruptedPull:n}=e;if(e.executionOnly||!n)return n5t;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 QJe(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 f=await u?.startRun("periodic","pulling");try{let m=f?u?.createProgressObserver(f):void 0,g=await c.pullAndQueue({gitSync:t,directorySync:n,context:r,source:"periodic-sync",signal:p,...m?{onGitProgress:m}:{}});if(f)await u?.markPhase(f,"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}),f)await u?.attachBatch(f,h.batchId)}else if(f)await u?.completeRun(f,y.length===0?"Remote checked; no changes found":"Remote changes required no imports")}catch(m){if(p.aborted){if(f)await u?.clearRun(f)}else if(s.error("Periodic git sync failed",{error:m}),f)await u?.failRun(f,de(m,"Periodic Git sync failed"))}};a.schedulePeriodic(l,d),s.info("Started periodic git sync",{intervalMinutes:o})}async function YJe(e){try{return await e(),!0}catch(t){if(!(t instanceof Mm))throw t;return!1}}async function Iie(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 YJe(()=>e.deleteEntityFile(a.entityType,a.entityId));n.push(a),r||=l;continue}let c=await e.getEntity({entityType:a.entityType,id:a.entityId,visibilityScope:xn("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 YJe(()=>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 r5t=5000,o5t=100;class kie{queue=new ZS;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??r5t}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(o5t))}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.fileOps.writeEntity(s)}catch(a){if(a instanceof Mm)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 Iie({...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 Iie(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 Cie(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 i5t,existsSync as XJe,mkdirSync as s5t,mkdtempSync as a5t,rmSync as c5t}from"fs";import{tmpdir as u5t}from"os";import{fileURLToPath as l5t}from"url";import{join as d5t,resolve as p5t}from"path";async function Uh(e,t){let n=await Cie(["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 f5t(e){return e.startsWith("file://")}function m5t(e){return l5t(e)}async function g5t(e,t){return(await Cie(["git","--git-dir",e,"show-ref","--verify","--quiet",`refs/heads/${t}`])).exitCode===0}async function eVe(e){if(!e.bootstrapFromSeed)return;if(!e.gitUrl||!f5t(e.gitUrl))return;if(!e.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let t=e.branch??"main",n=m5t(e.gitUrl),r=p5t(e.seedContentPath);if(!XJe(r))throw Error(`Seed content path not found: ${r}`);if(!XJe(n))e.logger.debug("Creating local bare content remote",{remotePath:n,branch:t}),s5t(n,{recursive:!0}),await Uh(process.cwd(),["init","--bare",`--initial-branch=${t}`,n]);if(await g5t(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=a5t(d5t(u5t(),"directory-sync-seed-"));try{await Uh(o,["init",`--initial-branch=${t}`]),await Uh(o,["config","user.name",e.authorName??"Brain"]),await Uh(o,["config","user.email",e.authorEmail??"brain@localhost"]),i5t(r,o,{recursive:!0,filter:(s)=>!s.split("/").includes(".git")}),await Uh(o,["add","."]),await Uh(o,["commit","-m","seed content remote"]),await Uh(o,["remote","add","origin",e.gitUrl]),await Uh(o,["push","-u","origin",t])}finally{c5t(o,{recursive:!0,force:!0})}}function tVe(e,t,n,r,o){e.runtime.answer(wY,({request:s})=>{let a=HS(s),{relativePath:c,owner:u,writable:l}=WS(s.entityType,s.entityId,a,Fh(e.entityService)),[d,...p]=Wp(s.entityId),f=p.at(-1)??d,m=c.length-a.length,g=f&&c.endsWith(`${f}${a}`)?{start:m-f.length,end:m}:null;return{relativePath:c,leaf:g,owner:u,writable:l}}),e.runtime.answer(EY,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 h5t(r?.(),n),...a?{managementUrl:a}:{}}}),n.debug("Registered message handlers")}async function h5t(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}}W();async function $1(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}}W();var nVe=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 rVe(e,t){let n=`${e.entityType}/${e.id}.md`;try{if(e.sha){let o=await t.show(e.sha,n);return Il({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 Il({commits:[]},`No history found for ${e.entityType}/${e.id}`);return Il({commits:r,entityType:e.entityType,id:e.id},`${r.length} version${r.length===1?"":"s"} found`)}catch(r){return Cm(de(r,"History lookup failed"))}}var y5t=i.object({action:i.enum(["sync","status"]).default("sync").describe("Use sync for a refresh request and status for a status check")}),b5t=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")}),S5t=i.discriminatedUnion("action",[i.object({action:i.literal("sync")}),i.object({action:i.literal("status")})]),x5t=i.discriminatedUnion("action",[i.object({action:i.literal("sync"),full:i.boolean().optional()}),i.object({action:i.literal("status")}),nVe]);function oVe(e,t,n,r,o){return[m_("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?b5t:y5t,async(a,c)=>{let u=r?x5t.parse(a):S5t.parse(a);if(u.action==="sync")return v5t({directorySync:e,pluginContext:t,pluginId:n,gitSync:r,operationStatus:o,context:c,full:"full"in u&&u.full===!0});if(u.action==="status")return w5t(e,r);if(!r)return Cm("History is unavailable because git is not configured");return rVe(u,r)},{visibility:"admin",sideEffects:"external",cli:{name:"sync"}})]}async function v5t(e){try{let t=e.context.channelId?`${e.context.interfaceType}:${e.context.channelId}`:`plugin:${e.pluginId}`,n=await $1({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 Il({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 Il({gitPulled:!1,...n.runId?{runId:n.runId}:{}},"No files to sync");return Il({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 Cm(de(t,"Sync failed"))}}async function w5t(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 Il(r)}catch(n){return Cm(de(n,"Status check failed"))}}is();W();import{isAbsolute as iVe,relative as E5t}from"path";var cVe=i.enum(["manual","periodic","watcher","save","startup"]),T5t=i.enum(["pulling","scanning","importing","settling"]),I5t=i.enum(["succeeded","attention","failed"]),k5t=i.enum(["quarantined","import","export","placement","git","source"]),uVe=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()}),Aie=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:cVe,state:T5t,startedAt:i.string().datetime(),lastProgressAt:i.string().datetime(),jobId:i.string().min(1).optional(),batchId:i.string().min(1).optional(),...uVe.shape})),Pie=i.object({id:i.string().min(1),source:cVe,outcome:I5t,startedAt:i.string().datetime(),completedAt:i.string().datetime(),summary:i.string().min(1).max(240),...uVe.shape}),_ie=i.object({id:i.string().min(1),kind:k5t,path:i.string().min(1).max(300).optional(),message:i.string().min(1).max(400),occurredAt:i.string().datetime()}),C5t=i.object({activeRun:Aie.optional(),recentRuns:i.array(Pie).max(5),issues:i.array(_ie)}),R5t=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()}),sVe={imported:0,skipped:0,failed:0,quarantined:0,exported:0},A5t={recentRuns:[],issues:[]},P5t=i.object({lastProgressAt:i.string().datetime()}),_5t="directory-sync.operation-status",O5t="current",D5t="directory-sync.operation-progress",z5t=1000,M5t=30000;class Oie{store;progressStore;jobs;logger;now;inactivityTimeoutMs;staleGraceMs;progressPersistenceIntervalMs;lastProgressPersistence=new Map;syncPath;constructor(e,t,n,r,o={}){this.store=new qS({runtimeState:e,namespace:_5t,key:O5t,schema:C5t,createEmpty:()=>structuredClone(A5t)}),this.progressStore=e.scoped({namespace:D5t,schema:P5t}),this.jobs=t,this.logger=n,this.syncPath=r,this.now=o.now??Date.now,this.inactivityTimeoutMs=o.inactivityTimeoutMs??nD,this.staleGraceMs=o.staleGraceMs??M5t,this.progressPersistenceIntervalMs=o.progressPersistenceIntervalMs??z5t}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=jr(),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,...sVe},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=SO(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=SO(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:jr(),source:e,state:"settling",startedAt:s,lastProgressAt:s,...sVe,...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=R5t.safeParse(j5t(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 Rie();let t=await this.withEffectiveProgress(e.activeRun);if(t.jobId){if((await this.jobs.getStatus(t.jobId))?.status!=="processing")return Rie()}let n=Math.max(0,this.now()-Date.parse(t.lastProgressAt)),r=this.inactivityTimeoutMs+this.staleGraceMs;if(n<=r)return Rie();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:SO(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??SO(t.message,80)}`,kind:t.kind,...n?{path:n}:{},message:SO(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(!iVe(e))return aVe(e);let t=E5t(this.syncPath,e);if(t.startsWith("..")||iVe(t))return"content file";return aVe(t)}}function Rie(){return{status:"healthy",message:"No stale directory Git pull"}}function j5t(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function aVe(e){return e.replaceAll("\\","/").replace(/^\.\//,"").slice(0,300)||"content file"}function SO(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"}is();W();GN();var $5t=i.object({checkpoint:Kg.optional(),entityTypes:i.array(i.string()).optional(),fullScanRequest:i.string().optional()}),N5t="directory-sync.git-reconciliation",F5t="current";function lVe(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 Die{store;constructor(e){this.store=new qS({runtimeState:e,namespace:N5t,key:F5t,schema:$5t,createEmpty:()=>({})})}async getCheckpoint(){return(await this.store.snapshot()).checkpoint}saveCheckpoint(e,t){return this.store.mutate((n)=>{if(n.checkpoint=e,t)n.entityTypes=dVe(t)})}requireFullScan(){return this.store.mutate((e)=>{e.fullScanRequest=jr()})}async pullAndQueue(e){return await e.gitSync.pull(e.signal,e.onGitProgress),e.signal?.throwIfAborted(),this.queueCurrentDelta(e)}replayAndQueue(e){return this.queueCurrentDelta(e)}async queueCurrentDelta(e){e.signal?.throwIfAborted();let t=dVe(e.context.entityService.getEntityTypes()),n=await this.store.snapshot(),r=e.entityTypesIncomplete!==!0,o=e.full===!0||r&&(n.fullScanRequest!==void 0||!U5t(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,lVe(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,lVe(e.gitSync)),await a(s.checkpoint);return{mode:s.mode,files:c,deletedFiles:s.deletedFiles,batch:u,checkpointAdvanced:u!==null}}}function dVe(e){return[...new Set(e)].sort()}function U5t(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])}W();import{basename as B5t}from"path";var fVe=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:Aie.optional(),recentRuns:i.array(Pie),issues:i.array(_ie)}),zie=R_({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()})}),L5t=new Map([["M","Modified"],["A","Added"],["D","Deleted"],["R","Renamed"],["C","Copied"],["U","Unmerged"],["??","Untracked"]]);function Z5t(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 pVe=v_({id:"sync",label:"Content sync",permission:"admin",data:fVe,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?[Z5t(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:L5t.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((m,g)=>Date.parse(g.occurredAt)-Date.parse(m.occurredAt)),p=d[0];if(!p)return[];let f=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:`${f} needs attention`,text:[`${d.length} recorded ${d.length===1?"issue":"issues"}`,p.path].filter(Boolean).join(" \xB7 "),tone:"warn",details:d.map((m)=>[`Occurred: ${m.occurredAt}`,m.path?`Path: ${m.path}`:void 0,m.message].filter(Boolean).join(`
|
|
331
331
|
`))}]}),{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 Mie{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 fVe.parse({health:r.activeRun?"active":r.issues.length>0?"attention":"healthy",directory:{displayPath:B5t(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:pVe,bind:(r)=>pVe.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 $1({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:q5t(r.path),status:r.status.trim()||"changed"})),n=G5t(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 q5t(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/"))return"content file";return t.slice(0,300)||"content file"}function G5t(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$/,"")}`}}ei();class jie{resourceScope;scheduleScope;periodicScope;delayScope;scheduleFibers;periodicFibers;delayedFibers;clock;activeOperations=new Set;activeFailures=[];nextPeriodicId=0;closePromise=null;closed=!1;constructor(e={}){this.resourceScope=te.runSync(un.make()),this.scheduleScope=te.runSync(un.make()),this.periodicScope=te.runSync(un.make()),this.delayScope=te.runSync(un.make()),this.scheduleFibers=te.runSync(un.provide(Ig.make(),this.scheduleScope)),this.periodicFibers=te.runSync(un.provide(ca.make(),this.periodicScope)),this.delayedFibers=te.runSync(un.provide(ca.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(un.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||ca.hasUnsafe(this.periodicFibers,n))return;let a=te.tryPromise({try:t,catch:(c)=>c}).pipe(te.catch((c)=>te.sync(()=>{this.activeFailures.push(c)})));ca.setUnsafe(this.periodicFibers,n,te.runFork(a),{onlyIfMissing:!0})},o=te.sleep(e).pipe(te.andThen(te.sync(r)),te.forever),s=ua(o,this.clock);Ig.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=ua(r,this.clock),s=te.runFork(o);ca.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(un.close(e,Jt.void));if(Jt.isFailure(t))throw qn.squash(t.cause)}}function mVe(e){return{initialize:()=>e().initialize(),initializeDirectory:()=>e().initializeDirectory(),setJobQueueCallback:(t)=>e().setJobQueueCallback(t),sync:()=>e().sync(),processEntityExport:(t)=>e().processEntityExport(t),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 gVe(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),getReconciliationDelta:(t)=>e().getReconciliationDelta(t),cleanup:()=>e().cleanup(),log:(t,n)=>e().log(t,n),show:(t,n)=>e().show(t,n)}}function hVe(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 N1{config;context;logger;syncRequestJob;directorySync;gitSync;operationStatus;gitReconciliation;workspaceProvider;studioWorkspaceUrl;runtime=new jie;directorySyncFacade=mVe(()=>this.requireDirectorySync());gitSyncFacade=gVe(()=>this.requireGitSync());runtimeScheduler={scheduleTrailing:(e,t,n)=>{this.runtime.scheduleTrailing(e,t,n)}};watcherOwned=!1;gitBackgroundStarted=!1;entityExportDispatcher;pendingDeletes=new yO;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 kie({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:mE,basePrompt:"",formatter:new R1,requiredPermission:"admin"});let t=hVe({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 Oie(e.runtimeState,e.jobs,this.logger.child("OperationStatus"),t);let n=KJe({operationStatus:this.operationStatus,interruptedPull:await this.operationStatus.initialize({executionOnly:e.executionOnly}),executionOnly:e.executionOnly});if(this.registerOperationalHealth(e),this.gitReconciliation=new Die(e.runtimeState),!e.executionOnly&&this.config.autoSync)LJe(e,this.directorySync,t,this.operationStatus,await this.runtime.acquire(async()=>new $E({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=$m("sync-request",new O1(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",Eie({probe:wie(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),BJe(e,()=>this.requireEntityExportDispatcher().wake(),this.logger,this.config.entityTypes,this.operationStatus),this.config.initialSync)JJe({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 Mie({context:e,config:this.config,getDirectorySync:()=>this.requireDirectorySync(),getGitSync:()=>this.gitSync,operationStatus:this.requireOperationStatus()}),tVe(e,()=>this.requireDirectorySync(),this.logger,()=>this.gitSync,()=>this.studioWorkspaceUrl)}async ready(){if(this.config.seedContent&&this.config.strictSeedEntityTypes){let e=this.getContext();await I1(this.config.syncPath??e.dataDir,e.entityService)}await this.requireEntityExportDispatcher().start(),await this.startBackgroundWork(),this.studioWorkspaceUrl=await this.workspaceProvider?.registerStudioWorkspace()}tools(){return oVe(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 C1({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},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 eVe({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:NJe({logger:this.logger.child("GitOwner"),scheduler:this.runtimeScheduler,replay:$Je({client:()=>r.gitSync,replay:async(a)=>{await this.requireGitReconciliation().replayAndQueue({gitSync:a,directorySync:t,context:this.getContext(),source:"broker-replacement-replay"})}})}),s=await a_e({socketPath:this.getContext().gitBrokerSocket,checkoutPath:e,branch:n.branch,remoteUrl:rD({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)QJe({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[...UJe(this.context,this.directorySyncFacade,this.logger,()=>this.requireDirectorySync(),this.requireOperationStatus(),this.requireGitReconciliation()),...this.syncRequestJob?[this.syncRequestJob]:[]]}}function $ie(e={}){let t=tL({id:"directory-sync",config:xS,setup:async(n)=>{let r=VB(n),o=new N1(n.config,sHe(r));await o.registerCommon(),r.registering(()=>o.registerRoles()),r.ready(()=>o.ready()),n.lifecycle.onCleanup(()=>o.shutdown());let s={sync:o};return e.onSetup?.(s),s}});return A_(XB(t,({state:n})=>n.sync.jobHandlers()),({state:n})=>n.sync.tools())}var ohr=$ie();var yVe="./brain-data";var bhr=i.object({syncPath:i.string().optional(),git:i.object({repo:i.string().optional(),gitUrl:i.string().optional()}).optional()});async function bVe(e,t,n={}){let r=n.processImpl??process,o=n.startHost??WX,s=r.env[bE];if(!s)return{success:!1,message:`${bE} is unset; the Git broker is started by the Brain supervisor, not directly`,exitCode:1};let a=await o({socketPath:s,runtimeDir:SE(e),cwd:e,dataDir:yVe,pluginConfig:EU(t.plugins?.["directory-sync"]??{},r.env),logger:lo.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}}lo.setProcessRole("git-broker");var J5t=lo.getInstance(),V5t=i.object({plugins:i.object({"directory-sync":i.unknown().optional()}).optional()}),SVe=process.cwd(),xO=await Promise.resolve().then(()=>bVe(SVe,V5t.parse(lZ(W5t(H5t(SVe,"brain.yaml"),"utf8"))))).catch((e)=>({success:!1,message:`Git broker failed: ${de(e)}`,exitCode:1}));if(!xO.success&&xO.message)J5t.error(xO.message);process.exit(xO.success?0:xO.exitCode??1);
|