@rizom/brain 0.2.0-alpha.873 → 0.2.0-alpha.875
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 +10 -10
- package/dist/chunks/app-ekx3p63b.js +5 -0
- package/dist/chunks/{index-3tvzr6ge.js → index-02srst5t.js} +3 -3
- package/dist/chunks/{index-3tvzr6ge.js.map → index-02srst5t.js.map} +1 -1
- package/dist/chunks/{index-1vaa2761.js → index-5fa86d31.js} +2 -2
- package/dist/chunks/{index-nnwk2h8n.js → index-9kdd9kj5.js} +2 -2
- package/dist/chunks/{index-gnbfdewj.js → index-9mfc2kx2.js} +3 -3
- package/dist/chunks/{index-gnbfdewj.js.map → index-9mfc2kx2.js.map} +5 -5
- package/dist/chunks/{index-02pt9z7t.js → index-cywssss6.js} +2 -2
- package/dist/chunks/{index-wete5qfn.js → index-t822ntg2.js} +2 -2
- package/dist/chunks/{package-z5h1920s.js → package-c88dkedp.js} +3 -3
- package/dist/chunks/{package-z5h1920s.js.map → package-c88dkedp.js.map} +1 -1
- package/dist/entities.js +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +6 -6
- package/dist/model.js.map +5 -5
- package/dist/services.js +1 -1
- package/dist/testing.js +1 -1
- package/dist/ui/{studio-app-1edp4r57.js → studio-app-bb5xxwvn.js} +3 -3
- package/dist/ui/studio-asset-manifest.json +21 -21
- package/dist/ui/studio-chunks/{account-view-j9wkxck6.js → account-view-ak5tfxgg.js} +1 -1
- package/dist/ui/studio-chunks/{main-d5szcfbq.js → main-2g8gcg0r.js} +1 -1
- package/dist/ui/studio-chunks/{main-rt6yh800.js → main-2hbxfr9g.js} +1 -1
- package/dist/ui/studio-chunks/{main-pqx64crr.js → main-45xgzy0v.js} +2 -2
- package/dist/ui/studio-chunks/{main-pqx64crr.js.map → main-45xgzy0v.js.map} +5 -5
- package/dist/ui/studio-chunks/{main-fqzf25fv.js → main-q24zjy7e.js} +1 -1
- package/dist/ui/studio-chunks/{main-ggcgvxym.js → main-qyf00dty.js} +1 -1
- package/dist/ui/studio-chunks/{main-6qe1jp8h.js → main-tcyq2xnp.js} +1 -1
- package/dist/ui/studio-chunks/{studio-ask-panel-njthpfwq.js → studio-ask-panel-vjymeavp.js} +1 -1
- package/dist/ui/studio-chunks/{studio-chat-workspace-jw3pye8a.js → studio-chat-workspace-kzcn37qq.js} +1 -1
- package/package.json +1 -1
- package/dist/chunks/app-n0bqjatx.js +0 -5
- /package/dist/chunks/{app-n0bqjatx.js.map → app-ekx3p63b.js.map} +0 -0
- /package/dist/chunks/{index-1vaa2761.js.map → index-5fa86d31.js.map} +0 -0
- /package/dist/chunks/{index-nnwk2h8n.js.map → index-9kdd9kj5.js.map} +0 -0
- /package/dist/chunks/{index-02pt9z7t.js.map → index-cywssss6.js.map} +0 -0
- /package/dist/chunks/{index-wete5qfn.js.map → index-t822ntg2.js.map} +0 -0
- /package/dist/ui/{studio-app-1edp4r57.js.map → studio-app-bb5xxwvn.js.map} +0 -0
- /package/dist/ui/studio-chunks/{account-view-j9wkxck6.js.map → account-view-ak5tfxgg.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-d5szcfbq.js.map → main-2g8gcg0r.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-rt6yh800.js.map → main-2hbxfr9g.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-fqzf25fv.js.map → main-q24zjy7e.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-ggcgvxym.js.map → main-qyf00dty.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-6qe1jp8h.js.map → main-tcyq2xnp.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-ask-panel-njthpfwq.js.map → studio-ask-panel-vjymeavp.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-chat-workspace-jw3pye8a.js.map → studio-chat-workspace-kzcn37qq.js.map} +0 -0
package/dist/brain.js
CHANGED
|
@@ -262,7 +262,7 @@ ${e.endsWith(`
|
|
|
262
262
|
`).slice(1).join(`
|
|
263
263
|
`).trim()}if(i){let s=i.replace(/\s+/g," ").trim(),a=s.length>500?s.substring(0,500)+"...":s;t.push(a)}}return t.join(`
|
|
264
264
|
|
|
265
|
-
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}var SUr=E(()=>{pw();oe();cJ()});function kUr(e){return{parse:(t)=>e.parse(Ojr(t))}}function lh(e,t,n){try{return As(t,kUr(n)).metadata}catch(r){throw new zb(e,r)}}class EJ{entityType;purpose;schema;frontmatterSchema;createFieldsSchema;isSingleton;hasBody;supportsCoverImage;publishedStatuses;fmSchema;bodyFormatter;constructor(e){if(this.entityType=e.entityType,this.purpose=e.purpose,this.schema=e.schema,this.frontmatterSchema=e.presentedFrontmatterSchema??e.frontmatterSchema,this.fmSchema=e.frontmatterSchema,this.bodyFormatter=e.bodyFormatter??N8a,e.createFieldsSchema!==void 0)this.createFieldsSchema=e.createFieldsSchema;if(e.isSingleton!==void 0)this.isSingleton=e.isSingleton;if(e.hasBody!==void 0)this.hasBody=e.hasBody;if(e.supportsCoverImage!==void 0)this.supportsCoverImage=e.supportsCoverImage;if(e.publishedStatuses!==void 0)this.publishedStatuses=e.publishedStatuses}toMarkdown(e){let t=this.renderBody(e),r={...this.readExistingFrontmatter(e.content)},i=Object.keys(this.frontmatterSchema.shape);for(let[o,s]of Object.entries(e.metadata))if(i.includes(o))r[o]=s;return this.buildMarkdown(t,r)}renderBody(e){return this.extractBody(e.content)}readExistingFrontmatter(e){try{return As(e,Fcn).metadata}catch{return{}}}extractMetadata(e){return e.metadata}parseFrontMatter(e,t){return lh(this.entityType,e,t)}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter(e){return sJ(Fcn.parse(e.metadata))}extractBody(e){try{return As(e,Fcn).content}catch{return e}}parseFrontmatter(e){try{return As(e,kUr(this.fmSchema)).metadata}catch(t){throw new zb(this.entityType,t)}}buildMarkdown(e,t){return na(e,t)}}var N8a,Fcn;var jcn=E(()=>{oe();cJ();oce();N8a={generateBodyTemplate:()=>""},Fcn=u.record(u.string(),u.unknown())});var t7e;var CUr=E(()=>{iJ();jcn();t7e=class t7e extends EJ{constructor(){super({entityType:"note",purpose:"A generic entity with no specialized adapter.",schema:Qp,frontmatterSchema:Rft})}toMarkdown(e){return e.content}fromMarkdown(e){return{content:e}}}});var IUr=E(()=>{jcn();CUr()});class eht{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,i="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=i}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntityRaw({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function Ncn(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),i=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:i,updated:i,contentHash:""}}function L8a(e){return"getEntityRaw"in e&&typeof e.getEntityRaw==="function"}function n7e(e,t){let{publishedOnly:n,visibilityScope:r}=t;if(!n&&!r)return e;let i=(s)=>r?{...s,visibilityScope:r}:s,o=(s)=>{let a=i(s?.filter);return{...s,...n&&{publishedOnly:!0},...a&&{filter:a}}};return new Proxy(e,{get(s,a,c){if(a==="listEntities")return(d)=>s.listEntities({entityType:d.entityType,options:o(d.options)});if(a==="countEntities")return(d)=>s.countEntities({entityType:d.entityType,options:o(d.options)});if(a==="getEntity")return(d)=>s.getEntity({...d,visibilityScope:r,...n&&{publishedOnly:!0}});if(a==="getEntityRaw"&&L8a(s))return(d)=>s.getEntityRaw({...d,visibilityScope:r,...n&&{publishedOnly:!0}});if(a==="search")return(d)=>s.search({...d,options:{...d.options,...r&&{visibilityScope:r},...n&&{publishedOnly:!0}}});if(a==="getEntityCounts")return async(d)=>{let p=r??d;if(!n)return s.getEntityCounts(p);return(await Promise.all(s.getEntityTypes().map(async(m)=>({entityType:m,count:await s.countEntities({entityType:m,options:{publishedOnly:!0,...p&&{filter:{visibilityScope:p}}}})})))).filter(({count:m})=>m>0)};let l=Reflect.get(s,a,c);return typeof l==="function"?l.bind(s):l}})}function e3(e,t){return t==="public"?e:`${e}-${t}`}function ij(e,t,n,r){let i=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!i?.length||typeof n!=="string")return"non-publish";let o=typeof t==="string"&&i.includes(t);if(!i.includes(n))return"non-publish";return o?"within-publish-set":"boundary"}function tht(e){return JSON.stringify(Object.entries(e).filter(([t])=>t!==Lcn).sort(([t],[n])=>t.localeCompare(n)))}function _Ur(e){try{let t=Ei(e);return{header:t.frontmatter,body:t.content.trim()}}catch{return{header:{},body:e.trim()}}}function nht(e,t){if(e.visibility!==t.visibility)return!0;if(tht(e.metadata)!==tht(t.metadata))return!0;let n=_Ur(e.content),r=_Ur(t.content);return n.body!==r.body||tht(n.header)!==tht(r.header)}function z$(e,t,n,r){let i=ij(e,t.metadata[Lcn],n.metadata[Lcn],r);return rht(i,()=>nht(t,n))}function rht(e,t){if(e==="non-publish")return["update"];return t()?["publish","update"]:["publish"]}var Lcn="status";var TUr=E(()=>{vs()});class r7e{dataSources=new Map;logger;static createFresh(e){return new r7e(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!(t.generate??t.generateScoped);case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}}function zcn(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}var Ey;var BUr=E(()=>{oe();Ey=u.object({currentPage:u.number(),totalPages:u.number(),totalItems:u.number(),pageSize:u.number(),hasNextPage:u.boolean(),hasPrevPage:u.boolean()})});function DUr(e,t){let n=e[t];if(n!==void 0&&n!=="")return n;let r=RUr.find(({current:o,former:s})=>o===t||s===t);if(!r)return;let i=e[r.current===t?r.former:r.current];return i===void 0||i===""?void 0:i}function PUr(e){return RUr.filter(({current:t,former:n})=>!!e[n]&&!e[t]).map(({current:t,former:n})=>({former:n,current:t}))}var RUr;var qcn=E(()=>{RUr=[{current:"MAIL_TO",former:"SETUP_EMAIL_TO"},{current:"MAIL_API_KEY",former:"SETUP_EMAIL_API_KEY"},{current:"MAIL_FROM",former:"SETUP_EMAIL_FROM"}]});function OUr(e,t=process.env){let n=e.match(z8a);if(!n)return e;let r=e;for(let i of n){let o=i.slice(2,-1),s=DUr(t,o);if(s===void 0)return;r=r.replace(i,s)}return r}function $Ae(e,t=process.env){if(typeof e==="string")return OUr(e,t);if(Array.isArray(e))return e.map((n)=>$Ae(n,t)).filter((n)=>n!==void 0);if(typeof e==="object"&&e!==null){let n={};for(let[r,i]of Object.entries(e)){let o=OUr(r,t);if(o===void 0)continue;let s=$Ae(i,t);if(s===void 0)continue;n[o]=s}return n}return e}function Dr(e){return e.toLowerCase().trim().replace(/[\u00E4\u00F6\u00FC\u00DF]/g,(t)=>q8a[t]??t).normalize("NFKC").replace(/\p{Script=Latin}/gu,(t)=>t.normalize("NFD").replace(/\p{M}/gu,"")).replace(/[^\p{L}\p{M}\p{N}\s_-]/gu,"").replace(/(^|[^\p{L}\p{M}])\p{M}+/gu,"$1").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function q$(e,t){return Array.from(e).slice(0,t).join("").replace(/-+$/,"")}function HAe(e){try{return new URL(e).hostname.replace(/\./g,"-")}catch{return(e.split("/")[0]??e).replace(/\./g,"-")}}function fI(e,t){let n=Dr(e);if(!n){let r=W8a(e);return t?`id-${r}-${t}`:`id-${r}`}return t?`${n}-${t}`:n}function Ucn(e){return e.trim().toLowerCase().replace(/[_\s]+/g,"-")}function sA(e){return Array.from(new Set(e.map(Ucn).filter(Boolean)))}function t3(e){if(U8a.has(e.toLowerCase()))return e;if(e.endsWith("y")&&e.length>1){let t=e[e.length-2];if(!"aeiou".includes(t?.toLowerCase()??""))return e.slice(0,-1)+"ies"}if(e.endsWith("s")||e.endsWith("x")||e.endsWith("ch"))return e+"es";return e+"s"}function np(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}function DT(e){return e.replace(/[-_]/g," ").replace(/([A-Z])/g," $1").split(/\s+/).filter(Boolean).map((t)=>H8a[t.toLowerCase()]??t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function i7e(e){for(let t of $8a){let n=e[t];if(typeof n==="string"&&n.trim())return n.trim()}return}function MUr(e){let t=e.split(" ").at(-1)?.toLowerCase()??"";if(e.endsWith("s")||G8a.has(t))return e;return t3(e)}function GAe(e){let t=e.toLowerCase(),n=Z8a[t];if(n!==void 0)return n;return e.replace(/\b\w/g,(r)=>r.toUpperCase())}function n3(e,t){if(!t)return e;try{return new URL(e,t).toString()}catch{return e}}function FUr(e){let n=e.split(/\s+/).filter((r)=>r.length>0).length;return Math.max(1,Math.ceil(n/200))}function SJ(e){let t=e.replace(/\s+/g," ").trim();if(!t)return;let n=t.match(/^(.*?[.!?])(?:\s|$)/);if(n?.[1])return n[1];return t.length<=200?t:`${t.slice(0,197)}\u2026`}function qb(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.lastIndexOf(" ");return r>0?n.slice(0,r)+"...":n+"..."}function JE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function br(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ef(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function W8a(e){return Array.from(e).reduce((n,r)=>Math.imul(n^(r.codePointAt(0)??0),16777619)>>>0,2166136261).toString(36)}function $cn(e){if(e<1000)return`${e} ${e===1?"byte":"bytes"}`;let[t,n]=e<1e6?[e/1000,"KB"]:[e/1e6,"MB"];return`${Number(t.toFixed(1))} ${n}`}function V8a(e,t){let n=Array.from({length:t.length+1},(i,o)=>o);return[...e].reduce((i,o,s)=>[...t].reduce((a,c,l)=>[...a,Math.min((i[l+1]??0)+1,(a[l]??0)+1,(i[l]??0)+(o===c?0:1))],[s+1]),n)[t.length]??0}function iht(e,t,n=2){return t.map((r)=>({candidate:r,distance:V8a(e,r)})).filter(({distance:r})=>r<=n).sort((r,i)=>r.distance-i.distance)[0]?.candidate}var z8a,q8a,U8a,$8a,H8a,G8a,Z8a;var or=E(()=>{qcn();z8a=/\$\{[^}]+\}/g;q8a={\u{e4}:"ae",\u{f6}:"oe",\u{fc}:"ue",\u{df}:"ss"};U8a=new Set(["series","species","sheep","deer","fish"]);$8a=["title","name","question"];H8a={ai:"AI",api:"API",atproto:"AT Protocol",css:"CSS",cta:"CTA",faq:"FAQ",github:"GitHub",html:"HTML",id:"ID",json:"JSON",linkedin:"LinkedIn",og:"OG",pdf:"PDF",rss:"RSS",seo:"SEO",ui:"UI",uri:"URI",url:"URL"},G8a=new Set(["content","info","information","data","media"]);Z8a={github:"GitHub",instagram:"Instagram",linkedin:"LinkedIn",email:"Email",website:"Website"}});async function kJ(e,{entityType:t,identifier:n},{visibilityScope:r,logger:i,read:o={}}){let s={...o.signal&&{signal:o.signal},...o.publishedOnly&&{publishedOnly:!0},...o.source&&{source:!0}};try{s.signal?.throwIfAborted();let a=await e.getEntityRaw({entityType:t,id:n,visibilityScope:r,...s});if(s.signal?.throwIfAborted(),a)return a;let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),c[0])return c[0];let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),l[0])return l[0];let d=Dr(n);if(d!==""&&d!==n){let h=await e.getEntityRaw({entityType:t,id:d,visibilityScope:r,...s});if(s.signal?.throwIfAborted(),h)return h}let p=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Dr(n)},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),p[0])return p[0];let f=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:r},...s}});s.signal?.throwIfAborted();let m=Dr(n);return f.find((h)=>typeof h.metadata.title==="string"&&Dr(h.metadata.title)===m)??null}catch(a){if(i)i.error(`Failed to find entity ${t}:${n}`,{error:a});throw a}}async function CR(e,t,{label:n="Entity",...r}){let i=await kJ(e,t,r);if(!i)return{ok:!1,error:`${n} not found: ${t.entityType}/${t.identifier}`};return{ok:!0,entity:i}}var jUr=E(()=>{or()});function zUr(e){if(e===void 0)return{sql:`(${NUr} AND content = '')`,args:[]};return{sql:`(${NUr} AND (content = '' OR ${LUr} = ? OR (content LIKE '---%' AND substr(${LUr}, -length(?)) = ?)))`,args:[e,e,e]}}async function Tce(e,t,n){let r=`${nR}%`,i=zUr(n),[o,s,a,c,l]=await Promise.all([e.execute({sql:`SELECT id FROM entities WHERE entityType = ? AND content NOT LIKE ? AND NOT ${i.sql} ORDER BY id`,args:[t,r,...i.args]}),e.execute({sql:`SELECT id, content <> '' AS placeholder FROM entities WHERE entityType = ? AND ${i.sql} ORDER BY id`,args:[t,...i.args]}),e.execute({sql:"SELECT COUNT(*) AS count FROM entities WHERE entityType = ? AND content LIKE ?",args:[t,r]}),X8a(e,t),e.execute("SELECT digest FROM assets")]),d=s.rows.map((p)=>J8a.parse(p));return{inlineIds:o.rows.map((p)=>Q8a.parse(p).id),awaitingIds:d.map((p)=>p.id),placeholderIds:d.filter((p)=>p.placeholder===1).map((p)=>p.id),referenceCount:Hcn.parse(a.rows[0]).count,ftsRows:c,storedDigests:new Set(l.rows.map((p)=>Y8a.parse(p).digest))}}function ZAe(e){return sOe({url:`file:${e}`})}async function X8a(e,t){let n=await e.execute("SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name = 'entity_fts'");if(Hcn.parse(n.rows[0]).count===0)return 0;let r=await e.execute({sql:"SELECT COUNT(*) AS count FROM entity_fts WHERE entity_type = ?",args:[t]});return Hcn.parse(r.rows[0]).count}async function o7e(e,t,n,r){let i=zUr(r),s=(await e.execute({sql:`SELECT id, content, contentHash FROM entities WHERE entityType = ? AND id = ? AND content NOT LIKE ? AND NOT ${i.sql}`,args:[t,n,`${nR}%`,...i.args]})).rows[0];return s?K8a.parse(s):null}var K8a,Q8a,Hcn,J8a,Y8a,NUr="COALESCE(json_extract(metadata, '$.status'), '') IN ('pending', 'failed')",LUr="trim(content, char(32, 9, 10, 13))";var Gcn=E(()=>{pQ();oe();pdt();K8a=u.object({id:u.string(),content:u.string(),contentHash:u.string()}),Q8a=u.object({id:u.string()}),Hcn=u.object({count:u.number()}),J8a=u.object({id:u.string(),placeholder:u.number()}),Y8a=u.object({digest:u.string()})});async function Zcn(e,t,n){let r=new dce(e.db),i=await Tce(e.client,t,n),o=await e.client.execute({sql:"SELECT id, content, metadata FROM entities WHERE entityType = ? AND content LIKE ? ORDER BY id",args:[t,`${nR}%`]}),s=new Map,a=[];for(let c of o.rows){let l=e5a.parse(c),d=MC(l.content),p=s.get(d)??n5a(r,d);s.set(d,p);let f=await p,m=t5a.parse(JSON.parse(l.metadata));a.push(r5a(l.id,d,f,m.sizeBytes))}return{rows:a,inlineRows:i.inlineIds.length,placeholderRows:i.placeholderIds.length,ftsRows:i.ftsRows}}async function n5a(e,t){try{return{status:"verified",verification:await e.verify(t)}}catch(n){if(n instanceof mJ)return{status:"missing"};if(n instanceof J4)return{status:"corrupt",detail:n.message};throw n}}function r5a(e,t,n,r){if(n.status==="missing")return{id:e,ref:t,status:"missing"};if(n.status==="corrupt")return{id:e,ref:t,status:"corrupt",detail:n.detail};let{verification:i}=n;if(!i.valid)return{id:e,ref:t,status:"corrupt",detail:`stored bytes hash to ${i.actualDigest}`};if(r!==void 0&&r!==i.sizeBytes)return{id:e,ref:t,status:"size-mismatch",detail:`row records ${r} bytes; the asset holds ${i.sizeBytes}`};return{id:e,ref:t,status:"valid"}}var e5a,t5a;var qUr=E(()=>{pQ();oe();NMe();Gcn();e5a=u.object({id:u.string(),content:u.string(),metadata:u.string()}),t5a=u.object({sizeBytes:u.number()}).partial()});class WAe{db;repository;ftsTable;constructor(e){this.db=e.db,this.repository=new dce(e.db)}async migrateRow(e,t){let n=await this.hasFtsTable();return this.publishing(t,async(r,i,o)=>{let[s]=await r.select({content:gt.content,contentHash:gt.contentHash,metadata:gt.metadata}).from(gt).where(this.row(e,t.id));if(s?.contentHash!==t.expectedContentHash||s.content.startsWith(nR))return{outcome:"changed"};await this.repository.bindEntityContent(r,i.ref,o);let a=Ur(i.ref);if(await r.update(gt).set({content:i.ref,contentHash:a,metadata:{...s.metadata,...t.metadata}}).where(this.row(e,t.id)),n)await r.run(Te`DELETE FROM entity_fts WHERE entity_id = ${t.id} AND entity_type = ${e}`);return{outcome:"migrated",ref:i.ref,contentHash:a}})}async restoreAsset(e,t){return this.publishing(t,async(n,r,i)=>{let[o]=await n.select({content:gt.content}).from(gt).where(this.row(e,t.id));if(o?.content!==t.ref||r.ref!==t.ref)return{outcome:"changed"};return await this.repository.bindEntityContent(n,r.ref,i),{outcome:"restored"}})}async createRow(e,t){return this.publishing(t,async(n,r,i)=>{let[o]=await n.select({id:gt.id}).from(gt).where(this.row(e,t.id));if(o)return{outcome:"changed"};await this.repository.bindEntityContent(n,r.ref,i);let s=Ur(r.ref);return await n.insert(gt).values({id:t.id,entityType:e,content:r.ref,contentHash:s,metadata:t.metadata,created:t.created,updated:t.updated}),{outcome:"created",ref:r.ref,contentHash:s}})}async clearPlaceholder(e,t){let n=await this.hasFtsTable();return this.db.transaction(async(r)=>{let[i]=await r.select({contentHash:gt.contentHash,metadata:gt.metadata}).from(gt).where(this.row(e,t.id));if(i?.contentHash!==t.expectedContentHash)return{outcome:"changed"};if(await r.update(gt).set({content:"",contentHash:Ur(""),metadata:Object.fromEntries(Object.entries(i.metadata).filter(([o])=>!i5a.includes(o)))}).where(this.row(e,t.id)),n)await r.run(Te`DELETE FROM entity_fts WHERE entity_id = ${t.id} AND entity_type = ${e}`);return{outcome:"cleared"}})}async publishing(e,t){let n=await this.repository.stage(e.bytes,{expectedSize:e.expectedSize}),r=this.repository.claim(n);try{return await this.db.transaction((i)=>t(i,n,r))}finally{await this.repository.release(n)}}row(e,t){return Bt(Ie(gt.entityType,e),Ie(gt.id,t))}hasFtsTable(){return this.ftsTable??=this.db.all(Te`SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name = 'entity_fts'`).then((e)=>Number(e[0]?.count)>0),this.ftsTable}}var i5a;var UUr=E(()=>{pQ();Oo();ca();oR();NMe();i5a=["format","width","height","mediaType","sizeBytes"]});var ro=E(()=>{_Xt();pQ();yan();han();Gft();uLr();Hft();Yft();CQ();EAe();Msn();SUr();IUr();ian();NMe();fan();oce();xnn();iJ();Dft();TUr();vAe();jft();qft();cJ();zsn();BUr();jUr();Can();Gcn();qUr();UUr();xan();wan();CQ()});function s7e(e){return _o(Wcn(e))}function Wcn(e,t=new Set){if(e===null)return"null";if(typeof e==="string"||typeof e==="boolean")return JSON.stringify(e);if(typeof e==="number"){if(!Number.isFinite(e))throw Error("Projection inputs cannot contain non-finite numbers");if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw Error("Projection inputs cannot contain unsafe integers");return JSON.stringify(e)}if(typeof e!=="object")throw Error(`Projection inputs cannot contain ${typeof e} values`);if(t.has(e))throw Error("Projection inputs cannot contain circular values");let n=new Set(t).add(e);if(Array.isArray(e))return`[${e.map((i)=>Wcn(i,n)).join(",")}]`;let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Error("Projection inputs must contain only plain JSON objects");return`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${JSON.stringify(i)}:${Wcn(o,n)}`).join(",")}}`}var Vcn=E(()=>{Oo()});async function VAe(e,t){let n=await e.searchWithDistances({query:t.query,types:[t.entityType],maxDistance:t.maxDistance}),i=(await Promise.all(n.filter((a)=>a.entityType===t.entityType&&a.distance<=t.maxDistance&&!t.excludeIds?.includes(a.entityId)).map((a)=>e.getEntity({entityType:t.entityType,id:a.entityId,visibilityScope:t.visibility})))).filter((a)=>a?.visibility===t.visibility),o=t.confirm;if(!o)return i[0];let s=async(a)=>{let c=i[a];if(!c)return;return await o(c)?c:s(a+1)};return s(0)}async function r3(e,t={}){let n=t.pollMs??100,r=Date.now()+(t.timeoutMs??60000),i=async()=>{if((await e.getActiveJobs([cy.embedding])).length===0)return;if(Date.now()>=r)throw Error("Embeddings did not drain before the deadline");return await new Promise((s)=>setTimeout(s,n)),i()};return i()}var Kcn=E(()=>{lt()});function Qcn(e){if(e!==null&&typeof e==="object"){for(let t of Object.values(e))Qcn(t);Object.freeze(e)}return e}function Y6(e){let t=o5a.parse({id:e.id,version:e.version,sources:e.sources,targetType:e.targetType,sourceChangeBatchDelayMs:e.sourceChangeBatchDelayMs});if(typeof e.selectInput!=="function")throw Error(`Projection rule "${t.id}" must select input`);if(typeof e.derive!=="function")throw Error(`Projection rule "${t.id}" must derive output`);let n=t.sources.map((r)=>{let i=Object.freeze([...r.types]),o=r.excludeTypes?Object.freeze([...r.excludeTypes]):void 0,s={kind:"entity",types:i,...o?{excludeTypes:o}:{}};return Object.freeze(s)});return Object.freeze({id:t.id,version:t.version,sources:Object.freeze(n),targetType:t.targetType,sourceChangeBatchDelayMs:t.sourceChangeBatchDelayMs,inputSchema:e.inputSchema,selectInput:async(r,i,o)=>{let s=await e.selectInput(r,i,o),a=wx.parse(s);return Qcn(e.inputSchema.parse(a))},fingerprint:s7e,derive:async(r,i,o)=>{let s=e.inputSchema.parse(r),a=u.array(pJ).parse(await e.derive(s,i,o));for(let c of a){let l=c.operation==="upsert"?c.entity.entityType:c.entityType;if(l!==t.targetType)throw Error(`Projection rule "${t.id}" cannot write entity type "${l}"`)}return Qcn(a)}})}var o5a;var Jcn=E(()=>{ro();oe();Vcn();ro();o5a=u.strictObject({id:u.string().trim().min(1),version:u.string().trim().min(1),sources:u.array(u.strictObject({kind:u.literal("entity"),types:u.array(u.string().trim().min(1)).min(1),excludeTypes:u.array(u.string().trim().min(1)).optional()})),targetType:u.string().trim().min(1),sourceChangeBatchDelayMs:u.number().int().nonnegative().default(0)})});function c7e(e,t,n){if(e.toLowerCase()===t.toLowerCase())return n;let r=`/${e.toLowerCase()}`;return n==="/"?r:`${r}${n}`}var GUr,s5a,a5a,c5a,YE,Bce,a7e,l5a,Ycn,u5a,d5a,HUr,p5a,f5a,ZUr,WUr,VUr;var l7e=E(()=>{vF();GUr=["primary","secondary"],s5a=u.custom((e)=>typeof e==="function","Expected a React component"),a5a=u.strictObject({show:u.boolean().optional(),label:u.string().min(1).optional(),slot:u.enum(GUr).optional(),priority:u.number().optional()}),c5a=u.strictObject({id:u.string().min(1),template:u.string().min(1),content:u.unknown().optional(),dataQuery:u.looseObject({entityType:u.string().optional(),template:u.string().optional(),query:u.record(u.string(),u.unknown()).optional()}).optional(),order:u.number().optional()}),YE=u.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Bce=u.strictObject({template:u.string().min(1),content:u.record(u.string(),u.json()),translations:u.record(YE,u.record(u.string(),u.json())).optional()}),a7e=u.strictObject({title:u.string().optional(),description:u.string().optional(),navigationLabel:u.string().optional()}),l5a=u.strictObject({id:u.string().min(1),path:u.string().startsWith("/"),title:u.string().optional(),pageLabel:u.string().optional(),description:u.string().optional(),sections:u.array(c5a).optional(),layout:u.string().min(1).optional(),fullscreen:u.boolean().optional(),pluginId:u.string().optional(),sourceEntityType:u.string().optional(),sourceEntityId:u.string().optional(),external:u.boolean().optional(),navigation:a5a.optional(),translations:u.record(YE,a7e).optional(),copy:u.literal("brain").optional()}),Ycn=u.strictObject({label:u.string().min(1),pluralName:u.string().min(1).optional(),layout:u.string().min(1).optional(),detailTemplate:u.string().min(1).optional(),paginate:u.boolean().optional(),pageSize:u.number().int().positive().optional(),citable:u.boolean().optional(),navigation:u.strictObject({show:u.boolean().optional(),slot:u.enum(GUr).optional(),priority:u.number().optional()}).optional()}),u5a=u.strictObject({schema:u.custom((e)=>e instanceof u.ZodType,"Expected a Zod schema"),component:u.custom((e)=>typeof e==="function","Expected a React component"),title:u.string().min(1),description:u.string(),requiredPermission:u.enum(["admin","trusted","public"]).optional(),fullscreen:u.boolean().optional(),dataSource:u.string().min(1).optional(),components:u.record(YE,u.custom((e)=>typeof e==="function","Expected a React component")).optional()}),d5a=u.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),HUr=u.strictObject({namespace:u.string().min(1),sections:u.record(u.string(),u5a)}),p5a=u.record(u.string(),u.json()),f5a=u.record(u.string(),u.record(u.string(),p5a));ZUr={layouts:u.record(u.string(),s5a).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:u.array(l5a),content:f5a.optional(),sections:u.union([HUr,u.array(HUr)]).optional(),themeOverride:u.string().optional(),headScripts:u.array(u.string()).optional(),entityDisplay:u.record(u.string(),Ycn),staticAssets:u.record(u.string(),u.string()).optional(),languages:u.array(YE).min(1).optional(),layoutCopy:Bce.optional(),dataSources:u.array(d5a).readonly().optional()},WUr=u.strictObject(ZUr).partial(),VUr=u.strictObject(ZUr).superRefine((e,t)=>{let n=e.languages??[],r=new Set;for(let[l,d]of n.entries()){let p=d.toLowerCase();if(r.has(p))t.addIssue({code:"custom",path:["languages",l],message:`Language "${d}" is declared twice`});r.add(p)}let i=n.slice(1).map((l)=>`/${l.toLowerCase()}`),o=new Set;for(let[l,d]of e.routes.entries()){if(o.has(d.id))t.addIssue({code:"custom",path:["routes",l,"id"],message:`Duplicate route id "${d.id}"`});o.add(d.id);let p=d.path.toLowerCase(),f=i.find((h)=>p===h||p.startsWith(`${h}/`));if(f)t.addIssue({code:"custom",path:["routes",l,"path"],message:`Route path "${d.path}" is under ${f}, where another language's pages are built`});let m=d.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",l,"layout"],message:`Unknown layout "${m}"`});for(let[h,g]of(d.sections??[]).entries()){let x=/^([^:.\s]+)\.([^:.\s]+)$/.exec(g.template);if(x)t.addIssue({code:"custom",path:["routes",l,"sections",h,"template"],message:`Section template "${g.template}" is written "${x[1]}:${x[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((l)=>[l.namespace,l]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let c=new Set;for(let[l,d]of(e.dataSources??[]).entries()){if(c.has(d.id))t.addIssue({code:"custom",path:["dataSources",l],message:`Data source "${d.id}" is declared twice`});c.add(d.id)}for(let l of s)for(let[d,p]of Object.entries(l.sections))if(p.dataSource&&!c.has(p.dataSource))t.addIssue({code:"custom",path:["sections",l.namespace,d,"dataSource"],message:`Section "${l.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[l,d]of Object.entries(e.content??{})){let p=a.get(l);if(!p){t.addIssue({code:"custom",path:["content",l],message:`Content namespace "${l}" has no section group`});continue}for(let[f,m]of Object.entries(d)){let h=p.sections[f];if(!h){t.addIssue({code:"custom",path:["content",l,f],message:`Content section "${l}:${f}" is not defined`});continue}let g=h.schema.safeParse(m);if(!g.success)t.addIssue({code:"custom",path:["content",l,f],message:`Content does not satisfy the "${l}:${f}" schema: ${u.prettifyError(g.error)}`})}}})});var KUr,u7e,QUr,i3,Xcn,d7e,JUr,YUr,p7e,XUr,e$r,f7e,oht;var eln=E(()=>{lt();oe();l7e();l7e();KUr=u.object({id:u.string(),template:u.string(),content:u.unknown().optional(),dataQuery:u.looseObject({entityType:u.string().optional(),template:u.string().optional(),query:u.looseObject({id:u.string().optional(),limit:u.number().optional(),offset:u.number().optional()}).optional()}).optional(),order:u.number().optional()}),u7e=["primary","secondary"],QUr=u.object({show:u.boolean().default(!1),label:u.string().optional(),slot:u.enum(u7e).default("primary"),priority:u.number().min(0).max(100).default(50)}).optional(),i3=u.object({id:u.string(),path:u.string(),title:u.string().default(""),pageLabel:u.string().optional(),description:u.string().default(""),sections:u.array(KUr).default([]),layout:u.string().default("default"),fullscreen:u.boolean().optional(),pluginId:u.string().optional(),sourceEntityType:u.string().optional(),sourceEntityId:u.string().optional(),external:u.boolean().optional(),navigation:QUr,translations:u.record(YE,a7e).optional(),languages:u.array(YE).optional(),copy:u.literal("brain").optional()}),Xcn=u.object({routes:u.array(i3),pluginId:u.string()}),d7e=Fr({channel:"plugin:site-builder:route:register",request:Xcn,response:u.void(),delivery:"command"}),JUr=u.strictObject({}),YUr=u.array(i3),p7e=Fr({channel:"site-builder:routes:list",request:JUr,response:YUr,delivery:"request"}),XUr=u.strictObject({}),e$r=u.array(i3),f7e=Fr({channel:"plugin:site-builder:pages",request:XUr,response:e$r,delivery:"collect"}),oht=u.object({label:u.string(),href:u.string(),priority:u.number()})});var t$r,n$r,r$r,m7e;var i$r=E(()=>{lt();oe();t$r=u.object({pluginId:u.string(),slotName:u.string(),render:u.custom((e)=>typeof e==="function"),priority:u.number().optional()}),n$r=u.strictObject({}),r$r=u.array(t$r),m7e=Fr({channel:"plugin:site-builder:slots",request:n$r,response:r$r,delivery:"collect"})});var o$r="site:metadata:updated",sht,KAe,s$r,PT,a$r,Rce,Dce,aht;var tln=E(()=>{lt();oe();eln();sht=u.object({heading:u.string().describe("Main CTA heading text"),subtitle:u.string().optional().describe("A line under the CTA heading"),buttonText:u.string().describe("Call-to-action button text"),buttonLink:u.string().describe("URL or anchor for the CTA button")}),KAe=u.object({title:u.string().optional(),description:u.string().optional(),copyright:u.string().optional(),cta:sht.optional()}),s$r=u.object({blurb:u.string().optional().describe("Short italic subtitle under the section title")}),PT=u.object({represents:u.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:u.string().describe("The site's title"),description:u.string().describe("The site's description"),url:u.string().optional().describe("Canonical site URL"),copyright:u.string().optional().describe("Copyright notice text"),logo:u.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:u.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:u.string().optional().describe("Analytics script HTML"),cta:sht.optional().describe("Call-to-action configuration"),sections:u.record(u.string(),s$r).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:u.record(YE,KAe).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),a$r=u.strictObject({}),Rce=Fr({channel:"site:metadata:get",request:a$r,response:PT,delivery:"request"}),Dce=fc(o$r,PT),aht=PT.extend({copyright:u.string(),navigation:u.object({primary:u.array(oht),secondary:u.array(oht)}),socialLinks:u.array($se).optional().describe("Social media links from profile metadata"),photo:u.string().optional().describe("The anchor's photo, as ")})});function nln(e,t){let n=m5a.safeParse(e);return n.success&&t.every((r)=>(r in n.data))}var m5a;var rln=E(()=>{oe();m5a=u.record(u.string(),u.unknown())});class CJ{parse(e){throw Error("This response format is read-only and cannot be parsed back to data")}formatKeyValue(e,t){if(t===void 0||t===null)return"";return`**${e}:** ${String(t)}`}formatList(e){return e.map((t)=>`- ${String(t)}`).join(`
|
|
265
|
+
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}var SUr=E(()=>{pw();oe();cJ()});function kUr(e){return{parse:(t)=>e.parse(Ojr(t))}}function lh(e,t,n){try{return As(t,kUr(n)).metadata}catch(r){throw new zb(e,r)}}class EJ{entityType;purpose;schema;frontmatterSchema;createFieldsSchema;isSingleton;hasBody;supportsCoverImage;publishedStatuses;fmSchema;bodyFormatter;constructor(e){if(this.entityType=e.entityType,this.purpose=e.purpose,this.schema=e.schema,this.frontmatterSchema=e.presentedFrontmatterSchema??e.frontmatterSchema,this.fmSchema=e.frontmatterSchema,this.bodyFormatter=e.bodyFormatter??N8a,e.createFieldsSchema!==void 0)this.createFieldsSchema=e.createFieldsSchema;if(e.isSingleton!==void 0)this.isSingleton=e.isSingleton;if(e.hasBody!==void 0)this.hasBody=e.hasBody;if(e.supportsCoverImage!==void 0)this.supportsCoverImage=e.supportsCoverImage;if(e.publishedStatuses!==void 0)this.publishedStatuses=e.publishedStatuses}toMarkdown(e){let t=this.renderBody(e),r={...this.readExistingFrontmatter(e.content)},i=Object.keys(this.frontmatterSchema.shape);for(let[o,s]of Object.entries(e.metadata))if(i.includes(o))r[o]=s;return this.buildMarkdown(t,r)}renderBody(e){return this.extractBody(e.content)}readExistingFrontmatter(e){try{return As(e,Fcn).metadata}catch{return{}}}extractMetadata(e){return e.metadata}parseFrontMatter(e,t){return lh(this.entityType,e,t)}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter(e){return sJ(Fcn.parse(e.metadata))}extractBody(e){try{return As(e,Fcn).content}catch{return e}}parseFrontmatter(e){try{return As(e,kUr(this.fmSchema)).metadata}catch(t){throw new zb(this.entityType,t)}}buildMarkdown(e,t){return na(e,t)}}var N8a,Fcn;var jcn=E(()=>{oe();cJ();oce();N8a={generateBodyTemplate:()=>""},Fcn=u.record(u.string(),u.unknown())});var t7e;var CUr=E(()=>{iJ();jcn();t7e=class t7e extends EJ{constructor(){super({entityType:"note",purpose:"A generic entity with no specialized adapter.",schema:Qp,frontmatterSchema:Rft})}toMarkdown(e){return e.content}fromMarkdown(e){return{content:e}}}});var IUr=E(()=>{jcn();CUr()});class eht{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,i="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=i}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntityRaw({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function Ncn(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),i=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:i,updated:i,contentHash:""}}function L8a(e){return"getEntityRaw"in e&&typeof e.getEntityRaw==="function"}function n7e(e,t){let{publishedOnly:n,visibilityScope:r}=t;if(!n&&!r)return e;let i=(s)=>r?{...s,visibilityScope:r}:s,o=(s)=>{let a=i(s?.filter);return{...s,...n&&{publishedOnly:!0},...a&&{filter:a}}};return new Proxy(e,{get(s,a,c){if(a==="listEntities")return(d)=>s.listEntities({entityType:d.entityType,options:o(d.options)});if(a==="countEntities")return(d)=>s.countEntities({entityType:d.entityType,options:o(d.options)});if(a==="getEntity")return(d)=>s.getEntity({...d,visibilityScope:r,...n&&{publishedOnly:!0}});if(a==="getEntityRaw"&&L8a(s))return(d)=>s.getEntityRaw({...d,visibilityScope:r,...n&&{publishedOnly:!0}});if(a==="search")return(d)=>s.search({...d,options:{...d.options,...r&&{visibilityScope:r},...n&&{publishedOnly:!0}}});if(a==="getEntityCounts")return async(d)=>{let p=r??d;if(!n)return s.getEntityCounts(p);return(await Promise.all(s.getEntityTypes().map(async(m)=>({entityType:m,count:await s.countEntities({entityType:m,options:{publishedOnly:!0,...p&&{filter:{visibilityScope:p}}}})})))).filter(({count:m})=>m>0)};let l=Reflect.get(s,a,c);return typeof l==="function"?l.bind(s):l}})}function e3(e,t){return t==="public"?e:`${e}-${t}`}function ij(e,t,n,r){let i=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!i?.length||typeof n!=="string")return"non-publish";let o=typeof t==="string"&&i.includes(t);if(!i.includes(n))return"non-publish";return o?"within-publish-set":"boundary"}function tht(e){return JSON.stringify(Object.entries(e).filter(([t])=>t!==Lcn).sort(([t],[n])=>t.localeCompare(n)))}function _Ur(e){try{let t=Ei(e);return{header:t.frontmatter,body:t.content.trim()}}catch{return{header:{},body:e.trim()}}}function nht(e,t){if(e.visibility!==t.visibility)return!0;if(tht(e.metadata)!==tht(t.metadata))return!0;let n=_Ur(e.content),r=_Ur(t.content);return n.body!==r.body||tht(n.header)!==tht(r.header)}function z$(e,t,n,r){let i=ij(e,t.metadata[Lcn],n.metadata[Lcn],r);return rht(i,()=>nht(t,n))}function rht(e,t){if(e==="non-publish")return["update"];return t()?["publish","update"]:["publish"]}var Lcn="status";var TUr=E(()=>{vs()});class r7e{dataSources=new Map;logger;static createFresh(e){return new r7e(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!(t.generate??t.generateScoped);case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}}function zcn(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}var Ey;var BUr=E(()=>{oe();Ey=u.object({currentPage:u.number(),totalPages:u.number(),totalItems:u.number(),pageSize:u.number(),hasNextPage:u.boolean(),hasPrevPage:u.boolean()})});function DUr(e,t){let n=e[t];if(n!==void 0&&n!=="")return n;let r=RUr.find(({current:o,former:s})=>o===t||s===t);if(!r)return;let i=e[r.current===t?r.former:r.current];return i===void 0||i===""?void 0:i}function PUr(e){return RUr.filter(({current:t,former:n})=>!!e[n]&&!e[t]).map(({current:t,former:n})=>({former:n,current:t}))}var RUr;var qcn=E(()=>{RUr=[{current:"MAIL_TO",former:"SETUP_EMAIL_TO"},{current:"MAIL_API_KEY",former:"SETUP_EMAIL_API_KEY"},{current:"MAIL_FROM",former:"SETUP_EMAIL_FROM"}]});function OUr(e,t=process.env){let n=e.match(z8a);if(!n)return e;let r=e;for(let i of n){let o=i.slice(2,-1),s=DUr(t,o);if(s===void 0)return;r=r.replace(i,s)}return r}function $Ae(e,t=process.env){if(typeof e==="string")return OUr(e,t);if(Array.isArray(e))return e.map((n)=>$Ae(n,t)).filter((n)=>n!==void 0);if(typeof e==="object"&&e!==null){let n={};for(let[r,i]of Object.entries(e)){let o=OUr(r,t);if(o===void 0)continue;let s=$Ae(i,t);if(s===void 0)continue;n[o]=s}return n}return e}function Dr(e){return e.toLowerCase().trim().replace(/[\u00E4\u00F6\u00FC\u00DF]/g,(t)=>q8a[t]??t).normalize("NFKC").replace(/\p{Script=Latin}/gu,(t)=>t.normalize("NFD").replace(/\p{M}/gu,"")).replace(/[^\p{L}\p{M}\p{N}\s_-]/gu,"").replace(/(^|[^\p{L}\p{M}])\p{M}+/gu,"$1").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function q$(e,t){return Array.from(e).slice(0,t).join("").replace(/-+$/,"")}function HAe(e){try{return new URL(e).hostname.replace(/\./g,"-")}catch{return(e.split("/")[0]??e).replace(/\./g,"-")}}function fI(e,t){let n=Dr(e);if(!n){let r=W8a(e);return t?`id-${r}-${t}`:`id-${r}`}return t?`${n}-${t}`:n}function Ucn(e){return e.trim().toLowerCase().replace(/[_\s]+/g,"-")}function sA(e){return Array.from(new Set(e.map(Ucn).filter(Boolean)))}function t3(e){if(U8a.has(e.toLowerCase()))return e;if(e.endsWith("y")&&e.length>1){let t=e[e.length-2];if(!"aeiou".includes(t?.toLowerCase()??""))return e.slice(0,-1)+"ies"}if(e.endsWith("s")||e.endsWith("x")||e.endsWith("ch"))return e+"es";return e+"s"}function np(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}function DT(e){return e.replace(/[-_]/g," ").replace(/([A-Z])/g," $1").split(/\s+/).filter(Boolean).map((t)=>H8a[t.toLowerCase()]??t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function i7e(e){for(let t of $8a){let n=e[t];if(typeof n==="string"&&n.trim())return n.trim()}return}function MUr(e){let t=e.split(" ").at(-1)?.toLowerCase()??"";if(e.endsWith("s")||G8a.has(t))return e;return t3(e)}function GAe(e){let t=e.toLowerCase(),n=Z8a[t];if(n!==void 0)return n;return e.replace(/\b\w/g,(r)=>r.toUpperCase())}function n3(e,t){if(!t)return e;try{return new URL(e,t).toString()}catch{return e}}function FUr(e){let n=e.split(/\s+/).filter((r)=>r.length>0).length;return Math.max(1,Math.ceil(n/200))}function SJ(e){let t=e.replace(/\s+/g," ").trim();if(!t)return;let n=t.match(/^(.*?[.!?])(?:\s|$)/);if(n?.[1])return n[1];return t.length<=200?t:`${t.slice(0,197)}\u2026`}function qb(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.lastIndexOf(" ");return r>0?n.slice(0,r)+"...":n+"..."}function JE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function br(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ef(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function W8a(e){return Array.from(e).reduce((n,r)=>Math.imul(n^(r.codePointAt(0)??0),16777619)>>>0,2166136261).toString(36)}function $cn(e){if(e<1000)return`${e} ${e===1?"byte":"bytes"}`;let[t,n]=e<1e6?[e/1000,"KB"]:[e/1e6,"MB"];return`${Number(t.toFixed(1))} ${n}`}function V8a(e,t){let n=Array.from({length:t.length+1},(i,o)=>o);return[...e].reduce((i,o,s)=>[...t].reduce((a,c,l)=>[...a,Math.min((i[l+1]??0)+1,(a[l]??0)+1,(i[l]??0)+(o===c?0:1))],[s+1]),n)[t.length]??0}function iht(e,t,n=2){return t.map((r)=>({candidate:r,distance:V8a(e,r)})).filter(({distance:r})=>r<=n).sort((r,i)=>r.distance-i.distance)[0]?.candidate}var z8a,q8a,U8a,$8a,H8a,G8a,Z8a;var or=E(()=>{qcn();z8a=/\$\{[^}]+\}/g;q8a={\u{e4}:"ae",\u{f6}:"oe",\u{fc}:"ue",\u{df}:"ss"};U8a=new Set(["series","species","sheep","deer","fish"]);$8a=["title","name","question"];H8a={ai:"AI",api:"API",atproto:"AT Protocol",css:"CSS",cta:"CTA",faq:"FAQ",github:"GitHub",html:"HTML",id:"ID",json:"JSON",linkedin:"LinkedIn",og:"OG",pdf:"PDF",rss:"RSS",seo:"SEO",ui:"UI",uri:"URI",url:"URL"},G8a=new Set(["content","info","information","data","media"]);Z8a={github:"GitHub",instagram:"Instagram",linkedin:"LinkedIn",email:"Email",website:"Website"}});async function kJ(e,{entityType:t,identifier:n},{visibilityScope:r,logger:i,read:o={}}){let s={...o.signal&&{signal:o.signal},...o.publishedOnly&&{publishedOnly:!0},...o.source&&{source:!0}};try{s.signal?.throwIfAborted();let a=await e.getEntityRaw({entityType:t,id:n,visibilityScope:r,...s});if(s.signal?.throwIfAborted(),a)return a;let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),c[0])return c[0];let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),l[0])return l[0];let d=Dr(n);if(d!==""&&d!==n){let h=await e.getEntityRaw({entityType:t,id:d,visibilityScope:r,...s});if(s.signal?.throwIfAborted(),h)return h}let p=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Dr(n)},visibilityScope:r},...s}});if(s.signal?.throwIfAborted(),p[0])return p[0];let f=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:r},...s}});s.signal?.throwIfAborted();let m=Dr(n);return f.find((h)=>typeof h.metadata.title==="string"&&Dr(h.metadata.title)===m)??null}catch(a){if(i)i.error(`Failed to find entity ${t}:${n}`,{error:a});throw a}}async function CR(e,t,{label:n="Entity",...r}){let i=await kJ(e,t,r);if(!i)return{ok:!1,error:`${n} not found: ${t.entityType}/${t.identifier}`};return{ok:!0,entity:i}}var jUr=E(()=>{or()});function zUr(e){if(e===void 0)return{sql:`(${NUr} AND content = '')`,args:[]};return{sql:`(${NUr} AND (content = '' OR ${LUr} = ? OR (content LIKE '---%' AND substr(${LUr}, -length(?)) = ?)))`,args:[e,e,e]}}async function Tce(e,t,n){let r=`${nR}%`,i=zUr(n),[o,s,a,c,l]=await Promise.all([e.execute({sql:`SELECT id FROM entities WHERE entityType = ? AND content NOT LIKE ? AND NOT ${i.sql} ORDER BY id`,args:[t,r,...i.args]}),e.execute({sql:`SELECT id, content <> '' AS placeholder FROM entities WHERE entityType = ? AND ${i.sql} ORDER BY id`,args:[t,...i.args]}),e.execute({sql:"SELECT COUNT(*) AS count FROM entities WHERE entityType = ? AND content LIKE ?",args:[t,r]}),X8a(e,t),e.execute("SELECT digest FROM assets")]),d=s.rows.map((p)=>J8a.parse(p));return{inlineIds:o.rows.map((p)=>Q8a.parse(p).id),awaitingIds:d.map((p)=>p.id),placeholderIds:d.filter((p)=>p.placeholder===1).map((p)=>p.id),referenceCount:Hcn.parse(a.rows[0]).count,ftsRows:c,storedDigests:new Set(l.rows.map((p)=>Y8a.parse(p).digest))}}function ZAe(e){return sOe({url:`file:${e}`})}async function X8a(e,t){let n=await e.execute("SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name = 'entity_fts'");if(Hcn.parse(n.rows[0]).count===0)return 0;let r=await e.execute({sql:"SELECT COUNT(*) AS count FROM entity_fts WHERE entity_type = ?",args:[t]});return Hcn.parse(r.rows[0]).count}async function o7e(e,t,n,r){let i=zUr(r),s=(await e.execute({sql:`SELECT id, content, contentHash FROM entities WHERE entityType = ? AND id = ? AND content NOT LIKE ? AND NOT ${i.sql}`,args:[t,n,`${nR}%`,...i.args]})).rows[0];return s?K8a.parse(s):null}var K8a,Q8a,Hcn,J8a,Y8a,NUr="COALESCE(json_extract(metadata, '$.status'), '') IN ('pending', 'failed')",LUr="trim(content, char(32, 9, 10, 13))";var Gcn=E(()=>{pQ();oe();pdt();K8a=u.object({id:u.string(),content:u.string(),contentHash:u.string()}),Q8a=u.object({id:u.string()}),Hcn=u.object({count:u.number()}),J8a=u.object({id:u.string(),placeholder:u.number()}),Y8a=u.object({digest:u.string()})});async function Zcn(e,t,n){let r=new dce(e.db),i=await Tce(e.client,t,n),o=await e.client.execute({sql:"SELECT id, content, metadata FROM entities WHERE entityType = ? AND content LIKE ? ORDER BY id",args:[t,`${nR}%`]}),s=new Map,a=[];for(let c of o.rows){let l=e5a.parse(c),d=MC(l.content),p=s.get(d)??n5a(r,d);s.set(d,p);let f=await p,m=t5a.parse(JSON.parse(l.metadata));a.push(r5a(l.id,d,f,m.sizeBytes))}return{rows:a,inlineRows:i.inlineIds.length,placeholderRows:i.placeholderIds.length,ftsRows:i.ftsRows}}async function n5a(e,t){try{return{status:"verified",verification:await e.verify(t)}}catch(n){if(n instanceof mJ)return{status:"missing"};if(n instanceof J4)return{status:"corrupt",detail:n.message};throw n}}function r5a(e,t,n,r){if(n.status==="missing")return{id:e,ref:t,status:"missing"};if(n.status==="corrupt")return{id:e,ref:t,status:"corrupt",detail:n.detail};let{verification:i}=n;if(!i.valid)return{id:e,ref:t,status:"corrupt",detail:`stored bytes hash to ${i.actualDigest}`};if(r!==void 0&&r!==i.sizeBytes)return{id:e,ref:t,status:"size-mismatch",detail:`row records ${r} bytes; the asset holds ${i.sizeBytes}`};return{id:e,ref:t,status:"valid"}}var e5a,t5a;var qUr=E(()=>{pQ();oe();NMe();Gcn();e5a=u.object({id:u.string(),content:u.string(),metadata:u.string()}),t5a=u.object({sizeBytes:u.number()}).partial()});class WAe{db;repository;ftsTable;constructor(e){this.db=e.db,this.repository=new dce(e.db)}async migrateRow(e,t){let n=await this.hasFtsTable();return this.publishing(t,async(r,i,o)=>{let[s]=await r.select({content:gt.content,contentHash:gt.contentHash,metadata:gt.metadata}).from(gt).where(this.row(e,t.id));if(s?.contentHash!==t.expectedContentHash||s.content.startsWith(nR))return{outcome:"changed"};await this.repository.bindEntityContent(r,i.ref,o);let a=Ur(i.ref);if(await r.update(gt).set({content:i.ref,contentHash:a,metadata:{...s.metadata,...t.metadata}}).where(this.row(e,t.id)),n)await r.run(Te`DELETE FROM entity_fts WHERE entity_id = ${t.id} AND entity_type = ${e}`);return{outcome:"migrated",ref:i.ref,contentHash:a}})}async restoreAsset(e,t){return this.publishing(t,async(n,r,i)=>{let[o]=await n.select({content:gt.content}).from(gt).where(this.row(e,t.id));if(o?.content!==t.ref||r.ref!==t.ref)return{outcome:"changed"};return await this.repository.bindEntityContent(n,r.ref,i),{outcome:"restored"}})}async createRow(e,t){return this.publishing(t,async(n,r,i)=>{let[o]=await n.select({id:gt.id}).from(gt).where(this.row(e,t.id));if(o)return{outcome:"changed"};await this.repository.bindEntityContent(n,r.ref,i);let s=Ur(r.ref);return await n.insert(gt).values({id:t.id,entityType:e,content:r.ref,contentHash:s,metadata:t.metadata,created:t.created,updated:t.updated}),{outcome:"created",ref:r.ref,contentHash:s}})}async clearPlaceholder(e,t){let n=await this.hasFtsTable();return this.db.transaction(async(r)=>{let[i]=await r.select({contentHash:gt.contentHash,metadata:gt.metadata}).from(gt).where(this.row(e,t.id));if(i?.contentHash!==t.expectedContentHash)return{outcome:"changed"};if(await r.update(gt).set({content:"",contentHash:Ur(""),metadata:Object.fromEntries(Object.entries(i.metadata).filter(([o])=>!i5a.includes(o)))}).where(this.row(e,t.id)),n)await r.run(Te`DELETE FROM entity_fts WHERE entity_id = ${t.id} AND entity_type = ${e}`);return{outcome:"cleared"}})}async publishing(e,t){let n=await this.repository.stage(e.bytes,{expectedSize:e.expectedSize}),r=this.repository.claim(n);try{return await this.db.transaction((i)=>t(i,n,r))}finally{await this.repository.release(n)}}row(e,t){return Bt(Ie(gt.entityType,e),Ie(gt.id,t))}hasFtsTable(){return this.ftsTable??=this.db.all(Te`SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name = 'entity_fts'`).then((e)=>Number(e[0]?.count)>0),this.ftsTable}}var i5a;var UUr=E(()=>{pQ();Oo();ca();oR();NMe();i5a=["format","width","height","mediaType","sizeBytes"]});var ro=E(()=>{_Xt();pQ();yan();han();Gft();uLr();Hft();Yft();CQ();EAe();Msn();SUr();IUr();ian();NMe();fan();oce();xnn();iJ();Dft();TUr();vAe();jft();qft();cJ();zsn();BUr();jUr();Can();Gcn();qUr();UUr();xan();wan();CQ()});function s7e(e){return _o(Wcn(e))}function Wcn(e,t=new Set){if(e===null)return"null";if(typeof e==="string"||typeof e==="boolean")return JSON.stringify(e);if(typeof e==="number"){if(!Number.isFinite(e))throw Error("Projection inputs cannot contain non-finite numbers");if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw Error("Projection inputs cannot contain unsafe integers");return JSON.stringify(e)}if(typeof e!=="object")throw Error(`Projection inputs cannot contain ${typeof e} values`);if(t.has(e))throw Error("Projection inputs cannot contain circular values");let n=new Set(t).add(e);if(Array.isArray(e))return`[${e.map((i)=>Wcn(i,n)).join(",")}]`;let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Error("Projection inputs must contain only plain JSON objects");return`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${JSON.stringify(i)}:${Wcn(o,n)}`).join(",")}}`}var Vcn=E(()=>{Oo()});async function VAe(e,t){let n=await e.searchWithDistances({query:t.query,types:[t.entityType],maxDistance:t.maxDistance}),i=(await Promise.all(n.filter((a)=>a.entityType===t.entityType&&a.distance<=t.maxDistance&&!t.excludeIds?.includes(a.entityId)).map((a)=>e.getEntity({entityType:t.entityType,id:a.entityId,visibilityScope:t.visibility})))).filter((a)=>a?.visibility===t.visibility),o=t.confirm;if(!o)return i[0];let s=async(a)=>{let c=i[a];if(!c)return;return await o(c)?c:s(a+1)};return s(0)}async function r3(e,t={}){let n=t.pollMs??100,r=Date.now()+(t.timeoutMs??60000),i=async()=>{if((await e.getActiveJobs([cy.embedding])).length===0)return;if(Date.now()>=r)throw Error("Embeddings did not drain before the deadline");return await new Promise((s)=>setTimeout(s,n)),i()};return i()}var Kcn=E(()=>{lt()});function Qcn(e){if(e!==null&&typeof e==="object"){for(let t of Object.values(e))Qcn(t);Object.freeze(e)}return e}function Y6(e){let t=o5a.parse({id:e.id,version:e.version,sources:e.sources,targetType:e.targetType,sourceChangeBatchDelayMs:e.sourceChangeBatchDelayMs});if(typeof e.selectInput!=="function")throw Error(`Projection rule "${t.id}" must select input`);if(typeof e.derive!=="function")throw Error(`Projection rule "${t.id}" must derive output`);let n=t.sources.map((r)=>{let i=Object.freeze([...r.types]),o=r.excludeTypes?Object.freeze([...r.excludeTypes]):void 0,s={kind:"entity",types:i,...o?{excludeTypes:o}:{}};return Object.freeze(s)});return Object.freeze({id:t.id,version:t.version,sources:Object.freeze(n),targetType:t.targetType,sourceChangeBatchDelayMs:t.sourceChangeBatchDelayMs,inputSchema:e.inputSchema,selectInput:async(r,i,o)=>{let s=await e.selectInput(r,i,o),a=wx.parse(s);return Qcn(e.inputSchema.parse(a))},fingerprint:s7e,derive:async(r,i,o)=>{let s=e.inputSchema.parse(r),a=u.array(pJ).parse(await e.derive(s,i,o));for(let c of a){let l=c.operation==="upsert"?c.entity.entityType:c.entityType;if(l!==t.targetType)throw Error(`Projection rule "${t.id}" cannot write entity type "${l}"`)}return Qcn(a)}})}var o5a;var Jcn=E(()=>{ro();oe();Vcn();ro();o5a=u.strictObject({id:u.string().trim().min(1),version:u.string().trim().min(1),sources:u.array(u.strictObject({kind:u.literal("entity"),types:u.array(u.string().trim().min(1)).min(1),excludeTypes:u.array(u.string().trim().min(1)).optional()})),targetType:u.string().trim().min(1),sourceChangeBatchDelayMs:u.number().int().nonnegative().default(0)})});function c7e(e,t,n){if(e.toLowerCase()===t.toLowerCase())return n;let r=`/${e.toLowerCase()}`;return n==="/"?r:`${r}${n}`}var GUr,s5a,a5a,c5a,YE,Bce,a7e,l5a,Ycn,u5a,d5a,HUr,p5a,f5a,ZUr,WUr,VUr;var l7e=E(()=>{vF();GUr=["primary","secondary"],s5a=u.custom((e)=>typeof e==="function","Expected a React component"),a5a=u.strictObject({show:u.boolean().optional(),label:u.string().min(1).optional(),slot:u.enum(GUr).optional(),priority:u.number().optional()}),c5a=u.strictObject({id:u.string().min(1),template:u.string().min(1),content:u.unknown().optional(),dataQuery:u.looseObject({entityType:u.string().optional(),template:u.string().optional(),query:u.record(u.string(),u.unknown()).optional()}).optional(),order:u.number().optional()}),YE=u.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Bce=u.strictObject({template:u.string().min(1),content:u.record(u.string(),u.json()),translations:u.record(YE,u.record(u.string(),u.json())).optional()}),a7e=u.strictObject({title:u.string().optional(),description:u.string().optional(),navigationLabel:u.string().optional()}),l5a=u.strictObject({id:u.string().min(1),path:u.string().startsWith("/"),title:u.string().optional(),pageLabel:u.string().optional(),description:u.string().optional(),sections:u.array(c5a).optional(),layout:u.string().min(1).optional(),fullscreen:u.boolean().optional(),pluginId:u.string().optional(),sourceEntityType:u.string().optional(),sourceEntityId:u.string().optional(),external:u.boolean().optional(),navigation:a5a.optional(),translations:u.record(YE,a7e).optional(),copy:u.literal("brain").optional()}),Ycn=u.strictObject({label:u.string().min(1),pluralName:u.string().min(1).optional(),layout:u.string().min(1).optional(),detailTemplate:u.string().min(1).optional(),paginate:u.boolean().optional(),pageSize:u.number().int().positive().optional(),citable:u.boolean().optional(),navigation:u.strictObject({show:u.boolean().optional(),slot:u.enum(GUr).optional(),priority:u.number().optional()}).optional()}),u5a=u.strictObject({schema:u.custom((e)=>e instanceof u.ZodType,"Expected a Zod schema"),component:u.custom((e)=>typeof e==="function","Expected a React component"),title:u.string().min(1),description:u.string(),requiredPermission:u.enum(["admin","trusted","public"]).optional(),fullscreen:u.boolean().optional(),dataSource:u.string().min(1).optional(),components:u.record(YE,u.custom((e)=>typeof e==="function","Expected a React component")).optional()}),d5a=u.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),HUr=u.strictObject({namespace:u.string().min(1),sections:u.record(u.string(),u5a)}),p5a=u.record(u.string(),u.json()),f5a=u.record(u.string(),u.record(u.string(),p5a));ZUr={layouts:u.record(u.string(),s5a).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:u.array(l5a),content:f5a.optional(),sections:u.union([HUr,u.array(HUr)]).optional(),themeOverride:u.string().optional(),headScripts:u.array(u.string()).optional(),entityDisplay:u.record(u.string(),Ycn),staticAssets:u.record(u.string(),u.string()).optional(),languages:u.array(YE).min(1).optional(),layoutCopy:Bce.optional(),dataSources:u.array(d5a).readonly().optional()},WUr=u.strictObject(ZUr).partial(),VUr=u.strictObject(ZUr).superRefine((e,t)=>{let n=e.languages??[],r=new Set;for(let[l,d]of n.entries()){let p=d.toLowerCase();if(r.has(p))t.addIssue({code:"custom",path:["languages",l],message:`Language "${d}" is declared twice`});r.add(p)}let i=n.slice(1).map((l)=>`/${l.toLowerCase()}`),o=new Set;for(let[l,d]of e.routes.entries()){if(o.has(d.id))t.addIssue({code:"custom",path:["routes",l,"id"],message:`Duplicate route id "${d.id}"`});o.add(d.id);let p=d.path.toLowerCase(),f=i.find((h)=>p===h||p.startsWith(`${h}/`));if(f)t.addIssue({code:"custom",path:["routes",l,"path"],message:`Route path "${d.path}" is under ${f}, where another language's pages are built`});let m=d.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",l,"layout"],message:`Unknown layout "${m}"`});for(let[h,g]of(d.sections??[]).entries()){let x=/^([^:.\s]+)\.([^:.\s]+)$/.exec(g.template);if(x)t.addIssue({code:"custom",path:["routes",l,"sections",h,"template"],message:`Section template "${g.template}" is written "${x[1]}:${x[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((l)=>[l.namespace,l]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let c=new Set;for(let[l,d]of(e.dataSources??[]).entries()){if(c.has(d.id))t.addIssue({code:"custom",path:["dataSources",l],message:`Data source "${d.id}" is declared twice`});c.add(d.id)}for(let l of s)for(let[d,p]of Object.entries(l.sections))if(p.dataSource&&!c.has(p.dataSource))t.addIssue({code:"custom",path:["sections",l.namespace,d,"dataSource"],message:`Section "${l.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[l,d]of Object.entries(e.content??{})){let p=a.get(l);if(!p){t.addIssue({code:"custom",path:["content",l],message:`Content namespace "${l}" has no section group`});continue}for(let[f,m]of Object.entries(d)){let h=p.sections[f];if(!h){t.addIssue({code:"custom",path:["content",l,f],message:`Content section "${l}:${f}" is not defined`});continue}let g=h.schema.safeParse(m);if(!g.success)t.addIssue({code:"custom",path:["content",l,f],message:`Content does not satisfy the "${l}:${f}" schema: ${u.prettifyError(g.error)}`})}}})});var KUr,u7e,QUr,i3,Xcn,d7e,JUr,YUr,p7e,XUr,e$r,f7e,oht;var eln=E(()=>{lt();oe();l7e();l7e();KUr=u.object({id:u.string(),template:u.string(),content:u.unknown().optional(),dataQuery:u.looseObject({entityType:u.string().optional(),template:u.string().optional(),query:u.looseObject({id:u.string().optional(),limit:u.number().optional(),offset:u.number().optional()}).optional()}).optional(),order:u.number().optional()}),u7e=["primary","secondary"],QUr=u.object({show:u.boolean().default(!1),label:u.string().optional(),slot:u.enum(u7e).default("primary"),priority:u.number().min(0).max(100).default(50)}).optional(),i3=u.object({id:u.string(),path:u.string(),title:u.string().default(""),pageLabel:u.string().optional(),description:u.string().default(""),sections:u.array(KUr).default([]),layout:u.string().default("default"),fullscreen:u.boolean().optional(),pluginId:u.string().optional(),sourceEntityType:u.string().optional(),sourceEntityId:u.string().optional(),external:u.boolean().optional(),navigation:QUr,translations:u.record(YE,a7e).optional(),languages:u.array(YE).optional()}),Xcn=u.object({routes:u.array(i3),pluginId:u.string()}),d7e=Fr({channel:"plugin:site-builder:route:register",request:Xcn,response:u.void(),delivery:"command"}),JUr=u.strictObject({}),YUr=u.array(i3),p7e=Fr({channel:"site-builder:routes:list",request:JUr,response:YUr,delivery:"request"}),XUr=u.strictObject({}),e$r=u.array(i3),f7e=Fr({channel:"plugin:site-builder:pages",request:XUr,response:e$r,delivery:"collect"}),oht=u.object({label:u.string(),href:u.string(),priority:u.number()})});var t$r,n$r,r$r,m7e;var i$r=E(()=>{lt();oe();t$r=u.object({pluginId:u.string(),slotName:u.string(),render:u.custom((e)=>typeof e==="function"),priority:u.number().optional()}),n$r=u.strictObject({}),r$r=u.array(t$r),m7e=Fr({channel:"plugin:site-builder:slots",request:n$r,response:r$r,delivery:"collect"})});var o$r="site:metadata:updated",sht,KAe,s$r,PT,a$r,Rce,Dce,aht;var tln=E(()=>{lt();oe();eln();sht=u.object({heading:u.string().describe("Main CTA heading text"),subtitle:u.string().optional().describe("A line under the CTA heading"),buttonText:u.string().describe("Call-to-action button text"),buttonLink:u.string().describe("URL or anchor for the CTA button")}),KAe=u.object({title:u.string().optional(),description:u.string().optional(),copyright:u.string().optional(),cta:sht.optional()}),s$r=u.object({blurb:u.string().optional().describe("Short italic subtitle under the section title")}),PT=u.object({represents:u.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:u.string().describe("The site's title"),description:u.string().describe("The site's description"),url:u.string().optional().describe("Canonical site URL"),copyright:u.string().optional().describe("Copyright notice text"),logo:u.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:u.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:u.string().optional().describe("Analytics script HTML"),cta:sht.optional().describe("Call-to-action configuration"),sections:u.record(u.string(),s$r).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:u.record(YE,KAe).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),a$r=u.strictObject({}),Rce=Fr({channel:"site:metadata:get",request:a$r,response:PT,delivery:"request"}),Dce=fc(o$r,PT),aht=PT.extend({copyright:u.string(),navigation:u.object({primary:u.array(oht),secondary:u.array(oht)}),socialLinks:u.array($se).optional().describe("Social media links from profile metadata"),photo:u.string().optional().describe("The anchor's photo, as ")})});function nln(e,t){let n=m5a.safeParse(e);return n.success&&t.every((r)=>(r in n.data))}var m5a;var rln=E(()=>{oe();m5a=u.record(u.string(),u.unknown())});class CJ{parse(e){throw Error("This response format is read-only and cannot be parsed back to data")}formatKeyValue(e,t){if(t===void 0||t===null)return"";return`**${e}:** ${String(t)}`}formatList(e){return e.map((t)=>`- ${String(t)}`).join(`
|
|
266
266
|
`)}formatTable(e,t){let n=`| ${e.join(" | ")} |`,r=`| ${e.map(()=>"---").join(" | ")} |`,i=t.map((o)=>`| ${o.map((s)=>String(s??"")).join(" | ")} |`).join(`
|
|
267
267
|
`);return`${n}
|
|
268
268
|
${r}
|
|
@@ -293,9 +293,9 @@ ${x}
|
|
|
293
293
|
|
|
294
294
|
${h}`}}}}var b5a;var h$r=E(()=>{oe();oln();b5a=/^\s*(```|~~~)/u});function g$r(e){return e.replace(/[\\[\]]/g,(t)=>`\\${t}`)}function x$r(e){return e.replace(/\\([\\[\]])/g,"$1")}function E5a(e){let t=g$r(e.title),n=/[\s()]/.test(e.id)?`<${e.id}>`:e.id,r=e.url?`[${t}](${e.url} "${e.id}")`:`[${t}](${n})`,i=e.brain?` \u2014 from ${e.brain.url?`[${g$r(e.brain.name)}](${e.brain.url})`:e.brain.name}`:"";return`- ${r}${i}`}function S5a(e){let t=A5a.exec(e);if(!t)return{id:"",title:e};let[,n="",r="",i,o,s,a]=t,c=o?x$r(o):a?.trim(),l=r.replace(/^<(.*)>$/,"$1");return{id:i??l,title:x$r(n),...w5a.test(l)?{url:l}:{},...c?{brain:{name:c,...s?{url:s}:{}}}:{}}}function QAe(e){return e.map(E5a).join(`
|
|
295
295
|
`)}function JAe(e){return e.split(`
|
|
296
|
-
`).filter((t)=>t.trim().length>0).map((t)=>S5a(t.trim()))}var $$,A5a,w5a;var y$r=E(()=>{lt();oe();$$=u.object({id:u.string().min(1),title:u.string().min(1),url:u.url().optional(),brain:g4.optional()}),A5a=/^- \[((?:\\.|[^\]\\])+)\]\((<[^>]*>|\S+?)(?: "([^"]+)")?\)(?: \u2014 from (?:\[((?:\\.|[^\]\\])+)\]\((\S+?)\)|(.+)))?$/,w5a=/^https?:\/\//});var lht=E(()=>{h7e();c$r();l$r();u$r();oln();f$r();m$r();h$r();y$r();rln()});var D5a;var b$r=E(()=>{oe();D5a=u.object({slug:u.string(),title:u.string(),type:u.string(),entityId:u.string(),contentHash:u.string()})});var uh=E(()=>{lht();b$r();lht();lht()});function x7e(e,t){return t?e.nullable().default(null):e}function aln(e){switch(e.type){case"string":return x7e(u.string(),e.optional);case"number":return x7e(u.number(),e.optional);case"enum":return x7e(u.enum(e.options),e.optional);case"object":{let t={};for(let[n,r]of Object.entries(e.fields))t[n]=aln(r);return x7e(u.object(t),e.optional)}case"array":{let t=u.array(P5a(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return x7e(t,e.optional)}}}function P5a(e){let{items:t}=e;switch(t.type){case"string":return u.string();case"number":return u.number();case"enum":return u.enum(t.options);case"object":{let n={};for(let[r,i]of Object.entries(t.fields))n[r]=aln(i);return u.object(n)}}}function sln(e,t){switch(t.type){case"string":case"enum":return{key:e,label:t.label,type:"string"};case"number":return{key:e,label:t.label,type:"number"};case"object":return{key:e,label:t.label,type:"object",children:Object.entries(t.fields).map(([n,r])=>sln(n,r))};case"array":{let n={key:e,label:t.label,type:"array"};switch(t.items.type){case"string":case"enum":return n.itemType="string",n;case"number":return n.itemType="number",n;case"object":return n.itemType="object",n.itemMappings=Object.entries(t.items.fields).map(([r,i])=>sln(r,i)),n}}}}function cln(e,t){let n={};for(let[o,s]of Object.entries(t.fields))n[o]=aln(s);let r=u.object(n),i=new Zu(r,{title:t.title,mappings:Object.entries(t.fields).map(([o,s])=>sln(o,s))});return{name:e,description:t.description,schema:r,formatter:i,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function YAe(e){let t={};for(let[n,r]of Object.entries(e.sections))t[n]=cln(n,r);return t}var v$r=E(()=>{uh();oe()});function XAe(e,t){let n={...e};return Object.defineProperty(n,A$r,{value:t,enumerable:!1}),n}function oj(e){return Reflect.get(e,A$r)}var A$r;var lln=E(()=>{A$r=Symbol.for("@brains/site-composition:site-runtime")});function Pce(e,t){return(n)=>t(e.parse(n))}function w$r(e,t){let n=Object.fromEntries(Object.entries(t??{}).map(([r,i])=>[r,Pce(e,i)]));return Object.keys(n).length>0?n:void 0}function Ln(e){let{layout:t,schema:n,...r}=e;if(!t)return{...r,schema:n};let i={...r,schema:n.transform((s)=>qh.parse(s)),layout:{}},o;if(t.renderSchema)i.layout.component=Pce(t.renderSchema,t.component),o=w$r(t.renderSchema,t.formats);else{if(t.component)i.layout.component=Pce(n,t.component);o=w$r(n,t.formats)}if(t.fullscreen!==void 0)i.layout.fullscreen=t.fullscreen;if(o)i.layout.formats=o;return i}function ewe(e){let{component:t,formats:n}=e.layout??{};return{...t?{web:t}:{},...n?.image?{image:n.image}:{},...n?.pdf?{pdf:n.pdf}:{},...n?.epub?{epub:n.epub}:{}}}var Sy,aA,E$r;var uht=E(()=>{oe();lt();Sy={url:u.string(),typeLabel:u.string(),listUrl:u.string(),listLabel:u.string()},aA={url:u.string().nullable().default(null),typeLabel:u.string().nullable().default(null),listUrl:u.string().nullable().default(null),listLabel:u.string().nullable().default(null)};E$r=u.object({name:u.string(),description:u.string(),schema:u.unknown(),basePrompt:u.string().optional(),useKnowledgeContext:u.boolean().optional(),requiredPermission:u.enum(["admin","trusted","public"]),formatter:u.unknown().optional(),overlayFormatter:u.unknown().optional(),layout:u.object({component:u.unknown().optional(),fullscreen:u.boolean().optional(),formats:u.unknown().optional()}).optional(),dataSourceId:u.string().optional()})});class mI{static canGenerate(e){return!!e.basePrompt&&!!e.dataSourceId&&e.dataSourceId.includes("ai-content")}static canFetch(e){return!!e.dataSourceId&&!this.canGenerate(e)}static canRender(e){return Object.keys(ewe(e)).length>0}static isStaticOnly(e){return!this.canGenerate(e)&&!this.canFetch(e)}static getCapabilities(e){return{canGenerate:this.canGenerate(e),canFetch:this.canFetch(e),canRender:this.canRender(e),isStaticOnly:this.isStaticOnly(e)}}static validate(e){let t=[];if(e.dataSourceId?.includes("ai-content")&&!e.basePrompt)t.push(`Template "${e.name}" has AI-content dataSourceId but no basePrompt. AI generation requires a basePrompt.`);if(e.basePrompt&&!e.dataSourceId?.includes("ai-content"))t.push(`Template "${e.name}" has basePrompt but no AI-content dataSourceId. The basePrompt won't be used.`);return t}static logCapabilities(e,t){let n=this.getCapabilities(e),r=this.validate(e);if(t)t.debug(`Template capabilities for "${e.name}":`,{...n,errors:r.length>0?r:void 0})}}var dht=E(()=>{uht()});class twe{templates=new Map;logger;static createFresh(e){return new twe(e)}constructor(e){this.logger=e}register(e,t){this.templates.set(e,t);let n=mI.validate(t);if(n.length>0)n.forEach((r)=>{this.logger?.error(`Template configuration error: ${r}`)});mI.logCapabilities(t,this.logger),this.logger?.debug(`Registered template: ${e}`)}get(e){return this.templates.get(e)}getAll(){return new Map(this.templates)}has(e){return this.templates.has(e)}getNames(){return Array.from(this.templates.keys())}list(){return Array.from(this.templates.values())}unregister(e){let t=this.templates.has(e);if(t)this.templates.delete(e),this.logger?.debug(`Unregistered template: ${e}`);return t}clear(){let e=this.templates.size;this.templates.clear(),this.logger?.debug(`Cleared ${e} templates from registry`)}size(){return this.templates.size}getPluginTemplates(e){let t=`${e}:`;return Array.from(this.templates.entries()).filter(([n])=>n.startsWith(t)).map(([,n])=>n)}getPluginTemplateNames(e){let t=`${e}:`;return Array.from(this.templates.keys()).filter((n)=>n.startsWith(t))}}var S$r=E(()=>{dht()});function eD(e,t){if(e===t)return!0;let n=k$r.get(e);if(!n){let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=new RegExp(`^${r.replace(/\*/g,".*")}$`),k$r.set(e,n)}return n.test(t)}var k$r;var uln=E(()=>{k$r=new Map});class dh{admins;anchors;trusted;configuredPrincipalSeeds;rules;spaces;entityActions;entityActionFloor;constructor(e,t={}){if(this.configuredPrincipalSeeds={admins:[...e.admins??[]],anchors:[...e.anchors??[]],trusted:[...e.trusted??[]]},this.admins=dln(this.configuredPrincipalSeeds.admins),this.anchors=dln(this.configuredPrincipalSeeds.anchors),this.trusted=dln(this.configuredPrincipalSeeds.trusted),this.rules=e.rules??[],this.spaces=t.spaces??[],this.entityActionFloor=t.entityActionFloor,e.entityActions)this.entityActions=Mce.parse(e.entityActions)}determineUserLevel(e,t,n={}){let r=`${e}:${t}`,i=nwe(e,FU(e,t));if(this.admins.has(i))return"admin";if(this.trusted.has(i))return"trusted";let o=this.getPatternLevel(r);if(o==="admin"||o==="trusted")return o;if(this.spaces.length>0&&this.matchesConfiguredSpace({interfaceType:e,...n}))return"trusted";return o??"public"}isAnchor(e,t){return this.anchors.has(nwe(e,FU(e,t)))}getConfiguredPrincipalSeeds(){return{admins:[...this.configuredPrincipalSeeds.admins],anchors:[...this.configuredPrincipalSeeds.anchors],trusted:[...this.configuredPrincipalSeeds.trusted]}}replaceRuntimePrincipalState(e){this.admins=new Set(e.grants.filter((t)=>t.permissionLevel==="admin").map((t)=>nwe(t.interfaceType,t.principalKeyHash))),this.trusted=new Set(e.grants.filter((t)=>t.permissionLevel==="trusted").map((t)=>nwe(t.interfaceType,t.principalKeyHash))),this.anchors=new Set(e.anchors.map((t)=>nwe(t.interfaceType,t.principalKeyHash)))}getResolvedEntityActionPolicy(e){let t=this.entityActionFloor?.(e),n={...this.entityActions?.["*"]};for(let i of pln.options){let o=t?.[i],s=n[i];if(o&&s!=="never"&&(o==="never"||!s||this.hasPermission(o,s)))n[i]=o}let r={...n,...this.entityActions?.[e]};return Object.keys(r).length>0?r:void 0}getEntityActionRequiredLevel(e,t){return this.getResolvedEntityActionPolicy(e)?.[t]}getRequiredEntityActionLevel(e,t){return this.getEntityActionRequiredLevel(e,t)}canPerformEntityAction(e,t,n){let r=this.getEntityActionRequiredLevel(t,n);if(!r)return!0;if(r==="never")return!1;return this.hasPermission(e??"public",r)}assertEntityActionAllowed(e,t,n){let r=this.getEntityActionRequiredLevel(e,t);if(!r)return;if(r==="never")throw Error(`${I$r[t]} \`${e}\` is not allowed through system tools.`);let i=n??"public";if(this.hasPermission(i,r))return;throw new pht({entityType:e,action:t,callerLevel:i,requiredLevel:r})}hasPermission(e,t){return dh.hasPermission(e,t)}filterByPermission(e,t){return e.filter((n)=>{let r=n.visibility??"public";return this.hasPermission(t,r)})}static hasPermission(e,t){if(t==="public")return!0;if(t==="trusted")return e==="trusted"||e==="admin";return e==="admin"}getPatternLevel(e){for(let t of this.rules)if(eD(t.pattern,e))return t.level;return}matchesConfiguredSpace(e){if(e.isBot||e.isGuest)return!1;if(!e.channelId)return!1;let t=`${e.interfaceType}:${e.channelId}`;return this.spaces.some((n)=>eD(n,t))}}function dln(e){return new Set(e.map((t)=>{let n=_be(t);return nwe(n.interfaceType,FU(n.interfaceType,n.subject))}))}function nwe(e,t){return`${e.trim().toLowerCase()}:${t}`}var Mm,pln,o3,Oce,Mce,I$r,C$r,pht;var _$r=E(()=>{lt();oe();uln();Mm=u.enum(["admin","trusted","public"]),pln=u.enum(["create","update","delete","extract","publish"]),o3=u.enum(["never","admin","trusted","public"]),Oce=u.strictObject({create:o3.optional(),update:o3.optional(),delete:o3.optional(),extract:o3.optional(),publish:o3.optional()}),Mce=u.record(u.string(),Oce),I$r={create:"Creating",update:"Updating",delete:"Deleting",extract:"Extracting",publish:"Publishing"},C$r={public:"Public",trusted:"Trusted",admin:"Admin"};pht=class pht extends Error{entityType;action;callerLevel;requiredLevel;constructor(e){super(`${I$r[e.action]} \`${e.entityType}\` requires ${C$r[e.requiredLevel]} permission; your current permission is ${C$r[e.callerLevel]}.`);this.name="EntityActionPermissionError",this.entityType=e.entityType,this.action=e.action,this.callerLevel=e.callerLevel,this.requiredLevel=e.requiredLevel}}});class rwe{templateRegistry;static createFresh(e){return new rwe(e)}constructor(e){this.templateRegistry=e}get(e){let t=this.templateRegistry.get(e);return t?fht(e,t):void 0}list(){return this.templateRegistry.getNames().map((e)=>this.get(e)).filter((e)=>e!==void 0)}validate(e,t){let n=this.templateRegistry.get(e);if(!n||!mI.canRender(n))return!1;try{return n.schema.parse(t),!0}catch{return!1}}findViewTemplate(e){return this.list().find((n)=>{if(e.name&&n.name!==e.name)return!1;if(e.pluginId&&n.pluginId!==e.pluginId)return!1;if(e.namePattern){if(!new RegExp(e.namePattern).test(n.name))return!1}return!0})}getRenderer(e,t){let n=this.get(e);if(!n)return;return n.renderers[t]}hasRenderer(e,t){return this.getRenderer(e,t)!==void 0}listFormats(e){let t=this.get(e);if(!t)return[];let n=[];if(t.renderers.web)n.push("web");if(t.renderers.image)n.push("image");if(t.renderers.pdf)n.push("pdf");if(t.renderers.epub)n.push("epub");return n}}function fht(e,t){if(!mI.canRender(t))return;let n=e.split(":"),r=n.length>=2&&n[0]?n[0]:"shell",i={name:e,schema:t.schema,description:t.description,pluginId:r,renderers:ewe(t)};if(t.layout.fullscreen)i.fullscreen=t.layout.fullscreen;if(t.runtimeScripts&&t.runtimeScripts.length>0)i.runtimeScripts=t.runtimeScripts;if(t.staticAssets&&Object.keys(t.staticAssets).length>0)i.staticAssets=t.staticAssets;return i}var T$r=E(()=>{dht();uht()});var B$r,fln,mht,R$r,D$r,P$r;var O$r=E(()=>{oe();B$r=u.enum(["site-content-preview","site-content-production"]),fln=u.enum(["web","image","pdf","epub"]),mht=u.custom((e)=>typeof e==="function"),R$r=u.object({name:u.string(),schema:u.unknown(),description:u.string().optional(),pluginId:u.string(),renderers:u.object({web:u.union([mht,u.string()]).optional(),image:u.union([mht,u.string()]).optional(),pdf:u.union([mht,u.string()]).optional(),epub:u.union([mht,u.string()]).optional()})}),D$r=u.object({enableContentGeneration:u.boolean().default(!1),outputDir:u.string(),workingDir:u.string().optional(),environment:u.enum(["preview","production"]).default("preview"),siteConfig:u.object({title:u.string(),description:u.string(),url:u.string().optional()}).optional()}),P$r=u.object({success:u.boolean(),routesBuilt:u.number(),errors:u.array(u.string()).optional(),warnings:u.array(u.string()).optional()})});var M$r={};fi(M$r,{BuildResultSchema:()=>P$r,EntityActionPermissionError:()=>pht,EntityActionRequiredLevelSchema:()=>o3,EntityActionSchema:()=>pln,InMemoryTemplateRegistry:()=>twe,OutputFormatSchema:()=>fln,PermissionService:()=>dh,RenderService:()=>rwe,SiteBuilderOptionsSchema:()=>D$r,SiteContentEntityTypeSchema:()=>B$r,TemplateCapabilities:()=>mI,TemplateSchema:()=>E$r,UserPermissionLevelSchema:()=>Mm,ViewTemplateSchema:()=>R$r,createTemplate:()=>Ln,createTypedComponent:()=>Pce,entityActionPolicyConfigSchema:()=>Mce,entityActionPolicyRuleSchema:()=>Oce,matchSpaceSelector:()=>eD,renderedLinkFields:()=>Sy,templateRenderers:()=>ewe,toViewTemplate:()=>fht,viewLinkFields:()=>aA});var Fm=E(()=>{uht();S$r();dht();_$r();uln();T$r();O$r()});import{createContext as O5a}from"react";var iwe;var mln=E(()=>{iwe=O5a(void 0)});import{useContext as M5a}from"react";function F5a(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").split(" ").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function F$r(e){let t=e;while(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodDefault)t=t.unwrap();return t}function j5a(e,t){let n=F5a(e),r=F$r(t);if(r instanceof u.ZodString||r instanceof u.ZodEnum||r instanceof u.ZodLiteral)return{key:e,label:n,type:"string"};if(r instanceof u.ZodNumber)return{key:e,label:n,type:"number"};if(r instanceof u.ZodObject)return{key:e,label:n,type:"object",children:hln(r)};if(r instanceof u.ZodArray){let i=F$r(r.element);if(i instanceof u.ZodObject)return{key:e,label:n,type:"array",itemType:"object",itemMappings:hln(i)};if(i instanceof u.ZodNumber)return{key:e,label:n,type:"array",itemType:"number"};return{key:e,label:n,type:"array",itemType:"string"}}throw Error(`Section field "${e}" has a schema type the markdown formatter cannot `+"derive headings for \u2014 use string/number/enum/object/array.")}function hln(e){return Object.entries(e.shape).map(([t,n])=>j5a(t,n))}function N5a(e,t){if(!t||Object.keys(t).length===0)return e;return function(r){let i=M5a(iwe)?.toLowerCase();return(Object.entries(t).find(([s])=>s.toLowerCase()===i)?.[1]??e)(r)}}function j$r(e,t,n={}){let r=t.schema;if(!(r instanceof u.ZodObject))throw Error(`Section "${e}" schema must be a zod object.`);let i=t.dataSource?n.dataSourceId?.(t.dataSource):void 0;if(t.dataSource&&!i)throw Error(`Section "${e}" reads data source "${t.dataSource}", which only a site registers`);let o=new Zu(r,{title:t.title,layout:"compact",mappings:hln(r)});return{name:e,description:t.description,schema:t.schema,formatter:o,requiredPermission:t.requiredPermission??"public",...i?{dataSourceId:i}:{},layout:{component:Pce(t.schema,N5a(t.component,t.components)),...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}}}}function hht(e,t={}){let n={};for(let[r,i]of Object.entries(e.sections))n[r]=j$r(r,i,t);return n}var N$r=E(()=>{uh();Fm();mln();oe()});function L$r(e){return OT.parse(Qf(e).fields)}async function owe(e){let n=(await e.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!n)throw Error("Site info not found \u2014 create a site-info entity");return L$r(n)}var L5a,OT;var z$r=E(()=>{lt();oe();tln();L5a=PT.omit({url:!0,analyticsScript:!0}),OT=L5a.extend({title:u.string().optional().describe("Optional site title override"),description:u.string().optional().describe("Optional site description override")})});function Fce(e,t={}){let n=q$r(e),r=q$r(t.sharedDomain??"rizom.ai").replace(/^\./,""),i=`.${r}`;if(n.endsWith(i)){let o=n.slice(0,-i.length);if(o.length>0&&!o.includes("."))return`${o}-preview.${r}`}return`preview.${n}`}function q$r(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class MT{entityDisplay;constructor(e){this.entityDisplay=e}hasRoute(e){return this.entityDisplay?.[e]!==void 0}isCitable(e){if(this.entityDisplay?.[e]?.citable===!1)return!1;if(!Object.values(this.entityDisplay??{}).some((n)=>n.citable===!0))return this.hasRoute(e);return this.entityDisplay?.[e]?.citable===!0}generateUrl(e,t){let n=this.entityDisplay?.[e];if(n)return`/${n.pluralName??n.label.toLowerCase()+"s"}/${t}`;return`/${t3(e)}/${t}`}}var U$r=E(()=>{or()});function z5a(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,i]of Object.entries(t))n[r]={...e[r]??{},...i};return n}function $$r(e){if(!e)return[];return Array.isArray(e)?e:[e]}function q5a(e,t){let n=[...$$r(e),...$$r(t)];return n.length>0?n:void 0}function U5a(e,t){if(!t||t.length===0)return e;let n=[...e],r=new Map;for(let[i,o]of n.entries())r.set(o.id,i);for(let i of t){let o=r.get(i.id);if(o!==void 0){n[o]=i;continue}r.set(i.id,n.length),n.push(i)}return n}function _J(e,t={}){if(Object.keys(t).length===0&&oj(t)===void 0)return e;let{layouts:n,entityDisplay:r,staticAssets:i,themeOverride:o,headScripts:s}=t,a=n?{...e.layouts,...n}:e.layouts,c=r?{...e.entityDisplay,...Object.fromEntries(Object.entries(r).map(([v,w])=>[v,{...e.entityDisplay[v],...w}]))}:e.entityDisplay,l=i?{...e.staticAssets??{},...i}:e.staticAssets,d=[e.themeOverride,o].filter(Boolean).join(`
|
|
296
|
+
`).filter((t)=>t.trim().length>0).map((t)=>S5a(t.trim()))}var $$,A5a,w5a;var y$r=E(()=>{lt();oe();$$=u.object({id:u.string().min(1),title:u.string().min(1),url:u.url().optional(),brain:g4.optional()}),A5a=/^- \[((?:\\.|[^\]\\])+)\]\((<[^>]*>|\S+?)(?: "([^"]+)")?\)(?: \u2014 from (?:\[((?:\\.|[^\]\\])+)\]\((\S+?)\)|(.+)))?$/,w5a=/^https?:\/\//});var lht=E(()=>{h7e();c$r();l$r();u$r();oln();f$r();m$r();h$r();y$r();rln()});var D5a;var b$r=E(()=>{oe();D5a=u.object({slug:u.string(),title:u.string(),type:u.string(),entityId:u.string(),contentHash:u.string()})});var uh=E(()=>{lht();b$r();lht();lht()});function x7e(e,t){return t?e.nullable().default(null):e}function aln(e){switch(e.type){case"string":return x7e(u.string(),e.optional);case"number":return x7e(u.number(),e.optional);case"enum":return x7e(u.enum(e.options),e.optional);case"object":{let t={};for(let[n,r]of Object.entries(e.fields))t[n]=aln(r);return x7e(u.object(t),e.optional)}case"array":{let t=u.array(P5a(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return x7e(t,e.optional)}}}function P5a(e){let{items:t}=e;switch(t.type){case"string":return u.string();case"number":return u.number();case"enum":return u.enum(t.options);case"object":{let n={};for(let[r,i]of Object.entries(t.fields))n[r]=aln(i);return u.object(n)}}}function sln(e,t){switch(t.type){case"string":case"enum":return{key:e,label:t.label,type:"string"};case"number":return{key:e,label:t.label,type:"number"};case"object":return{key:e,label:t.label,type:"object",children:Object.entries(t.fields).map(([n,r])=>sln(n,r))};case"array":{let n={key:e,label:t.label,type:"array"};switch(t.items.type){case"string":case"enum":return n.itemType="string",n;case"number":return n.itemType="number",n;case"object":return n.itemType="object",n.itemMappings=Object.entries(t.items.fields).map(([r,i])=>sln(r,i)),n}}}}function cln(e,t){let n={};for(let[o,s]of Object.entries(t.fields))n[o]=aln(s);let r=u.object(n),i=new Zu(r,{title:t.title,mappings:Object.entries(t.fields).map(([o,s])=>sln(o,s))});return{name:e,description:t.description,schema:r,formatter:i,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function YAe(e){let t={};for(let[n,r]of Object.entries(e.sections))t[n]=cln(n,r);return t}var v$r=E(()=>{uh();oe()});function XAe(e,t){let n={...e};return Object.defineProperty(n,A$r,{value:t,enumerable:!1}),n}function oj(e){return Reflect.get(e,A$r)}var A$r;var lln=E(()=>{A$r=Symbol.for("@brains/site-composition:site-runtime")});function Pce(e,t){return(n)=>t(e.parse(n))}function w$r(e,t){let n=Object.fromEntries(Object.entries(t??{}).map(([r,i])=>[r,Pce(e,i)]));return Object.keys(n).length>0?n:void 0}function Ln(e){let{layout:t,schema:n,...r}=e;if(!t)return{...r,schema:n};let i={...r,schema:n.transform((s)=>qh.parse(s)),layout:{}},o;if(t.renderSchema)i.layout.component=Pce(t.renderSchema,t.component),o=w$r(t.renderSchema,t.formats);else{if(t.component)i.layout.component=Pce(n,t.component);o=w$r(n,t.formats)}if(t.fullscreen!==void 0)i.layout.fullscreen=t.fullscreen;if(o)i.layout.formats=o;return i}function ewe(e){let{component:t,formats:n}=e.layout??{};return{...t?{web:t}:{},...n?.image?{image:n.image}:{},...n?.pdf?{pdf:n.pdf}:{},...n?.epub?{epub:n.epub}:{}}}var Sy,aA,E$r;var uht=E(()=>{oe();lt();Sy={url:u.string(),typeLabel:u.string(),listUrl:u.string(),listLabel:u.string()},aA={url:u.string().nullable().default(null),typeLabel:u.string().nullable().default(null),listUrl:u.string().nullable().default(null),listLabel:u.string().nullable().default(null)};E$r=u.object({name:u.string(),description:u.string(),schema:u.unknown(),basePrompt:u.string().optional(),useKnowledgeContext:u.boolean().optional(),requiredPermission:u.enum(["admin","trusted","public"]),formatter:u.unknown().optional(),overlayFormatter:u.unknown().optional(),layout:u.object({component:u.unknown().optional(),fullscreen:u.boolean().optional(),formats:u.unknown().optional()}).optional(),dataSourceId:u.string().optional()})});class mI{static canGenerate(e){return!!e.basePrompt&&!!e.dataSourceId&&e.dataSourceId.includes("ai-content")}static canFetch(e){return!!e.dataSourceId&&!this.canGenerate(e)}static canRender(e){return Object.keys(ewe(e)).length>0}static isStaticOnly(e){return!this.canGenerate(e)&&!this.canFetch(e)}static getCapabilities(e){return{canGenerate:this.canGenerate(e),canFetch:this.canFetch(e),canRender:this.canRender(e),isStaticOnly:this.isStaticOnly(e)}}static validate(e){let t=[];if(e.dataSourceId?.includes("ai-content")&&!e.basePrompt)t.push(`Template "${e.name}" has AI-content dataSourceId but no basePrompt. AI generation requires a basePrompt.`);if(e.basePrompt&&!e.dataSourceId?.includes("ai-content"))t.push(`Template "${e.name}" has basePrompt but no AI-content dataSourceId. The basePrompt won't be used.`);return t}static logCapabilities(e,t){let n=this.getCapabilities(e),r=this.validate(e);if(t)t.debug(`Template capabilities for "${e.name}":`,{...n,errors:r.length>0?r:void 0})}}var dht=E(()=>{uht()});class twe{templates=new Map;logger;static createFresh(e){return new twe(e)}constructor(e){this.logger=e}register(e,t){this.templates.set(e,t);let n=mI.validate(t);if(n.length>0)n.forEach((r)=>{this.logger?.error(`Template configuration error: ${r}`)});mI.logCapabilities(t,this.logger),this.logger?.debug(`Registered template: ${e}`)}get(e){return this.templates.get(e)}getAll(){return new Map(this.templates)}has(e){return this.templates.has(e)}getNames(){return Array.from(this.templates.keys())}list(){return Array.from(this.templates.values())}unregister(e){let t=this.templates.has(e);if(t)this.templates.delete(e),this.logger?.debug(`Unregistered template: ${e}`);return t}clear(){let e=this.templates.size;this.templates.clear(),this.logger?.debug(`Cleared ${e} templates from registry`)}size(){return this.templates.size}getPluginTemplates(e){let t=`${e}:`;return Array.from(this.templates.entries()).filter(([n])=>n.startsWith(t)).map(([,n])=>n)}getPluginTemplateNames(e){let t=`${e}:`;return Array.from(this.templates.keys()).filter((n)=>n.startsWith(t))}}var S$r=E(()=>{dht()});function eD(e,t){if(e===t)return!0;let n=k$r.get(e);if(!n){let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=new RegExp(`^${r.replace(/\*/g,".*")}$`),k$r.set(e,n)}return n.test(t)}var k$r;var uln=E(()=>{k$r=new Map});class dh{admins;anchors;trusted;configuredPrincipalSeeds;rules;spaces;entityActions;entityActionFloor;constructor(e,t={}){if(this.configuredPrincipalSeeds={admins:[...e.admins??[]],anchors:[...e.anchors??[]],trusted:[...e.trusted??[]]},this.admins=dln(this.configuredPrincipalSeeds.admins),this.anchors=dln(this.configuredPrincipalSeeds.anchors),this.trusted=dln(this.configuredPrincipalSeeds.trusted),this.rules=e.rules??[],this.spaces=t.spaces??[],this.entityActionFloor=t.entityActionFloor,e.entityActions)this.entityActions=Mce.parse(e.entityActions)}determineUserLevel(e,t,n={}){let r=`${e}:${t}`,i=nwe(e,FU(e,t));if(this.admins.has(i))return"admin";if(this.trusted.has(i))return"trusted";let o=this.getPatternLevel(r);if(o==="admin"||o==="trusted")return o;if(this.spaces.length>0&&this.matchesConfiguredSpace({interfaceType:e,...n}))return"trusted";return o??"public"}isAnchor(e,t){return this.anchors.has(nwe(e,FU(e,t)))}getConfiguredPrincipalSeeds(){return{admins:[...this.configuredPrincipalSeeds.admins],anchors:[...this.configuredPrincipalSeeds.anchors],trusted:[...this.configuredPrincipalSeeds.trusted]}}replaceRuntimePrincipalState(e){this.admins=new Set(e.grants.filter((t)=>t.permissionLevel==="admin").map((t)=>nwe(t.interfaceType,t.principalKeyHash))),this.trusted=new Set(e.grants.filter((t)=>t.permissionLevel==="trusted").map((t)=>nwe(t.interfaceType,t.principalKeyHash))),this.anchors=new Set(e.anchors.map((t)=>nwe(t.interfaceType,t.principalKeyHash)))}getResolvedEntityActionPolicy(e){let t=this.entityActionFloor?.(e),n={...this.entityActions?.["*"]};for(let i of pln.options){let o=t?.[i],s=n[i];if(o&&s!=="never"&&(o==="never"||!s||this.hasPermission(o,s)))n[i]=o}let r={...n,...this.entityActions?.[e]};return Object.keys(r).length>0?r:void 0}getEntityActionRequiredLevel(e,t){return this.getResolvedEntityActionPolicy(e)?.[t]}getRequiredEntityActionLevel(e,t){return this.getEntityActionRequiredLevel(e,t)}canPerformEntityAction(e,t,n){let r=this.getEntityActionRequiredLevel(t,n);if(!r)return!0;if(r==="never")return!1;return this.hasPermission(e??"public",r)}assertEntityActionAllowed(e,t,n){let r=this.getEntityActionRequiredLevel(e,t);if(!r)return;if(r==="never")throw Error(`${I$r[t]} \`${e}\` is not allowed through system tools.`);let i=n??"public";if(this.hasPermission(i,r))return;throw new pht({entityType:e,action:t,callerLevel:i,requiredLevel:r})}hasPermission(e,t){return dh.hasPermission(e,t)}filterByPermission(e,t){return e.filter((n)=>{let r=n.visibility??"public";return this.hasPermission(t,r)})}static hasPermission(e,t){if(t==="public")return!0;if(t==="trusted")return e==="trusted"||e==="admin";return e==="admin"}getPatternLevel(e){for(let t of this.rules)if(eD(t.pattern,e))return t.level;return}matchesConfiguredSpace(e){if(e.isBot||e.isGuest)return!1;if(!e.channelId)return!1;let t=`${e.interfaceType}:${e.channelId}`;return this.spaces.some((n)=>eD(n,t))}}function dln(e){return new Set(e.map((t)=>{let n=_be(t);return nwe(n.interfaceType,FU(n.interfaceType,n.subject))}))}function nwe(e,t){return`${e.trim().toLowerCase()}:${t}`}var Mm,pln,o3,Oce,Mce,I$r,C$r,pht;var _$r=E(()=>{lt();oe();uln();Mm=u.enum(["admin","trusted","public"]),pln=u.enum(["create","update","delete","extract","publish"]),o3=u.enum(["never","admin","trusted","public"]),Oce=u.strictObject({create:o3.optional(),update:o3.optional(),delete:o3.optional(),extract:o3.optional(),publish:o3.optional()}),Mce=u.record(u.string(),Oce),I$r={create:"Creating",update:"Updating",delete:"Deleting",extract:"Extracting",publish:"Publishing"},C$r={public:"Public",trusted:"Trusted",admin:"Admin"};pht=class pht extends Error{entityType;action;callerLevel;requiredLevel;constructor(e){super(`${I$r[e.action]} \`${e.entityType}\` requires ${C$r[e.requiredLevel]} permission; your current permission is ${C$r[e.callerLevel]}.`);this.name="EntityActionPermissionError",this.entityType=e.entityType,this.action=e.action,this.callerLevel=e.callerLevel,this.requiredLevel=e.requiredLevel}}});class rwe{templateRegistry;static createFresh(e){return new rwe(e)}constructor(e){this.templateRegistry=e}get(e){let t=this.templateRegistry.get(e);return t?fht(e,t):void 0}list(){return this.templateRegistry.getNames().map((e)=>this.get(e)).filter((e)=>e!==void 0)}validate(e,t){let n=this.templateRegistry.get(e);if(!n||!mI.canRender(n))return!1;try{return n.schema.parse(t),!0}catch{return!1}}findViewTemplate(e){return this.list().find((n)=>{if(e.name&&n.name!==e.name)return!1;if(e.pluginId&&n.pluginId!==e.pluginId)return!1;if(e.namePattern){if(!new RegExp(e.namePattern).test(n.name))return!1}return!0})}getRenderer(e,t){let n=this.get(e);if(!n)return;return n.renderers[t]}hasRenderer(e,t){return this.getRenderer(e,t)!==void 0}listFormats(e){let t=this.get(e);if(!t)return[];let n=[];if(t.renderers.web)n.push("web");if(t.renderers.image)n.push("image");if(t.renderers.pdf)n.push("pdf");if(t.renderers.epub)n.push("epub");return n}}function fht(e,t){if(!mI.canRender(t))return;let n=e.split(":"),r=n.length>=2&&n[0]?n[0]:"shell",i={name:e,schema:t.schema,description:t.description,pluginId:r,renderers:ewe(t)};if(t.layout.fullscreen)i.fullscreen=t.layout.fullscreen;if(t.runtimeScripts&&t.runtimeScripts.length>0)i.runtimeScripts=t.runtimeScripts;if(t.staticAssets&&Object.keys(t.staticAssets).length>0)i.staticAssets=t.staticAssets;return i}var T$r=E(()=>{dht();uht()});var B$r,fln,mht,R$r,D$r,P$r;var O$r=E(()=>{oe();B$r=u.enum(["site-content-preview","site-content-production"]),fln=u.enum(["web","image","pdf","epub"]),mht=u.custom((e)=>typeof e==="function"),R$r=u.object({name:u.string(),schema:u.unknown(),description:u.string().optional(),pluginId:u.string(),renderers:u.object({web:u.union([mht,u.string()]).optional(),image:u.union([mht,u.string()]).optional(),pdf:u.union([mht,u.string()]).optional(),epub:u.union([mht,u.string()]).optional()})}),D$r=u.object({enableContentGeneration:u.boolean().default(!1),outputDir:u.string(),workingDir:u.string().optional(),environment:u.enum(["preview","production"]).default("preview"),siteConfig:u.object({title:u.string(),description:u.string(),url:u.string().optional()}).optional()}),P$r=u.object({success:u.boolean(),routesBuilt:u.number(),errors:u.array(u.string()).optional(),warnings:u.array(u.string()).optional()})});var M$r={};fi(M$r,{BuildResultSchema:()=>P$r,EntityActionPermissionError:()=>pht,EntityActionRequiredLevelSchema:()=>o3,EntityActionSchema:()=>pln,InMemoryTemplateRegistry:()=>twe,OutputFormatSchema:()=>fln,PermissionService:()=>dh,RenderService:()=>rwe,SiteBuilderOptionsSchema:()=>D$r,SiteContentEntityTypeSchema:()=>B$r,TemplateCapabilities:()=>mI,TemplateSchema:()=>E$r,UserPermissionLevelSchema:()=>Mm,ViewTemplateSchema:()=>R$r,createTemplate:()=>Ln,createTypedComponent:()=>Pce,entityActionPolicyConfigSchema:()=>Mce,entityActionPolicyRuleSchema:()=>Oce,matchSpaceSelector:()=>eD,renderedLinkFields:()=>Sy,templateRenderers:()=>ewe,toViewTemplate:()=>fht,viewLinkFields:()=>aA});var Fm=E(()=>{uht();S$r();dht();_$r();uln();T$r();O$r()});import{createContext as O5a}from"react";var iwe;var mln=E(()=>{iwe=O5a(void 0)});import{useContext as M5a}from"react";function F5a(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").split(" ").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function F$r(e){let t=e;while(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodDefault)t=t.unwrap();return t}function j5a(e,t){let n=F5a(e),r=F$r(t);if(r instanceof u.ZodString||r instanceof u.ZodEnum||r instanceof u.ZodLiteral)return{key:e,label:n,type:"string"};if(r instanceof u.ZodNumber)return{key:e,label:n,type:"number"};if(r instanceof u.ZodObject)return{key:e,label:n,type:"object",children:hln(r)};if(r instanceof u.ZodArray){let i=F$r(r.element);if(i instanceof u.ZodObject)return{key:e,label:n,type:"array",itemType:"object",itemMappings:hln(i)};if(i instanceof u.ZodNumber)return{key:e,label:n,type:"array",itemType:"number"};return{key:e,label:n,type:"array",itemType:"string"}}throw Error(`Section field "${e}" has a schema type the markdown formatter cannot `+"derive headings for \u2014 use string/number/enum/object/array.")}function hln(e){return Object.entries(e.shape).map(([t,n])=>j5a(t,n))}function N5a(e,t){if(!t||Object.keys(t).length===0)return e;return function(r){let i=M5a(iwe)?.toLowerCase();return(Object.entries(t).find(([s])=>s.toLowerCase()===i)?.[1]??e)(r)}}function j$r(e,t,n={}){let r=t.schema;if(!(r instanceof u.ZodObject))throw Error(`Section "${e}" schema must be a zod object.`);let i=t.dataSource?n.dataSourceId?.(t.dataSource):void 0;if(t.dataSource&&!i)throw Error(`Section "${e}" reads data source "${t.dataSource}", which only a site registers`);let o=new Zu(r,{title:t.title,layout:"compact",mappings:hln(r)});return{name:e,description:t.description,schema:t.schema,formatter:o,requiredPermission:t.requiredPermission??"public",...i?{dataSourceId:i}:{},layout:{component:Pce(t.schema,N5a(t.component,t.components)),...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}}}}function hht(e,t={}){let n={};for(let[r,i]of Object.entries(e.sections))n[r]=j$r(r,i,t);return n}var N$r=E(()=>{uh();Fm();mln();oe()});function L$r(e){return OT.parse(Qf(e).fields)}async function owe(e){let n=(await e.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!n)throw Error("Site info not found \u2014 create a site-info entity");return L$r(n)}var L5a,OT;var z$r=E(()=>{lt();oe();tln();L5a=PT.omit({url:!0,analyticsScript:!0}),OT=L5a.extend({title:u.string().optional().describe("Optional site title override"),description:u.string().optional().describe("Optional site description override")})});function Fce(e,t={}){let n=q$r(e),r=q$r(t.sharedDomain??"rizom.ai").replace(/^\./,""),i=`.${r}`;if(n.endsWith(i)){let o=n.slice(0,-i.length);if(o.length>0&&!o.includes("."))return`${o}-preview.${r}`}return`preview.${n}`}function q$r(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class MT{entityDisplay;constructor(e){this.entityDisplay=e}hasRoute(e){return this.entityDisplay?.[e]!==void 0}isCitable(e){if(this.entityDisplay?.[e]?.citable===!1)return!1;if(!Object.values(this.entityDisplay??{}).some((n)=>n.citable===!0))return this.hasRoute(e);return this.entityDisplay?.[e]?.citable===!0}generateUrl(e,t){let n=this.entityDisplay?.[e];if(n)return`/${n.pluralName??n.label.toLowerCase()+"s"}/${t}`;return`/${t3(e)}/${t}`}}var U$r=E(()=>{or()});function z5a(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,i]of Object.entries(t))n[r]={...e[r]??{},...i};return n}function $$r(e){if(!e)return[];return Array.isArray(e)?e:[e]}function q5a(e,t){let n=[...$$r(e),...$$r(t)];return n.length>0?n:void 0}function U5a(e,t){if(!t||t.length===0)return e;let n=[...e],r=new Map;for(let[i,o]of n.entries())r.set(o.id,i);for(let i of t){let o=r.get(i.id);if(o!==void 0){n[o]=i;continue}r.set(i.id,n.length),n.push(i)}return n}function _J(e,t={}){if(Object.keys(t).length===0&&oj(t)===void 0)return e;let{layouts:n,entityDisplay:r,staticAssets:i,themeOverride:o,headScripts:s}=t,a=n?{...e.layouts,...n}:e.layouts,c=r?{...e.entityDisplay,...Object.fromEntries(Object.entries(r).map(([w,S])=>[w,{...e.entityDisplay[w],...S}]))}:e.entityDisplay,l=i?{...e.staticAssets??{},...i}:e.staticAssets,d=[e.themeOverride,o].filter(Boolean).join(`
|
|
297
297
|
|
|
298
|
-
`),p=s??e.headScripts??[],f=z5a(e.content,t.content),m=q5a(e.sections,t.sections),h=t.languages??e.languages,g=[...e.dataSources??[],...t.dataSources??[]],
|
|
298
|
+
`),p=s??e.headScripts??[],f=z5a(e.content,t.content),m=q5a(e.sections,t.sections),h=t.languages??e.languages,g=t.layoutCopy??e.layoutCopy,x=[...e.dataSources??[],...t.dataSources??[]],y={layouts:a,routes:U5a(e.routes,t.routes),entityDisplay:c,...f?{content:f}:{},...m?{sections:m}:{},...d?{themeOverride:d}:{},...p.length>0?{headScripts:p}:{},...h?{languages:h}:{},...g?{layoutCopy:g}:{},...x.length>0?{dataSources:x}:{},...l&&Object.keys(l).length>0?{staticAssets:l}:{}},v=oj(t)??oj(e);return v===void 0?y:XAe(y,v)}var ght,gln;var H$r=E(()=>{oe();l7e();lln();ght=u.string(),gln=u.custom((e)=>ei(e)&&VUr.safeParse(e).success)});function $5a(e){return`<![CDATA[${e.replaceAll("]]>","]]]]><![CDATA[>")}]]>`}function G$r(e){return new Date(e).toUTCString()}function H5a(e,t){let n=e.category?`
|
|
299
299
|
<category>${Ef(e.category)}</category>`:"";return` <item>
|
|
300
300
|
<title>${Ef(e.title)}</title>
|
|
301
301
|
<link>${Ef(t)}</link>
|
|
@@ -1170,7 +1170,7 @@ ${i}
|
|
|
1170
1170
|
`}hr(){return Uc.gray("\u2500".repeat(50))+`
|
|
1171
1171
|
`}br(){return`
|
|
1172
1172
|
`}strong({tokens:e}){return Uc.bold(this.parser.parseInline(e))}em({tokens:e}){return Uc.italic(this.parser.parseInline(e))}codespan({text:e}){return Uc.bgGray.white(` ${e} `)}link({href:e,tokens:t}){let n=this.parser.parseInline(t);return Uc.blue.underline(n)+Uc.gray(` (${e})`)}image({text:e}){return`[${e}]`}text({text:e}){return e}}});import{useMemo as x8i}from"react";import{jsx as kde,jsxs as l1n}from"react/jsx-runtime";function y8i({messages:e,height:t,scrollOffset:n=0}){let r=new c1n,{stdout:i}=EX(),o=i.rows||24,s=t??Math.max(o-4,10),a=x8i(()=>{let p=[];return e.forEach((f,m)=>{let h=f.role==="user"?"You":f.role==="assistant"?"Brain":f.role==="error"?"Error":"System",g=f.timestamp.toLocaleTimeString();p.push({messageIndex:m,content:`${h} \u2022 ${g}`,isHeader:!0}),r.render(f.content).split(`
|
|
1173
|
-
`).filter((v)=>v.trim().length>0).forEach((v)=>{p.push({messageIndex:m,content:v,isHeader:!1})}),p.push({messageIndex:m,content:"",isHeader:!1})}),p},[e,r]),c=x8i(()=>{if(a.length===0)return[];let p=Math.max(1,s-2),f=a.length-n,m=Math.max(0,f-p);return a.slice(m,f)},[a,s,n]),l=n+c.length<a.length,d=n>0;return l1n(Go,{flexDirection:"column",overflow:"visible",children:[l&&kde(Go,{justifyContent:"center",children:l1n(bo,{dimColor:!0,italic:!0,children:["\u2191 ",a.length-(n+c.length)," more lines (Shift+\u2191 or PgUp to scroll)"]})}),c.map((p,f)=>{let m=e[p.messageIndex];if(p.isHeader&&m)return kde(Go,{marginBottom:0,children:kde(bo,{bold:!0,color:m.role==="user"?"blue":m.role==="assistant"?"green":m.role==="error"?"red":"gray",children:p.content})},f);else return kde(Go,{paddingLeft:p.content.trim()?2:0,children:kde(bo,{children:p.content})},f)}),d&&kde(Go,{justifyContent:"center",marginTop:1,children:l1n(bo,{dimColor:!0,italic:!0,children:["\u2193 ",n," more lines (Shift+\u2193 or PgDn to scroll)"]})}),kde(Rqe,{})]})}var b8i=E(async()=>{g8i();await tO()});import lIc,{useState as uIc,useEffect as dIc}from"react";function pIc({value:e,placeholder:t="",focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:o=!0,onChange:s,onSubmit:a}){let[c,l]=uIc({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:d,cursorWidth:p}=c;dIc(()=>{l((x)=>{if(!n||!o)return x;let y=e||"";if(x.cursorOffset>y.length-1)return{cursorOffset:y.length,cursorWidth:0};return x})},[e,n,o]);let f=i?p:0,m=r?r.repeat(e.length):e,h=m,g=t?Uc.grey(t):void 0;if(o&&n){g=t.length>0?Uc.inverse(t[0])+Uc.grey(t.slice(1)):Uc.inverse(" "),h=m.length>0?"":Uc.inverse(" ");let x=0;for(let y of m)h+=x>=d-f&&x<=d?Uc.inverse(y):y,x++;if(m.length>0&&d===m.length)h+=Uc.inverse(" ")}return wX((x,y)=>{if(y.upArrow||y.downArrow||y.ctrl&&x==="c"||y.tab||y.shift&&y.tab)return;if(y.return){if(a)a(e);return}let v=d,w=e,S=0;if(y.leftArrow){if(o)v--}else if(y.rightArrow){if(o)v++}else if(y.backspace||y.delete){if(d>0)w=e.slice(0,d-1)+e.slice(d,e.length),v--}else if(w=e.slice(0,d)+x+e.slice(d,e.length),v+=x.length,x.length>1)S=x.length;if(d<0)v=0;if(d>e.length)v=e.length;if(l({cursorOffset:v,cursorWidth:S}),w!==e)s(w)},{isActive:n}),lIc.createElement(bo,null,t?m.length>0?h:g:h)}var v8i;var A8i=E(async()=>{F1e();await tO();v8i=pIc});import{useState as w8i,useCallback as E8i}from"react";import{jsx as u1n,jsxs as S8i}from"react/jsx-runtime";function k8i({onSubmit:e,placeholder:t="Type a message or /help for commands...",isLoading:n=!1,history:r}){let[i,o]=w8i(""),[s,a]=w8i();wX((d,p)=>{if(n)return;if(p.upArrow){let f=r.previous();if(f!==void 0)o(f),a(f)}else if(p.downArrow){let f=r.next();if(f!==void 0)o(f),a(f)}});let c=E8i((d)=>{if(d.trim())r.add(d),e(d),o(""),a(void 0)},[e,r]),l=E8i((d)=>{if(o(d),s!==void 0&&d!==s)a(void 0)},[s]);if(n)return u1n(Go,{children:u1n(bo,{color:"gray",children:"Processing..."})});return S8i(Go,{children:[S8i(bo,{bold:!0,color:"green",children:["\u276F"," "]}),u1n(v8i,{value:i,onChange:l,onSubmit:c,placeholder:t})]})}var C8i=E(async()=>{await A6([tO(),A8i()])});import{jsx as I8i,jsxs as NSt}from"react/jsx-runtime";function yN({current:e,total:t,message:n,width:r=30,showPercentage:i=!0,showCounts:o=!0,barCompleteChar:s="\u2588",barIncompleteChar:a="\u2591",color:c="green"}){let l=Math.max(1,t||1),d=Math.max(0,e||0),p=Math.min(1,d/l),f=Math.round(p*100),m=Math.round(p*r),h=r-m,g=s.repeat(Math.max(0,m)),x=a.repeat(Math.max(0,h));return NSt(Go,{children:[n&&NSt(bo,{color:"gray",children:[n," "]}),I8i(bo,{color:c,children:g}),I8i(bo,{color:"gray",children:x}),o&&NSt(bo,{color:"gray",children:[" ",e,"/",t]}),i&&NSt(bo,{color:f===100?"green":"yellow",children:[" ",f,"%"]})]})}var jqe=E(async()=>{await tO()});import{useState as fIc,useEffect as _8i,useRef as T8i}from"react";import{jsx as s8,jsxs as LSt}from"react/jsx-runtime";function B8i({messageCount:e,isConnected:t,progressEvents:n}){let[i,o]=fIc([]),s=T8i(new Map),a=T8i(new Map);_8i(()=>()=>{a.current.forEach((p)=>clearTimeout(p)),a.current.clear()},[]),_8i(()=>{let p=Date.now(),f=new Map(n.map((m)=>[m.id,m]));return n.forEach((m)=>{if(!s.current.has(m.id))s.current.set(m.id,p)}),o((m)=>{let h=new Map(m.map((x)=>[x.id,x])),g=[];return m.forEach((x)=>{let y=f.get(x.id);if(y)g.push(y);else if(!a.current.has(x.id)){let v=p-(s.current.get(x.id)??p),w=Math.max(0,400-v),S=setTimeout(()=>{o((k)=>k.filter((C)=>C.id!==x.id)),s.current.delete(x.id),a.current.delete(x.id)},w);a.current.set(x.id,S),g.push(x)}else g.push(x)}),n.forEach((x)=>{if(!h.has(x.id))g.push(x)}),g}),()=>{}},[n]);let c=i.filter((p)=>p.type==="batch"),l=i.filter((p)=>p.type==="job"),d=c[0]??l[0];return s8(Go,{width:"100%",children:LSt(Go,{justifyContent:"space-between",width:"100%",children:[LSt(Go,{children:[s8(Go,{marginRight:1,children:s8(bo,{color:t?"green":"red",bold:!0,children:"\u25CF"})}),s8(bo,{color:t?"green":"red",children:t?"Connected":"Disconnected"}),s8(bo,{color:"gray",children:" \u2502 "}),s8(bo,{color:"gray",children:"Messages: "}),s8(bo,{color:"yellow",children:e})]}),s8(Go,{children:d?LSt(Go,{children:[LSt(bo,{color:"cyan",children:[d.metadata.operationType,d.metadata.operationTarget?`: ${d.metadata.operationTarget}`:""]}),s8(bo,{color:"gray",children:" "}),d.type==="batch"&&d.batchDetails?s8(yN,{current:d.batchDetails.completedOperations,total:d.batchDetails.totalOperations,width:30,color:"cyan",showPercentage:!0,showCounts:!1}):d.progress?s8(yN,{current:d.progress.current,total:d.progress.total,width:30,color:"cyan",showPercentage:!0,showCounts:!1}):s8(bo,{color:"gray",children:" Active"})]}):s8(bo,{color:"gray",dimColor:!0,children:"Ready"})})]})})}var R8i=E(async()=>{await A6([tO(),jqe()])});import{useMemo as mIc}from"react";import{jsx as iO,jsxs as GI,Fragment as D8i}from"react/jsx-runtime";function P8i({progressEvents:e,maxLines:t=5}){let{batchEvents:n,jobEvents:r}=mIc(()=>{let l=new Map;e.forEach((m)=>{l.set(m.id,m)});let d=Array.from(l.values()),p=d.filter((m)=>m.type==="batch"),f=d.filter((m)=>m.type==="job");return{batchEvents:p,jobEvents:f}},[e]),i=n.length+r.length,o=Math.min(t,i),s=[],a=n.slice(0,o);s.push(...a);let c=o-a.length;if(c>0){let l=r.slice(0,c);s.push(...l)}if(s.length===0)return iO(Go,{flexDirection:"column",children:iO(bo,{color:"gray",dimColor:!0,children:"No active operations"})});return GI(Go,{flexDirection:"column",children:[s.map((l)=>{if(l.type==="batch")return GI(Go,{flexDirection:"column",marginBottom:1,children:[GI(Go,{justifyContent:"space-between",children:[iO(Go,{children:GI(bo,{bold:!0,color:"cyan",children:["\u25B6 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),GI(Go,{children:[GI(bo,{color:"gray",dimColor:!0,children:[l.batchDetails?.completedOperations,"/",l.batchDetails?.totalOperations," ops"]}),l.progress&&GI(D8i,{children:[iO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})]})]}),l.batchDetails&&l.batchDetails.totalOperations>0&&iO(Go,{marginLeft:2,children:iO(yN,{current:l.batchDetails.completedOperations,total:l.batchDetails.totalOperations,width:40,color:"cyan",showPercentage:!0,showCounts:!1})})]},`batch-${l.id}`);else return GI(Go,{flexDirection:"column",marginBottom:1,children:[GI(Go,{justifyContent:"space-between",children:[iO(Go,{children:GI(bo,{color:"blue",children:["\u2022 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),iO(Go,{children:l.progress&&GI(D8i,{children:[GI(bo,{color:"gray",children:[l.progress.current,"/",l.progress.total]}),iO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})})]}),l.progress&&l.progress.total>0&&iO(Go,{marginLeft:2,children:iO(yN,{current:l.progress.current,total:l.progress.total,width:40,color:"blue",showPercentage:!0,showCounts:!1})})]},`job-${l.id}`)}),i>t&&GI(bo,{color:"gray",dimColor:!0,children:["...and ",i-t," more"]})]})}var O8i=E(async()=>{await A6([tO(),jqe()])});class d1n{history=[];index=-1;maxSize=1000;add(e){if(!e.trim()||e===this.history[this.history.length-1])return;if(this.history.push(e),this.history.length>this.maxSize)this.history.shift();this.index=this.history.length}previous(){if(this.index>0)return this.index--,this.history[this.index];return this.history[0]}next(){if(this.index<this.history.length-1)return this.index++,this.history[this.index];if(this.index===this.history.length-1)return this.index=this.history.length,"";return}getAll(){return[...this.history]}clear(){this.history=[],this.index=-1}search(e){return this.history.filter((t)=>t.toLowerCase().includes(e.toLowerCase()))}}var L8i={};fi(L8i,{default:()=>N8i});import{useState as H1e,useCallback as M8i,useEffect as F8i,useMemo as hIc}from"react";import{jsx as a8,jsxs as j8i}from"react/jsx-runtime";function N8i({interface:e,registerProgressCallback:t,unregisterProgressCallback:n,registerResponseCallback:r,registerSystemMessageCallback:i,unregisterMessageCallbacks:o}){let[s,a]=H1e([{role:"system",content:"Welcome to Brain CLI! Ask me anything or tell me what you'd like to do.",timestamp:new Date}]),[c,l]=H1e(!1),[d,p]=H1e(!0),[f,m]=H1e([]),[h,g]=H1e(!1),[x,y]=H1e(0),{exit:v}=TSt(),{stdout:w}=EX(),S=hIc(()=>new d1n,[]);F8i(()=>{let P=(H)=>{a((z)=>[...z,{role:"assistant",content:H,timestamp:new Date}]),l(!1),y(0)},L=(H)=>{a((z)=>{let D={role:"assistant",kind:"job-update",content:H,timestamp:new Date};return z[z.length-1]?.kind==="job-update"?[...z.slice(0,-1),D]:[...z,D]}),y(0)};return r(P),i(L),()=>{o()}},[r,i,o]);let k=M8i((P)=>{m(P)},[]);F8i(()=>(t(k),()=>{n()}),[t,n,k]);let C=M8i(async(P)=>{if(!P.trim())return;if(a((L)=>[...L,{role:"user",content:P,timestamp:new Date}]),P==="/exit"||P==="/quit"){v();return}if(P==="/clear"){a([{role:"system",content:"Screen cleared.",timestamp:new Date}]);return}if(P==="/progress"){g(!h),a((L)=>[...L,{role:"system",content:h?"Progress details hidden.":"Showing detailed progress.",timestamp:new Date}]);return}l(!0),p(!0),await e.processInput(P)},[e,v,h]);wX((P,L)=>{if(L.ctrl&&P==="c")v();if(L.ctrl&&P==="l")a([{role:"system",content:"Screen cleared.",timestamp:new Date}]),y(0);if(L.ctrl&&P==="p")g(!h);if(L.upArrow&&L.shift)y((H)=>H+1);if(L.downArrow&&L.shift)y((H)=>Math.max(H-1,0));if(L.pageUp)y((H)=>H+10);if(L.pageDown)y((H)=>Math.max(H-10,0))});let I=w.rows||24,B=h&&f.length>0?Math.min(f.length*3+2,12):0,R=Math.max(I-5-B,10);return j8i(Go,{flexDirection:"column",height:I,children:[a8(Go,{flexGrow:1,height:R,overflow:"hidden",children:a8(y8i,{messages:s,height:R,scrollOffset:x})}),h&&f.length>0&&a8(Go,{flexShrink:0,marginTop:1,marginBottom:1,children:a8(P8i,{progressEvents:f,maxLines:4})}),a8(Go,{flexShrink:0,marginTop:1,children:c?j8i(Go,{children:[a8(bo,{color:"green",children:a8(RSt,{type:"dots"})}),a8(bo,{color:"gray",children:" Processing..."})]}):a8(k8i,{onSubmit:C,isLoading:c,history:S})}),a8(Go,{flexShrink:0,marginTop:1,children:a8(B8i,{messageCount:s.length,isConnected:d,progressEvents:f})}),f.length>0&&!h&&a8(Go,{position:"absolute",marginLeft:2,marginTop:I-2,children:a8(bo,{color:"gray",dimColor:!0,children:"Press Ctrl+P or type /progress to show detailed progress"})})]})}var z8i=E(async()=>{await A6([tO(),QSn(),b8i(),C8i(),R8i(),O8i()])});var gIc,xIc,yIc,q8i;var U8i=E(()=>{_a();QH();nEn();XIi();gIc=uk({id:"cli",config:kEt,setup:(e)=>(If(e).logger.debug("CLI interface registered with AgentService"),JIi())}),xIc=NT(gIc,(e)=>{let{state:t}=e,n=If(e),{logger:r,messages:i}=n,o=YIi(n,t),s=()=>{t.responseCallback=void 0,t.systemMessageCallback=void 0},a=()=>{if(i.unregisterProgressCallback(),s(),t.removeSignalHandlers?.(),t.removeSignalHandlers=void 0,t.inkApp)t.inkApp.unmount(),t.inkApp=null};return{id:"cli",start:async()=>{r.debug("Starting CLI interface");try{let[c,l,d]=await Promise.all([tO().then(() => ZRi),import("react"),z8i().then(() => L8i)]),f=l.default.createElement(d.default,{interface:o,registerProgressCallback:(m)=>{i.registerProgressCallback(m)},unregisterProgressCallback:()=>{i.unregisterProgressCallback()},registerResponseCallback:(m)=>{t.responseCallback=m},registerSystemMessageCallback:(m)=>{t.systemMessageCallback=m},unregisterMessageCallbacks:s});t.inkApp=c.render(f),t.removeSignalHandlers=Gze(["SIGINT","SIGTERM"],()=>{r.debug("Received termination signal, stopping CLI"),a()})}catch(c){throw r.error("Failed to start CLI interface",{error:c}),c}},stop:async()=>{r.debug("Stopping CLI interface"),a()},healthCheck:async()=>{let c=t.inkApp!==null;return{status:c?"healthy":"error",message:c?"CLI interface is running":"CLI interface not running",lastCheck:new Date,details:{hasInkApp:t.inkApp!==null,hasCallbacks:i.hasProgressCallback()}}}}}),yIc=QJ(xIc,({state:e})=>({send:({message:t})=>{let n=typeof t==="string"?t:t.fallbackText??"";if(!n)return;(e.systemMessageCallback??e.responseCallback)?.(n)}})),q8i=yIc});import{jsx as ZI,jsxs as FD}from"react/jsx-runtime";function $8i({batchStatus:e,showDetails:t=!0}){let{batchId:n,totalOperations:r,completedOperations:i,failedOperations:o,currentOperation:s,errors:a,status:c}=e,l=c==="processing",d=c==="completed",p=c==="failed",f=i-o;return FD(Go,{flexDirection:"column",marginY:1,children:[ZI(Go,{marginBottom:1,children:FD(bo,{bold:!0,color:"cyan",children:["Batch Operation: ",n.slice(0,8),"..."]})}),ZI(Go,{marginBottom:1,children:ZI(yN,{current:i,total:r,message:"Overall Progress:",color:p?"red":d?"green":"yellow"})}),l&&s&&FD(Go,{marginBottom:1,children:[ZI(bo,{color:"green",children:ZI(RSt,{type:"dots"})}),FD(bo,{color:"gray",children:[" ",s]})]}),t&&FD(Go,{flexDirection:"column",marginLeft:2,children:[f>0&&FD(Go,{children:[ZI(bo,{color:"green",children:"\u2713 "}),FD(bo,{color:"gray",children:[f," successful"]})]}),o>0&&FD(Go,{children:[ZI(bo,{color:"red",children:"\u2717 "}),FD(bo,{color:"gray",children:[o," failed"]})]}),a.length>0&&FD(Go,{flexDirection:"column",marginTop:1,children:[ZI(bo,{color:"red",bold:!0,children:"Errors:"}),a.slice(0,3).map((m,h)=>FD(Go,{marginLeft:2,children:[ZI(bo,{color:"red",children:"\u2022 "}),ZI(bo,{color:"gray",children:m})]},h)),a.length>3&&ZI(Go,{marginLeft:2,children:FD(bo,{color:"gray",children:["... and ",a.length-3," more"]})})]})]}),d&&ZI(Go,{marginTop:1,children:ZI(bo,{color:"green",bold:!0,children:"\u2713 Batch completed successfully"})}),p&&ZI(Go,{marginTop:1,children:ZI(bo,{color:"red",bold:!0,children:"\u2717 Batch failed"})})]})}var H8i=E(async()=>{await A6([tO(),QSn(),jqe()])});var G8i={};fi(G8i,{BatchProgress:()=>$8i,ProgressBar:()=>yN,cliConfigSchema:()=>kEt,default:()=>q8i});var Z8i=E(async()=>{U8i();nEn();await A6([jqe(),H8i()])});var W8i=j(function(xIf,bIc){bIc.exports={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.873",dependencies:{"@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"},devDependencies:{"@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"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});async function V8i(e){let[{default:t},{default:n}]=await Promise.all([Z8i().then(() => G8i),Promise.resolve().then(() => yn(W8i(),1))]);return lA(t,e??{},{name:n.name,version:n.version},{pluginId:"cli"})}var K8i=E(()=>{Ki()});function Cde(e="admin"){return{interfaceType:"cli",actor:Nqe,userPermissionLevel:e}}var Nqe,Lqe;var zSt=E(()=>{Nqe={kind:"service",serviceId:"brain-cli"},Lqe=`${Nqe.kind}:${Nqe.serviceId}`});var vIc,zqe,qqe;var qSt=E(()=>{oe();lt();vIc=u.enum(["eval"]),zqe=u.enum(["person","team","organization"]),qqe=u.object({provider:u.enum(["hetzner","docker"]).default("hetzner"),serverSize:u.string().default("cx33"),location:u.string().default("fsn1"),domain:u.string().optional(),docker:u.object({enabled:u.boolean().default(!0),image:u.string().optional()}).prefault({}),ports:u.object({default:u.number().default(3333),preview:u.number().default(4321),production:u.number().default(8080)}).prefault({}),cdn:u.object({enabled:u.boolean().default(!1),provider:u.enum(["bunny","none"]).default("none")}).prefault({}),dns:u.object({enabled:u.boolean().default(!1),provider:u.enum(["bunny","none"]).default("none")}).prefault({}),paths:u.object({install:u.string().optional(),data:u.string().optional()}).prefault({})})});var p1n,USt;var G1e=E(()=>{oe();Ki();cde();cde();qSt();qSt();p1n=u.object({providerKeys:cEe.optional(),model:u.string().optional(),embeddingModel:u.string().optional(),modelRuntimeUrl:u.string().optional(),answerModel:u.string().optional(),visionModel:u.string().optional(),imageModel:u.string().optional(),reasoningEffort:rR.optional()}),USt=u.object({name:u.string().default("brain-app"),version:u.string().default("1.0.0"),database:u.string().optional(),ai:p1n.optional(),logLevel:pk.optional(),logFile:u.string().optional(),profileKind:u.string().trim().min(1).optional(),plugins:u.array(VLe).default([]),spaces:u.array(u.string()).default([]),identity:G7e.optional(),agentInstructions:u.array(u.string()).optional(),deployment:qqe.prefault({}),http:aX.prefault({})})});function wIc(){return process.env[AIc]}function f1n(){return wIc()==="production"}function Q8i(){return!f1n()}var AIc="NODE_ENV";function SIc(){return Object.fromEntries(AI.map((e)=>[e,EIc]))}function J8i(e){let n={...USt.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function $St(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return kIc(n),CIc(e,n),IIc(e,n,t),_Ic(e,n),TIc(e,n),BIc(e,n),RIc(e,n),DIc(e,n),OIc(e,n),PIc(e,n),n}function kIc(e){let t=wEt();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=KIi(),e.gitBrokerCheckout??=VIi()}function CIc(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function IIc(e,t,n){let r=n?.mode==="startup-check",{providerKeys:i,...o}=Ar(e.ai??{});if(!i&&Object.keys(o).length===0&&!r)return;t.ai={...t.ai,providerKeys:{...r&&SIc(),...t.ai?.providerKeys,...i},...o}}function _Ic(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function TIc(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((r)=>r.pattern===Lqe)?n:[{pattern:Lqe,level:"admin"},...n]}}function BIc(e,t){if(e.spaces)t.spaces=e.spaces}function RIc(e,t){if(e.identity)t.identity=e.identity}function DIc(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function PIc(e,t){t.http??={...Ar(e.http),port:e.deployment.ports.production}}function OIc(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=Q8i(),t.production=f1n()}var EIc="startup-check";var m1n=E(()=>{cde();zSt();G1e();SEt()});var Y8i={};fi(Y8i,{App:()=>Z1e});class Z1e{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(e,t){return new Z1e(J8i(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=ja.getInstance();await new Hze(e).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(e,t){this.shell=$ze.createFresh($St(this.config,e),void 0,{...t?.processRole&&{processRole:t.processRole},...t?.peerChannel&&{peerChannel:t.peerChannel}})}wantsCLI(e){return this.hasCLI||e?.cli===!0}async registerCLIInterface(e){if(!this.wantsCLI(e))return;let t=this.getShell().getPluginManager();for(let n of await V8i(this.config.cliConfig))t.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(e,t)}if(await this.registerCLIInterface(t),this.stopPromise)return;await this.getShell().initialize(e)}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(e){let n={debug:_m.DEBUG,info:_m.INFO,warn:_m.WARN,error:_m.ERROR}[this.config.logLevel??"info"]??_m.INFO,r=this.wantsCLI(e),i=ja.createFresh({level:n,context:this.config.name,useStderr:r});if(r)ja.getInstance().setUseStderr(!0);i.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,e),this.stopPromise)return;await this.start(),e?.onRuntimeReady?.(),i.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(o){i.error(`\u274C Failed to start ${this.config.name}:`,o),process.exit(1)}}static async run(e,t,n){await Z1e.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=Ne.runSync(ti.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},r=Gze(["SIGINT"],t),i=Gze(["SIGTERM"],n);Ne.runSync(ti.addFinalizer(e,Ne.sync(()=>{i(),r()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=ja.getInstance();t.info(`
|
|
1173
|
+
`).filter((v)=>v.trim().length>0).forEach((v)=>{p.push({messageIndex:m,content:v,isHeader:!1})}),p.push({messageIndex:m,content:"",isHeader:!1})}),p},[e,r]),c=x8i(()=>{if(a.length===0)return[];let p=Math.max(1,s-2),f=a.length-n,m=Math.max(0,f-p);return a.slice(m,f)},[a,s,n]),l=n+c.length<a.length,d=n>0;return l1n(Go,{flexDirection:"column",overflow:"visible",children:[l&&kde(Go,{justifyContent:"center",children:l1n(bo,{dimColor:!0,italic:!0,children:["\u2191 ",a.length-(n+c.length)," more lines (Shift+\u2191 or PgUp to scroll)"]})}),c.map((p,f)=>{let m=e[p.messageIndex];if(p.isHeader&&m)return kde(Go,{marginBottom:0,children:kde(bo,{bold:!0,color:m.role==="user"?"blue":m.role==="assistant"?"green":m.role==="error"?"red":"gray",children:p.content})},f);else return kde(Go,{paddingLeft:p.content.trim()?2:0,children:kde(bo,{children:p.content})},f)}),d&&kde(Go,{justifyContent:"center",marginTop:1,children:l1n(bo,{dimColor:!0,italic:!0,children:["\u2193 ",n," more lines (Shift+\u2193 or PgDn to scroll)"]})}),kde(Rqe,{})]})}var b8i=E(async()=>{g8i();await tO()});import lIc,{useState as uIc,useEffect as dIc}from"react";function pIc({value:e,placeholder:t="",focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:o=!0,onChange:s,onSubmit:a}){let[c,l]=uIc({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:d,cursorWidth:p}=c;dIc(()=>{l((x)=>{if(!n||!o)return x;let y=e||"";if(x.cursorOffset>y.length-1)return{cursorOffset:y.length,cursorWidth:0};return x})},[e,n,o]);let f=i?p:0,m=r?r.repeat(e.length):e,h=m,g=t?Uc.grey(t):void 0;if(o&&n){g=t.length>0?Uc.inverse(t[0])+Uc.grey(t.slice(1)):Uc.inverse(" "),h=m.length>0?"":Uc.inverse(" ");let x=0;for(let y of m)h+=x>=d-f&&x<=d?Uc.inverse(y):y,x++;if(m.length>0&&d===m.length)h+=Uc.inverse(" ")}return wX((x,y)=>{if(y.upArrow||y.downArrow||y.ctrl&&x==="c"||y.tab||y.shift&&y.tab)return;if(y.return){if(a)a(e);return}let v=d,w=e,S=0;if(y.leftArrow){if(o)v--}else if(y.rightArrow){if(o)v++}else if(y.backspace||y.delete){if(d>0)w=e.slice(0,d-1)+e.slice(d,e.length),v--}else if(w=e.slice(0,d)+x+e.slice(d,e.length),v+=x.length,x.length>1)S=x.length;if(d<0)v=0;if(d>e.length)v=e.length;if(l({cursorOffset:v,cursorWidth:S}),w!==e)s(w)},{isActive:n}),lIc.createElement(bo,null,t?m.length>0?h:g:h)}var v8i;var A8i=E(async()=>{F1e();await tO();v8i=pIc});import{useState as w8i,useCallback as E8i}from"react";import{jsx as u1n,jsxs as S8i}from"react/jsx-runtime";function k8i({onSubmit:e,placeholder:t="Type a message or /help for commands...",isLoading:n=!1,history:r}){let[i,o]=w8i(""),[s,a]=w8i();wX((d,p)=>{if(n)return;if(p.upArrow){let f=r.previous();if(f!==void 0)o(f),a(f)}else if(p.downArrow){let f=r.next();if(f!==void 0)o(f),a(f)}});let c=E8i((d)=>{if(d.trim())r.add(d),e(d),o(""),a(void 0)},[e,r]),l=E8i((d)=>{if(o(d),s!==void 0&&d!==s)a(void 0)},[s]);if(n)return u1n(Go,{children:u1n(bo,{color:"gray",children:"Processing..."})});return S8i(Go,{children:[S8i(bo,{bold:!0,color:"green",children:["\u276F"," "]}),u1n(v8i,{value:i,onChange:l,onSubmit:c,placeholder:t})]})}var C8i=E(async()=>{await A6([tO(),A8i()])});import{jsx as I8i,jsxs as NSt}from"react/jsx-runtime";function yN({current:e,total:t,message:n,width:r=30,showPercentage:i=!0,showCounts:o=!0,barCompleteChar:s="\u2588",barIncompleteChar:a="\u2591",color:c="green"}){let l=Math.max(1,t||1),d=Math.max(0,e||0),p=Math.min(1,d/l),f=Math.round(p*100),m=Math.round(p*r),h=r-m,g=s.repeat(Math.max(0,m)),x=a.repeat(Math.max(0,h));return NSt(Go,{children:[n&&NSt(bo,{color:"gray",children:[n," "]}),I8i(bo,{color:c,children:g}),I8i(bo,{color:"gray",children:x}),o&&NSt(bo,{color:"gray",children:[" ",e,"/",t]}),i&&NSt(bo,{color:f===100?"green":"yellow",children:[" ",f,"%"]})]})}var jqe=E(async()=>{await tO()});import{useState as fIc,useEffect as _8i,useRef as T8i}from"react";import{jsx as s8,jsxs as LSt}from"react/jsx-runtime";function B8i({messageCount:e,isConnected:t,progressEvents:n}){let[i,o]=fIc([]),s=T8i(new Map),a=T8i(new Map);_8i(()=>()=>{a.current.forEach((p)=>clearTimeout(p)),a.current.clear()},[]),_8i(()=>{let p=Date.now(),f=new Map(n.map((m)=>[m.id,m]));return n.forEach((m)=>{if(!s.current.has(m.id))s.current.set(m.id,p)}),o((m)=>{let h=new Map(m.map((x)=>[x.id,x])),g=[];return m.forEach((x)=>{let y=f.get(x.id);if(y)g.push(y);else if(!a.current.has(x.id)){let v=p-(s.current.get(x.id)??p),w=Math.max(0,400-v),S=setTimeout(()=>{o((k)=>k.filter((C)=>C.id!==x.id)),s.current.delete(x.id),a.current.delete(x.id)},w);a.current.set(x.id,S),g.push(x)}else g.push(x)}),n.forEach((x)=>{if(!h.has(x.id))g.push(x)}),g}),()=>{}},[n]);let c=i.filter((p)=>p.type==="batch"),l=i.filter((p)=>p.type==="job"),d=c[0]??l[0];return s8(Go,{width:"100%",children:LSt(Go,{justifyContent:"space-between",width:"100%",children:[LSt(Go,{children:[s8(Go,{marginRight:1,children:s8(bo,{color:t?"green":"red",bold:!0,children:"\u25CF"})}),s8(bo,{color:t?"green":"red",children:t?"Connected":"Disconnected"}),s8(bo,{color:"gray",children:" \u2502 "}),s8(bo,{color:"gray",children:"Messages: "}),s8(bo,{color:"yellow",children:e})]}),s8(Go,{children:d?LSt(Go,{children:[LSt(bo,{color:"cyan",children:[d.metadata.operationType,d.metadata.operationTarget?`: ${d.metadata.operationTarget}`:""]}),s8(bo,{color:"gray",children:" "}),d.type==="batch"&&d.batchDetails?s8(yN,{current:d.batchDetails.completedOperations,total:d.batchDetails.totalOperations,width:30,color:"cyan",showPercentage:!0,showCounts:!1}):d.progress?s8(yN,{current:d.progress.current,total:d.progress.total,width:30,color:"cyan",showPercentage:!0,showCounts:!1}):s8(bo,{color:"gray",children:" Active"})]}):s8(bo,{color:"gray",dimColor:!0,children:"Ready"})})]})})}var R8i=E(async()=>{await A6([tO(),jqe()])});import{useMemo as mIc}from"react";import{jsx as iO,jsxs as GI,Fragment as D8i}from"react/jsx-runtime";function P8i({progressEvents:e,maxLines:t=5}){let{batchEvents:n,jobEvents:r}=mIc(()=>{let l=new Map;e.forEach((m)=>{l.set(m.id,m)});let d=Array.from(l.values()),p=d.filter((m)=>m.type==="batch"),f=d.filter((m)=>m.type==="job");return{batchEvents:p,jobEvents:f}},[e]),i=n.length+r.length,o=Math.min(t,i),s=[],a=n.slice(0,o);s.push(...a);let c=o-a.length;if(c>0){let l=r.slice(0,c);s.push(...l)}if(s.length===0)return iO(Go,{flexDirection:"column",children:iO(bo,{color:"gray",dimColor:!0,children:"No active operations"})});return GI(Go,{flexDirection:"column",children:[s.map((l)=>{if(l.type==="batch")return GI(Go,{flexDirection:"column",marginBottom:1,children:[GI(Go,{justifyContent:"space-between",children:[iO(Go,{children:GI(bo,{bold:!0,color:"cyan",children:["\u25B6 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),GI(Go,{children:[GI(bo,{color:"gray",dimColor:!0,children:[l.batchDetails?.completedOperations,"/",l.batchDetails?.totalOperations," ops"]}),l.progress&&GI(D8i,{children:[iO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})]})]}),l.batchDetails&&l.batchDetails.totalOperations>0&&iO(Go,{marginLeft:2,children:iO(yN,{current:l.batchDetails.completedOperations,total:l.batchDetails.totalOperations,width:40,color:"cyan",showPercentage:!0,showCounts:!1})})]},`batch-${l.id}`);else return GI(Go,{flexDirection:"column",marginBottom:1,children:[GI(Go,{justifyContent:"space-between",children:[iO(Go,{children:GI(bo,{color:"blue",children:["\u2022 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),iO(Go,{children:l.progress&&GI(D8i,{children:[GI(bo,{color:"gray",children:[l.progress.current,"/",l.progress.total]}),iO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})})]}),l.progress&&l.progress.total>0&&iO(Go,{marginLeft:2,children:iO(yN,{current:l.progress.current,total:l.progress.total,width:40,color:"blue",showPercentage:!0,showCounts:!1})})]},`job-${l.id}`)}),i>t&&GI(bo,{color:"gray",dimColor:!0,children:["...and ",i-t," more"]})]})}var O8i=E(async()=>{await A6([tO(),jqe()])});class d1n{history=[];index=-1;maxSize=1000;add(e){if(!e.trim()||e===this.history[this.history.length-1])return;if(this.history.push(e),this.history.length>this.maxSize)this.history.shift();this.index=this.history.length}previous(){if(this.index>0)return this.index--,this.history[this.index];return this.history[0]}next(){if(this.index<this.history.length-1)return this.index++,this.history[this.index];if(this.index===this.history.length-1)return this.index=this.history.length,"";return}getAll(){return[...this.history]}clear(){this.history=[],this.index=-1}search(e){return this.history.filter((t)=>t.toLowerCase().includes(e.toLowerCase()))}}var L8i={};fi(L8i,{default:()=>N8i});import{useState as H1e,useCallback as M8i,useEffect as F8i,useMemo as hIc}from"react";import{jsx as a8,jsxs as j8i}from"react/jsx-runtime";function N8i({interface:e,registerProgressCallback:t,unregisterProgressCallback:n,registerResponseCallback:r,registerSystemMessageCallback:i,unregisterMessageCallbacks:o}){let[s,a]=H1e([{role:"system",content:"Welcome to Brain CLI! Ask me anything or tell me what you'd like to do.",timestamp:new Date}]),[c,l]=H1e(!1),[d,p]=H1e(!0),[f,m]=H1e([]),[h,g]=H1e(!1),[x,y]=H1e(0),{exit:v}=TSt(),{stdout:w}=EX(),S=hIc(()=>new d1n,[]);F8i(()=>{let P=(H)=>{a((z)=>[...z,{role:"assistant",content:H,timestamp:new Date}]),l(!1),y(0)},L=(H)=>{a((z)=>{let D={role:"assistant",kind:"job-update",content:H,timestamp:new Date};return z[z.length-1]?.kind==="job-update"?[...z.slice(0,-1),D]:[...z,D]}),y(0)};return r(P),i(L),()=>{o()}},[r,i,o]);let k=M8i((P)=>{m(P)},[]);F8i(()=>(t(k),()=>{n()}),[t,n,k]);let C=M8i(async(P)=>{if(!P.trim())return;if(a((L)=>[...L,{role:"user",content:P,timestamp:new Date}]),P==="/exit"||P==="/quit"){v();return}if(P==="/clear"){a([{role:"system",content:"Screen cleared.",timestamp:new Date}]);return}if(P==="/progress"){g(!h),a((L)=>[...L,{role:"system",content:h?"Progress details hidden.":"Showing detailed progress.",timestamp:new Date}]);return}l(!0),p(!0),await e.processInput(P)},[e,v,h]);wX((P,L)=>{if(L.ctrl&&P==="c")v();if(L.ctrl&&P==="l")a([{role:"system",content:"Screen cleared.",timestamp:new Date}]),y(0);if(L.ctrl&&P==="p")g(!h);if(L.upArrow&&L.shift)y((H)=>H+1);if(L.downArrow&&L.shift)y((H)=>Math.max(H-1,0));if(L.pageUp)y((H)=>H+10);if(L.pageDown)y((H)=>Math.max(H-10,0))});let I=w.rows||24,B=h&&f.length>0?Math.min(f.length*3+2,12):0,R=Math.max(I-5-B,10);return j8i(Go,{flexDirection:"column",height:I,children:[a8(Go,{flexGrow:1,height:R,overflow:"hidden",children:a8(y8i,{messages:s,height:R,scrollOffset:x})}),h&&f.length>0&&a8(Go,{flexShrink:0,marginTop:1,marginBottom:1,children:a8(P8i,{progressEvents:f,maxLines:4})}),a8(Go,{flexShrink:0,marginTop:1,children:c?j8i(Go,{children:[a8(bo,{color:"green",children:a8(RSt,{type:"dots"})}),a8(bo,{color:"gray",children:" Processing..."})]}):a8(k8i,{onSubmit:C,isLoading:c,history:S})}),a8(Go,{flexShrink:0,marginTop:1,children:a8(B8i,{messageCount:s.length,isConnected:d,progressEvents:f})}),f.length>0&&!h&&a8(Go,{position:"absolute",marginLeft:2,marginTop:I-2,children:a8(bo,{color:"gray",dimColor:!0,children:"Press Ctrl+P or type /progress to show detailed progress"})})]})}var z8i=E(async()=>{await A6([tO(),QSn(),b8i(),C8i(),R8i(),O8i()])});var gIc,xIc,yIc,q8i;var U8i=E(()=>{_a();QH();nEn();XIi();gIc=uk({id:"cli",config:kEt,setup:(e)=>(If(e).logger.debug("CLI interface registered with AgentService"),JIi())}),xIc=NT(gIc,(e)=>{let{state:t}=e,n=If(e),{logger:r,messages:i}=n,o=YIi(n,t),s=()=>{t.responseCallback=void 0,t.systemMessageCallback=void 0},a=()=>{if(i.unregisterProgressCallback(),s(),t.removeSignalHandlers?.(),t.removeSignalHandlers=void 0,t.inkApp)t.inkApp.unmount(),t.inkApp=null};return{id:"cli",start:async()=>{r.debug("Starting CLI interface");try{let[c,l,d]=await Promise.all([tO().then(() => ZRi),import("react"),z8i().then(() => L8i)]),f=l.default.createElement(d.default,{interface:o,registerProgressCallback:(m)=>{i.registerProgressCallback(m)},unregisterProgressCallback:()=>{i.unregisterProgressCallback()},registerResponseCallback:(m)=>{t.responseCallback=m},registerSystemMessageCallback:(m)=>{t.systemMessageCallback=m},unregisterMessageCallbacks:s});t.inkApp=c.render(f),t.removeSignalHandlers=Gze(["SIGINT","SIGTERM"],()=>{r.debug("Received termination signal, stopping CLI"),a()})}catch(c){throw r.error("Failed to start CLI interface",{error:c}),c}},stop:async()=>{r.debug("Stopping CLI interface"),a()},healthCheck:async()=>{let c=t.inkApp!==null;return{status:c?"healthy":"error",message:c?"CLI interface is running":"CLI interface not running",lastCheck:new Date,details:{hasInkApp:t.inkApp!==null,hasCallbacks:i.hasProgressCallback()}}}}}),yIc=QJ(xIc,({state:e})=>({send:({message:t})=>{let n=typeof t==="string"?t:t.fallbackText??"";if(!n)return;(e.systemMessageCallback??e.responseCallback)?.(n)}})),q8i=yIc});import{jsx as ZI,jsxs as FD}from"react/jsx-runtime";function $8i({batchStatus:e,showDetails:t=!0}){let{batchId:n,totalOperations:r,completedOperations:i,failedOperations:o,currentOperation:s,errors:a,status:c}=e,l=c==="processing",d=c==="completed",p=c==="failed",f=i-o;return FD(Go,{flexDirection:"column",marginY:1,children:[ZI(Go,{marginBottom:1,children:FD(bo,{bold:!0,color:"cyan",children:["Batch Operation: ",n.slice(0,8),"..."]})}),ZI(Go,{marginBottom:1,children:ZI(yN,{current:i,total:r,message:"Overall Progress:",color:p?"red":d?"green":"yellow"})}),l&&s&&FD(Go,{marginBottom:1,children:[ZI(bo,{color:"green",children:ZI(RSt,{type:"dots"})}),FD(bo,{color:"gray",children:[" ",s]})]}),t&&FD(Go,{flexDirection:"column",marginLeft:2,children:[f>0&&FD(Go,{children:[ZI(bo,{color:"green",children:"\u2713 "}),FD(bo,{color:"gray",children:[f," successful"]})]}),o>0&&FD(Go,{children:[ZI(bo,{color:"red",children:"\u2717 "}),FD(bo,{color:"gray",children:[o," failed"]})]}),a.length>0&&FD(Go,{flexDirection:"column",marginTop:1,children:[ZI(bo,{color:"red",bold:!0,children:"Errors:"}),a.slice(0,3).map((m,h)=>FD(Go,{marginLeft:2,children:[ZI(bo,{color:"red",children:"\u2022 "}),ZI(bo,{color:"gray",children:m})]},h)),a.length>3&&ZI(Go,{marginLeft:2,children:FD(bo,{color:"gray",children:["... and ",a.length-3," more"]})})]})]}),d&&ZI(Go,{marginTop:1,children:ZI(bo,{color:"green",bold:!0,children:"\u2713 Batch completed successfully"})}),p&&ZI(Go,{marginTop:1,children:ZI(bo,{color:"red",bold:!0,children:"\u2717 Batch failed"})})]})}var H8i=E(async()=>{await A6([tO(),QSn(),jqe()])});var G8i={};fi(G8i,{BatchProgress:()=>$8i,ProgressBar:()=>yN,cliConfigSchema:()=>kEt,default:()=>q8i});var Z8i=E(async()=>{U8i();nEn();await A6([jqe(),H8i()])});var W8i=j(function(xIf,bIc){bIc.exports={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.875",dependencies:{"@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"},devDependencies:{"@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"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});async function V8i(e){let[{default:t},{default:n}]=await Promise.all([Z8i().then(() => G8i),Promise.resolve().then(() => yn(W8i(),1))]);return lA(t,e??{},{name:n.name,version:n.version},{pluginId:"cli"})}var K8i=E(()=>{Ki()});function Cde(e="admin"){return{interfaceType:"cli",actor:Nqe,userPermissionLevel:e}}var Nqe,Lqe;var zSt=E(()=>{Nqe={kind:"service",serviceId:"brain-cli"},Lqe=`${Nqe.kind}:${Nqe.serviceId}`});var vIc,zqe,qqe;var qSt=E(()=>{oe();lt();vIc=u.enum(["eval"]),zqe=u.enum(["person","team","organization"]),qqe=u.object({provider:u.enum(["hetzner","docker"]).default("hetzner"),serverSize:u.string().default("cx33"),location:u.string().default("fsn1"),domain:u.string().optional(),docker:u.object({enabled:u.boolean().default(!0),image:u.string().optional()}).prefault({}),ports:u.object({default:u.number().default(3333),preview:u.number().default(4321),production:u.number().default(8080)}).prefault({}),cdn:u.object({enabled:u.boolean().default(!1),provider:u.enum(["bunny","none"]).default("none")}).prefault({}),dns:u.object({enabled:u.boolean().default(!1),provider:u.enum(["bunny","none"]).default("none")}).prefault({}),paths:u.object({install:u.string().optional(),data:u.string().optional()}).prefault({})})});var p1n,USt;var G1e=E(()=>{oe();Ki();cde();cde();qSt();qSt();p1n=u.object({providerKeys:cEe.optional(),model:u.string().optional(),embeddingModel:u.string().optional(),modelRuntimeUrl:u.string().optional(),answerModel:u.string().optional(),visionModel:u.string().optional(),imageModel:u.string().optional(),reasoningEffort:rR.optional()}),USt=u.object({name:u.string().default("brain-app"),version:u.string().default("1.0.0"),database:u.string().optional(),ai:p1n.optional(),logLevel:pk.optional(),logFile:u.string().optional(),profileKind:u.string().trim().min(1).optional(),plugins:u.array(VLe).default([]),spaces:u.array(u.string()).default([]),identity:G7e.optional(),agentInstructions:u.array(u.string()).optional(),deployment:qqe.prefault({}),http:aX.prefault({})})});function wIc(){return process.env[AIc]}function f1n(){return wIc()==="production"}function Q8i(){return!f1n()}var AIc="NODE_ENV";function SIc(){return Object.fromEntries(AI.map((e)=>[e,EIc]))}function J8i(e){let n={...USt.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function $St(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return kIc(n),CIc(e,n),IIc(e,n,t),_Ic(e,n),TIc(e,n),BIc(e,n),RIc(e,n),DIc(e,n),OIc(e,n),PIc(e,n),n}function kIc(e){let t=wEt();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=KIi(),e.gitBrokerCheckout??=VIi()}function CIc(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function IIc(e,t,n){let r=n?.mode==="startup-check",{providerKeys:i,...o}=Ar(e.ai??{});if(!i&&Object.keys(o).length===0&&!r)return;t.ai={...t.ai,providerKeys:{...r&&SIc(),...t.ai?.providerKeys,...i},...o}}function _Ic(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function TIc(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((r)=>r.pattern===Lqe)?n:[{pattern:Lqe,level:"admin"},...n]}}function BIc(e,t){if(e.spaces)t.spaces=e.spaces}function RIc(e,t){if(e.identity)t.identity=e.identity}function DIc(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function PIc(e,t){t.http??={...Ar(e.http),port:e.deployment.ports.production}}function OIc(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=Q8i(),t.production=f1n()}var EIc="startup-check";var m1n=E(()=>{cde();zSt();G1e();SEt()});var Y8i={};fi(Y8i,{App:()=>Z1e});class Z1e{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(e,t){return new Z1e(J8i(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=ja.getInstance();await new Hze(e).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(e,t){this.shell=$ze.createFresh($St(this.config,e),void 0,{...t?.processRole&&{processRole:t.processRole},...t?.peerChannel&&{peerChannel:t.peerChannel}})}wantsCLI(e){return this.hasCLI||e?.cli===!0}async registerCLIInterface(e){if(!this.wantsCLI(e))return;let t=this.getShell().getPluginManager();for(let n of await V8i(this.config.cliConfig))t.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(e,t)}if(await this.registerCLIInterface(t),this.stopPromise)return;await this.getShell().initialize(e)}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(e){let n={debug:_m.DEBUG,info:_m.INFO,warn:_m.WARN,error:_m.ERROR}[this.config.logLevel??"info"]??_m.INFO,r=this.wantsCLI(e),i=ja.createFresh({level:n,context:this.config.name,useStderr:r});if(r)ja.getInstance().setUseStderr(!0);i.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,e),this.stopPromise)return;await this.start(),e?.onRuntimeReady?.(),i.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(o){i.error(`\u274C Failed to start ${this.config.name}:`,o),process.exit(1)}}static async run(e,t,n){await Z1e.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=Ne.runSync(ti.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},r=Gze(["SIGINT"],t),i=Gze(["SIGTERM"],n);Ne.runSync(ti.addFinalizer(e,Ne.sync(()=>{i(),r()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=ja.getInstance();t.info(`
|
|
1174
1174
|
Received ${e}, shutting down gracefully...`);let n=Ne.tryPromise({try:()=>this.stop(),catch:(r)=>r}).pipe(Ne.match({onFailure:(r)=>{t.error("Error during shutdown:",r),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=Ne.runFork(n)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await Ne.runPromise(ti.close(e,mi.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}var h1n=E(()=>{cde();ly();tEn();K8i();m1n();Nl()});function HSt(e){let n={...USt.parse({...e,plugins:e.plugins??[]}),plugins:e.plugins??[]};if(e.permissions)n.permissions=e.permissions;if(e.spaces)n.spaces=e.spaces;if(e.cliConfig)n.cliConfig=e.cliConfig;if(e.shellConfig)n.shellConfig=e.shellConfig;if(e.identity)n.identity=e.identity;return n}var g1n=E(()=>{G1e()});var e5i={};fi(e5i,{aggregateUsage:()=>jIc,parseUsageLine:()=>X8i});function X8i(e){try{let t=FIc.safeParse(JSON.parse(e));if(!t.success)return null;let n=t.data.data[0];if(n===void 0)return null;return{ts:String(t.data.ts??""),data:n}}catch{return null}}function jIc(e){let t=[];for(let o of e.trim().split(`
|
|
1175
1175
|
`)){let s=X8i(o);if(s)t.push(s)}let n=new Map,r=0,i=0;for(let{data:o}of t){let s=`${o.provider}/${o.model}`,a=n.get(s)??{calls:0,inputTokens:0,outputTokens:0};a.calls++,a.inputTokens+=o.inputTokens,a.outputTokens+=o.outputTokens,n.set(s,a),r+=o.inputTokens,i+=o.outputTokens}return{events:t,firstTs:t[0]?.ts??"",lastTs:t[t.length-1]?.ts??"",totalInputTokens:r,totalOutputTokens:i,byModel:n}}var MIc,FIc;var t5i=E(()=>{oe();MIc=u.looseObject({operation:u.string(),provider:u.string(),model:u.string(),inputTokens:u.number(),outputTokens:u.number()}),FIc=u.looseObject({msg:u.literal("ai:usage"),ts:u.unknown().optional(),data:u.array(MIc).min(1)})});function NIc(e){process.on("uncaughtException",(t)=>{console.error(I4(`\u274C ${e} crashed:`),t),process.exit(1)}),process.on("unhandledRejection",(t)=>{console.error(I4(`\u274C ${e} unhandled rejection:`),t),process.exit(1)})}async function LIc(e){let{App:t}=await Promise.resolve().then(() => (h1n(),Y8i));return NIc(e.name),{argv:process.argv.slice(2),env:process.env,log:console.log,error:console.error,exit:process.exit,app:t}}function n5i(e,t){let n=e.indexOf(t);return n!==-1?e[n+1]:void 0}function r5i(e,t,n){let r=n5i(e.argv,t);if(r===void 0)e.error(n),e.exit(1);return r}function x1n(e,t,n,r){let i=n5i(e,t);return i?r.parse(JSON.parse(i)):n}function o5i(e){return{...e,plugins:(e.plugins??[]).filter((t)=>t.type!=="interface"),http:{...e.http,enabled:!1}}}async function UIc(){let{ConsoleLogger:e}=await Promise.resolve().then(() => (ly(),dnn));e.getInstance().setUseStderr(!0)}async function y1n(e,t,n){await UIc();let r=t.app.create(o5i(e));return await r.initialize(n),r}function $Ic(e,t){if("needsConfirmation"in t){let n=t.preview?`
|
|
1176
1176
|
|
|
@@ -1730,7 +1730,7 @@ ${e.issues.map((n)=>` - ${n.path.length>0?n.path.join("."):"(root)"}: ${n.messa
|
|
|
1730
1730
|
`+e}var F1n=E(()=>{L5i()});var KSt,q5i;var QSt=E(()=>{Su();l7e();Xc();oe();KSt=u.custom((e)=>gln.safeParse(e).success),q5i=u.custom((e)=>Cr(e)&&WUr.safeParse(e).success)});function z_c(e){if(!e)return[];return Array.isArray(e)?e:[e]}class $5i{id="site-package";version="0.1.0";type="service";description="Declarative site package adapter";packageName;site;runtimeConfig;constructor(e,t,n={}){this.packageName=e,this.site=t,this.runtimeConfig=n}async register(e){dpn(e,this.packageName,oj(this.site),this.runtimeConfig);let t=(r)=>`${this.packageName}:${r}`,n=e.getDataSourceRegistry();for(let r of this.site.dataSources??[]){if(!spn(r))throw Error(`Site data source "${String(Reflect.get(r,"id"))}" is not a fetching source declared with defineDataSource`);let i=t(r.id);n.register(nH(r,i,{publicId:i,runtimeState:e.getRuntimeState(),dataSources:n}))}for(let r of z_c(this.site.sections))e.registerTemplates(hht(r,{dataSourceId:t}),r.namespace);return{tools:[],resources:[]}}}function H5i(e,t,n,r=!1){if(!e||!r&&!Hqe(n,"site-builder"))return[];let i=[];if(e.sections||e.dataSources||oj(e)!==void 0)i.push(new $5i(t?.site?.package??"@rizom/site-package",e,{entityDisplay:e.entityDisplay,...E5i(t?.site)}));return i}function G_c(e,t){return t?qwe(e,t):e}function Z_c(e,t){if(!t.site)return;let n=H_c.safeParse(e);if(!n.success)return;let{pluginConfig:r,...i}=n.data,o=_J(t.site,i);return G_c(o,r)}function W_c(e,t,n){if(e===r2){let i=Z_c(t,n);if(i)return i}let r=KSt.safeParse(t);return r.success?r.data:void 0}function G5i(e,t){let n=t?.site?.package;if(!n)return e.site;if(!nG(n))throw Error(`brain.yaml site.package "${n}" could not be resolved \u2014 the package is not installed or failed to import. Refusing to fall back to the default site.`);let r=W_c(n,tG(n),e);if(r)return r;throw Error(`Package "${n}" is not a valid SitePackage`)}function U5i(e){if(nG(e)){let t=tG(e),n=ght.safeParse(t);if(!n.success)throw Error(`Package "${e}" does not export theme CSS`);return n.data}return e}function Z5i(e,t,n){let r=t?.site?.theme?U5i(t.site.theme):e.theme,i=n?.themeOverride,o=t?.site?.themeOverride?U5i(t.site.themeOverride):void 0,s=[r,i,o].filter(Boolean).join(`
|
|
1731
1731
|
|
|
1732
1732
|
`);if(!s)return;return VSt(s)}var q_c,U_c,$_c,H_c;var W5i=E(()=>{Ki();F1n();oe();IX();QSt();Su();kX();O1n();q_c=u.looseObject({id:u.string().min(1)}),U_c=u.looseObject({label:u.string().min(1)}),$_c=u.looseObject({layouts:u.record(u.string(),u.unknown()).optional(),pluginConfig:u.record(u.string(),u.unknown()).optional(),routes:u.array(q_c).optional(),entityDisplay:u.record(u.string(),U_c).optional(),content:u.unknown().optional(),themeOverride:u.string().optional(),headScripts:u.array(u.string()).optional(),staticAssets:u.record(u.string(),u.string()).optional()}),H_c=u.custom((e)=>$_c.safeParse(e).success)});function V_c(e,t){let{httpEnabled:n,site:r,theme:i,anchor:o,accountSettingsEncryptionKey:s}=t,a=e.mcp??{};if(e.mcp=iG({transport:n?"http":"stdio"},a),r||i!==void 0){let l=e["site-builder"]??{},d={...i!==void 0&&{themeCSS:i},...r&&{routes:r.routes,layouts:r.layouts,...r.headScripts&&{headScripts:r.headScripts},...r.languages&&{languages:r.languages},...r.layoutCopy&&{layoutCopy:r.layoutCopy}},...r?.staticAssets&&{staticAssets:r.staticAssets}};e["site-builder"]=iG(d,l)}let c=e["auth-service"]??{};if(e["auth-service"]={...c,anchor:o,...s?{accountSettingsEncryptionKey:s}:{}},i!==void 0){let l={themeCSS:i},d=e.dashboard??{};e.dashboard=iG(l,d)}}function K_c(e,t,n){if(e.http===!0)return!0;if(n?.mode==="eval")return!1;let r=new Set(t.activeBundles);return t.bundleDefinitions.some((i)=>i.http===!0&&r.has(i.id))}function Q_c(e,t,n,r,i){let o=[];for(let[s,a,c]of e.capabilities){if(!Hqe(n.activeIds,s))continue;let l=typeof c==="function"?c(t,{bundles:n.activeBundles}):c??{},d=n.resolution.configByMember[s],p=d?iG(l,d):l,f=r[s],m=f?iG(p,f):p;try{let h=a(m);o.push(...CX(h))}catch(h){if(!Kht(h)||!Vht(h))throw h;i?.warn(`Skipping capability "${s}": missing required config`)}}return o}function J_c(e,t,n,r,i){let o=[];for(let[s,a,c]of e.interfaces){if(!Hqe(n.activeIds,s))continue;let l=c(t);if(!l)continue;let d=n.resolution.configByMember[s],p=d?iG(l,d):l,f=r[s],m=f?iG(p,f):p;try{o.push(...CX(a(m)))}catch(h){if(!Kht(h)||!Vht(h))throw h;i?.warn(`Skipping interface "${s}": missing required config`)}}return o}function Y_c(e){return e.identity?{name:e.identity.characterName,role:e.identity.role,purpose:e.identity.purpose,values:e.identity.values}:void 0}function X_c(e,t){let n={...e.deployment??{}};if(t?.domain)n.domain=t.domain;if(t?.port)n.ports={...n.ports??{},production:t.port};return n}function eTc(e,t){return{...t?.logLevel?{logLevel:t.logLevel}:pk.safeParse(e.LOG_LEVEL).success?{logLevel:pk.parse(e.LOG_LEVEL)}:{},...t?.logFile?{logFile:t.logFile}:e.LOG_FILE?{logFile:e.LOG_FILE}:{},...t?.database?{database:t.database}:e.DATABASE_URL?{database:e.DATABASE_URL}:{}}}function tTc(e,t){if(t.extra)Object.assign(e,t.extra)}function nTc(e,t){if(t?.enabled===void 0)return;e.shellConfig={...e.shellConfig,embedding:{...e.shellConfig?.embedding,enabled:t.enabled}}}function rTc(e,t){if(t===void 0)return;e.shellConfig={...e.shellConfig,themeCSS:t}}function iTc(e,t){if(!t)return;let n=e.shellConfig??{},r=n.entityDisplay??{};e.shellConfig={...n,entityDisplay:{...t.entityDisplay,...r}}}function oTc(e,t){let n=e.bundleContract;if(n===void 0)return;let r=t?.bundleContract;if(r===n)return;throw Error(r===void 0?`Brain "${e.name}" requires bundleContract "${n}"; this brain.yaml predates the active bundle taxonomy. Run "brain config migrate" with an explicitly reviewed recipe before startup.`:`Brain "${e.name}" requires bundleContract "${n}", received "${r}".`)}function sTc(e,t,n){if(!n)return;let r=[...e.capabilities.map(([o])=>o),...e.interfaces.map(([o])=>o)],i=new Set(r);for(let o of["add","remove"])for(let s of t?.[o]??[]){if(i.has(s))continue;n.warn(`brain.yaml ${o} names "${s}", which is not a capability or interface of this brain; it is ignored. Known: ${[...new Set(r)].sort().join(", ")}`)}}function aTc(e,t,n,r){oTc(e,n);let i=C5i(e,n);sTc(e,n,r);let o=i.activeIds,s=P5i(i.bundleDefinitions,i.resolution.permissionContributions),a=T5i(w5i(n?.plugins)),c=n?.model??e.model,l=n?.reasoningEffort??e.reasoningEffort,d=n?.anchor??e.anchor??"person",p=n?.kind??e.kind,f=n?.http?.enabled??K_c(e,i,n),m=I5i(e,o,"site-builder"),h=G5i(e,n),g=Z5i(e,n,h);V_c(a,{httpEnabled:f,site:h,theme:g,anchor:d,accountSettingsEncryptionKey:t.ACCOUNT_SETTINGS_ENCRYPTION_KEY});let x=[...H5i(h,n,o,i.bundleDefinitions.length===0),...Q_c(e,t,i,a,r)],y=J_c(e,t,i,a,r),v=Y_c(e),w=X_c(e,n),S=[...e.agentInstructions??[],...i.resolution.agentInstructions],k={name:n?.name??e.name,version:e.version,plugins:[...x,...y],ai:S5i(t,{...c&&{model:c},...n?.embeddingModel&&{embeddingModel:n.embeddingModel},...n?.modelRuntime&&{modelRuntimeUrl:n.modelRuntime.url},...n?.answerModel&&{answerModel:n.answerModel},...n?.visionModel&&{visionModel:n.visionModel},...n?.imageModel&&{imageModel:n.imageModel},...l&&{reasoningEffort:l}}),...v&&{identity:v},...p&&{profileKind:p},...S.length>0?{agentInstructions:S}:{},...F5i(e.permissions,s,n,x),...n?.spaces?{spaces:n.spaces}:{},deployment:w,http:{...n?.http,enabled:f,preview:n?.http?.preview??m},...eTc(t,n)};return tTc(k,e),nTc(k,n?.embedding),rTc(k,g),iTc(k,h),HSt(k)}function V5i(e,t,n,r){let i=_de(e)?WSt(e):e;return aTc(i,t,n,r)}var j1n=E(()=>{Ki();R1n();IX();k5i();g1n();G1e();O1n();_5i();B5i();O5i();N5i();W5i()});import{existsSync as Q5i,readFileSync as J5i}from"fs";import{dirname as Y5i,join as N1n}from"path";function cTc(e,t){return e===t||e.startsWith(`${t}/`)}function L1n(e){let t=Y5i(e);return t===e?[e]:[e,...L1n(t)]}function t6i(e,t){return Object.freeze({name:e.name,version:e.version,dependencies:Object.freeze({...e.dependencies??{}}),peerDependencies:Object.freeze({...e.peerDependencies??{}}),directory:t})}function n6i(e){let t=L1n(e).find((o)=>Q5i(N1n(o,"package.json")));if(t===void 0)throw Error(`No package.json at or above "${e}"; run from the package's own directory`);let n=N1n(t,"package.json"),r=JSON.parse(J5i(n,"utf8")),i=X5i.safeParse(r);if(!i.success)throw Error(`"${n}" must declare non-empty name and version fields`);return t6i(i.data,t)}function sG(e,t){let n;try{n=Bun.resolveSync(e,t)}catch(r){throw Error(`Could not resolve installed package "${e}" from "${t}"; install it in the Brain application or correct the package reference`,{cause:r})}for(let r of L1n(Y5i(n))){let i=N1n(r,"package.json");if(!Q5i(i))continue;let o=JSON.parse(J5i(i,"utf8")),s=X5i.safeParse(o);if(s.success&&cTc(e,s.data.name))return t6i(s.data,r)}throw Error(`Resolved package "${e}" from "${t}" but could not find valid package metadata; ensure its package.json declares matching non-empty name and version fields`)}function K5i(e,t){let n=e.peerDependencies["@rizom/brain"];if(!n||!Bun.semver.satisfies(t,n))throw new e6i(e,t,n)}function JSt(e,t){let n=sG(e,t);if(n.name==="@rizom/brain")return[];let r=sG("@rizom/brain",t);K5i(n,r.version);let i=Object.keys(n.dependencies).map((o)=>sG(o,n.directory)).filter((o)=>o.peerDependencies["@rizom/brain"]!==void 0);for(let o of i)K5i(o,r.version);return i}var X5i,e6i;var Gqe=E(()=>{oe();X5i=u.looseObject({name:u.string().min(1),version:u.string().min(1),dependencies:u.record(u.string(),u.string()).optional(),peerDependencies:u.record(u.string(),u.string()).optional()});e6i=class e6i extends Error{constructor(e,t,n){super(n?`Package "${e.name}@${e.version}" requires @rizom/brain "${n}", but "${t}" 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 _X(e="brain"){if(e==="brain"||e==="@rizom/brain"||e==="@rizom/brain/model")return"@rizom/brain/model";if(e.startsWith("@")&&!e.startsWith("@brains/"))return e;throw Error(`Unsupported brain definition "${e}"; run \`brain config migrate\` for a legacy config`)}function J1e(e){let t=[],n=e.site?.package;if(n&&oG(n))t.push(n);let r=e.site?.theme;if(r&&oG(r))t.push(r);let i=e.site?.themeOverride;if(i&&oG(i))t.push(i);if(e.plugins){for(let o of Object.values(e.plugins))for(let s of Object.values(o))if(typeof s==="string"&&oG(s))t.push(s)}return[...new Set(t)]}var YSt=E(()=>{j1n()});import{existsSync as z1n}from"fs";import{relative as lTc,sep as uTc}from"path";function q1n(e,t){let n=lTc(e,t).split(uTc).join("/");return n.startsWith(".")?n:`./${n}`}function dTc(e,t){return`import * as __pkg${t} from "${e}";`}function pTc(e,t){let n=e.version?`, { version: ${JSON.stringify(e.version)} }`:"";return`registerPackage("${e.ref}", __pkg${t}.default ?? __pkg${t}${n});`}function fTc(e){return{importLines:e.map(({ref:t},n)=>dTc(t,n)),registrationLines:e.map(pTc)}}function r6i(e,t){if(!t)return;try{return sG(e,t)}catch{return}}function mTc(e,t){if(!t||e==="@rizom/brain/model")return[];return JSt(e,t)}function hTc(e){let t=["resolve","handleCLI","parseInstanceOverrides"];if(e.hasRefs)t.push("registerPackage");if(e.hasConventions)t.push("applyConventionalSiteRefs","registerConventionalSitePackage");return t}function gTc(e){return[`import definition from "${e.brainPackage}";`,`import { ${e.appImports.join(", ")} } from "@brains/app";`,'import { readFileSync } from "fs";','import { join } from "path";',...e.packageImportLines,"",...e.brainRegistrationLine?[e.brainRegistrationLine]:[],...e.registrationLines,"",'const yaml = readFileSync(join(process.cwd(), "brain.yaml"), "utf-8");',"const overrides = parseInstanceOverrides(yaml);",...e.effectiveOverridesLine?[e.effectiveOverridesLine]:[],`const config = resolve(definition, process.env, ${e.configOverridesVariable});`,"await handleCLI(config);",""].join(`
|
|
1733
|
-
`)}function xTc(e,t,n){let r={imports:[],registrations:[],args:[]};if(!e)return r;let i=n,o=(d)=>{r.imports.push(d.importLine),r.registrations.push(d.registrationLine??`registerPackage("${d.packageRef}", __pkg${i});`),r.args.push(d.arg),i+=1},s=`${e}/src/site.tsx`;if(z1n(s)){let d=t.site?.package;o({packageRef:r2,importLine:`import __pkg${i} from "${q1n(e,s)}";`,arg:`sitePackageRef: "${r2}"`,registrationLine:`registerConventionalSitePackage(__pkg${i}, ${d===void 0?"undefined":JSON.stringify(d)});`})}let a=`${e}/src/theme.css`;if(!t.site?.themeOverride&&z1n(a))o({packageRef:oO,importLine:`import __pkg${i} from "${q1n(e,a)}" with { type: "text" };`,arg:`themeOverrideRef: "${oO}"`});let c=`${e}/src/site-content.ts`;if(t.plugins?.["site-content"]?.definitions===void 0&&z1n(c))o({packageRef:rG,importLine:`import __pkg${i} from "${q1n(e,c)}";`,arg:`siteContentDefinitionsRef: "${rG}"`});return r}function i6i(e,t={}){let n;try{n=Tde(e)}catch{return null}let r;try{r=_X(n.brain)}catch{return null}if(r==="@rizom/brain/model"&&n.bundles===void 0)return null;let i=mTc(r,t.cwd),o=new Map(i.map((m)=>[m.name,m])),s=[...new Set([...i.map(({name:m})=>m),...J1e(n).filter((m)=>m!==r)])],a=fTc(s.map((m)=>({ref:m,version:o.get(m)?.version??r6i(m,t.cwd)?.version}))),c=r6i(r,t.cwd),l=c?`registerPackage(${JSON.stringify(c.name)}, definition, { version: ${JSON.stringify(c.version)} });`:void 0,d=xTc(t.cwd,n,s.length),p=d.args.length>0,f=hTc({hasRefs:l!==void 0||s.length>0||d.registrations.length>0,hasConventions:p});return gTc({brainPackage:r,brainRegistrationLine:l,appImports:f,packageImportLines:[...a.importLines,...d.imports],registrationLines:[...a.registrationLines,...d.registrations],configOverridesVariable:p?"effectiveOverrides":"overrides",...p&&{effectiveOverridesLine:`const effectiveOverrides = applyConventionalSiteRefs(overrides, { ${d.args.join(", ")} });`}})}var o6i=E(()=>{Gqe();YSt();IX()});async function s6i(e,t=(r)=>import(r),n=ja.getInstance()){let r=J1e(e);await Promise.all(r.map(async(i)=>{if(nG(i))return;try{let o=await t(i),s;try{s=sG(i,process.cwd()).version}catch{}jD(i,o.default??o,s?{version:s}:void 0)}catch(o){let s=Re(o);n.error(`\u274C brain.yaml: failed to import package "${i}": ${s}`)}}))}var a6i=E(()=>{YSt();kX();Gqe();ly()});async function c6i(e,t,n,r=yTc){let i=sG(e,n);jD(i.name,t,{version:i.version});let o=JSt(e,n);await Promise.all(o.map(async(s)=>{let a=await r(s.name),c=a.default;if(c===void 0&&Object.values(a).some(X$))throw Error(`Plugin package "${s.name}" must default-export its declarative package definition; named alpha exports are not supported`);jD(s.name,c??a,{version:s.version})}))}var yTc=async(e)=>import(e);var l6i=E(()=>{Ki();Gqe();kX()});import{existsSync as U1n,readFileSync as bTc}from"fs";import{join as $1n}from"path";import{pathToFileURL as u6i}from"url";function vTc(e,t){return t?qwe(e,t):e}function H1n(e,t){if(!t){jD(r2,e);return}let n=KSt.safeParse(tG(t));if(!n.success)throw Error(`brain.yaml site.package "${t}" could not be resolved as the base for src/site.tsx`);if(!ei(e))throw Error("Conventional site file src/site.tsx must default-export site overrides");let{pluginConfig:r,...i}=e;if(r!==void 0&&!ei(r))throw Error("src/site.tsx pluginConfig must be a mapping");let o=_J(n.data,q5i.parse(i));jD(r2,vTc(o,r))}async function XSt(e,t){let n=t,r=$1n(e,"src/site.tsx");if(U1n(r)){let a=await import(u6i(r).href);if(a.default===void 0)throw Error(`Conventional site file ${r} must default-export a SitePackage or site overrides`);H1n(a.default,t.site?.package),n=Q1e(n,{sitePackageRef:r2})}let i=$1n(e,"src/theme.css");if(!t.site?.themeOverride&&U1n(i))jD(oO,bTc(i,"utf-8")),n=Q1e(n,{themeOverrideRef:oO});let o=$1n(e,"src/site-content.ts");if(n.plugins?.["site-content"]?.definitions===void 0&&U1n(o)){let a=await import(u6i(o).href);if(a.default===void 0)throw Error(`Conventional site-content file ${o} must default-export site content definitions`);jD(rG,a.default),n=Q1e(n,{siteContentDefinitionsRef:rG})}return n}var d6i=E(()=>{IX();Ki();kX();QSt();IX()});var Zqe={};fi(Zqe,{App:()=>Z1e,CLI_OPERATOR_ACTOR:()=>Nqe,CLI_OPERATOR_PRINCIPAL:()=>Lqe,CONVENTIONAL_SITE_CONTENT_PACKAGE_REF:()=>rG,CONVENTIONAL_SITE_PACKAGE_REF:()=>r2,CONVENTIONAL_THEME_PACKAGE_REF:()=>oO,InstanceOverridesParseError:()=>K1e,MigrationManager:()=>Hze,SeedDataManager:()=>b1n,applyConventionalSiteRefs:()=>Q1e,brainAnchorConfigKindSchema:()=>zqe,buildShellConfig:()=>$St,collectOverridePackageRefs:()=>J1e,createCliOperatorContext:()=>Cde,defineBrain:()=>ZSt,defineBundle:()=>WI,defineConfig:()=>HSt,deploymentConfigSchema:()=>qqe,extendSite:()=>_J,findPackageManifest:()=>n6i,generateEntrypoint:()=>i6i,getPackage:()=>tG,getPackageMetadata:()=>y5i,handleCLI:()=>a5i,hasPackage:()=>nG,isConfiguredPluginDefinition:()=>GSt,isDeclarativeBrainDefinition:()=>_de,isScopedPackageRef:()=>oG,logLevelSchema:()=>pk,normalizeDeclarativeBrainDefinition:()=>WSt,parseInstanceOverrides:()=>Tde,pluginOverrideEntrySchema:()=>P1n,reasoningEffortSchema:()=>rR,registerBrainDefinitionPackages:()=>c6i,registerConventionalSitePackage:()=>H1n,registerConventionalSiteTheme:()=>XSt,registerOverridePackages:()=>s6i,registerPackage:()=>jD,resolve:()=>V5i,resolveBrainPackageName:()=>_X,resolveBundleSelection:()=>Uqe,resolveStandardConfig:()=>wEt,resolveStandardConfigWithDirectories:()=>EEt,resolveStandardPaths:()=>y1e,use:()=>u5i});var bN=E(()=>{h1n();m1n();g1n();c5i();zSt();l5i();tEn();SEt();G1e();v1n();A1n();S1n();I1n();R1n();j1n();Gqe();kX();YSt();o6i();a6i();l6i();IX();d6i();QSt()});async function ATc(e){let{normalizeDeclarativeBrainDefinition:t}=await Promise.resolve().then(() => (bN(),Zqe)),n=t(e);return e.plugins.some(({definition:r})=>r.family==="interface")?{...n,http:!0}:n}function p6i(e){Bde=e}async function wTc(){if(!Bde)throw Error("Canonical brain definition is not registered");if(typeof Bde==="function")Bde=await Bde();return Bde}function e1t(){return Bde!==void 0}function ETc(e){return e!==null&&typeof e==="object"&&"capabilities"in e&&Array.isArray(e.capabilities)&&"interfaces"in e&&Array.isArray(e.interfaces)}async function Y1e(e){if(e==="brain")return wTc();let{isDeclarativeBrainDefinition:t,registerBrainDefinitionPackages:n}=await Promise.resolve().then(() => (bN(),Zqe)),i=(await import(e)).default;if(!ETc(i)&&!t(i))throw Error(`Brain definition package "${e}" has no valid default definition export`);return await n(e,i,process.cwd()),t(i)?ATc(i):i}var Bde;var t1t;var G1n=E(()=>{oe();t1t=u.object({type:u.literal("peer-event"),event:u.object({type:u.string(),payload:u.unknown()})})});var W1n={};fi(W1n,{bootBrain:()=>STc,resetBootFn:()=>kTc,setBootFn:()=>Z1n});function Z1n(e){n1t=e}async function STc(e,t,n){if(!n1t)throw Error("In-process boot not available. Run from the monorepo or install @rizom/brain globally.");return n1t(e,t,n)}function kTc(){n1t=void 0}var n1t;var mk="BRAIN_GIT_BROKER_SOCKET",aG="BRAIN_GIT_BROKER_CHECKOUT";import{tmpdir as CTc}from"os";import{join as V1n,resolve as m6i}from"path";function TX(e){return V1n(e,".brain-runtime")}function cG(e){let t=V1n(e,"git-broker.sock");if(Buffer.byteLength(t)<=ITc)return t;let n=_o(m6i(e)).slice(0,24);return V1n(CTc(),`brain-git-broker-${n}.sock`)}function X1e(e){return m6i(e.cwd,e.syncPath??e.dataDir)}var ITc=107;var Rde=E(()=>{Oo()});var r1t=E(()=>{Rde()});function h6i(e,t,n){if(e>0)return{kind:"pending"};if(t)return{kind:"resolve",result:t};if(n)return{kind:"resolve",result:{success:!0}};return{kind:"pending"}}import{spawn as _Tc}from"child_process";function vN(e){let t=e.spawnImpl??_Tc,n=e.processImpl??Pw;return new Promise((r)=>{let i=t("bun",["--no-orphans",...e.args],{cwd:e.cwd,stdio:"inherit",env:e.env??n.env}),o=!1,s=()=>{n.removeListener("SIGINT",l),n.removeListener("SIGTERM",d),n.removeListener("exit",p)},a=(f)=>{if(o)return;o=!0,s(),r(f)},c=(f)=>{if(i.exitCode!==null||i.killed)return;try{i.kill(f)}catch{}},l=()=>c("SIGINT"),d=()=>c("SIGTERM"),p=()=>c("SIGTERM");n.on("SIGINT",l),n.on("SIGTERM",d),n.on("exit",p),i.on("error",(f)=>{a({success:!1,message:`Failed to spawn bun: ${f.message}`})}),i.on("close",(f,m)=>{if(m==="SIGINT"||m==="SIGTERM"){a({success:!0});return}a({success:f===0,...f!==0?{...e.failureMessage&&{message:e.failureMessage(f)},exitCode:f??1}:{}})})})}var g6i,Pw;var lG=E(()=>{g6i=process,Pw={env:process.env,kill:(e,t)=>t===void 0?process.kill(e):process.kill(e,t),on:(e,t)=>g6i.on(e,t),removeListener:(e,t)=>g6i.removeListener(e,t)}});function x6i(e,t){try{return e(-t,0),!1}catch(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ESRCH"}}function y6i(e,t,n){if(e)return{kind:"replace"};if(t>=n)return{kind:"give-up"};return{kind:"probe-again"}}function b6i(e,t,n){return e.filter((r)=>t-r<n)}function v6i(e,t){if(e===0)return 0;let n=Math.min(e-1,10);return t*2**n}function A6i(e,t){return e>=t}import{spawn as TTc}from"child_process";function S6i(e,t=PTc){let n=t.setInterval(e,E6i);return()=>t.clearInterval(n)}function k6i(e){let t=e.find((r)=>r.startsWith("--child="));if(!t)return;let n=t.slice(8);if(n==="web"||n==="worker"||n==="git-broker"||n==="migrate")return n;throw Error(`Invalid internal Brain child role "${n}"`)}function Wqe(e,t){return typeof e==="object"&&e!==null&&"type"in e&&e.type===t}function OTc(e,t){if(e.startupTimedOut)return{success:!1,message:"Brain git broker missed its ready deadline",exitCode:1};if(!e.ready)return{success:!1,message:"Brain git broker exited before it was ready",exitCode:t??1};return{success:!1,message:`Brain git broker exited with code ${t}`,exitCode:t??1}}function MTc(e,t){if(e.startupTimedOut)return{success:!1,message:"Brain web child missed its runtime-ready deadline",exitCode:1};if(!e.ready)return{success:!1,message:"Brain web child exited before runtime-ready",exitCode:t??1};if(t===0)return{success:!0};return{success:!1,message:`Brain web child exited with code ${t}`,exitCode:t??1}}function FTc(e){return new Promise((t)=>{let n=!1,r=!1,i,o,s,a,c,l,d,p=0,f=[],m=()=>[s,a,c].filter((O)=>O!==void 0&&!O.closed),h=(O)=>{if(O.startupTimer!==void 0)e.clock.clearTimeout(O.startupTimer),O.startupTimer=void 0;if(O.heartbeatTimer!==void 0)e.clock.clearTimeout(O.heartbeatTimer),O.heartbeatTimer=void 0},g=()=>{if(e.processImpl.removeListener("SIGINT",H),e.processImpl.removeListener("SIGTERM",z),e.processImpl.removeListener("exit",D),l!==void 0)e.clock.clearTimeout(l);if(d!==void 0)e.clock.clearTimeout(d);if(s)h(s);if(a)h(a);if(c)h(c)},x=(O)=>{if(n)return;n=!0,g(),t(O)},y=(O,F)=>{if(!O)return;try{if(O.role==="git-broker"&&O.process.pid!==void 0){e.processImpl.kill(-O.process.pid,F);return}if(O.closed||O.process.exitCode!==null)return;O.process.kill(F)}catch{}},v=(O)=>{if(O.role!=="worker"||!O.ready||O.closed||r)return;if(O.heartbeatTimer!==void 0)e.clock.clearTimeout(O.heartbeatTimer);O.heartbeatTimer=e.clock.setTimeout(()=>{if(O.heartbeatTimer=void 0,O.closed||O.heartbeatTimedOut||r)return;O.heartbeatTimedOut=!0,e.reportIncident({type:"worker-heartbeat-timeout",missedBeats:w6i,intervalMs:e.workerHeartbeatIntervalMs}),y(O,"SIGKILL")},e.workerHeartbeatIntervalMs*w6i)},w=(O,F=1)=>{if(n||r||o)return;let V=y6i(x6i((Y,X)=>e.processImpl.kill(Y,X),O),F,e.brokerGroupProbeAttempts);if(V.kind==="replace"){e.reportIncident({type:"git-broker-group-absent",attempts:F}),s=void 0,L("git-broker");return}if(V.kind==="give-up"){e.reportIncident({type:"git-broker-group-absence-unproven",attempts:F}),o??={success:!1,message:"Brain git broker process group could not be proven gone; the runtime is exiting for external cleanup",exitCode:1},B("SIGTERM");return}e.clock.setTimeout(()=>{w(O,F+1)},e.brokerGroupProbeIntervalMs)},S=()=>{let O=h6i(m().length,o,r);if(O.kind==="resolve")x(O.result)},k=(O)=>{if(r)return;o??=O,B("SIGTERM")},C=(O)=>{i=O,y(c,O),y(a,O),I(),l??=e.clock.setTimeout(()=>{y(c,"SIGKILL"),y(a,"SIGKILL"),y(s,O),y(s,"SIGKILL")},e.shutdownGraceMs)},I=()=>{if(i===void 0)return;if([a,c].filter((F)=>F!==void 0&&!F.closed).length>0)return;y(s,i)},B=(O)=>{if(r=!0,d!==void 0)e.clock.clearTimeout(d),d=void 0;C(O),S()},R=()=>{if(n||r||o||!a?.ready||a.closed||c!==void 0&&!c.closed||d!==void 0)return;let O=e.clock.now(),F=b6i(f,O,e.workerRestartWindowMs);if(f.length=0,f.push(...F),A6i(f.length,e.workerRestartBudget)){e.reportIncident({type:"worker-supervision-exhausted",attempts:f.length,windowMs:e.workerRestartWindowMs}),k({success:!1,message:`Brain worker restart budget exhausted after ${f.length} attempts`,exitCode:1});return}let V=v6i(p,e.workerRestartBaseMs);if(V===0){L("worker");return}d=e.clock.setTimeout(()=>{d=void 0,L("worker")},V)},P=(O,F,V)=>{if(O.closed)return;if(O.closed=!0,h(O),O.process.removeListener("message",O.handleMessage),O.role!=="git-broker")I();if(O.role==="git-broker"){if(!r&&!o)e.reportIncident({type:"git-broker-exited",code:F,signal:V,ready:O.ready});let Y=O.process.pid;if(!r&&O.ready&&Y!==void 0&&!o){w(Y);return}k(OTc(O,F)),S();return}if(O.role==="web"){k(MTc(O,F)),S();return}if(r||o){S();return}p+=1,e.reportIncident({type:"worker-exited",code:F,signal:V,ready:O.ready}),R()},L=(O)=>{if(n||r||o)return;if(O==="worker")f.push(e.clock.now());let F=O==="git-broker"?e.gitBroker?.entrypointPath:void 0,V=e.spawnImpl("bun",F?[F]:[e.entrypointPath,"start",`--child=${O}`],{cwd:e.cwd,stdio:["inherit","inherit","inherit","ipc"],detached:O==="git-broker",env:e.gitBroker?{...e.processImpl.env,[mk]:e.gitBroker.socketPath,[aG]:e.gitBroker.checkoutPath}:e.processImpl.env}),Y={role:O,process:V,ready:!1,closed:!1,startupTimedOut:!1,heartbeatTimedOut:!1,startupTimer:void 0,heartbeatTimer:void 0,handleMessage:()=>{}};if(O==="git-broker")s=Y;else if(O==="web")a=Y;else c=Y;Y.handleMessage=(X)=>{if(Y.closed)return;if(O!=="git-broker"&&Wqe(X,"peer-event")){let K=t1t.safeParse(X),ie=O==="web"?c:a;if(K.success&&ie&&!ie.closed)ie.process.send?.(K.data);return}if(O==="git-broker"&&Wqe(X,"broker-ready")){if(Y.ready)return;if(Y.ready=!0,h(Y),e.reportReady(O),a===void 0)L("web");return}if(O==="web"&&Wqe(X,"runtime-ready")){if(Y.ready)return;Y.ready=!0,h(Y),e.reportReady(O),R();return}if(O==="worker"&&Wqe(X,"worker-ready")){if(Y.ready)return;if(Y.ready=!0,p=0,Y.startupTimer!==void 0)e.clock.clearTimeout(Y.startupTimer),Y.startupTimer=void 0;e.reportReady(O),v(Y);return}if(O==="worker"&&Y.ready&&!Y.heartbeatTimedOut&&Wqe(X,"worker-heartbeat"))v(Y)},Y.startupTimer=e.clock.setTimeout(()=>{if(Y.ready||Y.closed)return;Y.startupTimedOut=!0,e.reportIncident({type:`${O}-startup-timeout`,timeoutMs:e.startupTimeoutMs}),y(Y,"SIGKILL")},e.startupTimeoutMs),V.on("message",Y.handleMessage),V.on("error",(X)=>{e.reportIncident({type:`${O}-spawn-error`,message:X.message})}),V.on("close",(X,K)=>{P(Y,X,K)})},H=()=>B("SIGINT"),z=()=>B("SIGTERM"),D=()=>B("SIGTERM");e.processImpl.on("SIGINT",H),e.processImpl.on("SIGTERM",z),e.processImpl.on("exit",D),L(e.gitBroker?"git-broker":"web")})}function C6i(e,t,n={}){return FTc({cwd:e,entrypointPath:t,spawnImpl:n.spawnImpl??TTc,processImpl:n.processImpl??Pw,clock:n.clock??DTc,startupTimeoutMs:n.startupTimeoutMs??30000,shutdownGraceMs:n.shutdownGraceMs??15000,workerRestartBaseMs:n.workerRestartBaseMs??1000,workerRestartBudget:n.workerRestartBudget??3,workerRestartWindowMs:n.workerRestartWindowMs??3600000,workerHeartbeatIntervalMs:n.workerHeartbeatIntervalMs??E6i,brokerGroupProbeIntervalMs:n.brokerGroupProbeIntervalMs??BTc,brokerGroupProbeAttempts:n.brokerGroupProbeAttempts??RTc,gitBroker:n.gitBroker,reportIncident:n.reportIncident??((r)=>{console.error(JSON.stringify(r))}),reportReady:n.reportReady??((r)=>{console.log(`Brain ${r} runtime ready`)})})}var E6i=5000,w6i=3,BTc=500,RTc=20,DTc,PTc;var K1n=E(()=>{r1t();G1n();lG();DTc={now:Date.now,setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},PTc={setInterval:(e,t)=>setInterval(e,t),clearInterval:(e)=>clearInterval(e)}});var ND;var o1t=E(()=>{ND={name:"@rizom/brain",version:"0.2.0-alpha.873",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/conflict":"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/identity-service":"workspace:*","@brains/image":"workspace:*","@brains/image-plugin":"workspace:*","@brains/knowledge-map":"workspace:*","@brains/link":"workspace:*","@brains/linkedin-import":"workspace:*","@brains/matrix-server":"workspace:*","@brains/mcp":"workspace:*","@brains/mcp-service":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/oauth-broker":"workspace:*","@brains/obsidian-plugin":"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/reference":"workspace:*","@brains/refined-note":"workspace:*","@brains/sdk":"workspace:*","@brains/seminar":"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/translation":"workspace:*","@brains/typescript-config":"workspace:*","@brains/unified-inbox":"workspace:*","@brains/utils":"workspace:*","@brains/vault-sync":"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","reflect-metadata":"^0.2.2",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 j6i}from"fs";import{dirname as F6i,join as N6i}from"path";function J1n(e){let t=e,n=F6i(t);while(t!==n){if(j6i(N6i(t,"bun.lock")))return t;t=n,n=F6i(t)}return}function BX(e){let t=J1n(e);if(t){let n=N6i(t,"shell","app","src","runner.ts");if(j6i(n))return{path:n}}return}function tke(e){if(e1t())return"builtin";if(BX(e))return"monorepo";return}function Dde(e){return tke(e)==="monorepo"?BX(e):void 0}var s1t=()=>{};var z6i={};fi(z6i,{MCPClient:()=>L6i});import{Client as $Tc,StreamableHTTPClientTransport as HTc}from"@modelcontextprotocol/client";class L6i{client;transport;constructor(e,t){let n={};if(t)n.Authorization=`Bearer ${t}`;this.transport=new HTc(new URL(e),{requestInit:{headers:n}}),this.client=new $Tc({name:"brain-cli",version:"0.1.0"},{versionNegotiation:{mode:"auto"}})}async connect(){await this.client.connect(this.transport)}async close(){await this.client.close()}async listTools(){return(await this.client.listTools()).tools}async callTool(e,t){let r=(await this.client.callTool({name:e,arguments:t})).content;if(Array.isArray(r)){let i=r.find((o)=>o.type==="text");if(i&&"text"in i)return i.text}return""}}var q6i=()=>{};var b1t=`ARG BUN_VERSION=1.4.0
|
|
1733
|
+
`)}function xTc(e,t,n){let r={imports:[],registrations:[],args:[]};if(!e)return r;let i=n,o=(d)=>{r.imports.push(d.importLine),r.registrations.push(d.registrationLine??`registerPackage("${d.packageRef}", __pkg${i});`),r.args.push(d.arg),i+=1},s=`${e}/src/site.tsx`;if(z1n(s)){let d=t.site?.package;o({packageRef:r2,importLine:`import __pkg${i} from "${q1n(e,s)}";`,arg:`sitePackageRef: "${r2}"`,registrationLine:`registerConventionalSitePackage(__pkg${i}, ${d===void 0?"undefined":JSON.stringify(d)});`})}let a=`${e}/src/theme.css`;if(!t.site?.themeOverride&&z1n(a))o({packageRef:oO,importLine:`import __pkg${i} from "${q1n(e,a)}" with { type: "text" };`,arg:`themeOverrideRef: "${oO}"`});let c=`${e}/src/site-content.ts`;if(t.plugins?.["site-content"]?.definitions===void 0&&z1n(c))o({packageRef:rG,importLine:`import __pkg${i} from "${q1n(e,c)}";`,arg:`siteContentDefinitionsRef: "${rG}"`});return r}function i6i(e,t={}){let n;try{n=Tde(e)}catch{return null}let r;try{r=_X(n.brain)}catch{return null}if(r==="@rizom/brain/model"&&n.bundles===void 0)return null;let i=mTc(r,t.cwd),o=new Map(i.map((m)=>[m.name,m])),s=[...new Set([...i.map(({name:m})=>m),...J1e(n).filter((m)=>m!==r)])],a=fTc(s.map((m)=>({ref:m,version:o.get(m)?.version??r6i(m,t.cwd)?.version}))),c=r6i(r,t.cwd),l=c?`registerPackage(${JSON.stringify(c.name)}, definition, { version: ${JSON.stringify(c.version)} });`:void 0,d=xTc(t.cwd,n,s.length),p=d.args.length>0,f=hTc({hasRefs:l!==void 0||s.length>0||d.registrations.length>0,hasConventions:p});return gTc({brainPackage:r,brainRegistrationLine:l,appImports:f,packageImportLines:[...a.importLines,...d.imports],registrationLines:[...a.registrationLines,...d.registrations],configOverridesVariable:p?"effectiveOverrides":"overrides",...p&&{effectiveOverridesLine:`const effectiveOverrides = applyConventionalSiteRefs(overrides, { ${d.args.join(", ")} });`}})}var o6i=E(()=>{Gqe();YSt();IX()});async function s6i(e,t=(r)=>import(r),n=ja.getInstance()){let r=J1e(e);await Promise.all(r.map(async(i)=>{if(nG(i))return;try{let o=await t(i),s;try{s=sG(i,process.cwd()).version}catch{}jD(i,o.default??o,s?{version:s}:void 0)}catch(o){let s=Re(o);n.error(`\u274C brain.yaml: failed to import package "${i}": ${s}`)}}))}var a6i=E(()=>{YSt();kX();Gqe();ly()});async function c6i(e,t,n,r=yTc){let i=sG(e,n);jD(i.name,t,{version:i.version});let o=JSt(e,n);await Promise.all(o.map(async(s)=>{let a=await r(s.name),c=a.default;if(c===void 0&&Object.values(a).some(X$))throw Error(`Plugin package "${s.name}" must default-export its declarative package definition; named alpha exports are not supported`);jD(s.name,c??a,{version:s.version})}))}var yTc=async(e)=>import(e);var l6i=E(()=>{Ki();Gqe();kX()});import{existsSync as U1n,readFileSync as bTc}from"fs";import{join as $1n}from"path";import{pathToFileURL as u6i}from"url";function vTc(e,t){return t?qwe(e,t):e}function H1n(e,t){if(!t){jD(r2,e);return}let n=KSt.safeParse(tG(t));if(!n.success)throw Error(`brain.yaml site.package "${t}" could not be resolved as the base for src/site.tsx`);if(!ei(e))throw Error("Conventional site file src/site.tsx must default-export site overrides");let{pluginConfig:r,...i}=e;if(r!==void 0&&!ei(r))throw Error("src/site.tsx pluginConfig must be a mapping");let o=_J(n.data,q5i.parse(i));jD(r2,vTc(o,r))}async function XSt(e,t){let n=t,r=$1n(e,"src/site.tsx");if(U1n(r)){let a=await import(u6i(r).href);if(a.default===void 0)throw Error(`Conventional site file ${r} must default-export a SitePackage or site overrides`);H1n(a.default,t.site?.package),n=Q1e(n,{sitePackageRef:r2})}let i=$1n(e,"src/theme.css");if(!t.site?.themeOverride&&U1n(i))jD(oO,bTc(i,"utf-8")),n=Q1e(n,{themeOverrideRef:oO});let o=$1n(e,"src/site-content.ts");if(n.plugins?.["site-content"]?.definitions===void 0&&U1n(o)){let a=await import(u6i(o).href);if(a.default===void 0)throw Error(`Conventional site-content file ${o} must default-export site content definitions`);jD(rG,a.default),n=Q1e(n,{siteContentDefinitionsRef:rG})}return n}var d6i=E(()=>{IX();Ki();kX();QSt();IX()});var Zqe={};fi(Zqe,{App:()=>Z1e,CLI_OPERATOR_ACTOR:()=>Nqe,CLI_OPERATOR_PRINCIPAL:()=>Lqe,CONVENTIONAL_SITE_CONTENT_PACKAGE_REF:()=>rG,CONVENTIONAL_SITE_PACKAGE_REF:()=>r2,CONVENTIONAL_THEME_PACKAGE_REF:()=>oO,InstanceOverridesParseError:()=>K1e,MigrationManager:()=>Hze,SeedDataManager:()=>b1n,applyConventionalSiteRefs:()=>Q1e,brainAnchorConfigKindSchema:()=>zqe,buildShellConfig:()=>$St,collectOverridePackageRefs:()=>J1e,createCliOperatorContext:()=>Cde,defineBrain:()=>ZSt,defineBundle:()=>WI,defineConfig:()=>HSt,deploymentConfigSchema:()=>qqe,extendSite:()=>_J,findPackageManifest:()=>n6i,generateEntrypoint:()=>i6i,getPackage:()=>tG,getPackageMetadata:()=>y5i,handleCLI:()=>a5i,hasPackage:()=>nG,isConfiguredPluginDefinition:()=>GSt,isDeclarativeBrainDefinition:()=>_de,isScopedPackageRef:()=>oG,logLevelSchema:()=>pk,normalizeDeclarativeBrainDefinition:()=>WSt,parseInstanceOverrides:()=>Tde,pluginOverrideEntrySchema:()=>P1n,reasoningEffortSchema:()=>rR,registerBrainDefinitionPackages:()=>c6i,registerConventionalSitePackage:()=>H1n,registerConventionalSiteTheme:()=>XSt,registerOverridePackages:()=>s6i,registerPackage:()=>jD,resolve:()=>V5i,resolveBrainPackageName:()=>_X,resolveBundleSelection:()=>Uqe,resolveStandardConfig:()=>wEt,resolveStandardConfigWithDirectories:()=>EEt,resolveStandardPaths:()=>y1e,use:()=>u5i});var bN=E(()=>{h1n();m1n();g1n();c5i();zSt();l5i();tEn();SEt();G1e();v1n();A1n();S1n();I1n();R1n();j1n();Gqe();kX();YSt();o6i();a6i();l6i();IX();d6i();QSt()});async function ATc(e){let{normalizeDeclarativeBrainDefinition:t}=await Promise.resolve().then(() => (bN(),Zqe)),n=t(e);return e.plugins.some(({definition:r})=>r.family==="interface")?{...n,http:!0}:n}function p6i(e){Bde=e}async function wTc(){if(!Bde)throw Error("Canonical brain definition is not registered");if(typeof Bde==="function")Bde=await Bde();return Bde}function e1t(){return Bde!==void 0}function ETc(e){return e!==null&&typeof e==="object"&&"capabilities"in e&&Array.isArray(e.capabilities)&&"interfaces"in e&&Array.isArray(e.interfaces)}async function Y1e(e){if(e==="brain")return wTc();let{isDeclarativeBrainDefinition:t,registerBrainDefinitionPackages:n}=await Promise.resolve().then(() => (bN(),Zqe)),i=(await import(e)).default;if(!ETc(i)&&!t(i))throw Error(`Brain definition package "${e}" has no valid default definition export`);return await n(e,i,process.cwd()),t(i)?ATc(i):i}var Bde;var t1t;var G1n=E(()=>{oe();t1t=u.object({type:u.literal("peer-event"),event:u.object({type:u.string(),payload:u.unknown()})})});var W1n={};fi(W1n,{bootBrain:()=>STc,resetBootFn:()=>kTc,setBootFn:()=>Z1n});function Z1n(e){n1t=e}async function STc(e,t,n){if(!n1t)throw Error("In-process boot not available. Run from the monorepo or install @rizom/brain globally.");return n1t(e,t,n)}function kTc(){n1t=void 0}var n1t;var mk="BRAIN_GIT_BROKER_SOCKET",aG="BRAIN_GIT_BROKER_CHECKOUT";import{tmpdir as CTc}from"os";import{join as V1n,resolve as m6i}from"path";function TX(e){return V1n(e,".brain-runtime")}function cG(e){let t=V1n(e,"git-broker.sock");if(Buffer.byteLength(t)<=ITc)return t;let n=_o(m6i(e)).slice(0,24);return V1n(CTc(),`brain-git-broker-${n}.sock`)}function X1e(e){return m6i(e.cwd,e.syncPath??e.dataDir)}var ITc=107;var Rde=E(()=>{Oo()});var r1t=E(()=>{Rde()});function h6i(e,t,n){if(e>0)return{kind:"pending"};if(t)return{kind:"resolve",result:t};if(n)return{kind:"resolve",result:{success:!0}};return{kind:"pending"}}import{spawn as _Tc}from"child_process";function vN(e){let t=e.spawnImpl??_Tc,n=e.processImpl??Pw;return new Promise((r)=>{let i=t("bun",["--no-orphans",...e.args],{cwd:e.cwd,stdio:"inherit",env:e.env??n.env}),o=!1,s=()=>{n.removeListener("SIGINT",l),n.removeListener("SIGTERM",d),n.removeListener("exit",p)},a=(f)=>{if(o)return;o=!0,s(),r(f)},c=(f)=>{if(i.exitCode!==null||i.killed)return;try{i.kill(f)}catch{}},l=()=>c("SIGINT"),d=()=>c("SIGTERM"),p=()=>c("SIGTERM");n.on("SIGINT",l),n.on("SIGTERM",d),n.on("exit",p),i.on("error",(f)=>{a({success:!1,message:`Failed to spawn bun: ${f.message}`})}),i.on("close",(f,m)=>{if(m==="SIGINT"||m==="SIGTERM"){a({success:!0});return}a({success:f===0,...f!==0?{...e.failureMessage&&{message:e.failureMessage(f)},exitCode:f??1}:{}})})})}var g6i,Pw;var lG=E(()=>{g6i=process,Pw={env:process.env,kill:(e,t)=>t===void 0?process.kill(e):process.kill(e,t),on:(e,t)=>g6i.on(e,t),removeListener:(e,t)=>g6i.removeListener(e,t)}});function x6i(e,t){try{return e(-t,0),!1}catch(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ESRCH"}}function y6i(e,t,n){if(e)return{kind:"replace"};if(t>=n)return{kind:"give-up"};return{kind:"probe-again"}}function b6i(e,t,n){return e.filter((r)=>t-r<n)}function v6i(e,t){if(e===0)return 0;let n=Math.min(e-1,10);return t*2**n}function A6i(e,t){return e>=t}import{spawn as TTc}from"child_process";function S6i(e,t=PTc){let n=t.setInterval(e,E6i);return()=>t.clearInterval(n)}function k6i(e){let t=e.find((r)=>r.startsWith("--child="));if(!t)return;let n=t.slice(8);if(n==="web"||n==="worker"||n==="git-broker"||n==="migrate")return n;throw Error(`Invalid internal Brain child role "${n}"`)}function Wqe(e,t){return typeof e==="object"&&e!==null&&"type"in e&&e.type===t}function OTc(e,t){if(e.startupTimedOut)return{success:!1,message:"Brain git broker missed its ready deadline",exitCode:1};if(!e.ready)return{success:!1,message:"Brain git broker exited before it was ready",exitCode:t??1};return{success:!1,message:`Brain git broker exited with code ${t}`,exitCode:t??1}}function MTc(e,t){if(e.startupTimedOut)return{success:!1,message:"Brain web child missed its runtime-ready deadline",exitCode:1};if(!e.ready)return{success:!1,message:"Brain web child exited before runtime-ready",exitCode:t??1};if(t===0)return{success:!0};return{success:!1,message:`Brain web child exited with code ${t}`,exitCode:t??1}}function FTc(e){return new Promise((t)=>{let n=!1,r=!1,i,o,s,a,c,l,d,p=0,f=[],m=()=>[s,a,c].filter((O)=>O!==void 0&&!O.closed),h=(O)=>{if(O.startupTimer!==void 0)e.clock.clearTimeout(O.startupTimer),O.startupTimer=void 0;if(O.heartbeatTimer!==void 0)e.clock.clearTimeout(O.heartbeatTimer),O.heartbeatTimer=void 0},g=()=>{if(e.processImpl.removeListener("SIGINT",H),e.processImpl.removeListener("SIGTERM",z),e.processImpl.removeListener("exit",D),l!==void 0)e.clock.clearTimeout(l);if(d!==void 0)e.clock.clearTimeout(d);if(s)h(s);if(a)h(a);if(c)h(c)},x=(O)=>{if(n)return;n=!0,g(),t(O)},y=(O,F)=>{if(!O)return;try{if(O.role==="git-broker"&&O.process.pid!==void 0){e.processImpl.kill(-O.process.pid,F);return}if(O.closed||O.process.exitCode!==null)return;O.process.kill(F)}catch{}},v=(O)=>{if(O.role!=="worker"||!O.ready||O.closed||r)return;if(O.heartbeatTimer!==void 0)e.clock.clearTimeout(O.heartbeatTimer);O.heartbeatTimer=e.clock.setTimeout(()=>{if(O.heartbeatTimer=void 0,O.closed||O.heartbeatTimedOut||r)return;O.heartbeatTimedOut=!0,e.reportIncident({type:"worker-heartbeat-timeout",missedBeats:w6i,intervalMs:e.workerHeartbeatIntervalMs}),y(O,"SIGKILL")},e.workerHeartbeatIntervalMs*w6i)},w=(O,F=1)=>{if(n||r||o)return;let V=y6i(x6i((Y,X)=>e.processImpl.kill(Y,X),O),F,e.brokerGroupProbeAttempts);if(V.kind==="replace"){e.reportIncident({type:"git-broker-group-absent",attempts:F}),s=void 0,L("git-broker");return}if(V.kind==="give-up"){e.reportIncident({type:"git-broker-group-absence-unproven",attempts:F}),o??={success:!1,message:"Brain git broker process group could not be proven gone; the runtime is exiting for external cleanup",exitCode:1},B("SIGTERM");return}e.clock.setTimeout(()=>{w(O,F+1)},e.brokerGroupProbeIntervalMs)},S=()=>{let O=h6i(m().length,o,r);if(O.kind==="resolve")x(O.result)},k=(O)=>{if(r)return;o??=O,B("SIGTERM")},C=(O)=>{i=O,y(c,O),y(a,O),I(),l??=e.clock.setTimeout(()=>{y(c,"SIGKILL"),y(a,"SIGKILL"),y(s,O),y(s,"SIGKILL")},e.shutdownGraceMs)},I=()=>{if(i===void 0)return;if([a,c].filter((F)=>F!==void 0&&!F.closed).length>0)return;y(s,i)},B=(O)=>{if(r=!0,d!==void 0)e.clock.clearTimeout(d),d=void 0;C(O),S()},R=()=>{if(n||r||o||!a?.ready||a.closed||c!==void 0&&!c.closed||d!==void 0)return;let O=e.clock.now(),F=b6i(f,O,e.workerRestartWindowMs);if(f.length=0,f.push(...F),A6i(f.length,e.workerRestartBudget)){e.reportIncident({type:"worker-supervision-exhausted",attempts:f.length,windowMs:e.workerRestartWindowMs}),k({success:!1,message:`Brain worker restart budget exhausted after ${f.length} attempts`,exitCode:1});return}let V=v6i(p,e.workerRestartBaseMs);if(V===0){L("worker");return}d=e.clock.setTimeout(()=>{d=void 0,L("worker")},V)},P=(O,F,V)=>{if(O.closed)return;if(O.closed=!0,h(O),O.process.removeListener("message",O.handleMessage),O.role!=="git-broker")I();if(O.role==="git-broker"){if(!r&&!o)e.reportIncident({type:"git-broker-exited",code:F,signal:V,ready:O.ready});let Y=O.process.pid;if(!r&&O.ready&&Y!==void 0&&!o){w(Y);return}k(OTc(O,F)),S();return}if(O.role==="web"){k(MTc(O,F)),S();return}if(r||o){S();return}p+=1,e.reportIncident({type:"worker-exited",code:F,signal:V,ready:O.ready}),R()},L=(O)=>{if(n||r||o)return;if(O==="worker")f.push(e.clock.now());let F=O==="git-broker"?e.gitBroker?.entrypointPath:void 0,V=e.spawnImpl("bun",F?[F]:[e.entrypointPath,"start",`--child=${O}`],{cwd:e.cwd,stdio:["inherit","inherit","inherit","ipc"],detached:O==="git-broker",env:e.gitBroker?{...e.processImpl.env,[mk]:e.gitBroker.socketPath,[aG]:e.gitBroker.checkoutPath}:e.processImpl.env}),Y={role:O,process:V,ready:!1,closed:!1,startupTimedOut:!1,heartbeatTimedOut:!1,startupTimer:void 0,heartbeatTimer:void 0,handleMessage:()=>{}};if(O==="git-broker")s=Y;else if(O==="web")a=Y;else c=Y;Y.handleMessage=(X)=>{if(Y.closed)return;if(O!=="git-broker"&&Wqe(X,"peer-event")){let K=t1t.safeParse(X),ie=O==="web"?c:a;if(K.success&&ie&&!ie.closed)ie.process.send?.(K.data);return}if(O==="git-broker"&&Wqe(X,"broker-ready")){if(Y.ready)return;if(Y.ready=!0,h(Y),e.reportReady(O),a===void 0)L("web");return}if(O==="web"&&Wqe(X,"runtime-ready")){if(Y.ready)return;Y.ready=!0,h(Y),e.reportReady(O),R();return}if(O==="worker"&&Wqe(X,"worker-ready")){if(Y.ready)return;if(Y.ready=!0,p=0,Y.startupTimer!==void 0)e.clock.clearTimeout(Y.startupTimer),Y.startupTimer=void 0;e.reportReady(O),v(Y);return}if(O==="worker"&&Y.ready&&!Y.heartbeatTimedOut&&Wqe(X,"worker-heartbeat"))v(Y)},Y.startupTimer=e.clock.setTimeout(()=>{if(Y.ready||Y.closed)return;Y.startupTimedOut=!0,e.reportIncident({type:`${O}-startup-timeout`,timeoutMs:e.startupTimeoutMs}),y(Y,"SIGKILL")},e.startupTimeoutMs),V.on("message",Y.handleMessage),V.on("error",(X)=>{e.reportIncident({type:`${O}-spawn-error`,message:X.message})}),V.on("close",(X,K)=>{P(Y,X,K)})},H=()=>B("SIGINT"),z=()=>B("SIGTERM"),D=()=>B("SIGTERM");e.processImpl.on("SIGINT",H),e.processImpl.on("SIGTERM",z),e.processImpl.on("exit",D),L(e.gitBroker?"git-broker":"web")})}function C6i(e,t,n={}){return FTc({cwd:e,entrypointPath:t,spawnImpl:n.spawnImpl??TTc,processImpl:n.processImpl??Pw,clock:n.clock??DTc,startupTimeoutMs:n.startupTimeoutMs??30000,shutdownGraceMs:n.shutdownGraceMs??15000,workerRestartBaseMs:n.workerRestartBaseMs??1000,workerRestartBudget:n.workerRestartBudget??3,workerRestartWindowMs:n.workerRestartWindowMs??3600000,workerHeartbeatIntervalMs:n.workerHeartbeatIntervalMs??E6i,brokerGroupProbeIntervalMs:n.brokerGroupProbeIntervalMs??BTc,brokerGroupProbeAttempts:n.brokerGroupProbeAttempts??RTc,gitBroker:n.gitBroker,reportIncident:n.reportIncident??((r)=>{console.error(JSON.stringify(r))}),reportReady:n.reportReady??((r)=>{console.log(`Brain ${r} runtime ready`)})})}var E6i=5000,w6i=3,BTc=500,RTc=20,DTc,PTc;var K1n=E(()=>{r1t();G1n();lG();DTc={now:Date.now,setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},PTc={setInterval:(e,t)=>setInterval(e,t),clearInterval:(e)=>clearInterval(e)}});var ND;var o1t=E(()=>{ND={name:"@rizom/brain",version:"0.2.0-alpha.875",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/conflict":"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/identity-service":"workspace:*","@brains/image":"workspace:*","@brains/image-plugin":"workspace:*","@brains/knowledge-map":"workspace:*","@brains/link":"workspace:*","@brains/linkedin-import":"workspace:*","@brains/matrix-server":"workspace:*","@brains/mcp":"workspace:*","@brains/mcp-service":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/oauth-broker":"workspace:*","@brains/obsidian-plugin":"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/reference":"workspace:*","@brains/refined-note":"workspace:*","@brains/sdk":"workspace:*","@brains/seminar":"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/translation":"workspace:*","@brains/typescript-config":"workspace:*","@brains/unified-inbox":"workspace:*","@brains/utils":"workspace:*","@brains/vault-sync":"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","reflect-metadata":"^0.2.2",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 j6i}from"fs";import{dirname as F6i,join as N6i}from"path";function J1n(e){let t=e,n=F6i(t);while(t!==n){if(j6i(N6i(t,"bun.lock")))return t;t=n,n=F6i(t)}return}function BX(e){let t=J1n(e);if(t){let n=N6i(t,"shell","app","src","runner.ts");if(j6i(n))return{path:n}}return}function tke(e){if(e1t())return"builtin";if(BX(e))return"monorepo";return}function Dde(e){return tke(e)==="monorepo"?BX(e):void 0}var s1t=()=>{};var z6i={};fi(z6i,{MCPClient:()=>L6i});import{Client as $Tc,StreamableHTTPClientTransport as HTc}from"@modelcontextprotocol/client";class L6i{client;transport;constructor(e,t){let n={};if(t)n.Authorization=`Bearer ${t}`;this.transport=new HTc(new URL(e),{requestInit:{headers:n}}),this.client=new $Tc({name:"brain-cli",version:"0.1.0"},{versionNegotiation:{mode:"auto"}})}async connect(){await this.client.connect(this.transport)}async close(){await this.client.close()}async listTools(){return(await this.client.listTools()).tools}async callTool(e,t){let r=(await this.client.callTool({name:e,arguments:t})).content;if(Array.isArray(r)){let i=r.find((o)=>o.type==="text");if(i&&"text"in i)return i.text}return""}}var q6i=()=>{};var b1t=`ARG BUN_VERSION=1.4.0
|
|
1734
1734
|
FROM oven/bun:\${BUN_VERSION}-slim AS runtime
|
|
1735
1735
|
|
|
1736
1736
|
LABEL ai.rizom.brain.watchdog="true"
|
|
@@ -2729,7 +2729,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
2729
2729
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
2730
2730
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ikt(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&t.sep&&!t.value){let o=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":o.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)o.length=0;break;default:o.length=0}}if(o.length>=2)i=t.sep.splice(o[1])}switch(this.type){case"anchor":case"tag":if(r||t.value)i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(r||t.value)i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(qX(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=yke(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(qX(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(K4i(t.key)&&!qX(t.sep,"newline")){let o=yke(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:a}]})}else if(i.length>0)t.sep=t.sep.concat(i,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||r)e.items.push({start:i,key:null,sep:[this.sourceToken]});else if(qX(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(r||t.value)e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0;return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!qX(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(n)e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ikt(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||qX(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:r,sep:[]});else if(t.sep)this.stack.push(r);else Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);if(n)this.stack.push(n);else yield*this.pop(),yield*this.step()}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Ckt(n),i=yke(r);V4i(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
2731
2731
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
2732
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ckt(e),n=yke(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ckt(e),n=yke(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((n)=>n.type==="newline"||n.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}pOc.Parser=Q4i});var t3i=j(function(AOc){var J4i=uIn(),mOc=CUe(),DUe=IUe(),hOc=vCn(),gOc=Cd(),xOc=vIn(),Y4i=AIn();function X4i(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new xOc.LineCounter||null,prettyErrors:t}}function yOc(e,t={}){let{lineCounter:n,prettyErrors:r}=X4i(t),i=new Y4i.Parser(n?.addNewLine),o=new J4i.Composer(t),s=Array.from(o.compose(i.parse(e)));if(r&&n)for(let a of s)a.errors.forEach(DUe.prettifyError(e,n)),a.warnings.forEach(DUe.prettifyError(e,n));if(s.length>0)return s;return Object.assign([],{empty:!0},o.streamInfo())}function e3i(e,t={}){let{lineCounter:n,prettyErrors:r}=X4i(t),i=new Y4i.Parser(n?.addNewLine),o=new J4i.Composer(t),s=null;for(let a of o.compose(i.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new DUe.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(r&&n)s.errors.forEach(DUe.prettifyError(e,n)),s.warnings.forEach(DUe.prettifyError(e,n));return s}function bOc(e,t,n){let r=void 0;if(typeof t==="function")r=t;else if(n===void 0&&t&&typeof t==="object")n=t;let i=e3i(e,n);if(!i)return null;if(i.warnings.forEach((o)=>hOc.warn(i.options.logLevel,o)),i.errors.length>0)if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[];return i.toJS(Object.assign({reviver:r},n))}function vOc(e,t,n){let r=null;if(typeof t==="function"||Array.isArray(t))r=t;else if(n===void 0&&t)n=t;if(typeof n==="string")n=n.length;if(typeof n==="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}if(gOc.isDocument(e)&&!r)return e.toString(n);return new mOc.Document(e,r,n).toString(n)}AOc.parse=bOc;AOc.parseAllDocuments=yOc;AOc.parseDocument=e3i;AOc.stringify=vOc});var COc,IOc,_Oc,wIn,TOc,UX,BOc,ROc,DOc,POc,oDf,OOc,MOc,FOc,_kt,n3i,jOc,NOc,LOc,zOc,qOc,UOc,$Oc,HOc,GOc,ZOc,bke,vke,WOc,CN,EIn,VOc,KOc,QOc,JOc,YOc,XOc,eMc,tMc,nMc,SIn,kIn,rMc,iMc;var CIn=E(()=>{COc=uIn(),IOc=CUe(),_Oc=VCn(),wIn=IUe(),TOc=pUe(),UX=Cd(),BOc=jX(),ROc=rv(),DOc=LX(),POc=zX(),oDf=Skt(),OOc=bIn(),MOc=vIn(),FOc=AIn(),_kt=t3i(),n3i=uUe();jOc=COc.Composer,NOc=IOc.Document,LOc=_Oc.Schema,zOc=wIn.YAMLError,qOc=wIn.YAMLParseError,UOc=wIn.YAMLWarning,$Oc=TOc.Alias,HOc=UX.isAlias,GOc=UX.isCollection,ZOc=UX.isDocument,bke=UX.isMap,vke=UX.isNode,WOc=UX.isPair,CN=UX.isScalar,EIn=UX.isSeq,VOc=BOc.Pair,KOc=ROc.Scalar,QOc=DOc.YAMLMap,JOc=POc.YAMLSeq,YOc=OOc.Lexer,XOc=MOc.LineCounter,eMc=FOc.Parser,tMc=_kt.parse,nMc=_kt.parseAllDocuments,SIn=_kt.parseDocument,kIn=_kt.stringify,rMc=n3i.visit,iMc=n3i.visitAsync});var i3i;var r3i=E(()=>{i3i={name:"@rizom/site",version:"0.2.0-alpha.
|
|
2732
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ckt(e),n=yke(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ckt(e),n=yke(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((n)=>n.type==="newline"||n.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}pOc.Parser=Q4i});var t3i=j(function(AOc){var J4i=uIn(),mOc=CUe(),DUe=IUe(),hOc=vCn(),gOc=Cd(),xOc=vIn(),Y4i=AIn();function X4i(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new xOc.LineCounter||null,prettyErrors:t}}function yOc(e,t={}){let{lineCounter:n,prettyErrors:r}=X4i(t),i=new Y4i.Parser(n?.addNewLine),o=new J4i.Composer(t),s=Array.from(o.compose(i.parse(e)));if(r&&n)for(let a of s)a.errors.forEach(DUe.prettifyError(e,n)),a.warnings.forEach(DUe.prettifyError(e,n));if(s.length>0)return s;return Object.assign([],{empty:!0},o.streamInfo())}function e3i(e,t={}){let{lineCounter:n,prettyErrors:r}=X4i(t),i=new Y4i.Parser(n?.addNewLine),o=new J4i.Composer(t),s=null;for(let a of o.compose(i.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new DUe.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(r&&n)s.errors.forEach(DUe.prettifyError(e,n)),s.warnings.forEach(DUe.prettifyError(e,n));return s}function bOc(e,t,n){let r=void 0;if(typeof t==="function")r=t;else if(n===void 0&&t&&typeof t==="object")n=t;let i=e3i(e,n);if(!i)return null;if(i.warnings.forEach((o)=>hOc.warn(i.options.logLevel,o)),i.errors.length>0)if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[];return i.toJS(Object.assign({reviver:r},n))}function vOc(e,t,n){let r=null;if(typeof t==="function"||Array.isArray(t))r=t;else if(n===void 0&&t)n=t;if(typeof n==="string")n=n.length;if(typeof n==="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}if(gOc.isDocument(e)&&!r)return e.toString(n);return new mOc.Document(e,r,n).toString(n)}AOc.parse=bOc;AOc.parseAllDocuments=yOc;AOc.parseDocument=e3i;AOc.stringify=vOc});var COc,IOc,_Oc,wIn,TOc,UX,BOc,ROc,DOc,POc,oDf,OOc,MOc,FOc,_kt,n3i,jOc,NOc,LOc,zOc,qOc,UOc,$Oc,HOc,GOc,ZOc,bke,vke,WOc,CN,EIn,VOc,KOc,QOc,JOc,YOc,XOc,eMc,tMc,nMc,SIn,kIn,rMc,iMc;var CIn=E(()=>{COc=uIn(),IOc=CUe(),_Oc=VCn(),wIn=IUe(),TOc=pUe(),UX=Cd(),BOc=jX(),ROc=rv(),DOc=LX(),POc=zX(),oDf=Skt(),OOc=bIn(),MOc=vIn(),FOc=AIn(),_kt=t3i(),n3i=uUe();jOc=COc.Composer,NOc=IOc.Document,LOc=_Oc.Schema,zOc=wIn.YAMLError,qOc=wIn.YAMLParseError,UOc=wIn.YAMLWarning,$Oc=TOc.Alias,HOc=UX.isAlias,GOc=UX.isCollection,ZOc=UX.isDocument,bke=UX.isMap,vke=UX.isNode,WOc=UX.isPair,CN=UX.isScalar,EIn=UX.isSeq,VOc=BOc.Pair,KOc=ROc.Scalar,QOc=DOc.YAMLMap,JOc=POc.YAMLSeq,YOc=OOc.Lexer,XOc=MOc.LineCounter,eMc=FOc.Parser,tMc=_kt.parse,nMc=_kt.parseAllDocuments,SIn=_kt.parseDocument,kIn=_kt.stringify,rMc=n3i.visit,iMc=n3i.visitAsync});var i3i;var r3i=E(()=>{i3i={name:"@rizom/site",version:"0.2.0-alpha.253",description:"Public authoring SDK for Rizom site packages",type:"module",exports:{".":"./src/index.ts"},files:["src"],scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix"},dependencies:{zod:"^4.2.0"},peerDependencies:{react:"^19.2.7","react-dom":"^19.2.7"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/react":"^19.2.17","@types/react-dom":"^19.0.3",eslint:"^10.5.0",react:"^19.2.7","react-dom":"^19.2.7",typescript:"^7.0.2"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/site"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/site#readme",bugs:{url:"https://github.com/rizom-ai/brains/issues"},engines:{bun:">=1.3.3"},private:!0}});var o3i=E(()=>{IX()});import{existsSync as sMc,readFileSync as aMc}from"fs";import{join as cMc}from"path";function IN(e){let t=cMc(e,"brain.yaml");if(!sMc(t))throw Error(`No brain.yaml found in ${e}. Run 'brain init <dir>' first.`);let n=aMc(t,"utf-8"),r=uMc(n);if(r!==void 0)_X(r);let i;try{i=Tde(n)}catch(s){throw Error(`Invalid brain.yaml: ${Re(s)}`,{cause:s})}let o;try{o=_X(i.brain)}catch(s){throw Error(Re(s),{cause:s})}if(o==="@rizom/brain/model"){if(i.bundles===void 0)throw Error('Invalid canonical brain.yaml: expected explicit "bundles"');if(i.bundleContract!==Ow)throw Error(`Invalid canonical brain.yaml: expected bundleContract "${Ow}". Run "brain config migrate" with an explicitly reviewed recipe.`)}return{...i,brain:o==="@rizom/brain/model"?"brain":o}}function uMc(e){let t=cEt(e,lMc);return t.ok?t.data.brain:void 0}var lMc;var Ake=E(()=>{o3i();lEt();oe();lMc=u.object({brain:u.string()})});var d3i={};fi(d3i,{scaffold:()=>mMc});import{mkdirSync as a3i,writeFileSync as PUe,chmodSync as OUe,existsSync as MUe,readFileSync as IIn,cpSync as dMc}from"fs";import{basename as Tkt,dirname as Bkt,join as Um,resolve as c3i}from"path";import{fileURLToPath as l3i}from"url";function mMc(e,t){let n=MUe(Um(e,"brain.yaml"))?IN(e):void 0,r=t.recipe,i=n?.domain??t.domain??`${Tkt(c3i(e))}.rizom.ai`;if(hMc(e,r,i,t),gMc(e,r),PMc(e),FMc(e,r),yMc(e),DMc(e),jMc(e),u3i(r))OMc(e),MMc(e);if(bMc(e,t.backend),t.apiKeys&&Object.keys(t.apiKeys).length>0)vMc(e,t.apiKeys,t.contentRepo);if(t.deploy)xMc(e,t.regen),AMc(e,t.regen),wMc(e,t.regen),IMc(e,t.regen),SMc(e,t.regen),_Mc(e,t.regen),RMc(e,t.regen)}function GD(e,t,n=!1,r=!1){if(a3i(Bkt(e),{recursive:!0}),r){if(PUe(e,t),n)OUe(e,493);return}try{PUe(e,t,{flag:"wx"})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="EEXIST")return;throw i}if(n)OUe(e,493)}function wke(e){let{path:t,content:n,executable:r=!1,shouldReconcile:i,regen:o=!1}=e;if(a3i(Bkt(t),{recursive:!0}),o){if(PUe(t,n),r)OUe(t,493);return}if(!MUe(t)){if(PUe(t,n,{flag:"wx"}),r)OUe(t,493);return}let s=IIn(t,"utf-8");if(s===n)return;if(!(i?.(s)??!1))return;if(PUe(t,n),r)OUe(t,493)}function u3i(e){return wN(e).site!==void 0}function hMc(e,t,n,r){let{contentRepo:i,model:o,imageModel:s}=r,a=wN(t),c={...a.plugins??{}};if(t!=="headless")c["auth-service"]={setupEmail:"${MAIL_TO}"},c.notifications={defaultRecipient:{type:"email",address:"${MAIL_TO}"}},c.email={transport:"resend",apiKey:"${MAIL_API_KEY}",from:"${MAIL_FROM}"};if(i)c["directory-sync"]={...c["directory-sync"]??{},git:{repo:i.replace("github:",""),authToken:"${GIT_SYNC_TOKEN}"}};let l=kIn({brain:"brain",bundleContract:a.bundleContract,...a.anchor?{anchor:a.anchor}:{},...a.kind?{kind:a.kind}:{},domain:n,...o?{model:o}:{},...s?{imageModel:s}:{},bundles:a.bundles,...a.add?{add:a.add}:{},...a.remove?{remove:a.remove}:{},...a.site?{site:a.site}:{},admins:[],anchors:[],plugins:c},{lineWidth:0});GD(Um(e,"brain.yaml"),l)}function gMc(e,t){let n=Um(e,"seed-content");if(MUe(n))return;let r=Bkt(l3i(import.meta.url)),o=[Um(r,"..","..","templates","recipes",t,"seed-content"),Um(r,"..","templates","recipes",t,"seed-content")].find((s)=>MUe(s));if(!o)throw Error(`Missing seed template for recipe "${t}"`);dMc(o,n,{recursive:!0,errorOnExist:!0})}function xMc(e,t=!1){let n=Fkn({serviceName:"brain"});wke({path:Um(e,"config","deploy.yml"),content:n,shouldReconcile:JDi,regen:t})}function yMc(e){GD(Um(e,".env.example"),`# AI provider keys: set the ones your brain.yaml models use.
|
|
2733
2733
|
# The default chat, image and embedding models are OpenAI's.
|
|
2734
2734
|
OPENAI_API_KEY=
|
|
2735
2735
|
# ANTHROPIC_API_KEY=
|
|
@@ -3646,7 +3646,7 @@ ${e.preview}`:"";return console.log(`Confirmation needed: ${e.summary}${n}`),t}i
|
|
|
3646
3646
|
`).find((y)=>y.startsWith("data: "));if(!d)continue;let p;try{let y=Agl.safeParse(JSON.parse(d.slice(6)));if(!y.success)continue;p=y.data}catch{return await pOn(r),{success:!1,error:"Malformed SSE event from remote agent"}}let f=p.result;if(f?.kind==="artifact-update"&&f.artifact)a.push(f.artifact);if(!f?.final)continue;await pOn(r);let m=f.status,h=m?.state??"unknown",x=(m?.message?.parts??[]).filter((y)=>y.kind==="text"&&typeof y.text==="string").map((y)=>y.text).join(`
|
|
3647
3647
|
`)||"No response text";return{success:!0,data:{state:h,response:x,sources:bgl(a)}}}s=await rdo(r,t,n)}return{success:!1,error:"Stream ended without a terminal event"}}async function Tgl(e,t,n,r,i){return uOn((o)=>e(t,{...n,signal:o}),{timeoutMs:r,onTimeout:()=>new mOn(r),signal:i})}async function rdo(e,t,n){try{return await uOn(()=>e.read(),{timeoutMs:t,onTimeout:()=>new UWe(t),signal:n})}catch(r){if(r instanceof UWe||n?.aborted)await pOn(e,r);throw r}}async function pOn(e,t){try{await e.cancel(t)}catch{}}function Bgl(e){if(e instanceof mOn||e instanceof UWe)return!1;return e instanceof Error}function dOn(e,t){let n=t>1?` after ${t} attempts`:"";if(e instanceof UWe)return`${e.message}${n}`;let r=Re(e,"Unknown network error");return`Failed to reach remote agent${n}: ${r}`}async function A8t(e,t={},n={}){let r=t.fetch??globalThis.fetch,i=n.signal;i?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??wgl,streamIdleTimeoutMs:t.streamIdleTimeoutMs??Egl,maxNetworkAttempts:t.maxNetworkAttempts??Sgl},s=Igl(e.agent),a=Ui(n.userPermissionLevel);if(!s.ok){let p=t.entityService?await edo(t.entityService,e.agent,a):void 0;if(typeof p==="string")return{success:!1,error:p};if(!p)return{success:!1,error:s.error}}if(!t.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let c=s.ok?s.agentId:e.agent.trim(),l=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(i?.throwIfAborted(),!l&&!tdo(c)){let p=await edo(t.entityService,e.agent,a);if(i?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)l=p,c=p.id}if(!l){if(n.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!tdo(c))return{success:!1,error:`Agent ${e.agent} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let p=await t2(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:i});if(!p.ok){if(uN(p.reason))return{success:!1,error:p.error};return{success:!1,error:`Could not verify an A2A Agent Card for ${c}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"}}let f=await ndo(p.card.url,e.message,r,t.requestSigner,o,i);if("success"in f&&f.success===!0){let m=typeof f.data==="object"&&f.data!==null?f.data:{};return{...f,data:{...m,agentCall:{mode:"one-shot",agent:c},agentContactCandidate:{source:{kind:"url",url:(s.ok?s.sourceUrl:void 0)??c}}}}}return f}if(l.metadata.status==="archived")return{success:!1,error:`Agent ${c} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(!await t.isContactApproved?.(c))return{success:!1,error:`Agent ${c} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let d=await t2(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:i});if(!d.ok){if(uN(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return ndo(d.card.url,e.message,r,t.requestSigner,o,i)}function odo(e={}){return{name:"agent_call",description:"Call a remote A2A agent by exact domain-like target, saved local agent id, or the name of a saved contact as the user calls it, such as Yeehaa. A domain-like id is bare text with a dot and no slash/protocol, such as partner-brain.example or save-it-regression.example; .example test domains are exact domain-like ids. When the user asks to ask, message, talk to, or contact that id, asks what it has to say, or asks that agent for its skills/capabilities, call this tool directly in the same turn with no system_list/system_get preflight: the tool reports structured errors such as invalid Agent Card, not approved, or archived. Do not stop after listing the agent, drafting the question, searching local content, or reading its saved entity. If the user provides an HTTPS URL such as https://docs.example/a2a, pass only the hostname docs.example. Never pass a full URL, a brain's display name like Brain, or a non-HTTPS URL; for a non-HTTPS URL, ask for the HTTPS agent URL or exact id instead. For saved agents, the tool enforces approved/not-archived status before network contact; a discovered but not approved agent must be approved first, so do not call it. For unsaved exact domains, the tool verifies the A2A Agent Card over HTTPS and may perform a one-shot call without saving; after success you may offer to save/connect it, but never auto-save. Answer from the agent's response without supplementing it with reads of the agent entity unless the user asks for its directory/profile details, and never save the user's question as a note in the same turn. If the call fails (auth, network, an invalid or unverifiable Agent Card, an unavailable agent), report that failure directly: do not say the agent was saved or connected, do not answer from memory, local docs, or general knowledge, and do not create a wish, reminder, todo, note, or other entity; you may offer to add the contact using the word add. Each new turn that asks the same id something, including short follow-ups like 'tell me more' and even after a refusal or error, needs its own fresh call with that same id. If a name matches several saved agents, ask a concise clarification naming their ids and end the turn without calling; never choose the first match.",inputSchema:kgl,visibility:"trusted",sideEffects:"external",handler:async(t,n)=>{let r=Cgl.safeParse(t);if(!r.success)return{success:!1,error:`Invalid input: ${r.error.message}`};return A8t(r.data,e,{userPermissionLevel:n.userPermissionLevel,...n.signal?{signal:n.signal}:{}})}}}var _km,fOn,xgl,ido,ygl,Tkm,Bkm,Rkm,Dkm,vgl,Agl,wgl=30000,Egl=60000,Sgl=2,kgl,Cgl,mOn,UWe;var hOn=E(()=>{oe();_a();Xuo();lt();v8t();_km=u.object({kind:u.literal("text"),text:u.string()}),fOn=u.array(u.looseObject({kind:u.string()})),xgl=u.object({kind:u.literal("data"),data:u.object({sources:u.array(u.unknown())})}),ido=u.looseObject({name:u.string().optional(),parts:fOn}),ygl=u.array(ido);Tkm=u.object({error:u.object({message:u.string()})}),Bkm=u.object({kind:u.literal("message"),parts:fOn}),Rkm=u.object({kind:u.literal("task"),id:u.string().optional(),status:u.object({state:u.string(),message:u.object({parts:fOn}).optional()}),artifacts:ygl.optional()}),Dkm=u.object({result:u.unknown()}),vgl=u.looseObject({kind:u.string(),text:u.string().optional()}),Agl=u.looseObject({result:u.looseObject({kind:u.string().optional(),final:u.boolean().optional(),artifact:ido.optional(),status:u.looseObject({state:u.string().optional(),message:u.looseObject({parts:u.array(vgl).optional()}).optional()}).optional()}).optional()}),kgl={agent:u.string().describe("Exact domain-like agent target, saved local agent id, or the name of a saved contact as the user calls it, such as partner-brain.example, save-it-regression.example, or Yeehaa. If the user provides an HTTPS URL, pass only its hostname as the agent id (for https://docs.example/a2a, pass docs.example). Any bare string with a dot and no slash/protocol is domain-like, including .example test domains. The tool verifies unsaved exact domains with an Agent Card before contact and never auto-saves. Never pass a full URL, a brain's display name like Brain, or a non-HTTPS URL."),message:u.string().describe("Message to send to the remote agent")},Cgl=u.object({agent:u.string(),message:u.string()});mOn=class mOn extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}};UWe=class UWe extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}});function aM(e,t){return{status:"refused",code:e,error:t}}async function sdo(e,t,n){let r=e.trim().toLowerCase(),i=await n.entityService?.getEntity({entityType:"agent",id:r,visibilityScope:Ui("admin")});if(!i)return aM("agent_not_saved",`Agent ${r} is not saved.`);if(i.metadata.status==="archived")return aM("agent_archived",`Agent ${r} is archived.`);if(!await n.isContactApproved?.(r))return aM("agent_not_approved",`Agent ${r} is not approved yet. Approve it first.`);let{requestSigner:o}=n;if(!o)return aM("unsigned","This brain cannot sign A2A requests, and a peer shares only with callers it can verify.");let s=n.fetch??fetch,a=n.requestTimeoutMs??Rgl,c=await t2(r,{fetch:s,timeoutMs:a});if(!c.ok)return aM("agent_card_unavailable",c.error);if(!c.card.extensions.includes(PU))return aM("not_offered",`${r} does not offer shared entities.`);let l={"Content-Type":"application/json","X-A2A-Extensions":PU},d=JSON.stringify({jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:{message:{kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"data",data:t}]}}});await o({method:"POST",url:c.card.url,headers:l,body:d});let p;try{p=await s(c.card.url,{method:"POST",headers:l,body:d,signal:AbortSignal.timeout(a)})}catch(m){return aM("peer_failed",Re(m,`${r} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return aM("peer_failed",`${r} answered HTTP ${p.status}`);let f=Dgl.safeParse(await p.json().catch(()=>null));return{status:"answered",agentId:r,data:f.success?f.data.result.parts.filter((m)=>m.kind==="data").map((m)=>m.data):[],fetchFn:s,timeoutMs:a}}async function ado(e,t){let n=await sdo(e.agent,{op:"list"},t);if(n.status!=="answered")return n;let r=n.data.map((i)=>fut.safeParse(i)).find((i)=>i.success)?.data;return r?{status:"found",entities:r.entities}:aM("unreadable_answer",`${n.agentId} did not answer with a list.`)}async function cdo(e,t){let n=await sdo(e.agent,{op:"get",entityType:e.entityType,id:e.id},t);if(n.status!=="answered")return n;let{agentId:r,fetchFn:i,timeoutMs:o}=n,s=n.data.map((c)=>mut.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return aM("unreadable_answer",`${r} did not answer with the entity asked for.`);let a=aM("unverified",`${r} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ur(s.markdown))return a;try{if((await Suo(V4e(s),s.attestation.signature,s.attestation.keyId,new LWe({fetch:(l)=>i(l,{signal:AbortSignal.timeout(o)})}))).domain!==r)return a}catch{return a}return{status:"found",entity:s}}var Rgl=30000,Dgl;var ldo=E(()=>{lt();y8t();Oo();_a();oe();Dgl=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})})});function ddo(e,t){let n="code"in e&&Pgl.has(e.code??"")?"permission_denied":"handler_failed",r="error"in e?e.error:t;return new gr(n,{publicMessage:Dse(r)})}function Ogl(e){return[e,"","Asked on behalf of a visitor to another brain's site. Answer briefly, from your own public content, and cite what you draw on."].join(`
|
|
3648
3648
|
`)}async function udo(e,t,n,r){let i=AbortSignal.timeout(r),o=(c)=>new gr("deadline_exceeded",{publicMessage:`${t} did not answer within ${r} ms`,cause:c}),s;try{s=await A8t({agent:t,message:n},{...e,maxNetworkAttempts:1},{requireSaved:!0,signal:i})}catch(c){if(i.aborted)throw o(c);throw new gr("handler_failed",{message:Re(c,`${t} did not answer`),publicMessage:`${t} did not answer`,cause:c})}if(i.aborted)throw o();if(!("success"in s)||s.success!==!0)throw ddo(s,`${t} did not answer`);let a=_se.safeParse(s.data);if(!a.success)throw new gr("handler_failed",{publicMessage:`${t} gave no readable answer`});if(a.data.state!=="completed")throw new gr("handler_failed",{publicMessage:Dse(`${t} did not answer: ${a.data.response}`)});return a.data}function pdo(e,t,n={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(U4e,({request:{agent:r,question:i}})=>udo(t,r,Ogl(i),n.networkAskTimeoutMs),w8t),e.answer($4e,({request:{agent:r,message:i}})=>udo(t,r,i,n.turnTimeoutMs),w8t),e.answer(K4e,({request:r})=>cdo(r,t),w8t),e.answer(Q4e,({request:r})=>ado(r,t),w8t),e.answer(H4e,async({request:{agent:r,instruction:i,selection:o,userPermissionLevel:s}})=>{let a=await A8t({agent:r,message:["A Studio author is asking about selected markdown.",`Instruction: ${i}`,"","Selected markdown:",o].join(`
|
|
3649
|
-
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw ddo(a,"Agent call failed");let c=_se.safeParse(a.data);if(!c.success)throw new gr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(G4e,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:Ui(r)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var Pgl,w8t;var fdo=E(()=>{lt();ldo();_a();lt();hOn();Pgl=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);w8t={everyProcess:!0}});var hdo;var mdo=E(()=>{hdo={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.873",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});function jgl(e){let t=e.auth();if(!t)return;let n=t.getIssuer();if(n2(n)||new URL(n).protocol!=="https:")return;return async(r)=>{let i=await t.getA2ASigningKey();await Auo(r,i.privateJwk,i.keyId)}}function Ngl(e){let t=e.auth();if(!t)return;let n=t.getIssuer();if(n2(n)||new URL(n).protocol!=="https:")return;return async(r)=>{let i=await t.getA2ASigningKey();return{keyId:i.keyId,signature:Euo(r,i.privateJwk)}}}function gOn(e,t,n){let r=jgl(e);return{...r?{requestSigner:r}:{},...n.fetch?{fetch:n.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:n.isContactApproved??((i)=>e.classRuntimeState.scoped({namespace:Z4e,schema:W4e}).has(i.trim().toLowerCase()))}}async function Lgl(e,t,n){if(!n.cardReady)return;return Fuo({character:e.identity.get(),profile:e.identity.getProfile(),version:hdo.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function zgl(e,t,n,r){let i=new URL(n.url),o=new URL(`${i.pathname}${i.search}`,r8(n)),s=await wuo({method:n.method,url:o.toString(),headers:n.headers,body:r},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function qgl(e,t,n){let r=new _ze,i=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await Lgl(e,t,n);if(!s)return c_(o.json({error:"Agent Card not ready"},503));return c_(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await Nuo(e.entityReads);return c_(o.json(s))}),r.get("/a2a",(o)=>c_(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>c_(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return c_(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await zgl(e,n,o.req.raw,s)}catch{return c_(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return c_(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=$uo.safeParse(c);if(!l.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(uuo(o.req.raw.headers)){let p=l.data.method==="message/send"?duo(l.data.params):void 0,f=p?.op==="list"?await muo(e.entityReads,a.permissionLevel):await fuo(e.entityReads,a.permissionLevel,p,Ngl(e));if(!f)return c_(o.json({error:"Not found"},404));return c_(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:f}]}}))}if(l.data.method==="message/stream"){let p=Kuo.safeParse(l.data.params??{});if(!p.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let f=Quo(l.data.id,p.data.message,{taskManager:n.taskManager,turnSupervisor:n.turnSupervisor,agentService:i,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:n.publicAsks});if("error"in f)return c_(o.json(f));return c_(new Response(f.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await Zuo(l.data,{taskManager:n.taskManager,turnSupervisor:n.turnSupervisor,agentService:i,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:n.publicAsks});return c_(o.json(d))}),r}function xOn(e={}){let t=uk({id:"a2a",config:Ouo,setup:(o)=>{let{config:s}=o,a=If(o),{servesHttp:c}=a,l=gOn(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new cOn,turnSupervisor:new lOn,jwksResolver:new LWe(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new sOn(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"This brain's agent card: how other agents discover and talk to it.",href:"/.well-known/agent-card.json",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),n=h0t(t,(o)=>{let s=If(o);pdo(s,gOn(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),r=Cf(n,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=If(o),l=qgl(c,s,a),d=(f)=>Promise.resolve(l.fetch(f)),p=(f,m)=>({path:f,method:m,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),i=NT(r,(o)=>{let{state:s}=o,{logger:a}=If(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return qd(i,(o)=>{let{config:s}=o,a=If(o),c=()=>odo(gOn(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var Fgl,c_=(e)=>_1t(e,Fgl);var yOn=E(()=>{huo();lt();_a();QH();y8t();WAn();Muo();juo();Luo();v8t();zuo();Yuo();hOn();fdo();aOn();mdo();Fgl={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"}});var Ugl,gdo;var xdo=E(()=>{yOn();yOn();Ugl=xOn(),gdo=Ugl});function S9(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function dte(e,t){return{registration:e,actionIds:t.map((n)=>n.name)}}function k9(e){return $gl.format(new Date(e))}function N8(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Hw(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function E8t(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function zfe(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let n=e.slice(t.length);if(n.length===0)return e;return n.split(":").map(decodeURIComponent).join("/")}var $gl;var qfe=E(()=>{$gl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"})});function vOn(e){let t=Hgl[e];if(t)return t;let n=e.replaceAll(/[._-]+/g," ").trim();return n.length===0?e:np(n)}function bdo(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function vdo(e,t){return e?t.get(e)??"Former Admin":"System"}function Ado(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}function wdo(e){let t=e.studio.source({definition:bOn,bind:(n)=>bOn.bind(n,{load:async({query:r})=>{let i=N8(e),o=r.get(AOn),[s,a]=await Promise.all([i.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),i.listUsers()]);return{query:o,events:s.events.map(bdo),...s.selectedEvent?{selectedEvent:bdo(s.selectedEvent)}:{},users:E8t(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:vOn(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return dte(t,bOn.actions)}var Hgl,AOn,ydo,Ggl,Zgl,bOn;var Edo=E(()=>{Zo();or();oe();qfe();Hgl={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};AOn=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(S9,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(S9,u.number().int().min(1).max(100)).default(25)}),ydo=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),Ggl=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),Zgl=u.strictObject({query:AOn,events:u.array(ydo),selectedEvent:ydo.optional(),users:u.array(Ggl),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});bOn=Sf({id:"audit",label:"Audit",priority:90,permission:"admin",query:AOn,data:Zgl,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),n=e.selectedEvent,i=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...n?{open:{forId:n.id,title:vOn(n.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:vdo(n.actorUserId,t)},{label:"Action",value:n.action},{label:"Target",value:Ado(n,t)},{label:"Occurred",value:k9(n.createdAt)},{label:"Event ID",value:n.id},{label:"Action ID",value:n.action},...n.targetId?[{label:"Target ID",value:n.targetId}]:[],...n.actorUserId?[{label:"Actor ID",value:n.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:vOn(o.action),description:`${vdo(o.actorUserId,t)} \u2192 ${Ado(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:i}}})});function tTe(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}function C8t(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function I8t(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function _8t(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((n)=>({value:n.type,label:n.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((n)=>({value:n.type,label:n.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((n)=>({value:n,label:n==="automatic"?"Automatic":"Manual"}))}}}var cM,S8t,k8t;var T8t=E(()=>{oe();cM=u.strictObject({status:u.string()}),S8t=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});k8t=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))})});import{randomUUID as Wgl}from"crypto";function kOn(e,t){let n=e.filter((r)=>r.id===t);if(n.length!==1||!n[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return n[0]}function wOn(e,t){let n=kOn(e,t);switch(n.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return n}}function Rdo(e,t){let n=kOn(e,"invitation-totals");if(n.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[wOn(e,"create-invitation-unavailable")]:[],i=kOn(e,"invitations");if(i.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=wOn(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...r,wOn(e,"invitation-filters"),i,{...o,presentation:"disclosure",blocks:[...o.blocks,n,...s]}]}}function Ygl(e){if(Vgl.has(e.state))return[];return[...e.deliveryAttemptId?[{action:TOn,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:IOn,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:Ddo}]:[],...e.state!=="expired"?[{action:_On,input:{invitationId:e.id}}]:[]]}function Cdo(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return np(e.state)}function Ido(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function Pdo(e){let t=N8(e),n=new Map,r=e.studio.source({definition:EOn,bind:(i)=>{let o=SOn.bind(i,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},Hw(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)n.set(p.invitation.id,p.registration.deliveryAttemptId);return Ido(p)}),s=IOn.bind(i,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Hw(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)n.set(p.invitation.id,p.registration.deliveryAttemptId);return Ido(p)}),a=_On.bind(i,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Hw(d));return n.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=TOn.bind(i,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Hw(d));return n.delete(l.invitationId),{invitationId:p.id,state:p.state}});return EOn.bind(i,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(COn),[p,f]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),m=f.filter((k)=>k.deliveryModes.length>0),h=p.filter((k)=>k.invitation!==void 0),g=h.filter((k)=>k.invitation&&!Sdo.has(k.invitation.state)),x=h.filter((k)=>k.invitation&&Sdo.has(k.invitation.state)),y=d.state==="pending"?g:x,v=h.flatMap((k)=>{let C=k.invitation;if(!C)return[];let I=k.identities.find((R)=>R.type!=="passkey")?.label??k.externalPeers[0]?.peerId??"Not recorded",B=n.get(C.id);return[{id:C.id,displayName:k.displayName,role:k.role,state:C.state,destination:I,updatedAt:C.claimedAt??C.cancelledAt??C.expiredAt??C.sentAt??C.updatedAt,...B?{deliveryAttemptId:B}:{}}]}),w=new Map(v.map((k)=>[k.id,k])),S=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:Wgl(),channels:m.map((k)=>({type:k.type,displayName:k.displayName,subjectLabel:k.subjectLabel,deliveryModes:k.deliveryModes})),invitations:y.slice(d.offset,d.offset+d.limit).flatMap((k)=>{let C=k.invitation?w.get(k.invitation.id):void 0;return C?[C]:[]}),...S?{selectedInvitation:S}:{},selectedTotal:y.length,pendingCount:g.length,historyCount:x.length,failureCount:g.filter((k)=>k.invitation?.state==="failed").length}}})}});return dte(r,EOn.actions)}var Sdo,Vgl,COn,_do,Kgl,Tdo,Qgl,Bdo,SOn,IOn,_On,TOn,kdo,Jgl,Ddo,EOn;var Odo=E(()=>{Zo();T8t();or();oe();qfe();Sdo=new Set(["claimed","expired","cancelled"]),Vgl=new Set(["claimed","cancelled"]),COn=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(S9,u.number().int().min(0)).optional().default(0),limit:u.preprocess(S9,u.number().int().min(1).max(100)).optional().default(25)}),_do=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),Kgl=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),Tdo=u.strictObject({invitationId:u.string().min(1)}),Qgl=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),Bdo=u.strictObject({invitationId:u.string(),state:u.string()}),SOn=La({name:"create-invitation",label:"Add a person",permission:"admin",input:Kgl,output:_do}),IOn=La({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:Tdo,output:_do}),_On=La({name:"cancel-invitation",destructive:!0,label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:Tdo,output:Bdo}),TOn=La({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:Qgl,output:Bdo}),kdo=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),Jgl=u.strictObject({query:COn,idempotencyKey:u.string(),channels:u.array(k8t),invitations:u.array(kdo),selectedInvitation:kdo.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});Ddo=tTe("Invitation setup");EOn=Sf({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:COn,data:Jgl,actions:[SOn,IOn,_On,TOn],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],n=C8t(e.channels),r;if(e.channels.length>0&&n.length>0)r={action:SOn,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:I8t("Role"),..._8t(e.channels,n)}},result:Ddo};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let i=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${np(o.role)} \xB7 ${Cdo(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...i?{open:{forId:i.id,title:i.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:np(i.role)},{label:"Delivery",value:Cdo(i)},{label:"Destination",value:i.destination},{label:"Updated",value:k9(i.updatedAt)}]},{type:"actions",id:"invitation-actions",items:Ygl(i)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(np).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...r?{primaryAction:r}:{},blocks:t}}})});function B8t(e,t){let n=e.filter((i)=>i.id===t);if(n.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=n[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function OOn(e){let t=e.some((n)=>n.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[B8t(e,"peers"),B8t(e,"link-peer"),B8t(e,t)],invitations:[B8t(e,t)]}}function Mdo(e){let t=N8(e),n=e.studio.source({definition:BOn,bind:(r)=>{let i=ROn.bind(r,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Hw(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=DOn.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Hw(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return BOn.bind(r,{actions:[i,o],load:async({query:s})=>{let a=s.get(POn),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((f)=>({peerId:f.peerId,displayName:p.displayName,role:p.role,verificationStatus:f.verificationStatus,createdAt:f.createdAt}))),people:E8t(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return dte(n,BOn.actions)}var POn,Xgl,e0l,ROn,DOn,t0l,n0l,BOn;var Fdo=E(()=>{Zo();or();oe();T8t();qfe();POn=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),Xgl=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),e0l=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),ROn=La({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:Xgl,output:S8t}),DOn=La({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:e0l,output:cM}),t0l=u.strictObject({query:POn,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(k8t)});n0l=tTe("Peer invitation setup"),BOn=Sf({id:"peers",label:"Peers",priority:12,permission:"admin",query:POn,data:t0l,actions:[ROn,DOn],view:({data:e})=>{let t=C8t(e.channels),n=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)n.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:ROn,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:I8t("Local role"),..._8t(e.channels,t)}},result:n0l}]});else n.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return n.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:DOn,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((r)=>({value:r.userId,label:r.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:zfe(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:k9(r.createdAt)},compact:{title:zfe(r.peerId),metadata:[r.displayName,np(r.role),k9(r.createdAt)],badges:[{label:np(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:n}}})});function MOn(e,t){let n=e.filter((r)=>r.id===t);if(n.length!==1||!n[0])throw Error(`People tab composition requires block "${t}" exactly once`);return n[0]}function jdo(e,t,n){let r=MOn(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let i=MOn(e,"people");if(i.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=MOn(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...n].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[i,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}function o0l(e){return e.revokedAt===void 0&&e.type!=="passkey"}function s0l(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}function m0l(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function FOn(e){return{type:"notice",tone:"warn",text:e}}function h0l(e){return{type:"action",action:WOn,input:{userId:e},result:f0l}}function g0l(e,t){return{type:"action",action:VOn,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((n)=>({value:n.type,label:n.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function x0l(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}function R8t(e,t){return e.find((n)=>n.userId===t)?.displayName??"person"}async function y0l(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function Ndo(e){let t=N8(e),n=e.studio.source({definition:jOn,bind:(r)=>{let i=NOn.bind(r,async({input:m,caller:h})=>(await t.updateUserRole(m.userId,m.role,Hw(h)),{status:`Role changed to ${np(m.role)}.`}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Change ${R8t(h,m.userId)}\u2019s role to ${np(m.role)}?`,revision:`${m.userId}:${m.role}`}}),o=LOn.bind(r,async({input:m,caller:h})=>(await t.updateUserStatus(m.userId,m.status,Hw(h)),{status:`Person ${m.status}.`}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`${m.status==="active"?"Reactivate":"Suspend"} ${R8t(h,m.userId)}?`,revision:`${m.userId}:${m.status}`}}),s=zOn.bind(r,async({input:m,caller:h})=>(await t.deleteSuspendedUser(m.userId,Hw(h)),{status:"Suspended person permanently deleted."}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Permanently delete ${R8t(h,m.userId)}? Audit history is retained.`,revision:m.userId}}),a=qOn.bind(r,async({input:m,caller:h})=>(await t.revokePasskey(m.credentialId,Hw(h)),{status:"Passkey revoked."}),({input:m})=>({summary:"Revoke this passkey immediately?",revision:`${m.userId}:${m.credentialId}`})),c=WOn.bind(r,async({input:m,caller:h})=>{let g=await t.startPasskeyRegistrationForUser(m.userId,Hw(h));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=UOn.bind(r,async({input:m,caller:h})=>{let g=await t.revokeUserSessionsAndRefreshTokens(m.userId,Hw(h));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Sign ${R8t(h,m.userId)} out everywhere?`,revision:m.userId}}),d=VOn.bind(r,async({input:m,caller:h})=>(await t.attachIdentity({userId:m.userId,type:m.type,subject:m.subject,...m.issuer?{issuer:m.issuer}:{},...m.label?{label:m.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Hw(h)),{status:"Verified channel attached."})),p=$On.bind(r,async({input:m,caller:h})=>(await t.detachIdentity(m.identityId,Hw(h)),{status:"Channel detached."}),({input:m})=>({summary:"Detach this channel identity?",revision:`${m.userId}:${m.identityId}`})),f=HOn.bind(r,async({input:m,caller:h})=>(await t.unlinkExternalPeer(m,Hw(h)),{status:"External peer unlinked from the local person."}),({input:m})=>({summary:`Unlink ${m.peerId}? Local access will not change.`,revision:`${m.peerId}:${m.userId}`}));return jOn.bind(r,{actions:[i,o,s,a,c,l,d,p,f],load:async({query:m,caller:h})=>{let g=m.get(GOn),[x,y,v]=await Promise.all([y0l(t),t.listAdminUsers(),t.listInvitationChannels()]),w=y.filter((B)=>B.status!=="invited"),S=w.find((B)=>B.isAnchor)??w.find((B)=>B.role==="admin"&&B.status==="active"),k=x??x0l(S?.displayName??"Brain owner",w.filter((B)=>B.role==="admin"&&B.status==="active").length),C=w.filter((B)=>B.status==="active"),I=new Map(v.map((B)=>[B.type,B.displayName]));return{query:g,anchor:{kind:k.kind,configuredKind:k.configuredKind,displayName:k.displayName,administeredBy:k.administeredBy},people:w.flatMap((B)=>{if(B.status==="invited")return[];return[{userId:B.userId,displayName:B.displayName,role:B.role,status:B.status,isAnchor:B.isAnchor,isSelf:h?.actor.id===B.userId,...B.profileEntityId?{profileEntityId:B.profileEntityId}:{},passkeys:B.passkeys.map((R)=>({id:R.id,kind:s0l(R),createdAt:R.createdAt})),identities:B.identities.filter(o0l).map((R)=>({id:R.id,type:R.type,displayName:I.get(R.type)??np(R.type),label:R.label??"Connected identity",verified:R.verifiedAt!==void 0})),peers:B.externalPeers.map((R)=>({peerId:R.peerId,verificationStatus:R.verificationStatus}))}]}),activeCount:C.length,activeAdminCount:C.filter((B)=>B.role==="admin").length,suspendedCount:w.length-C.length,channelTypes:v.map((B)=>({type:B.type,displayName:B.displayName}))}}})}});return dte(n,jOn.actions)}var GOn,ZOn,r0l,i0l,a0l,c0l,l0l,u0l,NOn,LOn,zOn,qOn,WOn,UOn,VOn,$On,HOn,d0l,p0l,f0l,jOn;var Ldo=E(()=>{Zo();or();oe();T8t();qfe();GOn=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),ZOn=u.strictObject({userId:u.string().min(1)}),r0l=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),i0l=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});a0l=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),c0l=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),l0l=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),u0l=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),NOn=La({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:r0l,output:cM}),LOn=La({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:i0l,output:cM}),zOn=La({name:"delete-person",destructive:!0,label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:ZOn,output:cM}),qOn=La({name:"revoke-person-passkey",destructive:!0,label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:a0l,output:cM}),WOn=La({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:ZOn,output:S8t}),UOn=La({name:"revoke-person-sessions",destructive:!0,label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:ZOn,output:cM}),VOn=La({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:c0l,output:cM}),$On=La({name:"detach-person-identity",destructive:!0,label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:l0l,output:cM}),HOn=La({name:"unlink-external-peer",destructive:!0,label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:u0l,output:cM}),d0l=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),p0l=u.strictObject({query:GOn,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(d0l),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),f0l=tTe("Passkey setup");jOn=Sf({id:"people",label:"People",priority:10,permission:"admin",query:GOn,data:p0l,actions:[NOn,LOn,zOn,qOn,WOn,UOn,VOn,$On,HOn],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((i)=>i.userId===e.query.selected),n=[];if(t){let i=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":i?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":i?"Add another active Admin before suspending this person.":void 0;if(n.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:np(t.role)},{label:"Status",value:np(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)n.push({type:"notice",tone:"warn",text:o});else n.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:NOn,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});n.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:LOn,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0,destructive:t.status==="active"},...t.status==="active"&&!t.isSelf?[{action:UOn,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:zOn,input:{userId:t.userId}}]:[]]},...t.isSelf?[m0l()]:[],...s&&t.status==="active"?[FOn(s)]:[]]}),n.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:k9(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${k9(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:qOn,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[h0l(t.userId)]:[FOn("A verified channel is required for setup delivery.")]:[]]}),n.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:$On,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[g0l(t.userId,e.channelTypes)]:[FOn("No attachable channel type is configured.")]]}),n.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),n.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:zfe(a.peerId),description:`Vouched in by ${zfe(a.peerId)} \xB7 ${a.peerId}`,metadata:[np(a.verificationStatus)],actions:[{action:HOn,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((i,o)=>Number(o.isSelf)-Number(i.isSelf)||Number(i.isAnchor)-Number(o.isAnchor)||i.displayName.localeCompare(o.displayName)).map((i)=>({id:i.userId,title:i.displayName,description:[np(i.role),np(i.status),...i.isSelf?["You"]:[],...i.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[i.identities.length===0?"No linked identities":i.identities.length===1?"One linked identity":`${i.identities.length} linked identities`,...i.peers.length>0?[`Arrived via ${zfe(i.peers[0]?.peerId)}`]:[]],...i.isSelf?{link:{detail:{itemId:i.userId}}}:{},links:[{label:i.isSelf?"Account \u2192":i.isAnchor?"View protection":"Manage person",target:i.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:i.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:n}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}})});function v0l(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function A0l(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function w0l(e,t){if(!A0l(e))throw Error(`${t} tab returned invalid workspace data`);return e}function zdo(e,t){let n=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);n.push(r)}return n}function KOn(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function $We(e,t,n,r){return w0l(await e.dataProvider(t,n,r),e.label)}async function E0l(e,t,n,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,n,r)}function S0l(e){let t=new Map;for(let n of e)for(let r of n.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!n.registration.actionHandler)throw Error(`Administration source "${n.registration.label}" declares actions without a handler`);t.set(r,n.registration)}return t}function qdo(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function k0l(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function Udo(e){if(!e.studio.isAvailable())return;let t=Ndo(e),n=Pdo(e),r=Mdo(e),i=wdo(e),o=S0l([t,n,r,i]),s=t.registration,a=n.registration,c=r.registration,l=i.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:u3,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,f)=>{let m=b0l.parse(p??{}),h,g=KOn("People"),x=KOn("Invitations"),y=KOn("Audit");if(m.tab==="people"){let[v,w]=await Promise.all([$We(s,d,{...m.selected?{selected:m.selected}:{}},f),$We(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=OOn(w.view.blocks);g=[...jdo(zdo(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},S.people).blocks]}else if(m.tab==="invitations"){let[v,w]=await Promise.all([$We(a,d,{...m.state?{state:m.state}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f),$We(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=OOn(w.view.blocks),k=Rdo(v.view.blocks,S.invitations);h=v.view.primaryAction,x=[...k.blocks]}else{let v=await $We(l,d,{...m.actorUserId?{actorUserId:m.actorUserId}:{},...m.action?{action:m.action}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f);y=zdo(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...h?{primaryAction:h}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:m.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:x},{id:"audit",label:"Access activity",blocks:y}]}]}}},actionHandler:async(d,p,f)=>{let m=v0l(d);if(!m)throw new gr("invalid_input",{publicMessage:"Administration action id is required"});let h=o.get(m);if(!h)throw new gr("not_found",{publicMessage:`Unknown Administration action: ${m}`});return E0l(h,d,p,f)},badgeProvider:async()=>{let d=qdo(await N8(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>k0l(qdo(await N8(e).listAdminUsers()))})}var b0l;var $do=E(()=>{wn();lt();oe();Edo();Odo();Fdo();Ldo();qfe();b0l=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(S9,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(S9,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()})});function T0l(e,t){let n=e.flatMap((r)=>{let i=r.invitation;if(!i)return[];if(i.state==="failed")return[{id:i.id,displayName:r.displayName,state:i.state,reason:"delivery-failed",...i.expiresAt!==void 0?{expiresAt:i.expiresAt}:{}}];if(!["pending","sending","sent"].includes(i.state)||i.expiresAt===void 0||i.expiresAt<=t||i.expiresAt>t+C0l)return[];return[{id:i.id,displayName:r.displayName,state:i.state,reason:"expiring",expiresAt:i.expiresAt}]});return n.sort((r,i)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(i.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(i.displayName)),{invitations:n,expiringCount:n.filter((r)=>r.reason==="expiring").length,failureCount:n.filter((r)=>r.reason==="delivery-failed").length}}async function Gdo(e,t){t.throwIfAborted();let n=await N8(e).listAdminUsers();return t.throwIfAborted(),T0l(n,Date.now())}var C0l=259200000,I0l,_0l,Hdo;var Zdo=E(()=>{Zo();qfe();I0l=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),_0l=u.strictObject({invitations:u.array(I0l),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),Hdo=zd({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:_0l,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${k9(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})})});var B0l,R0l,QOn;var Wdo=E(()=>{Zo();wn();$do();Zdo();B0l=u.strictObject({}),R0l=$i({id:"admin",config:B0l},{subscriptions:(e)=>{let t=ni(e);return t.registered(async()=>{await Udo(t)}),[]},dashboardWidgets:(e)=>{let t=ni(e);return[Hdo.bind(e,({signal:n})=>Gdo(t,n))]}}),QOn=R0l});var Vdo=E(()=>{Wdo()});var Jr=E(()=>{oe();Ki();Ki()});var Du="agent",Kdo="agent-network",Qdo="agent-proximity",JOn="agent-discovery:entities",Jdo="agent-discovery:proximity-map",YOn="proximity-map",XOn="agent-list",eMn="agent-detail",Gw="skill",Ydo=30,Xdo=120,D8t="skill-derivation",epo="skill-derivation",tMn="skill:skill-derivation",tpo="skills";var D0l,nMn,pte,HWe,fte;var _L=E(()=>{oe();_n();D0l=u.string().trim().min(1).max(Xdo),nMn=u.array(D0l).max(Ydo),pte=u.object({name:u.string(),description:u.string(),tags:nMn,examples:u.array(u.string())}),HWe=pte,fte=Qp.extend({entityType:u.literal(Gw),metadata:HWe})});var P8t,kZ,P0l,lM,GWe,Op,O0l,ZWe,M0l,F0l;var Zw=E(()=>{oe();_L();wn();_n();P8t=u.object({name:u.string(),description:u.string(),tags:nMn}),kZ=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),P0l=HH,lM=u.object({name:u.string(),kind:P0l,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:kZ,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GWe=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:kZ,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Op=Qp.extend({entityType:u.literal(Du),metadata:GWe}),O0l=Vs.extend({entityType:u.literal(Du),metadata:GWe}),ZWe=O0l.extend({frontmatter:lM,about:u.string(),skills:u.array(P8t),notes:u.string()}),M0l=ZWe.extend({url:u.string().optional(),typeLabel:u.string().optional()}),F0l=ZWe.extend({url:u.string(),typeLabel:u.string()})});function N0l(e){try{return As(e,j0l).content}catch{return e}}function rMn(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:HAe(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function npo(e){return lh(Du,e,lM)}function WWe(e){return{content:e,metadata:rMn(npo(e))}}function nTe(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:kZ.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},n=twt({about:e.about,skills:e.skills,notes:e.notes});return na(n,t)}function L8(e,t={}){return nTe({...e.frontmatter,...e.body,...t})}function VWe(e){return r1e(N0l(e))}function Ux(e){return{frontmatter:npo(e.content),body:VWe(e.content)}}function iMn(e){return na("",e)}var j0l;var Rk=E(()=>{wn();_n();or();oe();Zw();_L();j0l=u.record(u.string(),u.unknown())});function L0l(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function rpo(e,t,n={}){let r=n.minCount??1,i=n.topN??12,o=new Map,s=(a)=>{for(let c of sA(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=VWe(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(L0l).slice(0,i)}function ipo(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:n})=>`- ${t} (${n})`)].join(`
|
|
3649
|
+
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw ddo(a,"Agent call failed");let c=_se.safeParse(a.data);if(!c.success)throw new gr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(G4e,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:Ui(r)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var Pgl,w8t;var fdo=E(()=>{lt();ldo();_a();lt();hOn();Pgl=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);w8t={everyProcess:!0}});var hdo;var mdo=E(()=>{hdo={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.875",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});function jgl(e){let t=e.auth();if(!t)return;let n=t.getIssuer();if(n2(n)||new URL(n).protocol!=="https:")return;return async(r)=>{let i=await t.getA2ASigningKey();await Auo(r,i.privateJwk,i.keyId)}}function Ngl(e){let t=e.auth();if(!t)return;let n=t.getIssuer();if(n2(n)||new URL(n).protocol!=="https:")return;return async(r)=>{let i=await t.getA2ASigningKey();return{keyId:i.keyId,signature:Euo(r,i.privateJwk)}}}function gOn(e,t,n){let r=jgl(e);return{...r?{requestSigner:r}:{},...n.fetch?{fetch:n.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:n.isContactApproved??((i)=>e.classRuntimeState.scoped({namespace:Z4e,schema:W4e}).has(i.trim().toLowerCase()))}}async function Lgl(e,t,n){if(!n.cardReady)return;return Fuo({character:e.identity.get(),profile:e.identity.getProfile(),version:hdo.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function zgl(e,t,n,r){let i=new URL(n.url),o=new URL(`${i.pathname}${i.search}`,r8(n)),s=await wuo({method:n.method,url:o.toString(),headers:n.headers,body:r},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function qgl(e,t,n){let r=new _ze,i=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await Lgl(e,t,n);if(!s)return c_(o.json({error:"Agent Card not ready"},503));return c_(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await Nuo(e.entityReads);return c_(o.json(s))}),r.get("/a2a",(o)=>c_(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>c_(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return c_(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await zgl(e,n,o.req.raw,s)}catch{return c_(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return c_(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=$uo.safeParse(c);if(!l.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(uuo(o.req.raw.headers)){let p=l.data.method==="message/send"?duo(l.data.params):void 0,f=p?.op==="list"?await muo(e.entityReads,a.permissionLevel):await fuo(e.entityReads,a.permissionLevel,p,Ngl(e));if(!f)return c_(o.json({error:"Not found"},404));return c_(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:f}]}}))}if(l.data.method==="message/stream"){let p=Kuo.safeParse(l.data.params??{});if(!p.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let f=Quo(l.data.id,p.data.message,{taskManager:n.taskManager,turnSupervisor:n.turnSupervisor,agentService:i,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:n.publicAsks});if("error"in f)return c_(o.json(f));return c_(new Response(f.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await Zuo(l.data,{taskManager:n.taskManager,turnSupervisor:n.turnSupervisor,agentService:i,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:n.publicAsks});return c_(o.json(d))}),r}function xOn(e={}){let t=uk({id:"a2a",config:Ouo,setup:(o)=>{let{config:s}=o,a=If(o),{servesHttp:c}=a,l=gOn(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new cOn,turnSupervisor:new lOn,jwksResolver:new LWe(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new sOn(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"This brain's agent card: how other agents discover and talk to it.",href:"/.well-known/agent-card.json",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),n=h0t(t,(o)=>{let s=If(o);pdo(s,gOn(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),r=Cf(n,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=If(o),l=qgl(c,s,a),d=(f)=>Promise.resolve(l.fetch(f)),p=(f,m)=>({path:f,method:m,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),i=NT(r,(o)=>{let{state:s}=o,{logger:a}=If(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return qd(i,(o)=>{let{config:s}=o,a=If(o),c=()=>odo(gOn(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var Fgl,c_=(e)=>_1t(e,Fgl);var yOn=E(()=>{huo();lt();_a();QH();y8t();WAn();Muo();juo();Luo();v8t();zuo();Yuo();hOn();fdo();aOn();mdo();Fgl={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"}});var Ugl,gdo;var xdo=E(()=>{yOn();yOn();Ugl=xOn(),gdo=Ugl});function S9(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function dte(e,t){return{registration:e,actionIds:t.map((n)=>n.name)}}function k9(e){return $gl.format(new Date(e))}function N8(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Hw(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function E8t(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function zfe(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let n=e.slice(t.length);if(n.length===0)return e;return n.split(":").map(decodeURIComponent).join("/")}var $gl;var qfe=E(()=>{$gl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"})});function vOn(e){let t=Hgl[e];if(t)return t;let n=e.replaceAll(/[._-]+/g," ").trim();return n.length===0?e:np(n)}function bdo(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function vdo(e,t){return e?t.get(e)??"Former Admin":"System"}function Ado(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}function wdo(e){let t=e.studio.source({definition:bOn,bind:(n)=>bOn.bind(n,{load:async({query:r})=>{let i=N8(e),o=r.get(AOn),[s,a]=await Promise.all([i.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),i.listUsers()]);return{query:o,events:s.events.map(bdo),...s.selectedEvent?{selectedEvent:bdo(s.selectedEvent)}:{},users:E8t(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:vOn(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return dte(t,bOn.actions)}var Hgl,AOn,ydo,Ggl,Zgl,bOn;var Edo=E(()=>{Zo();or();oe();qfe();Hgl={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};AOn=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(S9,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(S9,u.number().int().min(1).max(100)).default(25)}),ydo=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),Ggl=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),Zgl=u.strictObject({query:AOn,events:u.array(ydo),selectedEvent:ydo.optional(),users:u.array(Ggl),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});bOn=Sf({id:"audit",label:"Audit",priority:90,permission:"admin",query:AOn,data:Zgl,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),n=e.selectedEvent,i=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...n?{open:{forId:n.id,title:vOn(n.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:vdo(n.actorUserId,t)},{label:"Action",value:n.action},{label:"Target",value:Ado(n,t)},{label:"Occurred",value:k9(n.createdAt)},{label:"Event ID",value:n.id},{label:"Action ID",value:n.action},...n.targetId?[{label:"Target ID",value:n.targetId}]:[],...n.actorUserId?[{label:"Actor ID",value:n.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:vOn(o.action),description:`${vdo(o.actorUserId,t)} \u2192 ${Ado(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:i}}})});function tTe(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}function C8t(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function I8t(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function _8t(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((n)=>({value:n.type,label:n.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((n)=>({value:n.type,label:n.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((n)=>({value:n,label:n==="automatic"?"Automatic":"Manual"}))}}}var cM,S8t,k8t;var T8t=E(()=>{oe();cM=u.strictObject({status:u.string()}),S8t=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});k8t=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))})});import{randomUUID as Wgl}from"crypto";function kOn(e,t){let n=e.filter((r)=>r.id===t);if(n.length!==1||!n[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return n[0]}function wOn(e,t){let n=kOn(e,t);switch(n.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return n}}function Rdo(e,t){let n=kOn(e,"invitation-totals");if(n.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[wOn(e,"create-invitation-unavailable")]:[],i=kOn(e,"invitations");if(i.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=wOn(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...r,wOn(e,"invitation-filters"),i,{...o,presentation:"disclosure",blocks:[...o.blocks,n,...s]}]}}function Ygl(e){if(Vgl.has(e.state))return[];return[...e.deliveryAttemptId?[{action:TOn,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:IOn,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:Ddo}]:[],...e.state!=="expired"?[{action:_On,input:{invitationId:e.id}}]:[]]}function Cdo(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return np(e.state)}function Ido(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function Pdo(e){let t=N8(e),n=new Map,r=e.studio.source({definition:EOn,bind:(i)=>{let o=SOn.bind(i,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},Hw(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)n.set(p.invitation.id,p.registration.deliveryAttemptId);return Ido(p)}),s=IOn.bind(i,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Hw(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)n.set(p.invitation.id,p.registration.deliveryAttemptId);return Ido(p)}),a=_On.bind(i,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Hw(d));return n.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=TOn.bind(i,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Hw(d));return n.delete(l.invitationId),{invitationId:p.id,state:p.state}});return EOn.bind(i,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(COn),[p,f]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),m=f.filter((k)=>k.deliveryModes.length>0),h=p.filter((k)=>k.invitation!==void 0),g=h.filter((k)=>k.invitation&&!Sdo.has(k.invitation.state)),x=h.filter((k)=>k.invitation&&Sdo.has(k.invitation.state)),y=d.state==="pending"?g:x,v=h.flatMap((k)=>{let C=k.invitation;if(!C)return[];let I=k.identities.find((R)=>R.type!=="passkey")?.label??k.externalPeers[0]?.peerId??"Not recorded",B=n.get(C.id);return[{id:C.id,displayName:k.displayName,role:k.role,state:C.state,destination:I,updatedAt:C.claimedAt??C.cancelledAt??C.expiredAt??C.sentAt??C.updatedAt,...B?{deliveryAttemptId:B}:{}}]}),w=new Map(v.map((k)=>[k.id,k])),S=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:Wgl(),channels:m.map((k)=>({type:k.type,displayName:k.displayName,subjectLabel:k.subjectLabel,deliveryModes:k.deliveryModes})),invitations:y.slice(d.offset,d.offset+d.limit).flatMap((k)=>{let C=k.invitation?w.get(k.invitation.id):void 0;return C?[C]:[]}),...S?{selectedInvitation:S}:{},selectedTotal:y.length,pendingCount:g.length,historyCount:x.length,failureCount:g.filter((k)=>k.invitation?.state==="failed").length}}})}});return dte(r,EOn.actions)}var Sdo,Vgl,COn,_do,Kgl,Tdo,Qgl,Bdo,SOn,IOn,_On,TOn,kdo,Jgl,Ddo,EOn;var Odo=E(()=>{Zo();T8t();or();oe();qfe();Sdo=new Set(["claimed","expired","cancelled"]),Vgl=new Set(["claimed","cancelled"]),COn=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(S9,u.number().int().min(0)).optional().default(0),limit:u.preprocess(S9,u.number().int().min(1).max(100)).optional().default(25)}),_do=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),Kgl=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),Tdo=u.strictObject({invitationId:u.string().min(1)}),Qgl=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),Bdo=u.strictObject({invitationId:u.string(),state:u.string()}),SOn=La({name:"create-invitation",label:"Add a person",permission:"admin",input:Kgl,output:_do}),IOn=La({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:Tdo,output:_do}),_On=La({name:"cancel-invitation",destructive:!0,label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:Tdo,output:Bdo}),TOn=La({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:Qgl,output:Bdo}),kdo=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),Jgl=u.strictObject({query:COn,idempotencyKey:u.string(),channels:u.array(k8t),invitations:u.array(kdo),selectedInvitation:kdo.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});Ddo=tTe("Invitation setup");EOn=Sf({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:COn,data:Jgl,actions:[SOn,IOn,_On,TOn],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],n=C8t(e.channels),r;if(e.channels.length>0&&n.length>0)r={action:SOn,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:I8t("Role"),..._8t(e.channels,n)}},result:Ddo};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let i=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${np(o.role)} \xB7 ${Cdo(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...i?{open:{forId:i.id,title:i.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:np(i.role)},{label:"Delivery",value:Cdo(i)},{label:"Destination",value:i.destination},{label:"Updated",value:k9(i.updatedAt)}]},{type:"actions",id:"invitation-actions",items:Ygl(i)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(np).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...r?{primaryAction:r}:{},blocks:t}}})});function B8t(e,t){let n=e.filter((i)=>i.id===t);if(n.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=n[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function OOn(e){let t=e.some((n)=>n.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[B8t(e,"peers"),B8t(e,"link-peer"),B8t(e,t)],invitations:[B8t(e,t)]}}function Mdo(e){let t=N8(e),n=e.studio.source({definition:BOn,bind:(r)=>{let i=ROn.bind(r,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Hw(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=DOn.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Hw(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return BOn.bind(r,{actions:[i,o],load:async({query:s})=>{let a=s.get(POn),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((f)=>({peerId:f.peerId,displayName:p.displayName,role:p.role,verificationStatus:f.verificationStatus,createdAt:f.createdAt}))),people:E8t(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return dte(n,BOn.actions)}var POn,Xgl,e0l,ROn,DOn,t0l,n0l,BOn;var Fdo=E(()=>{Zo();or();oe();T8t();qfe();POn=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),Xgl=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),e0l=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),ROn=La({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:Xgl,output:S8t}),DOn=La({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:e0l,output:cM}),t0l=u.strictObject({query:POn,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(k8t)});n0l=tTe("Peer invitation setup"),BOn=Sf({id:"peers",label:"Peers",priority:12,permission:"admin",query:POn,data:t0l,actions:[ROn,DOn],view:({data:e})=>{let t=C8t(e.channels),n=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)n.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:ROn,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:I8t("Local role"),..._8t(e.channels,t)}},result:n0l}]});else n.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return n.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:DOn,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((r)=>({value:r.userId,label:r.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:zfe(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:k9(r.createdAt)},compact:{title:zfe(r.peerId),metadata:[r.displayName,np(r.role),k9(r.createdAt)],badges:[{label:np(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:n}}})});function MOn(e,t){let n=e.filter((r)=>r.id===t);if(n.length!==1||!n[0])throw Error(`People tab composition requires block "${t}" exactly once`);return n[0]}function jdo(e,t,n){let r=MOn(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let i=MOn(e,"people");if(i.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=MOn(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...n].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[i,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}function o0l(e){return e.revokedAt===void 0&&e.type!=="passkey"}function s0l(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}function m0l(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function FOn(e){return{type:"notice",tone:"warn",text:e}}function h0l(e){return{type:"action",action:WOn,input:{userId:e},result:f0l}}function g0l(e,t){return{type:"action",action:VOn,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((n)=>({value:n.type,label:n.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function x0l(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}function R8t(e,t){return e.find((n)=>n.userId===t)?.displayName??"person"}async function y0l(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function Ndo(e){let t=N8(e),n=e.studio.source({definition:jOn,bind:(r)=>{let i=NOn.bind(r,async({input:m,caller:h})=>(await t.updateUserRole(m.userId,m.role,Hw(h)),{status:`Role changed to ${np(m.role)}.`}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Change ${R8t(h,m.userId)}\u2019s role to ${np(m.role)}?`,revision:`${m.userId}:${m.role}`}}),o=LOn.bind(r,async({input:m,caller:h})=>(await t.updateUserStatus(m.userId,m.status,Hw(h)),{status:`Person ${m.status}.`}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`${m.status==="active"?"Reactivate":"Suspend"} ${R8t(h,m.userId)}?`,revision:`${m.userId}:${m.status}`}}),s=zOn.bind(r,async({input:m,caller:h})=>(await t.deleteSuspendedUser(m.userId,Hw(h)),{status:"Suspended person permanently deleted."}),async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Permanently delete ${R8t(h,m.userId)}? Audit history is retained.`,revision:m.userId}}),a=qOn.bind(r,async({input:m,caller:h})=>(await t.revokePasskey(m.credentialId,Hw(h)),{status:"Passkey revoked."}),({input:m})=>({summary:"Revoke this passkey immediately?",revision:`${m.userId}:${m.credentialId}`})),c=WOn.bind(r,async({input:m,caller:h})=>{let g=await t.startPasskeyRegistrationForUser(m.userId,Hw(h));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=UOn.bind(r,async({input:m,caller:h})=>{let g=await t.revokeUserSessionsAndRefreshTokens(m.userId,Hw(h));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:m})=>{let h=await t.listAdminUsers();return{summary:`Sign ${R8t(h,m.userId)} out everywhere?`,revision:m.userId}}),d=VOn.bind(r,async({input:m,caller:h})=>(await t.attachIdentity({userId:m.userId,type:m.type,subject:m.subject,...m.issuer?{issuer:m.issuer}:{},...m.label?{label:m.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Hw(h)),{status:"Verified channel attached."})),p=$On.bind(r,async({input:m,caller:h})=>(await t.detachIdentity(m.identityId,Hw(h)),{status:"Channel detached."}),({input:m})=>({summary:"Detach this channel identity?",revision:`${m.userId}:${m.identityId}`})),f=HOn.bind(r,async({input:m,caller:h})=>(await t.unlinkExternalPeer(m,Hw(h)),{status:"External peer unlinked from the local person."}),({input:m})=>({summary:`Unlink ${m.peerId}? Local access will not change.`,revision:`${m.peerId}:${m.userId}`}));return jOn.bind(r,{actions:[i,o,s,a,c,l,d,p,f],load:async({query:m,caller:h})=>{let g=m.get(GOn),[x,y,v]=await Promise.all([y0l(t),t.listAdminUsers(),t.listInvitationChannels()]),w=y.filter((B)=>B.status!=="invited"),S=w.find((B)=>B.isAnchor)??w.find((B)=>B.role==="admin"&&B.status==="active"),k=x??x0l(S?.displayName??"Brain owner",w.filter((B)=>B.role==="admin"&&B.status==="active").length),C=w.filter((B)=>B.status==="active"),I=new Map(v.map((B)=>[B.type,B.displayName]));return{query:g,anchor:{kind:k.kind,configuredKind:k.configuredKind,displayName:k.displayName,administeredBy:k.administeredBy},people:w.flatMap((B)=>{if(B.status==="invited")return[];return[{userId:B.userId,displayName:B.displayName,role:B.role,status:B.status,isAnchor:B.isAnchor,isSelf:h?.actor.id===B.userId,...B.profileEntityId?{profileEntityId:B.profileEntityId}:{},passkeys:B.passkeys.map((R)=>({id:R.id,kind:s0l(R),createdAt:R.createdAt})),identities:B.identities.filter(o0l).map((R)=>({id:R.id,type:R.type,displayName:I.get(R.type)??np(R.type),label:R.label??"Connected identity",verified:R.verifiedAt!==void 0})),peers:B.externalPeers.map((R)=>({peerId:R.peerId,verificationStatus:R.verificationStatus}))}]}),activeCount:C.length,activeAdminCount:C.filter((B)=>B.role==="admin").length,suspendedCount:w.length-C.length,channelTypes:v.map((B)=>({type:B.type,displayName:B.displayName}))}}})}});return dte(n,jOn.actions)}var GOn,ZOn,r0l,i0l,a0l,c0l,l0l,u0l,NOn,LOn,zOn,qOn,WOn,UOn,VOn,$On,HOn,d0l,p0l,f0l,jOn;var Ldo=E(()=>{Zo();or();oe();T8t();qfe();GOn=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),ZOn=u.strictObject({userId:u.string().min(1)}),r0l=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),i0l=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});a0l=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),c0l=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),l0l=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),u0l=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),NOn=La({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:r0l,output:cM}),LOn=La({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:i0l,output:cM}),zOn=La({name:"delete-person",destructive:!0,label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:ZOn,output:cM}),qOn=La({name:"revoke-person-passkey",destructive:!0,label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:a0l,output:cM}),WOn=La({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:ZOn,output:S8t}),UOn=La({name:"revoke-person-sessions",destructive:!0,label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:ZOn,output:cM}),VOn=La({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:c0l,output:cM}),$On=La({name:"detach-person-identity",destructive:!0,label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:l0l,output:cM}),HOn=La({name:"unlink-external-peer",destructive:!0,label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:u0l,output:cM}),d0l=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),p0l=u.strictObject({query:GOn,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(d0l),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),f0l=tTe("Passkey setup");jOn=Sf({id:"people",label:"People",priority:10,permission:"admin",query:GOn,data:p0l,actions:[NOn,LOn,zOn,qOn,WOn,UOn,VOn,$On,HOn],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((i)=>i.userId===e.query.selected),n=[];if(t){let i=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":i?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":i?"Add another active Admin before suspending this person.":void 0;if(n.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:np(t.role)},{label:"Status",value:np(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)n.push({type:"notice",tone:"warn",text:o});else n.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:NOn,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});n.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:LOn,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0,destructive:t.status==="active"},...t.status==="active"&&!t.isSelf?[{action:UOn,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:zOn,input:{userId:t.userId}}]:[]]},...t.isSelf?[m0l()]:[],...s&&t.status==="active"?[FOn(s)]:[]]}),n.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:k9(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${k9(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:qOn,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[h0l(t.userId)]:[FOn("A verified channel is required for setup delivery.")]:[]]}),n.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:$On,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[g0l(t.userId,e.channelTypes)]:[FOn("No attachable channel type is configured.")]]}),n.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),n.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:zfe(a.peerId),description:`Vouched in by ${zfe(a.peerId)} \xB7 ${a.peerId}`,metadata:[np(a.verificationStatus)],actions:[{action:HOn,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((i,o)=>Number(o.isSelf)-Number(i.isSelf)||Number(i.isAnchor)-Number(o.isAnchor)||i.displayName.localeCompare(o.displayName)).map((i)=>({id:i.userId,title:i.displayName,description:[np(i.role),np(i.status),...i.isSelf?["You"]:[],...i.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[i.identities.length===0?"No linked identities":i.identities.length===1?"One linked identity":`${i.identities.length} linked identities`,...i.peers.length>0?[`Arrived via ${zfe(i.peers[0]?.peerId)}`]:[]],...i.isSelf?{link:{detail:{itemId:i.userId}}}:{},links:[{label:i.isSelf?"Account \u2192":i.isAnchor?"View protection":"Manage person",target:i.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:i.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:n}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}})});function v0l(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function A0l(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function w0l(e,t){if(!A0l(e))throw Error(`${t} tab returned invalid workspace data`);return e}function zdo(e,t){let n=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);n.push(r)}return n}function KOn(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function $We(e,t,n,r){return w0l(await e.dataProvider(t,n,r),e.label)}async function E0l(e,t,n,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,n,r)}function S0l(e){let t=new Map;for(let n of e)for(let r of n.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!n.registration.actionHandler)throw Error(`Administration source "${n.registration.label}" declares actions without a handler`);t.set(r,n.registration)}return t}function qdo(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function k0l(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function Udo(e){if(!e.studio.isAvailable())return;let t=Ndo(e),n=Pdo(e),r=Mdo(e),i=wdo(e),o=S0l([t,n,r,i]),s=t.registration,a=n.registration,c=r.registration,l=i.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:u3,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,f)=>{let m=b0l.parse(p??{}),h,g=KOn("People"),x=KOn("Invitations"),y=KOn("Audit");if(m.tab==="people"){let[v,w]=await Promise.all([$We(s,d,{...m.selected?{selected:m.selected}:{}},f),$We(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=OOn(w.view.blocks);g=[...jdo(zdo(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},S.people).blocks]}else if(m.tab==="invitations"){let[v,w]=await Promise.all([$We(a,d,{...m.state?{state:m.state}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f),$We(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=OOn(w.view.blocks),k=Rdo(v.view.blocks,S.invitations);h=v.view.primaryAction,x=[...k.blocks]}else{let v=await $We(l,d,{...m.actorUserId?{actorUserId:m.actorUserId}:{},...m.action?{action:m.action}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f);y=zdo(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...h?{primaryAction:h}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:m.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:x},{id:"audit",label:"Access activity",blocks:y}]}]}}},actionHandler:async(d,p,f)=>{let m=v0l(d);if(!m)throw new gr("invalid_input",{publicMessage:"Administration action id is required"});let h=o.get(m);if(!h)throw new gr("not_found",{publicMessage:`Unknown Administration action: ${m}`});return E0l(h,d,p,f)},badgeProvider:async()=>{let d=qdo(await N8(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>k0l(qdo(await N8(e).listAdminUsers()))})}var b0l;var $do=E(()=>{wn();lt();oe();Edo();Odo();Fdo();Ldo();qfe();b0l=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(S9,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(S9,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()})});function T0l(e,t){let n=e.flatMap((r)=>{let i=r.invitation;if(!i)return[];if(i.state==="failed")return[{id:i.id,displayName:r.displayName,state:i.state,reason:"delivery-failed",...i.expiresAt!==void 0?{expiresAt:i.expiresAt}:{}}];if(!["pending","sending","sent"].includes(i.state)||i.expiresAt===void 0||i.expiresAt<=t||i.expiresAt>t+C0l)return[];return[{id:i.id,displayName:r.displayName,state:i.state,reason:"expiring",expiresAt:i.expiresAt}]});return n.sort((r,i)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(i.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(i.displayName)),{invitations:n,expiringCount:n.filter((r)=>r.reason==="expiring").length,failureCount:n.filter((r)=>r.reason==="delivery-failed").length}}async function Gdo(e,t){t.throwIfAborted();let n=await N8(e).listAdminUsers();return t.throwIfAborted(),T0l(n,Date.now())}var C0l=259200000,I0l,_0l,Hdo;var Zdo=E(()=>{Zo();qfe();I0l=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),_0l=u.strictObject({invitations:u.array(I0l),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),Hdo=zd({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:_0l,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${k9(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})})});var B0l,R0l,QOn;var Wdo=E(()=>{Zo();wn();$do();Zdo();B0l=u.strictObject({}),R0l=$i({id:"admin",config:B0l},{subscriptions:(e)=>{let t=ni(e);return t.registered(async()=>{await Udo(t)}),[]},dashboardWidgets:(e)=>{let t=ni(e);return[Hdo.bind(e,({signal:n})=>Gdo(t,n))]}}),QOn=R0l});var Vdo=E(()=>{Wdo()});var Jr=E(()=>{oe();Ki();Ki()});var Du="agent",Kdo="agent-network",Qdo="agent-proximity",JOn="agent-discovery:entities",Jdo="agent-discovery:proximity-map",YOn="proximity-map",XOn="agent-list",eMn="agent-detail",Gw="skill",Ydo=30,Xdo=120,D8t="skill-derivation",epo="skill-derivation",tMn="skill:skill-derivation",tpo="skills";var D0l,nMn,pte,HWe,fte;var _L=E(()=>{oe();_n();D0l=u.string().trim().min(1).max(Xdo),nMn=u.array(D0l).max(Ydo),pte=u.object({name:u.string(),description:u.string(),tags:nMn,examples:u.array(u.string())}),HWe=pte,fte=Qp.extend({entityType:u.literal(Gw),metadata:HWe})});var P8t,kZ,P0l,lM,GWe,Op,O0l,ZWe,M0l,F0l;var Zw=E(()=>{oe();_L();wn();_n();P8t=u.object({name:u.string(),description:u.string(),tags:nMn}),kZ=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),P0l=HH,lM=u.object({name:u.string(),kind:P0l,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:kZ,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GWe=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:kZ,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Op=Qp.extend({entityType:u.literal(Du),metadata:GWe}),O0l=Vs.extend({entityType:u.literal(Du),metadata:GWe}),ZWe=O0l.extend({frontmatter:lM,about:u.string(),skills:u.array(P8t),notes:u.string()}),M0l=ZWe.extend({url:u.string().optional(),typeLabel:u.string().optional()}),F0l=ZWe.extend({url:u.string(),typeLabel:u.string()})});function N0l(e){try{return As(e,j0l).content}catch{return e}}function rMn(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:HAe(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function npo(e){return lh(Du,e,lM)}function WWe(e){return{content:e,metadata:rMn(npo(e))}}function nTe(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:kZ.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},n=twt({about:e.about,skills:e.skills,notes:e.notes});return na(n,t)}function L8(e,t={}){return nTe({...e.frontmatter,...e.body,...t})}function VWe(e){return r1e(N0l(e))}function Ux(e){return{frontmatter:npo(e.content),body:VWe(e.content)}}function iMn(e){return na("",e)}var j0l;var Rk=E(()=>{wn();_n();or();oe();Zw();_L();j0l=u.record(u.string(),u.unknown())});function L0l(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function rpo(e,t,n={}){let r=n.minCount??1,i=n.topN??12,o=new Map,s=(a)=>{for(let c of sA(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=VWe(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(L0l).slice(0,i)}function ipo(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:n})=>`- ${t} (${n})`)].join(`
|
|
3650
3650
|
`)}var Ufe=E(()=>{Rk();or();Zw();_L();or()});function rTe(e,t={}){let n=e.anchor?.name??e.brainName,r=e.anchor?.category??"person",i=[];if(e.anchor?.description)i.push(e.anchor.description);if(e.description)i.push(e.description);let o=t.status??"discovered",s=new Date().toISOString();return{content:nTe({name:n,kind:r,...e.anchor?.organization&&{organization:e.anchor.organization},brainName:e.brainName,url:e.url,status:o,discoveredAt:s,...t.provenance&&{introducedBy:t.provenance.introducedBy,hops:t.provenance.hops},about:i.join(`
|
|
3651
3651
|
|
|
3652
3652
|
`),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:sA(c.tags)})),notes:""}),metadata:{name:n,url:e.url,status:o,discoveredAt:s,slug:HAe(e.url)},anchorName:n}}var O8t=E(()=>{Rk();or();Ufe()});function TL(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let n=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(n)try{return new URL(n[0]).hostname}catch{return n[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}function opo(e){return{input:z0l,generate:async({input:t})=>{let n=TL(t.url??t.prompt??"");if(!n)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let r=await t2(n,{fetch:e??globalThis.fetch});if(!r.ok)return{success:!1,error:uN(r.reason)?r.error:`Could not fetch Agent Card from ${n}. Make sure the agent is running and accessible.`};let{content:i,metadata:o}=rTe(r.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:n,content:i,metadata:o}}}}var z0l;var spo=E(()=>{wn();oe();O8t();z0l=u.object({prompt:u.string().optional(),url:u.string().optional(),content:u.string().optional(),skipAi:u.boolean().optional(),status:u.enum(["discovered","approved","archived"]).optional()})});function oMn(e){let t=Op.parse(e),n=U0l(t);return n?{entity:t,parsed:n}:void 0}function lpo(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:n})=>(await n.list()).flatMap((r)=>{let i=oMn(r);return i?[i]:[]}).sort((r,i)=>i.parsed.frontmatter.discoveredAt.localeCompare(r.parsed.frontmatter.discoveredAt)).slice(0,q0l).map(({entity:r,parsed:i})=>$0l(r,i)),resolveDetail:async(n,{records:r,signal:i})=>{i.throwIfAborted();let o=oMn(await r.get(n));if(i.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=G0l(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,apo),truncated:s.length>apo}},act:async(n,r,{records:i,edits:o})=>{if(r!==sMn&&r!==cpo)throw Error("Invalid agent sighting Inbox action");let s=await i.get(n),a=s?oMn(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=r===sMn?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:L8(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function U0l(e){let t=Ux(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function $0l(e,t){let n=uM(t.frontmatter.name),r=uM(e.id),i=upo(n===r?n:`${n} \xB7 ${r}`,160);return{id:e.id,title:i,summary:H0l(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Du,entityId:e.id},actions:[{id:sMn,label:"Connect",confirm:!0},{id:cpo,label:"Dismiss",confirm:!0}]}}function H0l(e){let t=e.frontmatter.introducedBy??[],n=`Introduced by ${aMn(t.map(uM))}.`,r=uM(e.body.about),i=e.body.skills.map((s)=>uM(s.name)).filter(Boolean).slice(0,4),o=i.length>0?` Declared skills: ${aMn(i)}.`:"";return upo(`${n}${r?` ${r}`:""}${o}`,1000)}function G0l(e,t){let n=[`Agent: ${uM(t.frontmatter.name)}`,`Domain: ${uM(e.id)}`,`Introduced by: ${aMn((t.frontmatter.introducedBy??[]).map(uM))}`],r=uM(t.body.about);if(r)n.push(`About: ${r}`);if(t.body.skills.length>0)n.push("Skills:",...t.body.skills.map((i)=>{let o=uM(i.description);return`- ${uM(i.name)}${o?`: ${o}`:""}`}));return n.join(`
|
|
@@ -12187,7 +12187,7 @@ Guidelines:
|
|
|
12187
12187
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
12188
12188
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
12189
12189
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
12190
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`})});var NPd="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",sDe;var Abr=E(()=>{not();lt();Jr();_n();pbr();hbr();JHt();Eea();KHt();not();vbr();sDe=uu(ggt(Vr({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:WHt,markdown:VHt,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:NPd,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:fbr(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:bbr},generation:mbr,create:{fromUpload:wea},jobs:{"upload-import":Aea(()=>sDe)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:dbr}),[hgt(B3e,async({request:e,entities:t})=>{let{id:n,title:r,body:i}=e;if(await t.get(sDe,n))return{noteId:n,created:!1};return await t.create(sDe,{id:n,content:i,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:n,created:!0}})]),oDe)});var LPd,kea;var Cea=E(()=>{Jr();ubr();Abr();Abr();pbr();not();ubr();hbr();JHt();vbr();LPd=qc({id:"note",config:lbr,entities:[sDe]}),kea=LPd});var zPd,qPd,UPd,Iea;var _ea=E(()=>{lt();Zo();wn();zPd=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),qPd=u.looseObject({defaultRecipient:zPd.or(Iut).optional()}),UPd=$i({id:"notifications",config:qPd},{subscriptions:(e)=>{let{config:t}=e,n=ni(e),{logger:r}=n;return n.answer(A4,async({request:i})=>{let o=i.recipient??t.defaultRecipient;if(!o)return r.warn(k3e.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=n.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn(k3e.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:i.title,text:i.body,...i.html?{html:i.html}:{},...i.replyTo?{replyTo:i.replyTo}:{},sensitivity:i.sensitivity,idempotencyKey:i.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){r.warn(k3e.deliveryFailed,{transportCode:a.failureCode});let c=_ut.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),Iea=UPd});function WPd(e){return e.toLowerCase().includes("no data found for this memberid")}function VPd(e,t){let n=e.paging?.links?.find((i)=>i.rel==="next")?.href,r=n?Number(new URL(n,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class rot{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,n){if(n===Tea)throw Error(`LinkedIn snapshot exceeded ${Tea} pages`);let r=await this.fetchPage(e,t),i=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||i.length===0)return i;return[...i,...await this.fetchPages(e,VPd(r,t),n+1)]}async fetchPage(e,t){let n=new URL(`${HPd}/memberSnapshotData`);n.searchParams.set("q","criteria"),n.searchParams.set("domain",e),n.searchParams.set("start",String(t));let r=await this.fetchFn(n,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":GPd}});if(r.ok)return $Pd.parse(await r.json());let i=await r.text();if(r.status<500&&WPd(i))return null;throw new YHt(r.status,i.slice(0,ZPd))}}var Bea,$Pd,HPd="https://api.linkedin.com/rest",GPd="202312",Tea=1000,ZPd=1000,YHt;var iot=E(()=>{oe();Bea=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],$Pd=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()});YHt=class YHt extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}});class wbr{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:KPd})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function Ebr(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var KPd;var Sbr=E(()=>{Zo();oe();KPd=ale({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}})});async function t4d(e){try{return await e.json()}catch{return null}}class oot{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(QPd);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",Rea),t}async exchange(e,t){let n=await this.fetchFn(JPd,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),r=await t4d(n);if(!n.ok){let o=e4d.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${n.status})${s?`: ${s.slice(0,YPd)}`:""}`)}let i=XPd.parse(r);if(i.scope!==void 0&&i.scope!==Rea)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:i.access_token,expiresAt:new Date(t+i.expires_in*1000).toISOString()}}}function Dea(e){return new KJ({...Zgt,now:e})}var QPd="https://www.linkedin.com/oauth/v2/authorization",JPd="https://www.linkedin.com/oauth/v2/accessToken",Rea="r_dma_portability_3rd_party",YPd=500,XPd,e4d;var kbr=E(()=>{Wgt();oe();XPd=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),e4d=u.looseObject({error:u.string().optional(),error_description:u.string().optional()})});function Cbr(e,t={}){let n=(i)=>new oot({...e,redirectUri:i},t.fetch),r=t.now??Date.now;return{id:XHt,authorizationUrl:({redirectUri:i,state:o})=>n(i).authorizationUrl(o),exchange:async({code:i,redirectUri:o})=>{let s=await n(o).exchange(i,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class Ibr{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(qse.authorizations,{provider:XHt,brainState:e},"the connection");return new URL(Gen.parse(t).authorizationUrl)}async redeem(e){let t=Wen.parse(await this.post(qse.redeem,{provider:XHt,grant:e},"grant redemption"));if(t.provider!==XHt)throw Error("OAuth broker redeemed a grant for another provider");return n4d.parse(t.credential)}async post(e,t,n){let{instanceId:r,secret:i}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${i}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${n} (${o.status})`);return o.json()}}var XHt="linkedin",n4d;var _br=E(()=>{lt();oe();kbr();n4d=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()})});function r4d(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function wxe(e,t){return e.map((n)=>r4d(n[t])).find(Boolean)}function Pea(e){let t=[wxe(e,"First Name"),wxe(e,"Last Name")].filter(Boolean).join(" ")||void 0,n=wxe(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:wxe(e,"Headline"),industry:wxe(e,"Industry"),location:wxe(e,"Geo Location"),website:n,story:wxe(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}function Oea(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new gr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new gr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class Tbr{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:n}=await this.previewFields(t);return Oea(await this.messaging.request(Fbe,{fields:t,revision:n}))}async previewFields(e){return Oea(await this.messaging.request(Mbe,{fields:e}))}async imported(e){let t=new rot(e,this.fetchFn);return Pea(await t.fetchProfile())}}var Mea=E(()=>{lt();iot()});function Fea(e){return e?.permissionLevel==="admin"&&e.isAnchor}function sot(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function jea(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return sot(303,`${l}${d}connection=${c}`)},n=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&Fea(p)&&p?.userId===d?d:null},r=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${Re(d)}`),t("failed")}},i=async(c)=>{let l=await e.resolveSession(c);if(!l)return sot(401);if(!Fea(l))return sot(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return sot(302,p.oauth.authorizationUrl(d).toString());try{return sot(302,(await p.broker.authorize(d)).toString())}catch(f){return e.logger.warn(`LinkedIn broker connection failed: ${Re(f)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await n(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let f=d.get("code");if(!f)return t("failed");return r(p,()=>c.exchange(f,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await n(l,d.get("state")??""),f=Ven.safeParse(Object.fromEntries(d));if(!p||!f.success)return t("failed");if("error"in f.data)return t(f.data.error==="provider_denied"?"declined":"failed");let{grant:m}=f.data;return r(p,()=>c.redeem(m))},{mode:a}=e;return[{path:Bbr,method:"GET",public:!0,handler:i},a.kind==="direct"?{path:aot,method:"GET",public:!0,handler:o(a.oauth)}:{path:cot,method:"GET",public:!0,handler:s(a.broker)}]}var Bbr="/linkedin/oauth/start",aot="/linkedin/oauth/callback",cot="/linkedin/oauth/broker/return";var Nea=E(()=>{lt()});function qea(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function Lea(e){if(typeof e!=="string")return`<${qea(e)}>`;let t=e.trim();return o4d.find(([n])=>n.test(t))?.[1]??"<string>"}function s4d(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(Lea))].sort();return Lea(e)}function zea([e],[t]){return e.localeCompare(t)}function a4d(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>qea(a)))].sort(),presentCount:s.length}}),i=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(zea).map(([a,c])=>[a,s4d(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...i].sort(zea).map(([,o])=>o)}}async function Uea(e){let t=await Promise.all(Bea.map(async(n)=>[n,a4d(await e.fetchDomain(n))]));return Object.fromEntries(t)}var i4d,o4d;var $ea=E(()=>{iot();i4d=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,o4d=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[i4d,"<month-year>"]]});function Gea(e){if(e===null)return"\u2014";return e.length>Hea?`${e.slice(0,Hea-1)}\u2026`:e}function Zea(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function Wea(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Dbr(e){let t=e.connection?l4d[e.connection]:null;return t?[{type:"notice",...t}]:[]}function Pbr(e){if(e?.permission!=="admin"||!e.isAnchor)throw new gr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function p4d(e){if(e instanceof YHt&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${Re(e)}`}async function Qea(e,t){if(!e.isAvailable())return;let n=async(i)=>{let o=await t.connections.get(Pbr(i));if(!o||Ebr(o))throw new gr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:Vea,bind:(i)=>Vea.bind(i,{load:async({caller:o,query:s})=>{let a=Pbr(o),{connection:c}=s.get(Fbr),l=await t.connections.get(a);if(!l||Ebr(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:p4d(d),startUrl:t.startUrl,connection:c}}},actions:[Obr.bind(i,async({caller:o})=>t.profileImport.apply((await n(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await n(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>Kea[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new gr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${Zea(c)} from LinkedIn?${l.length>0?` Your ${Zea(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Mbr.bind(i,async({caller:o})=>{let s=await Uea(t.clientFor((await n(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),eGt.bind(i,async({caller:o})=>(await t.connections.forget(Pbr(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(i)=>i.isAnchor&&await r.accessHandler(i)})}var Kea,c4d,l4d,Hea=200,Obr,eGt,Mbr,Fbr,u4d,Rbr,d4d,Vea;var Jea=E(()=>{Zo();lt();oe();iot();Sbr();$ea();Kea={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},c4d={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},l4d={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},Obr=La({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),eGt=La({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),Mbr=La({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Fbr=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),u4d=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Rbr=Fbr.shape.connection,d4d=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Rbr}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Rbr}),u.object({status:u.literal("ready"),fields:u.array(u4d),connection:Rbr})]);Vea=Sf({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:Fbr,data:d4d,actions:[Obr,eGt,Mbr],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...Dbr(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],Wea(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Dbr(e),{type:"notice",tone:"warn",text:e.message},Wea(e.startUrl,"Connect LinkedIn again"),{type:"action",action:eGt,input:{}}]};let t=e.fields.some((n)=>n.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:Obr,input:{}}}:{},blocks:[...Dbr(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((n)=>({id:n.field,cells:{field:Kea[n.field],current:Gea(n.current),imported:Gea(n.imported),outcome:c4d[n.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:Mbr,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:eGt,input:{}}]}}})});var Xea;var Yea=E(()=>{Xea={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.873",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"}});function x4d(e,t){let{oauth:n,broker:r}=e;if(n&&r)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(n&&new URL(n.redirectUri).pathname!==aot)throw Error(`linkedin-import: oauth.redirectUri must end at ${aot}`);if(r&&new URL(r.returnUri).pathname!==cot)throw Error(`linkedin-import: broker.returnUri must end at ${cot}`);if(n)return{kind:"direct",oauth:new oot(n,t.fetch)};if(r)return{kind:"broker",broker:new Ibr(r,t.fetch)};return null}function tta(e={}){let t=$i({id:"linkedin-import",config:eta,setup:(n)=>{let{config:r}=n,i=x4d(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!i||!o)return{routes:[]};let s=ni(n),a=new wbr(s.accountSettings,{pluginId:s.pluginId,packageName:Xea.name}),c=m4d;return s.registered(async()=>{let l=await Qea(s.studio,{profileImport:new Tbr(s.messaging,e.fetch),clientFor:(d)=>new rot(d,e.fetch),connections:a,startUrl:new URL(Bbr,o).toString()});if(l)c=l}),{routes:jea({mode:i,states:Dea(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Cf(t,({state:n})=>n.routes)}var m4d="/studio",h4d,g4d,eta,jbr;var nta=E(()=>{Zo();wn();oe();iot();Sbr();_br();kbr();Mea();Nea();Jea();Yea();h4d=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${aot}, registered with the LinkedIn app`)}),g4d=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${cot}, registered with the broker`)}),eta=u.object({oauth:h4d.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:g4d.optional().describe("The managed broker holding the shared LinkedIn app")});jbr=tta()});var rta=E(()=>{nta()});var ita=E(()=>{_br()});import{createHash as y4d,timingSafeEqual as b4d}from"crypto";function ota(e){return y4d("sha256").update(e).digest()}function v4d(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),n=t.indexOf(":");if(n<=0||n===t.length-1)return null;return{id:t.slice(0,n),secret:t.slice(n+1)}}class Nbr{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ota(t.secret)}]))}authenticate(e){let t=v4d(e.headers.get("authorization")),n=t?this.instances.get(t.id):void 0;if(!t||!n)return null;return b4d(ota(t.secret),n.secretHash)?{id:n.id,returnUris:n.returnUris}:null}}var sta=()=>{};function Kie(e,t=200){return Response.json(e,{status:t,headers:Lbr})}function ata(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Lbr,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function cta(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function tGt(e,t){let n=new URL(e.returnUri);return n.searchParams.set("provider",e.provider),n.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,i])=>n.searchParams.set(r,i)),new Response(null,{status:303,headers:{...Lbr,Location:n.toString()}})}function lta(e){let t=new Map(e.providers.map((c)=>[c.id,c])),n=new Map,r=(c)=>{let l=e.now(),d=(n.get(c)??[]).filter((f)=>f>l-w4d),p=d.length<A4d;return n.set(c,p?[...d,l]:d),p},i=(c)=>new URL(But(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ata();let d=Hen.safeParse(await cta(c));if(!d.success)return Kie({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),f=l.returnUris[d.data.provider];if(!p||!f)return Kie({error:"Provider is unavailable for this instance"},400);if(!r(l.id))return Kie({error:"Too many connections started; try later"},429);let m=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:f,brainState:d.data.brainState}),h=p.authorizationUrl({redirectUri:i(p.id),state:m}).toString();return Kie({authorizationUrl:h})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ata();let d=Zen.safeParse(await cta(c));if(!d.success)return Kie({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,f=e.grants.take(d.data.grant,(m)=>m.provider===p&&m.instanceId===l.id);if(!f)return Kie({error:"Invalid or expired grant"},400);return Kie({provider:p,credential:f.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(m)=>m.provider===c.id);if(!p)return Kie({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return tGt(p,{error:"provider_denied"});let f=d.get("code")?.trim();if(!f)return tGt(p,{error:"authorization_incomplete"});try{let m=await c.exchange({code:f,redirectUri:i(c.id)}),h=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:m});return tGt(p,{grant:h})}catch(m){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Re(m)}`),tGt(p,{error:"credential_exchange_failed"})}};return[{path:qse.authorizations,method:"POST",public:!0,handler:o},{path:qse.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:But(c.id),method:"GET",public:!0,handler:a(c)}))]}var A4d=10,w4d=600000,Lbr;var uta=E(()=>{lt();Lbr={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"}});function I4d(e,t){return Object.entries(e.providers).map(([n,r])=>{let i=t.providers[n];if(!i)throw Error(`oauth-broker: no adapter for provider "${n}"`);let o=i(r);if(o.id!==n)throw Error(`oauth-broker: adapter for "${n}" reports provider "${o.id}"`);return o})}function zbr(e){let t=$i({id:"oauth-broker",config:pta,setup:(n)=>{let{config:r}=n,i=I4d(r,e);if(r.instances.length===0||i.length===0)return{routes:[]};return{routes:lta({publicUrl:r.publicUrl,providers:i,instances:new Nbr(r.instances),authorizations:new KJ({ttlMs:E4d,maxPending:dta,now:e.now}),grants:new KJ({ttlMs:S4d,maxPending:dta,now:e.now}),now:e.now??Date.now,logger:ni(n).logger})}}});return Cf(t,({state:n})=>n.routes)}var E4d=600000,S4d=120000,dta=1000,k4d,C4d,pta;var fta=E(()=>{lt();Zo();wn();Wgt();oe();sta();uta();k4d=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),C4d=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record($U,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),pta=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record($U,k4d).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(C4d).default([])})});var mta=E(()=>{fta()});function hta(e,t){let n=(r)=>r!==void 0&&t()-r.usedAt<_4d;return{get:async(r,i)=>{let o=await e.get(lot(r,i));return n(o)?{hash:o.hash,...o.conflictEdit!==void 0&&{conflictEdit:o.conflictEdit},...o.conflictId!==void 0&&{conflictId:o.conflictId}}:void 0},held:async(r,i,o)=>{await e.set(lot(r,i),{hash:o,usedAt:t()})},conflictKept:async(r,i,o,s)=>{let a=await e.get(lot(r,i));if(!n(a))return;await e.set(lot(r,i),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(r,i)=>{await e.delete(lot(r,i))},sweep:async()=>{let r=(await e.keys()).filter(({value:i})=>!n(i));await Promise.all(r.map(({key:i})=>e.delete(i)))}}}function gta(e=Date.now){let t=new Map;return hta({get:async(n)=>t.get(n),set:async(n,r)=>{t.set(n,r)},delete:async(n)=>{t.delete(n)},keys:async()=>[...t].map(([n,r])=>({key:n,value:r}))},e)}function xta(e,t=Date.now){let n=e.scoped({namespace:T4d,schema:B4d});return hta({get:async(r)=>await n.get(r)??void 0,set:async(r,i)=>{await n.set(r,i)},delete:async(r)=>{await n.delete(r)},keys:()=>n.list()},t)}var _4d=2592000000,lot=(e,t)=>Ur(`${e}
|
|
12190
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`})});var NPd="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",sDe;var Abr=E(()=>{not();lt();Jr();_n();pbr();hbr();JHt();Eea();KHt();not();vbr();sDe=uu(ggt(Vr({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:WHt,markdown:VHt,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:NPd,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:fbr(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:bbr},generation:mbr,create:{fromUpload:wea},jobs:{"upload-import":Aea(()=>sDe)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:dbr}),[hgt(B3e,async({request:e,entities:t})=>{let{id:n,title:r,body:i}=e;if(await t.get(sDe,n))return{noteId:n,created:!1};return await t.create(sDe,{id:n,content:i,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:n,created:!0}})]),oDe)});var LPd,kea;var Cea=E(()=>{Jr();ubr();Abr();Abr();pbr();not();ubr();hbr();JHt();vbr();LPd=qc({id:"note",config:lbr,entities:[sDe]}),kea=LPd});var zPd,qPd,UPd,Iea;var _ea=E(()=>{lt();Zo();wn();zPd=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),qPd=u.looseObject({defaultRecipient:zPd.or(Iut).optional()}),UPd=$i({id:"notifications",config:qPd},{subscriptions:(e)=>{let{config:t}=e,n=ni(e),{logger:r}=n;return n.answer(A4,async({request:i})=>{let o=i.recipient??t.defaultRecipient;if(!o)return r.warn(k3e.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=n.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn(k3e.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:i.title,text:i.body,...i.html?{html:i.html}:{},...i.replyTo?{replyTo:i.replyTo}:{},sensitivity:i.sensitivity,idempotencyKey:i.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){r.warn(k3e.deliveryFailed,{transportCode:a.failureCode});let c=_ut.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),Iea=UPd});function WPd(e){return e.toLowerCase().includes("no data found for this memberid")}function VPd(e,t){let n=e.paging?.links?.find((i)=>i.rel==="next")?.href,r=n?Number(new URL(n,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class rot{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,n){if(n===Tea)throw Error(`LinkedIn snapshot exceeded ${Tea} pages`);let r=await this.fetchPage(e,t),i=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||i.length===0)return i;return[...i,...await this.fetchPages(e,VPd(r,t),n+1)]}async fetchPage(e,t){let n=new URL(`${HPd}/memberSnapshotData`);n.searchParams.set("q","criteria"),n.searchParams.set("domain",e),n.searchParams.set("start",String(t));let r=await this.fetchFn(n,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":GPd}});if(r.ok)return $Pd.parse(await r.json());let i=await r.text();if(r.status<500&&WPd(i))return null;throw new YHt(r.status,i.slice(0,ZPd))}}var Bea,$Pd,HPd="https://api.linkedin.com/rest",GPd="202312",Tea=1000,ZPd=1000,YHt;var iot=E(()=>{oe();Bea=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],$Pd=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()});YHt=class YHt extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}});class wbr{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:KPd})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function Ebr(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var KPd;var Sbr=E(()=>{Zo();oe();KPd=ale({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}})});async function t4d(e){try{return await e.json()}catch{return null}}class oot{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(QPd);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",Rea),t}async exchange(e,t){let n=await this.fetchFn(JPd,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),r=await t4d(n);if(!n.ok){let o=e4d.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${n.status})${s?`: ${s.slice(0,YPd)}`:""}`)}let i=XPd.parse(r);if(i.scope!==void 0&&i.scope!==Rea)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:i.access_token,expiresAt:new Date(t+i.expires_in*1000).toISOString()}}}function Dea(e){return new KJ({...Zgt,now:e})}var QPd="https://www.linkedin.com/oauth/v2/authorization",JPd="https://www.linkedin.com/oauth/v2/accessToken",Rea="r_dma_portability_3rd_party",YPd=500,XPd,e4d;var kbr=E(()=>{Wgt();oe();XPd=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),e4d=u.looseObject({error:u.string().optional(),error_description:u.string().optional()})});function Cbr(e,t={}){let n=(i)=>new oot({...e,redirectUri:i},t.fetch),r=t.now??Date.now;return{id:XHt,authorizationUrl:({redirectUri:i,state:o})=>n(i).authorizationUrl(o),exchange:async({code:i,redirectUri:o})=>{let s=await n(o).exchange(i,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class Ibr{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(qse.authorizations,{provider:XHt,brainState:e},"the connection");return new URL(Gen.parse(t).authorizationUrl)}async redeem(e){let t=Wen.parse(await this.post(qse.redeem,{provider:XHt,grant:e},"grant redemption"));if(t.provider!==XHt)throw Error("OAuth broker redeemed a grant for another provider");return n4d.parse(t.credential)}async post(e,t,n){let{instanceId:r,secret:i}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${i}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${n} (${o.status})`);return o.json()}}var XHt="linkedin",n4d;var _br=E(()=>{lt();oe();kbr();n4d=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()})});function r4d(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function wxe(e,t){return e.map((n)=>r4d(n[t])).find(Boolean)}function Pea(e){let t=[wxe(e,"First Name"),wxe(e,"Last Name")].filter(Boolean).join(" ")||void 0,n=wxe(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:wxe(e,"Headline"),industry:wxe(e,"Industry"),location:wxe(e,"Geo Location"),website:n,story:wxe(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}function Oea(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new gr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new gr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class Tbr{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:n}=await this.previewFields(t);return Oea(await this.messaging.request(Fbe,{fields:t,revision:n}))}async previewFields(e){return Oea(await this.messaging.request(Mbe,{fields:e}))}async imported(e){let t=new rot(e,this.fetchFn);return Pea(await t.fetchProfile())}}var Mea=E(()=>{lt();iot()});function Fea(e){return e?.permissionLevel==="admin"&&e.isAnchor}function sot(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function jea(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return sot(303,`${l}${d}connection=${c}`)},n=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&Fea(p)&&p?.userId===d?d:null},r=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${Re(d)}`),t("failed")}},i=async(c)=>{let l=await e.resolveSession(c);if(!l)return sot(401);if(!Fea(l))return sot(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return sot(302,p.oauth.authorizationUrl(d).toString());try{return sot(302,(await p.broker.authorize(d)).toString())}catch(f){return e.logger.warn(`LinkedIn broker connection failed: ${Re(f)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await n(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let f=d.get("code");if(!f)return t("failed");return r(p,()=>c.exchange(f,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await n(l,d.get("state")??""),f=Ven.safeParse(Object.fromEntries(d));if(!p||!f.success)return t("failed");if("error"in f.data)return t(f.data.error==="provider_denied"?"declined":"failed");let{grant:m}=f.data;return r(p,()=>c.redeem(m))},{mode:a}=e;return[{path:Bbr,method:"GET",public:!0,handler:i},a.kind==="direct"?{path:aot,method:"GET",public:!0,handler:o(a.oauth)}:{path:cot,method:"GET",public:!0,handler:s(a.broker)}]}var Bbr="/linkedin/oauth/start",aot="/linkedin/oauth/callback",cot="/linkedin/oauth/broker/return";var Nea=E(()=>{lt()});function qea(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function Lea(e){if(typeof e!=="string")return`<${qea(e)}>`;let t=e.trim();return o4d.find(([n])=>n.test(t))?.[1]??"<string>"}function s4d(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(Lea))].sort();return Lea(e)}function zea([e],[t]){return e.localeCompare(t)}function a4d(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>qea(a)))].sort(),presentCount:s.length}}),i=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(zea).map(([a,c])=>[a,s4d(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...i].sort(zea).map(([,o])=>o)}}async function Uea(e){let t=await Promise.all(Bea.map(async(n)=>[n,a4d(await e.fetchDomain(n))]));return Object.fromEntries(t)}var i4d,o4d;var $ea=E(()=>{iot();i4d=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,o4d=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[i4d,"<month-year>"]]});function Gea(e){if(e===null)return"\u2014";return e.length>Hea?`${e.slice(0,Hea-1)}\u2026`:e}function Zea(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function Wea(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Dbr(e){let t=e.connection?l4d[e.connection]:null;return t?[{type:"notice",...t}]:[]}function Pbr(e){if(e?.permission!=="admin"||!e.isAnchor)throw new gr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function p4d(e){if(e instanceof YHt&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${Re(e)}`}async function Qea(e,t){if(!e.isAvailable())return;let n=async(i)=>{let o=await t.connections.get(Pbr(i));if(!o||Ebr(o))throw new gr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:Vea,bind:(i)=>Vea.bind(i,{load:async({caller:o,query:s})=>{let a=Pbr(o),{connection:c}=s.get(Fbr),l=await t.connections.get(a);if(!l||Ebr(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:p4d(d),startUrl:t.startUrl,connection:c}}},actions:[Obr.bind(i,async({caller:o})=>t.profileImport.apply((await n(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await n(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>Kea[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new gr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${Zea(c)} from LinkedIn?${l.length>0?` Your ${Zea(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Mbr.bind(i,async({caller:o})=>{let s=await Uea(t.clientFor((await n(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),eGt.bind(i,async({caller:o})=>(await t.connections.forget(Pbr(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(i)=>i.isAnchor&&await r.accessHandler(i)})}var Kea,c4d,l4d,Hea=200,Obr,eGt,Mbr,Fbr,u4d,Rbr,d4d,Vea;var Jea=E(()=>{Zo();lt();oe();iot();Sbr();$ea();Kea={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},c4d={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},l4d={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},Obr=La({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),eGt=La({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),Mbr=La({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Fbr=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),u4d=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Rbr=Fbr.shape.connection,d4d=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Rbr}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Rbr}),u.object({status:u.literal("ready"),fields:u.array(u4d),connection:Rbr})]);Vea=Sf({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:Fbr,data:d4d,actions:[Obr,eGt,Mbr],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...Dbr(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],Wea(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Dbr(e),{type:"notice",tone:"warn",text:e.message},Wea(e.startUrl,"Connect LinkedIn again"),{type:"action",action:eGt,input:{}}]};let t=e.fields.some((n)=>n.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:Obr,input:{}}}:{},blocks:[...Dbr(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((n)=>({id:n.field,cells:{field:Kea[n.field],current:Gea(n.current),imported:Gea(n.imported),outcome:c4d[n.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:Mbr,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:eGt,input:{}}]}}})});var Xea;var Yea=E(()=>{Xea={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.875",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"}});function x4d(e,t){let{oauth:n,broker:r}=e;if(n&&r)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(n&&new URL(n.redirectUri).pathname!==aot)throw Error(`linkedin-import: oauth.redirectUri must end at ${aot}`);if(r&&new URL(r.returnUri).pathname!==cot)throw Error(`linkedin-import: broker.returnUri must end at ${cot}`);if(n)return{kind:"direct",oauth:new oot(n,t.fetch)};if(r)return{kind:"broker",broker:new Ibr(r,t.fetch)};return null}function tta(e={}){let t=$i({id:"linkedin-import",config:eta,setup:(n)=>{let{config:r}=n,i=x4d(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!i||!o)return{routes:[]};let s=ni(n),a=new wbr(s.accountSettings,{pluginId:s.pluginId,packageName:Xea.name}),c=m4d;return s.registered(async()=>{let l=await Qea(s.studio,{profileImport:new Tbr(s.messaging,e.fetch),clientFor:(d)=>new rot(d,e.fetch),connections:a,startUrl:new URL(Bbr,o).toString()});if(l)c=l}),{routes:jea({mode:i,states:Dea(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Cf(t,({state:n})=>n.routes)}var m4d="/studio",h4d,g4d,eta,jbr;var nta=E(()=>{Zo();wn();oe();iot();Sbr();_br();kbr();Mea();Nea();Jea();Yea();h4d=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${aot}, registered with the LinkedIn app`)}),g4d=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${cot}, registered with the broker`)}),eta=u.object({oauth:h4d.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:g4d.optional().describe("The managed broker holding the shared LinkedIn app")});jbr=tta()});var rta=E(()=>{nta()});var ita=E(()=>{_br()});import{createHash as y4d,timingSafeEqual as b4d}from"crypto";function ota(e){return y4d("sha256").update(e).digest()}function v4d(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),n=t.indexOf(":");if(n<=0||n===t.length-1)return null;return{id:t.slice(0,n),secret:t.slice(n+1)}}class Nbr{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ota(t.secret)}]))}authenticate(e){let t=v4d(e.headers.get("authorization")),n=t?this.instances.get(t.id):void 0;if(!t||!n)return null;return b4d(ota(t.secret),n.secretHash)?{id:n.id,returnUris:n.returnUris}:null}}var sta=()=>{};function Kie(e,t=200){return Response.json(e,{status:t,headers:Lbr})}function ata(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Lbr,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function cta(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function tGt(e,t){let n=new URL(e.returnUri);return n.searchParams.set("provider",e.provider),n.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,i])=>n.searchParams.set(r,i)),new Response(null,{status:303,headers:{...Lbr,Location:n.toString()}})}function lta(e){let t=new Map(e.providers.map((c)=>[c.id,c])),n=new Map,r=(c)=>{let l=e.now(),d=(n.get(c)??[]).filter((f)=>f>l-w4d),p=d.length<A4d;return n.set(c,p?[...d,l]:d),p},i=(c)=>new URL(But(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ata();let d=Hen.safeParse(await cta(c));if(!d.success)return Kie({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),f=l.returnUris[d.data.provider];if(!p||!f)return Kie({error:"Provider is unavailable for this instance"},400);if(!r(l.id))return Kie({error:"Too many connections started; try later"},429);let m=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:f,brainState:d.data.brainState}),h=p.authorizationUrl({redirectUri:i(p.id),state:m}).toString();return Kie({authorizationUrl:h})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ata();let d=Zen.safeParse(await cta(c));if(!d.success)return Kie({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,f=e.grants.take(d.data.grant,(m)=>m.provider===p&&m.instanceId===l.id);if(!f)return Kie({error:"Invalid or expired grant"},400);return Kie({provider:p,credential:f.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(m)=>m.provider===c.id);if(!p)return Kie({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return tGt(p,{error:"provider_denied"});let f=d.get("code")?.trim();if(!f)return tGt(p,{error:"authorization_incomplete"});try{let m=await c.exchange({code:f,redirectUri:i(c.id)}),h=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:m});return tGt(p,{grant:h})}catch(m){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Re(m)}`),tGt(p,{error:"credential_exchange_failed"})}};return[{path:qse.authorizations,method:"POST",public:!0,handler:o},{path:qse.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:But(c.id),method:"GET",public:!0,handler:a(c)}))]}var A4d=10,w4d=600000,Lbr;var uta=E(()=>{lt();Lbr={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"}});function I4d(e,t){return Object.entries(e.providers).map(([n,r])=>{let i=t.providers[n];if(!i)throw Error(`oauth-broker: no adapter for provider "${n}"`);let o=i(r);if(o.id!==n)throw Error(`oauth-broker: adapter for "${n}" reports provider "${o.id}"`);return o})}function zbr(e){let t=$i({id:"oauth-broker",config:pta,setup:(n)=>{let{config:r}=n,i=I4d(r,e);if(r.instances.length===0||i.length===0)return{routes:[]};return{routes:lta({publicUrl:r.publicUrl,providers:i,instances:new Nbr(r.instances),authorizations:new KJ({ttlMs:E4d,maxPending:dta,now:e.now}),grants:new KJ({ttlMs:S4d,maxPending:dta,now:e.now}),now:e.now??Date.now,logger:ni(n).logger})}}});return Cf(t,({state:n})=>n.routes)}var E4d=600000,S4d=120000,dta=1000,k4d,C4d,pta;var fta=E(()=>{lt();Zo();wn();Wgt();oe();sta();uta();k4d=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),C4d=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record($U,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),pta=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record($U,k4d).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(C4d).default([])})});var mta=E(()=>{fta()});function hta(e,t){let n=(r)=>r!==void 0&&t()-r.usedAt<_4d;return{get:async(r,i)=>{let o=await e.get(lot(r,i));return n(o)?{hash:o.hash,...o.conflictEdit!==void 0&&{conflictEdit:o.conflictEdit},...o.conflictId!==void 0&&{conflictId:o.conflictId}}:void 0},held:async(r,i,o)=>{await e.set(lot(r,i),{hash:o,usedAt:t()})},conflictKept:async(r,i,o,s)=>{let a=await e.get(lot(r,i));if(!n(a))return;await e.set(lot(r,i),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(r,i)=>{await e.delete(lot(r,i))},sweep:async()=>{let r=(await e.keys()).filter(({value:i})=>!n(i));await Promise.all(r.map(({key:i})=>e.delete(i)))}}}function gta(e=Date.now){let t=new Map;return hta({get:async(n)=>t.get(n),set:async(n,r)=>{t.set(n,r)},delete:async(n)=>{t.delete(n)},keys:async()=>[...t].map(([n,r])=>({key:n,value:r}))},e)}function xta(e,t=Date.now){let n=e.scoped({namespace:T4d,schema:B4d});return hta({get:async(r)=>await n.get(r)??void 0,set:async(r,i)=>{await n.set(r,i)},delete:async(r)=>{await n.delete(r)},keys:()=>n.list()},t)}var _4d=2592000000,lot=(e,t)=>Ur(`${e}
|
|
12191
12191
|
${t}`),T4d="webdav.mount-base",B4d;var qbr=E(()=>{Oo();oe();B4d=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()})});function Exe(e){let[t]=e;return t!==void 0&&R4d.has(t)}function bta(){let e=new Map,t=(n)=>{let r=e.get(n)??new Map;return e.set(n,r),r};return{load:async(n)=>[...t(n).values()],put:async(n,r)=>{t(n).set(r.path,r)},remove:async(n,r)=>{r.forEach((i)=>t(n).delete(i))}}}function vta(e){let t=e.scoped({namespace:D4d,schema:P4d}),n=(i)=>`${Ur(i)}/`,r=(i,o)=>`${n(i)}${Ur(o)}`;return{load:async(i)=>(await t.list({keyPrefix:n(i)})).map(({value:o})=>({path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:new Uint8Array(Buffer.from(o.bytes,"base64"))}})),put:async(i,o)=>{await t.set(r(i,o.path),{path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:Buffer.from(o.bytes).toString("base64")}})},remove:async(i,o)=>{await Promise.all(o.map((s)=>t.delete(r(i,s))))}}}var R4d,yta=33554432,D4d="webdav.kept",P4d;var Ubr=E(()=>{Oo();oe();R4d=new Set([".obsidian"]);P4d=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()})});import{randomUUID as O4d}from"crypto";class $br{run=O4d().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??M4d}cursor(){return`${this.run}:${this.sequence}`}record(e){this.sequence+=1,this.recent=[...this.recent.slice(-(this.keep-1)),{sequence:this.sequence,type:e}];let t=[...this.waiting];this.waiting.clear();for(let n of t)n()}close(){this.closed=!0;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}since(e){if(e===null)return{cursor:this.cursor(),types:[]};let[t,n]=e.split(":"),r=Number(n),i=this.recent[0]?.sequence??this.sequence+1;if(t!==this.run||!Number.isInteger(r)||r>this.sequence||r<i-1)return{cursor:this.cursor(),reset:!0};return{cursor:this.cursor(),types:[...new Set(this.recent.filter((o)=>o.sequence>r).map((o)=>o.type))]}}async wait(e,t,n){let r=this.since(e);if("reset"in r||r.types.length>0||e===null)return r;if(t<=0||this.closed)return r;return await new Promise((i)=>{let o=()=>{clearTimeout(s),this.waiting.delete(o),n?.removeEventListener("abort",o),i()},s=setTimeout(o,t);this.waiting.add(o),n?.addEventListener("abort",o,{once:!0})}),this.since(e)}}var M4d=500;var Ata=()=>{};function Sta(e){let{principal:t}=e;return{userId:t.userId,personId:t.personId,displayName:t.displayName,permissionLevel:t.permissionLevel,isAnchor:t.isAnchor,...t.canonicalId!==void 0&&{canonicalId:t.canonicalId}}}async function z4d(e,t){let n=await e.entityAt(t.split("/"));if(!n)return;let r=await n.file.open();if(typeof r!=="string")return;let i=n.entity.metadata.title;return{entityType:n.entity.entityType,id:n.entity.id,title:typeof i==="string"&&i!==""?i:n.entity.id,content:r.slice(0,Cut)}}async function kta(e,t,n){let r=(n.cards??[]).flatMap((a)=>a.kind==="sources"?a.sources:[]),i=await Promise.all(r.map(async(a)=>{let c=a.entityType!==void 0&&a.entityId!==void 0&&a.brain===void 0?await e.pathOf(a.entityType,a.entityId):void 0;return{title:a.title??a.source,...c!==void 0&&{path:c},...a.url!==void 0&&{url:a.url},...a.excerpt!==void 0&&{excerpt:a.excerpt}}})),o=(n.pendingConfirmations??[]).map(({id:a,summary:c,preview:l})=>({id:a,summary:c,...l!==void 0&&{preview:l}})),s={conversation:t,text:n.text,...n.error!==void 0&&{error:j4d},sources:i,confirmations:o};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function Ita(e,t){let n=N4d.safeParse(t);if(!n.success)return new Response('Ask with { "question": "\u2026" }',{status:400});let{question:r,conversation:i,path:o}=n.data,s=o===void 0?void 0:await z4d(e.tree,o),a=await e.ask?.({asker:Sta(e.grant),interfaceType:wta,channelName:Eta,question:r,...i!==void 0&&{conversationId:i},...s!==void 0&&{entry:s}});if(!a)return Cta();if("message"in a)return new Response(a.message,{status:409});return kta(e.tree,a.conversationId,a.response)}async function _ta(e,t){let n=L4d.safeParse(t);if(!n.success)return new Response('Answer with { "conversation": "\u2026", "approval": "\u2026", "confirmed": true }',{status:400});let{conversation:r,approval:i,confirmed:o}=n.data,s=await e.confirmAsk?.({asker:Sta(e.grant),interfaceType:wta,channelName:Eta,conversationId:r,approvalId:i,confirmed:o});if(!s)return Cta();if("message"in s)return new Response(s.message,{status:409});return kta(e.tree,r,s.response)}var wta="obsidian",Eta="Obsidian",F4d=1024,j4d="Your brain could not answer this.",N4d,L4d,Cta=()=>new Response("Nothing answers questions here right now.",{status:503});var Tta=E(()=>{lt();oe();N4d=u.object({question:u.string().min(1).max(8000),conversation:u.string().min(1).max(yQ).optional(),path:u.string().min(1).max(F4d).optional()}),L4d=u.object({conversation:u.string().min(1).max(yQ),approval:u.string().min(1).max(yQ),confirmed:u.boolean()})});function Gbr(e){return Rta.has(e)}class Zbr{reader;scope;containment;everyType;constructor(e,t,n={}){this.reader=e,this.scope=t,this.containment=CL(e),this.everyType=n.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(Hbr))return;let t=await this.entityAt(e);if(t)return t.file;let[n]=e;if(this.everyType&&e.length===1&&n!==void 0&&this.isFolderType(n))return{kind:"folder",segments:e};return(await this.children(e)).length>0?{kind:"folder",segments:e}:void 0}async children(e){let{folders:t,files:n}=e.length===0?await this.rootChildren():await this.typeFolderChildren(e);return[...[...new Set(t)].sort(Bta).map((r)=>({kind:"folder",segments:[...e,r]})),...n.sort((r,i)=>Bta(r.segments.join("/"),i.segments.join("/")))]}async rootChildren(){let e=new Map((await this.reader.getEntityCounts(this.scope)).map((r)=>[r.entityType,r.count])),t=this.reader.getEntityTypes().filter((r)=>this.isFolderType(r)&&(this.everyType||[r,this.containedIn(r)].some((i)=>i!==void 0&&(e.get(i)??0)>0))),n=this.reader.getEntityTypes().includes(uot)?(await this.hierarchy(uot,[])).entities:[];return{folders:t,files:await this.filesIn([],n)}}async typeFolderChildren(e){let[t,...n]=e;if(t===void 0||!this.isFolderType(t))return{folders:[],files:[]};let r=await Promise.all([t,this.containedIn(t)].filter((i)=>i!==void 0).map((i)=>this.hierarchy(i,n)));return{folders:r.flatMap((i)=>i.folders),files:await this.filesIn(e,r.flatMap((i)=>i.entities))}}async hierarchy(e,t,n=0){let[r,...i]=t,o=await this.reader.queryEntityHierarchy({entityType:e,prefix:r===void 0?null:[r,...i],visibilityScope:this.scope,limit:U4d,offset:n,source:!0}),s=o.entities.map((l)=>l.entity),a=n+s.length,c=s.length>0&&a<o.totalEntities?(await this.hierarchy(e,t,a)).entities:[];return{folders:o.folders.map((l)=>l.name),entities:[...s,...c]}}async filesIn(e,t){return(await Promise.all(t.map((r)=>this.fileOf(r)))).filter((r)=>r!==void 0).filter((r)=>r.segments.length===e.length+1&&e.every((i,o)=>r.segments[o]===i))}async related(e,t){let n=await this.entityAt(e);if(!n)return;let r=await this.nearestTo(n.entity,t);if(r==="unindexed")return r;return(await Promise.all(r.map(async(o)=>{let s=await this.reader.getEntityRaw({entityType:o.entityType,id:o.entityId,visibilityScope:this.scope,source:!0}),a=s?await this.fileOf(s):void 0;if(!s||!a)return;let c=s.metadata.title;return{path:a.segments.join("/"),title:typeof c==="string"&&c!==""?c:s.id,entityType:s.entityType,distance:o.distance}}))).filter((o)=>o!==void 0)}async nearestTo(e,t){try{return await this.reader.nearestToEntity({origin:{entityType:e.entityType,entityId:e.id},types:this.reader.getEntityTypes().filter((n)=>!Gbr(n)&&n!==q4d),limit:t,visibilityScope:this.scope})}catch(n){if(n instanceof wR)return"unindexed";throw n}}async pathOf(e,t){if(!this.reader.getEntityTypes().includes(e))return;let n=await this.reader.getEntityRaw({entityType:e,id:t,visibilityScope:this.scope,source:!0});return(n?await this.fileOf(n):void 0)?.segments.join("/")}async entityAt(e){if(e.length===0||!e.every(Hbr))return;let{entityType:t,id:n}=ite(e.join("/"),this.containment);if(!this.reader.getEntityTypes().includes(t))return;let r=await this.reader.getEntityRaw({entityType:t,id:n,visibilityScope:this.scope,source:!0}),i=r?await this.fileOf(r):void 0;return r&&i?.segments.join("/")===e.join("/")?{entity:r,file:i}:void 0}textExtension(e){return this.reader.fileExtension(e)}placementAt(e,t){if(e.length===0||!e.every(Hbr))return;let n=e.join("/"),{entityType:r,id:i}=ite(n,this.containment);if(!this.reader.getEntityTypes().includes(r))return;let o=IL(r,i,t,this.containment);return o.writable&&o.relativePath===n?{entityType:r,id:i}:void 0}async fileOf(e){let t=ote(e,this.reader.fileExtension(e.entityType));if(!IL(e.entityType,e.id,t,this.containment).writable)return;let r={kind:"file",segments:W_e(e.id,e.entityType,t,this.containment).split("/"),contentType:$4d[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!Rta.has(e.entityType)||t===".md"){let a=t===".yaml"?B$(e.content):e.content;return{...r,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let i=Fa.safeParse(e.content);if(i.success){let a=await this.reader.statAsset(i.data);if(!a)return;return{...r,size:a.sizeBytes,open:async()=>H4d(await this.reader.openAsset(i.data))}}let o=/^data:[a-z0-9.+/-]+;base64,([\s\S]+)$/i.exec(e.content.trim())?.[1];if(!o)return;let s=Buffer.from(o.replace(/\s/g,""),"base64");return{...r,size:s.byteLength,open:async()=>s}}isFolderType(e){return e!==uot&&!this.containment.has(e)&&this.reader.getEntityTypes().includes(e)}folderTypeOf(e){return this.containment.get(e)??e}containedIn(e){return[...this.containment].find(([,t])=>t===e)?.[0]}}function Bta(e,t){return e<t?-1:e>t?1:0}function Hbr(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function H4d(e){let t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(n){let r=await t.next();if(r.done)n.close();else n.enqueue(r.value)},async cancel(){await t.return?.()}})}var q4d="conflict",uot="note",U4d=100,Rta,$4d;var Wbr=E(()=>{_n();ste();wn();Rta=new Set(["image","document"]);$4d={".md":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf",".epub":"application/epub+zip"}});import{createHash as G4d}from"crypto";import{posix as Z4d}from"path";async function Kbr(e,t){let n=Z4d.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Uw.includes(n))return Ota(e,t,n,Y4d);if(iM.includes(n))return Ota(e,t,n,X4d);let r=n===".yaml"?V4d(e,t):t;if(r===void 0)return await nGt(e,t)?Qie("No entry can be stored at this path"):rGt();if(n!==".md"&&n!==".yaml")return await nGt(e,r)?Qie("The drive stores notes, entries, images, PDFs and EPUBs"):rGt();if(r.bytes.byteLength>e.writes.maxFileBytes)return zta();let i=await e.tree.entityAt(r.segments),o=i?.entity.entityType??e.tree.placementAt(r.segments,n)?.entityType;if(o!==void 0&&Gbr(o))return Qie(o===Mta?"An image is stored as its image file":"A document is stored as its PDF or EPUB file");return i?K4d(e,r,i):J4d(e,r,n)}function V4d(e,t){let n=e.tree.placementAt(t.segments,".yaml")?.entityType;if(n===void 0||e.tree.textExtension(n)!==".yaml")return;let r=Uta(t.bytes);if(r===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(R$(r),"utf8"))}}async function K4d(e,t,{entity:n,file:r}){let{writes:i}=e,o=t.onlyIfAbsent===!0||!Qbr(t.ifMatch,r.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?iGt():Jie();let s=Nta(i,t.bytes,n.entityType);if("status"in s)return s;if(Q4d(i,s.parsed,n))return await e.mount.held(n.contentHash),{status:204,etag:await Lta(e,t,s.text)};let{visibility:a,...c}=s.parsed.metadata??n.metadata,l={...n,...s.parsed,id:n.id,entityType:n.entityType,content:s.text,metadata:c,visibility:s.parsed.visibility??n.visibility},d=await dot(e,t.grant,"update",l,z$(n.entityType,n,l,e.reader));if(d)return d;if(o)return Pta(e,t,{existing:n,base:t.onlyIfAbsent||t.ifMatch===null?void 0:{hash:t.ifMatch.replace(/^"|"$/g,"")},text:s.text,declared:s.parsed.visibility});if(t.ifMatch===null){let m=await e.mount.base();if(m!==void 0&&m.hash!==n.contentHash)return Pta(e,t,{existing:n,base:m,text:s.text,declared:s.parsed.visibility})}let p=await oGt(()=>i.updateEntity({entity:l,options:{expectedContentHash:n.contentHash,eventContext:pot(t.grant)}}));if(!p.ok)return qta(p.error);if(p.value.skipReason==="content-conflict")return Jie();if(!p.value.skipped)await Sxe(i,t.grant,"update","allowed",l);let f=await e.tree.entityAt(t.segments);if(f)await e.mount.held(f.entity.contentHash);return{status:204,etag:f?.entity.content===s.text?f.file.etag:void 0}}function Q4d(e,t,n){let r=Ybr(()=>e.deserializeEntity(n.content,n.entityType));return r.ok&&(t.visibility??n.visibility)===n.visibility&&Bun.deepEquals(t,r.value)}async function Pta(e,t,n){let{existing:r,base:i,text:o,declared:s}=n,a=Ur(o);if(i?.conflictEdit===a)return{status:204,conflictId:i.conflictId};let c=await e.recordConflict({entityType:r.entityType,entityId:r.id,origin:"drive",actor:t.grant.principal.userId,...i!==void 0&&{base:i.hash},current:r.contentHash,text:o,targetVisibility:r.visibility,...s!==void 0&&s!==r.visibility&&{declaredVisibility:s}});if(c===void 0)return Jie();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function J4d(e,t,n){let{writes:r,tree:i}=e,{segments:o}=t;if(!await nGt(e,t))return rGt();let s=i.placementAt(o,n);if(!s)return Qie("No entry can be stored at this path");let a=Nta(r,t.bytes,s.entityType);if("status"in a)return a;let{visibility:c,...l}=a.parsed.metadata??{},d=a.parsed.visibility??"public",p={...a.parsed,id:s.id,entityType:s.entityType,content:a.text,metadata:l,visibility:d},f=ij(s.entityType,void 0,l.status,e.reader)!=="non-publish",m=await dot(e,t.grant,"create",p,f?["create","publish"]:["create"]);if(m)return m;let h=await oGt(()=>r.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:pot(t.grant)}}));if(!h.ok)return Jbr(h.error);return await Sxe(r,t.grant,"create","allowed",p),{status:201,etag:await Lta(e,t,a.text)}}async function Ota(e,t,n,r){let{writes:i,tree:o}=e,{segments:s,bytes:a,grant:c}=t,l=await o.entityAt(s);if(!l&&!await nGt(e,t))return rGt();let d=l?{entityType:l.entity.entityType,id:l.entity.id}:o.placementAt(s,n);if(d?.entityType!==r.entityType)return Qie(r.wrongFolder);if(a.byteLength>i.maxAssetBytes)return zta();if(l&&t.onlyIfAbsent)return iGt();if(l&&!Qbr(t.ifMatch,l.file.etag))return Jie();let p=await r.describe({bytes:a,digest:G4d("sha256").update(a).digest("hex"),extension:n,name:s[s.length-1]??"",existing:l?.entity.metadata});if("status"in p)return p;let f=l?"update":"create",m={id:d.id,entityType:r.entityType,visibility:l?.entity.visibility??"public"},h=await dot(e,c,f,m,[f]);if(h)return h;if(l&&t.ifMatch===null){let k=await e.mount.base();if(k!==void 0&&k.hash!==l.entity.contentHash)return{status:409,message:`The ${r.noun} changed since this drive last read it`}}let g=await i.stageAsset(a,{maxBytes:i.maxAssetBytes,expectedSize:a.byteLength}),x={content:g.ref,metadata:{...p.metadata,sizeBytes:g.sizeBytes}},y={eventContext:pot(c)},v=await oGt(async()=>{if(l)return(await i.updateEntity({entity:{...l.entity,...x},stagedAsset:g,options:{...y,expectedContentHash:l.entity.contentHash}})).skipReason==="content-conflict"?Jie():void 0;await i.createEntity({entity:{...m,...x},stagedAsset:g,options:{...y,conditionalWrite:{expectedRevision:null}}});return}),w=v.ok?v.value:Jbr(v.error);if(w)return await i.discardStagedAsset(g),w;await Sxe(i,c,f,"allowed",m);let S=await o.entityAt(s);if(S)await e.mount.held(S.entity.contentHash);return{status:l?204:201,etag:S?.file.etag}}async function Fta(e,t){let{writes:n,tree:r}=e,i=await r.entityAt(t.from);if(!i)return{status:404,message:"Not found"};let{entity:o}=i,s=r.placementAt(t.to,".md");if(o.entityType!==Dta||s?.entityType!==Dta)return Qie("The drive renames notes only, to another note's name");if(await r.entityAt(t.to))return iGt();let a=await dot(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await oGt(()=>n.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:pot(t.grant)}}));if(!c.ok)return Jbr(c.error);if(!c.value.renamed)return Jie();return await Sxe(n,t.grant,"rename","allowed",o),{status:201}}async function jta(e,t){let n=await e.tree.entityAt(t.segments);if(!n)return{status:404,message:"Not found"};let{entity:r,file:i}=n;if(!Qbr(t.ifMatch,i.etag))return Jie();let o=await dot(e,t.grant,"delete",r,["delete"]);if(o)return o;if(t.ifMatch===null){let a=await e.mount.base();if(a!==void 0&&a.hash!==r.contentHash)return{status:409,message:"The file changed since this drive last read it"}}if(!await e.writes.deleteEntity({entityType:r.entityType,id:r.id,options:{expectedContentHash:r.contentHash,eventContext:pot(t.grant)}}))return Jie();return await e.mount.forget(),await Sxe(e.writes,t.grant,"delete","allowed",r),{status:204}}function Nta(e,t,n){let r=Uta(t);if(r===void 0)return{status:422,message:"The file is not UTF-8 text"};let i=Ybr(()=>e.deserializeEntity(r,n));return i.ok?{text:r,parsed:i.value}:{status:422,message:Re(i.error,"The file cannot be read")}}async function dot(e,t,n,r,i){let o=t.principal.permissionLevel,s=Ybr(()=>i.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(r.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await Sxe(e.writes,t,n,"denied",r,"entity-action-policy"),Qie(Re(s.error,"Not allowed"));if(n!=="delete"&&!Om(o,r.visibility))return await Sxe(e.writes,t,n,"denied",r,"visibility-policy"),Qie(`Cannot set visibility to "${r.visibility}" at ${o} permission`);return}function Sxe(e,t,n,r,i,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${Vbr}.entity.${n}.${r}`,targetType:"entity",targetId:i.id,metadata:{entityType:i.entityType,interfaceType:Vbr,outcome:r,...o?{reason:o}:{}}})}async function Lta(e,t,n){let r=await e.tree.entityAt(t.segments);return r?.entity.content===n?r.file.etag:void 0}function pot(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:Vbr}}function Qbr(e,t){return e===null||e==="*"||e===t}function nGt(e,t){return e.folderExists(t.segments.slice(0,-1))}function rGt(){return{status:409,message:"The folder does not exist"}}function zta(){return{status:413,message:"The file is larger than the drive accepts"}}function iGt(){return{status:412,message:"An entry already exists at this path"}}function Jbr(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?iGt():qta(e)}function Qie(e){return{status:403,message:e}}function Jie(){return{status:412,message:"The file changed since it was opened"}}function qta(e){if(T$(e))return{status:422,message:Re(e,"The file cannot be saved")};throw e}function Uta(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function Ybr(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function oGt(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}var Mta="image",W4d="document",Dta="note",Vbr="webdav",Y4d,X4d;var $ta=E(()=>{_n();Oo();_n();ste();Pf();YT();yrt();Wbr();Y4d={entityType:Mta,noun:"image",wrongFolder:"An image can only be stored in the image folder",describe:async({bytes:e,digest:t,extension:n,existing:r})=>{let i=await K3(sde(e));if(!i)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let o=Z_e(i.format);if(o!==n)return{status:422,message:`These bytes are stored as ${o}; save the image under that extension`};let s=r?.status;if(typeof s==="string"&&KH(t,s))return{status:422,message:"These bytes are the old pending placeholder, not this image's bytes"};return{metadata:{...r,...i}}}},X4d={entityType:W4d,noun:"document",wrongFolder:"A PDF or an EPUB can only be stored in the document folder",describe:async({bytes:e,digest:t,extension:n,name:r,existing:i})=>{let o;try{o=o6e(e)}catch(m){return{status:422,message:Re(m)}}let s=_We(o.mimeType);if(s!==n)return{status:422,message:`These bytes are stored as ${s}; save the document under that extension`};if(Tue(t))return{status:422,message:"These bytes are the old pending placeholder, not a document's bytes"};let{pageCount:a,sectionCount:c,status:l,processingJobId:d,processingError:p,...f}=i??{};return{metadata:{...i?f:{filename:r,attachmentType:"uploaded",origin:"uploaded"},...o}}}}});import{posix as e3d}from"path";function Gta(e){return e.startsWith(".")||!t3d.has(e3d.extname(e).toLowerCase())}class Xbr{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=bta()){this.now=e,this.kept=t}open(e){let t=this.opened.get(e)??this.kept.load(e).then((n)=>{n.forEach(({path:r,bytes:i,modified:o})=>{let s=r.split("/");if(i===void 0)this.foldersOf(e).set(r,o);else this.filesOf(e).set(r,{segments:s,bytes:i,modified:new Date(o),touched:o})})});return this.opened.set(e,t),t}settle(){return this.pending}persist(e){this.pending=this.pending.then(e)}get(e,t){let n=this.live(e).get(t.join("/"));if(n)n.touched=this.now();return n}list(e,t){return[...this.live(e).values()].filter((n)=>n.segments.length===t.length+1&&t.every((r,i)=>n.segments[i]===r)).sort((n,r)=>n.segments.join("/")<r.segments.join("/")?-1:1)}put(e,t,n){let r=this.live(e),i=t.join("/"),o=r.get(i),s=Exe(t);if([...r.values()].filter((l)=>Exe(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+n.byteLength>(s?yta:r3d))return"full";let c=this.now();if(r.set(i,{segments:t,bytes:n,modified:new Date(c),touched:c}),this.files.set(e,r),s)t.slice(0,-1).forEach((l,d)=>this.makeFolder(e,t.slice(0,d+1))),this.persist(()=>this.kept.put(e,{path:i,bytes:n,modified:c}));return o?"replaced":"created"}delete(e,t){let n=t.join("/"),r=this.live(e).delete(n);if(r&&Exe(t))this.persist(()=>this.kept.remove(e,[n]));return r}hasFolder(e,t){let n=this.liveFolders(e),r=t.join("/");if(!n.has(r))return!1;return n.set(r,this.now()),!0}listFolders(e,t){let n=t.length>0?`${t.join("/")}/`:"";return[...this.liveFolders(e).keys()].filter((r)=>r.startsWith(n)&&!r.slice(n.length).includes("/")).map((r)=>r.slice(n.length)).sort()}makeFolder(e,t){let n=this.liveFolders(e),r=t.join("/"),i=n.has(r),o=this.now();if(n.set(r,o),this.folders.set(e,n),!i&&Exe(t))this.persist(()=>this.kept.put(e,{path:r,modified:o}))}removeFolder(e,t){let n=t.join("/"),r=(a)=>a===n||a.startsWith(`${n}/`),i=this.liveFolders(e);if(!i.has(n))return!1;let o=this.live(e),s=[...i.keys(),...o.keys()].filter(r);if(s.forEach((a)=>{i.delete(a),o.delete(a)}),Exe(t))this.persist(()=>this.kept.remove(e,s));return!0}forgetFolders(e,t){let n=this.liveFolders(e);t.forEach((r,i)=>n.delete(t.slice(0,i+1).join("/")))}rename(e,t,n){let r=this.get(e,t);if(!r)return"missing";let i=this.put(e,n,r.bytes);if(i==="full")return"missing";return this.delete(e,t),i}foldersOf(e){let t=this.folders.get(e)??new Map;return this.folders.set(e,t),t}filesOf(e){let t=this.files.get(e)??new Map;return this.files.set(e,t),t}liveFolders(e){let t=this.folders.get(e)??new Map,n=this.now();if([...t].forEach(([r,i])=>{if(Hta(r,i,n))t.delete(r)}),t.size===0)this.folders.delete(e);return t}live(e){let t=this.files.get(e)??new Map,n=this.now();if([...t].forEach(([r,i])=>{if(Hta(r,i.touched,n))t.delete(r)}),t.size===0)this.files.delete(e);return t}}var t3d,n3d=600000,r3d=16777216,Hta=(e,t,n)=>!Exe(e.split("/"))&&n-t>=n3d;var Zta=E(()=>{ste();Ubr();t3d=new Set([".md",".yaml",...Uw,...iM])});class evr{expected=new Map;now;constructor(e=Date.now){this.now=e}expect(e,t){let n=this.now();for(let[r,i]of this.expected)if(i<=n)this.expected.delete(r);this.expected.set(Wta(e,t),n+30000)}take(e,t){let n=Wta(e,t),r=this.expected.get(n);if(r===void 0)return!1;return this.expected.delete(n),r>this.now()}}function Wta(e,t){return`${e}
|
|
12192
12192
|
${t.join("/")}`}import{createHash as i3d}from"crypto";class tvr{held=new Map;now;capBytes;constructor(e=Date.now,t=s3d){this.now=e,this.capBytes=t}hold(e,t,n){let r=this.live(e),i=t.join("/");r.delete(i);let o=this.now();r.set(i,{...n,savedAt:new Date(o),etag:`"held-${i3d("sha256").update(n.bytes).digest("hex")}"`,until:o+o3d});let s={bytes:0,full:!1,dropped:[]},{dropped:a}=[...r].reverse().reduce((c,[l,d],p)=>{let f=c.bytes+d.bytes.byteLength;return p>0&&(c.full||f>this.capBytes)?{...c,full:!0,dropped:[...c.dropped,l]}:{...c,bytes:f}},s);a.forEach((c)=>r.delete(c))}get(e,t){return this.live(e).get(t.join("/"))}release(e,t){this.held.get(e)?.delete(t.join("/"))}live(e){let t=this.now(),n=this.held.get(e)??new Map;return[...n].forEach(([r,i])=>{if(i.until<=t)n.delete(r)}),this.held.set(e,n),n}}var o3d=600000,s3d=16777216;var Vta=()=>{};import{randomUUID as a3d}from"crypto";class nvr{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,n){if(this.live(e))return;let r={token:`opaquelocktoken:${a3d()}`,userId:t,seconds:n,expires:this.now()+n*1000};return this.locks.set(e.join("/"),r),r}refresh(e,t,n,r){let i=this.live(e);if(!i||!Qta(i,t,n))return;return i.seconds=r,i.expires=this.now()+r*1000,i}release(e,t,n){let r=this.live(e);if(r?.userId!==t||r.token!==n)return!1;return this.locks.delete(e.join("/"))}permits(e,t,n){let r=this.live(e);return!r||Qta(r,t,n??"")}live(e){let t=e.join("/"),n=this.locks.get(t);if(n&&n.expires<=this.now()){this.locks.delete(t);return}return n}}function Qta(e,t,n){return e.userId===t&&n.includes(`<${e.token}>`)}function Jta(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):Kta,Kta)}var Kta=600;var Yta=()=>{};function c3d(e){let t=mce(e);if(t==="enum"){let n=F$(e);return n?{type:"enum",enumValues:n}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:hce(e)};if(t==="string")return{type:"string"};if(t==="number")return{type:"number"};if(t==="boolean")return{type:"boolean"};if(t==="array")return{type:"array"};if(t==="date")return{type:"date"};return{type:"unknown"}}function l3d(e){let t=[];for(let[n,r]of Object.entries(e.shape)){if(j$(r)?.studioWidget==="hidden")continue;let{inner:i,required:o,defaultValue:s}=KE(r),a=c3d(i),c={name:n,type:a.type,required:o},l=s!==void 0?s:a.defaultValue;if(l!==void 0)c.defaultValue=l;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function rvr(e){return e.types().flatMap((t)=>{if(e.fileExtension(t)===".yaml")return[];let n=e.frontmatterSchema(t);if(!n)return[];return[{entityType:t,singleton:e.isSingleton(t),bodyTemplate:e.bodyTemplate(t),fields:l3d(n)}]})}var ivr=E(()=>{gce()});function kxe(e){return e.replace(/[&<>]/g,(t)=>u3d[t]??t)}function d3d(e){return[`<D:supportedlock><D:lockentry>${Xta}</D:lockentry></D:supportedlock>`,`<D:displayname>${kxe(e.displayName)}</D:displayname>`,e.collection?"<D:resourcetype><D:collection/></D:resourcetype>":"<D:resourcetype/>",e.contentLength!==void 0?`<D:getcontentlength>${e.contentLength}</D:getcontentlength>`:"",e.contentType?`<D:getcontenttype>${kxe(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${kxe(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function ena(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((n)=>`<D:response><D:href>${kxe(n.href)}</D:href><D:propstat><D:prop>${d3d(n)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function tna(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function nna(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${Xta}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${kxe(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${kxe(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function rna(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${kxe(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var u3d,Xta="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";var ina=E(()=>{u3d={"&":"&","<":"<",">":">"}});function xna(e){let t={options:e,mounts:e.mounts??gta(e.now),scratch:new Xbr(e.now,e.kept),locks:new nvr(e.now),cleanups:new evr(e.now),holds:new tvr(e.now)},n={GET:(r,i)=>pna(r,i,!0),HEAD:(r,i)=>pna(r,i,!1),PROPFIND:I3d,POST:O3d,PUT:_3d,DELETE:N3d,MOVE:q3d,COPY:async()=>cDe("The drive does not copy files"),PROPPATCH:L3d,MKCOL:z3d,LOCK:H3d,UNLOCK:G3d};return gna.map((r)=>({path:e.basePath,match:"prefix",method:r,public:!0,handler:async(i)=>{if(r==="OPTIONS")return fot(V3d());let o=await e.resolveAppPassword(i);if(!o)return fot(K3d(e.realm));if(una(r)&&o.access!=="write")return fot(cDe("This app password is read-only"));let s=i.headers.get("x-brain-sync")?.trim()==="1",a={request:i,grant:o,tree:new Zbr(e.reader,Ui(o.principal.permissionLevel),{everyType:s}),path:Cna(e.basePath,new URL(i.url).pathname),sync:s};if(una(r)&&r!=="LOCK"&&r!=="UNLOCK"&&a.path&&!yna(t,a,a.path.segments))return fot(uvr());await t.scratch.open(o.principal.userId);let c=await n[r](t,a);return await t.scratch.settle(),fot(c)}}))}function yna(e,t,n){return e.locks.permits(n,t.grant.principal.userId,t.request.headers.get("if"))}function una(e){return hna.some((t)=>t===e)}function lGt(e,t){let{path:n}=t;return n&&!n.asFolder&&aDe(n.segments)?e.scratch.get(t.grant.principal.userId,n.segments):void 0}function aDe(e){let t=e[e.length-1];return t!==void 0&&(bna(e)||Gta(t))}function bna(e){return e.some((t)=>t.startsWith("."))}async function uGt(e,t){if(!t.path)return;let n=await t.tree.resolve(t.path.segments);if(n)return n.kind==="file"&&t.path.asFolder?void 0:n;return e.scratch.hasFolder(t.grant.principal.userId,t.path.segments)?{kind:"folder",segments:t.path.segments}:void 0}async function cvr(e,t,n){return n.length===0||e.scratch.hasFolder(t.grant.principal.userId,n)||(await t.tree.resolve(n))?.kind==="folder"}async function lvr(e,t,n){if(n.kind!=="file"||t.sync)return;let r=t.grant.appPasswordId,i=e.holds.get(r,n.segments);if(!i)return;let{conflictPending:o}=e.options;if((i.conflictId===void 0||o===void 0||await o(i.conflictId))&&n.etag===`"${i.storedHash}"`)return i;e.holds.release(r,n.segments);return}async function vna(e,t,n){let r=t.request.headers.get("if-match");if(r===null)return null;if(t.sync)return r;if(!e.holds.get(t.grant.appPasswordId,n))return r;let i=await t.tree.resolve(n);return(i?await lvr(e,t,i):void 0)?.etag===r?null:r}async function k3d(e,t){let n=new URL(t.request.url).searchParams,r=Number(n.get("wait")??ona),i=Number.isFinite(r)?Math.min(Math.max(r,0),f3d):ona,o=await e.wait(n.get("since"),i*1000,t.request.signal),s="reset"in o?o:{cursor:o.cursor,types:[...new Set(o.types.map((a)=>t.tree.folderTypeOf(a)))]};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function C3d(e){let t=new URL(e.request.url).searchParams,n=t.get("path")??"";if(n==="")return new Response("Name the file with ?path=",{status:400});let r=Number(t.get("limit")??lna),i=Number.isInteger(r)&&r>0?Math.min(r,v3d):lna,o=await e.tree.related(n.split("/"),i)??[];return new Response(JSON.stringify(o==="unindexed"?{related:[],indexed:!1}:{related:o,indexed:!0}),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function dna(e,t,n){let r=svr(n,e.options.basePath),i=await lvr(e,t,n);return i?{...r,contentLength:i.bytes.byteLength,etag:i.etag,lastModified:i.savedAt}:r}function Ana(e,t){let n=t.grant.appPasswordId,r=(t.path?.segments??[]).join("/");return{base:()=>e.mounts.get(n,r),held:(i)=>e.mounts.held(n,r,i),conflictKept:(i,o)=>e.mounts.conflictKept(n,r,i,o),forget:()=>e.mounts.forget(n,r)}}function dGt(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:Ana(e,t),recordConflict:async(n)=>e.options.recordConflict?.(n),folderExists:(n)=>cvr(e,t,n)}}async function pna(e,t,n){let{shapes:r,changes:i}=e.options;if(t.sync&&t.path?.segments.join("/")===b3d.join("/"))return C3d(t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===p3d.join("/"))return k3d(i,t);if(t.sync&&r!==void 0&&t.path?.segments.join("/")===A3d.join("/")){let c=JSON.stringify({shapes:rvr(r).filter((l)=>l.entityType===uot||t.tree.isFolderType(l.entityType))});return new Response(n?c:null,{status:200,headers:{"Content-Type":"application/json; charset=utf-8",ETag:`"${Ur(c)}"`}})}let o=lGt(e,t);if(o)return new Response(n?o.bytes:null,{status:200,headers:{"Content-Type":"application/octet-stream","Content-Disposition":"attachment","Content-Length":String(o.bytes.byteLength),ETag:kna(o),"Last-Modified":o.modified.toUTCString()}});let s=await uGt(e,t);if(!s)return Z5();if(s.kind==="folder")return avr();let a=await lvr(e,t,s);if(a)return new Response(n?a.bytes:null,{status:200,headers:{"Content-Type":s.contentType,"Content-Length":String(a.bytes.byteLength),ETag:a.etag,"Last-Modified":a.savedAt.toUTCString()}});return await Ana(e,t).held(s.etag.replace(/^"|"$/g,"")),new Response(n?await s.open():null,{status:200,headers:{"Content-Type":s.contentType,"Content-Length":String(s.size),ETag:s.etag,"Last-Modified":s.modified.toUTCString()}})}async function I3d(e,t){let n=t.request.headers.get("depth");if(n!=="0"&&n!=="1")return new Response(tna("propfind-finite-depth"),{status:403,headers:{"Content-Type":cGt}});let{basePath:r}=e.options,i=lGt(e,t);if(i)return ovr([mna(i,r)]);let o=await uGt(e,t);if(!o)return Z5();if(o.kind==="file"||n==="0")return ovr([await dna(e,t,o)]);let s=t.grant.principal.userId,a=await t.tree.children(o.segments),c=new Set(a.filter((l)=>l.kind==="folder").map((l)=>l.segments[l.segments.length-1]));return ovr([svr(o,r),...await Promise.all(a.map((l)=>dna(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>svr({kind:"folder",segments:[...o.segments,l]},r)),...e.scratch.list(s,o.segments).map((l)=>mna(l,r))])}async function _3d(e,t){let{path:n}=t;if(!n)return Z5();if(n.asFolder||n.segments.length===0)return avr();let{maxFileBytes:r,maxAssetBytes:i}=e.options.writes,o=await Sna(t.request,Math.max(r,i)),s=t.grant.principal.userId,a=aDe(n.segments);if(!o){if(!a)e.cleanups.expect(s,n.segments);return new Response("The file is larger than the drive accepts",{status:413})}if(a){if(await cvr(e,t,n.segments))return avr();return Ena(e.scratch.put(s,n.segments,o))}let c=await Kbr(dGt(e,t),{segments:n.segments,bytes:o,ifMatch:await vna(e,t,n.segments),onlyIfAbsent:t.request.headers.get("if-none-match")?.trim()==="*",keepAsConflict:t.sync&&t.request.headers.get("x-brain-keep")?.trim()==="conflict",grant:t.grant});if(t.sync)return T3d(e,t,n.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,n.segments);return await R3d(e,t,n.segments,o,c),hot(e,t,n.segments,c)}async function T3d(e,t,n,r,i){if("message"in i)return hot(e,t,n,i);e.holds.release(t.grant.appPasswordId,n);let o=await t.tree.entityAt(n),s={};if(o)s.ETag=o.file.etag,s["X-Brain-Stored"]=i.conflictId!==void 0?"conflict":await B3d(o.file,r)?"as-sent":"other-form";if(i.conflictId!==void 0)s["X-Brain-Conflict"]=i.conflictId;if(i.status===201)e.scratch.forgetFolders(t.grant.principal.userId,n.slice(0,-1));return new Response(null,{status:i.status,headers:s})}async function B3d(e,t){if(e.size!==t.byteLength)return!1;let n=new Uint8Array(await new Response(await e.open()).arrayBuffer());return Buffer.from(n).equals(Buffer.from(t))}async function R3d(e,t,n,r,i){if("message"in i)return;let o=t.grant.appPasswordId;if(i.etag!==void 0){e.holds.release(o,n);return}let s=await t.tree.entityAt(n);if(!s)return;e.holds.hold(o,n,{bytes:r,storedHash:s.entity.contentHash,conflictId:i.conflictId})}async function D3d(e){let t=await Sna(e,h3d);if(!t)return wna;try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}function P3d(){return new Response("The request is too large",{status:413})}async function O3d(e,t){let n=t.sync?t.path?.segments.join("/"):void 0,r=()=>({tree:t.tree,grant:t.grant,ask:e.options.ask,confirmAsk:e.options.confirmAsk}),i=[ana,cna,x3d.join("/")];if(n===void 0||!i.includes(n))return new Response("The drive takes no POST here",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});let o=await D3d(t.request);if(o===wna)return P3d();if(n===ana)return Ita(r(),o);if(n===cna)return _ta(r(),o);return M3d(e,t,o)}async function M3d(e,t,n){let r=y3d.safeParse(n);if(!r.success)return new Response('Name the file: { "path": "\u2026" }',{status:400});let i=await t.tree.entityAt(r.data.path.split("/"));if(!i)return new Response("There is no entry at this path.",{status:409});let o=await e.options.publish?.({entityType:i.entity.entityType,id:i.entity.id,userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel});if(!o)return new Response("Nothing publishes here right now.",{status:503});if("message"in o)return new Response(o.message,{status:409});return new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}function F3d(e){let[t,n,r,...i]=e;return t===sna[0]&&n===sna[1]&&r!==void 0&&i.length===0?r:void 0}async function j3d(e,t,n){return await e.options.resolveConflict?.({conflictId:n,action:"keep-current",userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel})?sGt():new Response("Conflicts cannot be settled here right now.",{status:503})}async function N3d(e,t){let{path:n}=t;if(!n)return Z5();let r=t.sync&&!n.asFolder?F3d(n.segments):void 0;if(r!==void 0)return j3d(e,t,r);let i=t.grant.principal.userId;if(e.scratch.removeFolder(i,n.segments))return sGt();if(!n.asFolder&&aDe(n.segments)){if(e.scratch.delete(i,n.segments))return sGt()}if(n.segments.length===0||(await t.tree.resolve(n.segments))?.kind==="folder")return cDe("The drive does not delete folders");if(n.asFolder)return Z5();if(t.request.headers.get("if-match")===null&&e.cleanups.take(i,n.segments))return new Response("The file is kept: the save just before was refused or stored in another form. Delete it again to remove it.",{status:409});let o=await jta(dGt(e,t),{segments:n.segments,ifMatch:await vna(e,t,n.segments),grant:t.grant});if(!("message"in o))e.holds.release(t.grant.appPasswordId,n.segments);return hot(e,t,n.segments,o)}async function L3d(e,t){let n=lGt(e,t)??await uGt(e,t);if(!n||!t.path)return Z5();let r="kind"in n&&n.kind==="folder",i=mot(t.path.segments);return new Response(rna(`${e.options.basePath}/${i}${r&&i?"/":""}`),{status:207,headers:{"Content-Type":cGt}})}async function z3d(e,t){let{path:n}=t;if(!n)return Z5();if((await t.request.arrayBuffer()).byteLength>0)return new Response("MKCOL takes no body",{status:415});let{segments:r}=n,i=t.grant.principal.userId;if(r.length===0||await t.tree.resolve(r)||e.scratch.hasFolder(i,r)||e.scratch.get(i,r))return new Response("Already exists",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});if(!await cvr(e,t,r.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=r;if(!bna(r)&&(o===void 0||!t.tree.isFolderType(o)))return cDe("Only an entity type can be a folder here");return e.scratch.makeFolder(i,r),new Response(null,{status:201})}async function q3d(e,t){let n=t.request.headers.get("destination");if(!n)return new Response("Destination required",{status:400});let r=Z3d(e.options.basePath,t.request,n);if(!r)return new Response("Destination is not on this drive",{status:502});let{path:i}=t;if(!i)return Z5();if(!yna(e,t,r.segments))return uvr();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(i.asFolder)return cDe("The drive does not rename files");if(!aDe(i.segments))return aDe(r.segments)?$3d(e,t,i.segments,r.segments,o):U3d(e,t,i.segments,r.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,i.segments);if(!a)return Z5();if(aDe(r.segments)){if(!o&&e.scratch.get(s,r.segments))return aGt("The destination exists");let l=e.scratch.rename(s,i.segments,r.segments);return l==="missing"?Z5():new Response(null,{status:l==="created"?201:204})}if(!o&&await t.tree.entityAt(r.segments))return aGt("The destination exists");let c=await Kbr(dGt(e,t),{segments:r.segments,bytes:a.bytes,ifMatch:null,grant:t.grant});if(c.status<300)e.scratch.delete(s,i.segments),e.holds.release(t.grant.appPasswordId,r.segments);return hot(e,t,r.segments,c)}async function U3d(e,t,n,r){let i=await Fta(dGt(e,t),{from:n,to:r,grant:t.grant});if(i.status<300){let o=t.grant.appPasswordId,s=await e.mounts.get(o,n.join("/"));if(await e.mounts.forget(o,n.join("/")),s)await e.mounts.held(o,r.join("/"),s.hash);e.holds.release(o,n)}return hot(e,t,r,i)}async function $3d(e,t,n,r,i){let o=await t.tree.entityAt(n);if(!o)return Z5();let s=t.grant.principal.userId;if(!i&&e.scratch.get(s,r))return aGt("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return Ena(e.scratch.put(s,r,a))}async function H3d(e,t){let{path:n}=t;if(!n||n.segments.length===0)return Z5();if(n.segments[0]===m3d)return cDe("There is nothing to lock here");let r=t.grant.principal.userId,i=Jta(t.request.headers.get("timeout")),o=t.request.headers.get("if"),s=(await t.request.arrayBuffer()).byteLength>0;if(o&&!s){let l=e.locks.refresh(n.segments,r,o,i);return l?fna(e,n.segments,l,200):aGt("No such lock to refresh")}let a=e.locks.acquire(n.segments,r,i);if(!a)return uvr();let c=lGt(e,t)!==void 0||await uGt(e,t)!==void 0;return fna(e,n.segments,a,c?200:201)}function fna(e,t,n,r){return new Response(nna({...n,href:`${e.options.basePath}/${mot(t)}`}),{status:r,headers:{"Content-Type":cGt,"Lock-Token":`<${n.token}>`}})}async function G3d(e,t){let{path:n}=t;if(!n)return Z5();let r=/<([^>]+)>/.exec(t.request.headers.get("lock-token")??"")?.[1];if(!r)return new Response("Lock-Token required",{status:400});return e.locks.release(n.segments,t.grant.principal.userId,r)?sGt():new Response("No such lock",{status:409})}function hot(e,t,n,r){if("message"in r)return new Response(r.message,{status:r.status});if(r.status===201)e.scratch.forgetFolders(t.grant.principal.userId,n.slice(0,-1));return new Response(null,{status:r.status,headers:r.etag?{ETag:r.etag}:{}})}function Ena(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function Sna(e,t){if(Number(e.headers.get("content-length")??0)>t)return;let n=new Uint8Array(await e.arrayBuffer());return n.byteLength>t?void 0:n}function svr(e,t){let n=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let r=mot(e.segments);return{href:r?`${t}/${r}/`:`${t}/`,displayName:n,collection:!0}}return{href:`${t}/${mot(e.segments)}`,displayName:n,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function mna(e,t){return{href:`${t}/${mot(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:kna(e),lastModified:e.modified}}function kna(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function mot(e){return e.map(encodeURIComponent).join("/")}function Cna(e,t){if(t!==e&&!t.startsWith(`${e}/`))return;let n=t.slice(e.length+1);if(n==="")return{segments:[],asFolder:!0};let r=n.endsWith("/"),o=(r?n.slice(0,-1):n).split("/").map(W3d);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:r}:void 0}function Z3d(e,t,n){let r=new URL(t.url),i=URL.canParse(n,r)?new URL(n,r):void 0;if(i?.host!==r.host)return;let o=Cna(e,i.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function W3d(e){try{return decodeURIComponent(e)}catch{return}}function ovr(e){return new Response(ena(e),{status:207,headers:{"Content-Type":cGt}})}function V3d(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:E3d,"MS-Author-Via":"DAV"}})}function K3d(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function avr(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function sGt(){return new Response(null,{status:204})}function Z5(){return new Response("Not found",{status:404})}function cDe(e){return new Response(e,{status:403})}function uvr(){return new Response("The file is locked",{status:423})}function aGt(e){return new Response(e,{status:412})}function fot(e){let t=new Headers(e.headers);return Object.entries(S3d).forEach(([n,r])=>t.set(n,r)),new Response(e.body,{status:e.status,headers:t})}var p3d,f3d=50,ona=25,sna,m3d=".brain",h3d=65536,g3d=1024,x3d,y3d,ana=".brain/ask",cna=".brain/ask/confirm",b3d,lna=10,v3d=25,A3d,w3d,hna,gna,E3d,cGt='application/xml; charset="utf-8"',S3d,wna;var Ina=E(()=>{oe();Tta();qbr();wn();$ta();Zta();Vta();Yta();Oo();ivr();Wbr();ina();p3d=[".brain","changes"],sna=[".brain","conflicts"],x3d=[".brain","publish"],y3d=u.object({path:u.string().min(1).max(g3d)}),b3d=[".brain","related"],A3d=[".brain","vault-shapes.json"],w3d=["OPTIONS","GET","HEAD","PROPFIND"],hna=["POST","PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],gna=[...w3d,...hna],E3d=gna.filter((e)=>e!=="POST").join(", "),S3d={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};wna=Symbol("too large")});var dvr="/dav",Q3d=5242880,_na,J3d,pvr;var fvr=E(()=>{lt();qbr();Ubr();lt();Zo();wn();Ata();Pf();oe();Ina();_na=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(Q3d)}),J3d=$i({id:"webdav",config:_na,setup:(e)=>{let t=ni(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(rh))return;throw Error(`webdav needs the "${rh}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let n=new $br;for(let i of[Jp,Gu,Wg,RT])t.listen(i,({payload:o})=>n.record(o.entityType),{mode:"observe"});t.listen(ga.shuttingDown,()=>n.close(),{mode:"observe"});let r=xta(t.classRuntimeState);return t.ready(()=>r.sweep()),t.interaction({id:P3e,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${dvr}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:xna({basePath:dvr,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:n,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:hN,stageAsset:(i,o)=>t.entityWrites.stageAsset(i,o),discardStagedAsset:(i)=>t.entityWrites.discardStagedAsset(i),deserializeEntity:(i,o)=>t.entityReads.deserializeEntity(i,o),createEntity:(i)=>t.entityWrites.createEntity(i),updateEntity:(i)=>t.entityWrites.updateEntity(i),deleteEntity:(i)=>t.entityWrites.deleteEntity(i),renameEntity:(i)=>t.entityWrites.renameEntity(i),permissions:t.permissions,recordAudit:async(i)=>{await t.auth()?.recordAuditEvent(i)}},resolveAppPassword:async(i)=>t.auth()?.resolveAppPassword(i),mounts:r,kept:vta(t.classRuntimeState),recordConflict:async(i)=>{let o=await t.messaging.request(OU,i);return o.status==="answered"?o.data.conflictId:void 0},ask:async(i)=>{let o=await t.messaging.request(b3e,i);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},confirmAsk:async(i)=>{let o=await t.messaging.request(v3e,i);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},publish:async(i)=>{let o=await t.messaging.request(y3e,i);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},resolveConflict:async(i)=>{let o=await t.messaging.request(Tse,i);if(o.status==="answered")return{resolved:!0};return o.status==="failed"?{message:o.error.message}:void 0},conflictPending:async(i)=>await t.entityReads.getEntityRaw({entityType:rh,id:i,visibilityScope:En("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),pvr=Cf(J3d,({state:e})=>e.routes)});var Tna;var Bna=E(()=>{fvr();fvr();ivr();Tna=pvr});async function mvr(e){let t=e.fetch??fetch,n=`${e.homeserverUrl.replace(/\/+$/,"")}/_matrix/client/v3`,r=e.userId.slice(1).split(":")[0]??"",i=(p,f)=>t(`${n}${p}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f)}),o=await i("/login",{type:"m.login.password",identifier:{type:"m.id.user",user:r},password:e.password,device_id:"brain-bootstrap"});if(o.ok)return"exists";let s=await Rna(o);if(s!=="M_FORBIDDEN")throw Error(`Matrix bot login failed: ${s??o.status}`);let a={username:r,password:e.password,inhibit_login:!0},c=await i("/register",a),l=X3d.safeParse(await c.json().catch(()=>{return}));if(!l.success)throw Error(`Matrix bot registration did not start: ${c.status}`);let d=await i("/register",{...a,auth:{type:"m.login.registration_token",token:e.registrationToken,session:l.data.session}});if(!d.ok)throw Error(`Matrix bot registration failed: ${await Rna(d)??d.status}`);return"registered"}async function Rna(e){let t=Y3d.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var Y3d,X3d;var hvr=E(()=>{oe();Y3d=u.object({errcode:u.string()}),X3d=u.object({session:u.string()})});function pGt(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Iq(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function xvr(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
12193
12193
|
server_name = ${Iq(e.serverName)}
|
|
@@ -12549,7 +12549,7 @@ ${h.join(`
|
|
|
12549
12549
|
2. Says what the series covers that its parts do not on their own
|
|
12550
12550
|
3. Works well as a series overview on a website
|
|
12551
12551
|
|
|
12552
|
-
Follow the supplied style guide for voice, tone, wording and form.`})});function UFd(e,t){return{content:bDe(t.title,"compact").format(Pxe(t.title,e)),frontmatter:{title:t.title,slug:t.slug,...t.coverImageId!==null&&{coverImageId:t.coverImageId}}}}var Gwr;var Zwr=E(()=>{Jr();_n();Hwr();hsa();xsa();vDe();bsa();Gwr=Vr({type:"series",purpose:"A series grouping related posts or content under one theme.",coverImage:!0,metadata:yDe,markdown:jm({decode:({content:e,frontmatter:t})=>{let n=nZt.parse(t);return{content:e,metadata:{title:n.title,slug:n.slug,coverImageId:n.coverImageId}}},encode:({content:e,metadata:t})=>UFd(e,t)}),config:{weight:0.5,projectionSourceRole:"supporting",memberGroup:{label:"Series",multiple:!1}},templates:{...msa(),description:ysa},projectionRules:({template:e})=>[gsa(e("description"))],atproto:$wr})});var $Fd,vsa;var Asa=E(()=>{Jr();Uwr();Zwr();Zwr();Uwr();Hwr();vDe();$Fd=qc({id:"series",entities:[Gwr],dataSources:[qwr]}),vsa=$Fd});async function wsa(e){return e.routes().flatMap((n)=>n.sections.flatMap((r)=>r.template?[{id:`${n.id}:${r.id}`,template:r.template}]:[])).reduce(async(n,r)=>{let i=await n,o=await e.savedBody(r.id);if(o===null)return i;let s;try{s=e.layOut(r.template,o)}catch(c){return e.warn("Section copy left in its stored layout",{id:r.id,template:r.template,error:Re(c)}),i}if(s===o)return i;let a=await e.restate(r.id,s);return a?[...i,a]:i},Promise.resolve([]))}function Esa(e){return async(t)=>(await e.getEntityRaw({entityType:"site-content",id:t}))?.content??null}var Ssa=()=>{};async function ksa(e){return e.routes().
|
|
12552
|
+
Follow the supplied style guide for voice, tone, wording and form.`})});function UFd(e,t){return{content:bDe(t.title,"compact").format(Pxe(t.title,e)),frontmatter:{title:t.title,slug:t.slug,...t.coverImageId!==null&&{coverImageId:t.coverImageId}}}}var Gwr;var Zwr=E(()=>{Jr();_n();Hwr();hsa();xsa();vDe();bsa();Gwr=Vr({type:"series",purpose:"A series grouping related posts or content under one theme.",coverImage:!0,metadata:yDe,markdown:jm({decode:({content:e,frontmatter:t})=>{let n=nZt.parse(t);return{content:e,metadata:{title:n.title,slug:n.slug,coverImageId:n.coverImageId}}},encode:({content:e,metadata:t})=>UFd(e,t)}),config:{weight:0.5,projectionSourceRole:"supporting",memberGroup:{label:"Series",multiple:!1}},templates:{...msa(),description:ysa},projectionRules:({template:e})=>[gsa(e("description"))],atproto:$wr})});var $Fd,vsa;var Asa=E(()=>{Jr();Uwr();Zwr();Zwr();Uwr();Hwr();vDe();$Fd=qc({id:"series",entities:[Gwr],dataSources:[qwr]}),vsa=$Fd});async function wsa(e){return e.routes().flatMap((n)=>n.sections.flatMap((r)=>r.template?[{id:`${n.id}:${r.id}`,template:r.template}]:[])).reduce(async(n,r)=>{let i=await n,o=await e.savedBody(r.id);if(o===null)return i;let s;try{s=e.layOut(r.template,o)}catch(c){return e.warn("Section copy left in its stored layout",{id:r.id,template:r.template,error:Re(c)}),i}if(s===o)return i;let a=await e.restate(r.id,s);return a?[...i,a]:i},Promise.resolve([]))}function Esa(e){return async(t)=>(await e.getEntityRaw({entityType:"site-content",id:t}))?.content??null}var Ssa=()=>{};async function ksa(e){return e.routes().flatMap((n)=>n.sections.flatMap((r)=>r.template&&r.content!==void 0&&r.dataQuery===void 0?[{id:`${n.id}:${r.id}`,template:r.template,content:r.content}]:[])).reduce(async(n,r)=>{let i=await n;try{if(await e.isStarted(r.id))return i;let o=await e.hasText(r.id);if(!o)await e.create(r.id,await e.write(r.template,r.content));return await e.remember(r.id),o?i:[...i,r.id]}catch(o){return e.warn("Section copy not started in the brain yet",{id:r.id,template:r.template,error:Re(o)}),i}},Promise.resolve([]))}var Csa=()=>{};var _sa=`@import "tailwindcss" source(none);
|
|
12553
12553
|
@plugin "@tailwindcss/typography";
|
|
12554
12554
|
/* Only what the build emits: the runtime scripts that toggle classes on its
|
|
12555
12555
|
pages, and the classes of the pages themselves, which the builder collects
|
|
@@ -12585,7 +12585,7 @@ Follow the supplied style guide for voice, tone, wording and form.`})});function
|
|
|
12585
12585
|
`)+`
|
|
12586
12586
|
|
|
12587
12587
|
`+p;await p1.writeFile(d,m,{encoding:"utf-8",signal:r})}this.logger.debug("CSS processed successfully with font imports")}async writePublicAssets(e,t){return ZFd(e,t,this.outputDir,this.logger)}async writeInlineStaticAssets(e,t){return WFd(e,t,this.outputDir,this.logger)}}async function ZFd(e,t,n,r){t.throwIfAborted();let i=Object.entries(e);if(i.length===0)return;r.debug(`Writing ${i.length} snapshotted public asset(s)`);for(let[o,s]of i){t.throwIfAborted();let a=vK(n,o);await p1.mkdir(Rsa(a),{recursive:!0}),await p1.writeFile(a,Buffer.from(s,"base64"),{signal:t}),r.debug(`Wrote public asset: ${o}`)}}async function WFd(e,t,n,r){if(t.throwIfAborted(),!e)return;let i=Object.entries(e);if(i.length===0)return;r.debug(`Writing ${i.length} inline static asset(s) from SitePackage`);let o=await Promise.allSettled(i.map(async([a,c])=>{t.throwIfAborted();let l=vK(n,a);await p1.mkdir(Rsa(l),{recursive:!0}),await p1.writeFile(l,c,{encoding:"utf-8",signal:t}),r.debug(`Wrote inline static asset: ${a}`)}));t.throwIfAborted();let s=o.find((a)=>a.status==="rejected");if(s)throw s.reason}function Vwr(e){return new Dsa(e)}async function Psa(e,t,n,r){r.throwIfAborted(),await(await p1.readdir(e,{withFileTypes:!0})).reduce(async(o,s)=>{await o;let a=Mot(e,s.name);if(s.isDirectory())await Psa(a,t,n,r);else if(s.name.endsWith(".html")&&!t.has(a))n.add(await p1.readFile(a,{encoding:"utf-8",signal:r}))},Promise.resolve())}function VFd(e,t){let[n]=e;if(!t||!n||e.length<2)return"";let r=t.replace(/\/+$/,"");return[...e,{...n,language:"x-default"}].map(({language:i,path:o})=>`
|
|
12588
|
-
<link rel="alternate" hreflang="${br(i)}" href="${br(r+o)}">`).join("")}function KFd(e,t){if(!t)return e;return{...e,...t.title!==void 0&&{title:t.title},...t.description!==void 0&&{description:t.description},...t.copyright!==void 0&&{copyright:t.copyright},...t.cta!==void 0&&{cta:t.cta}}}var Kwr=E(()=>{Oo();or();Su();cc();J8();Isa();Oot()});var Osa,QFd,JFd,FRg;var Msa=E(()=>{Su();oe();Osa=u.object({environment:u.enum(["preview","production"]),outputDir:u.string(),workingDir:u.string().optional(),sharedImagesDir:u.string().default("./dist/images"),enableContentGeneration:u.boolean().default(!1),cleanBeforeBuild:u.boolean().default(!0),siteConfig:PT,layouts:u.record(u.string(),u.custom()),themeCSS:u.string().optional(),languages:u.array(YE).min(1).optional(),layoutCopy:Bce.optional()}),QFd=u.enum(["build-failed","build-cancelled","output-commit-failed","unsafe-route-path","missing-layout","missing-template","missing-web-renderer","unsafe-static-asset-path","static-asset-collision","public-asset-snapshot-failed","section-content-resolution-failed","invalid-section-content","missing-site-url","staged-artifact-failed"]),JFd=u.object({severity:u.enum(["warning","error"]),code:QFd,message:u.string(),routeId:u.string().optional(),sectionId:u.string().optional(),template:u.string().optional(),path:u.string().optional()}),FRg=u.object({success:u.boolean(),cancelled:u.boolean().optional(),superseded:u.boolean().optional(),skipped:u.boolean().optional(),outputDir:u.string(),filesGenerated:u.number(),routesBuilt:u.number(),errors:u.array(u.string()).optional(),warnings:u.array(u.string()).optional(),diagnostics:u.array(JFd).optional()})});function Fot(e,t){let n=t.toLowerCase();return Object.entries(e??{}).find(([r])=>r.toLowerCase()===n)?.[1]}function Fsa(e,t=[]){return{list:()=>{let n=e.list(),r=new Set(n.map((i)=>i.path));return[...n,...t.filter((i)=>!r.has(i.path))]},getNavigationItems:(n)=>e.getNavigationItems(n)}}async function jsa(e,t){let n=e.list(),r=n.length===0?["No routes registered for site build"]:[],[i=YFd,...o]=t.languages??[],s=o.filter((p)=>Fot(t.siteTranslations,p)!==void 0),a=n.filter((p)=>XFd(p)||p.languages!==void 0),c=await Promise.all(s.map(async(p)=>({language:p,byRouteId:new Map((await Promise.all(a.map(async(f)=>{let m=await ejd(f,p,i,t.hasSavedCopy);return m?[f.id,m]:null}))).filter((f)=>f!==null))}))),l=(p)=>[{language:i,path:p.path},...c.flatMap(({language:f,byRouteId:m})=>{let h=m.get(p.id);return h?[{language:f,path:h.path}]:[]})],d=({language:p,byRouteId:f})=>{let m=new Map(n.flatMap((g)=>{let x=f.get(g.id),y=Fot(g.translations,p);return x?[[g.path,{href:x.path,label:y?.navigationLabel??y?.title}]]:[]})),h=(g)=>g.flatMap((x)=>{let y=m.get(x.href);return y?[{...x,href:y.href,label:y.label??x.label}]:[]});return{primary:h(e.getNavigationItems("primary")),secondary:h(e.getNavigationItems("secondary"))}};return{routes:[...n.map((p)=>({...p,language:i,alternates:l(p)})),...c.flatMap((p)=>{let f=d(p),m=Fot(t.siteTranslations,p.language);return n.flatMap((h)=>{let g=p.byRouteId.get(h.id);return g?[{...g,alternates:l(h),siteNavigation:f,siteTranslation:m}]:[]})})],warnings:r}}function XFd(e){return e.sections.length>0&&e.sections.every((t)=>t.template!==""&&t.dataQuery===void 0)}async function ejd(e,t,n,r){let i=`${t.toLowerCase()}:${e.id}`,o=Fot(e.translations,t);if(e.languages!==void 0)return e.languages.some((a)=>a.toLowerCase()===t.toLowerCase())?{...e,id:i,title:o?.title??"",description:o?.description??"",path:c7e(t,n,e.path),language:t}:void 0;if(!(await Promise.all(e.sections.map((a)=>r(`${i}:${a.id}`)))).every(Boolean))return;return{...e,id:i,title:o?.title??"",description:o?.description??"",path:c7e(t,n,e.path),language:t,sections:e.sections.map(({content:a,...c})=>c)}}var YFd="en";var Nsa=E(()=>{Su()});function Lsa(e){let t=[...new Set(e.definitions.flatMap((r)=>r.sections).map((r)=>r.template))],n=Object.fromEntries(t.flatMap((r)=>{let i=e.pipelineContext.services.getViewTemplate(r);return i?[[r,i]]:[]}));return{preparedBuild:e.envelope,routes:e.routes,viewTemplates:n,layouts:e.layouts,...e.slots&&{slots:e.slots}}}async function zsa(e){e.signal.throwIfAborted();let t=e.staticSiteBuilderFactory({logger:e.logger.child("StaticSiteBuilder"),workingDir:e.workingDir,outputDir:e.outputDir});if(e.cleanBeforeBuild)await t.clean();return e.signal.throwIfAborted(),t}async function qsa(e){await new P9t({logger:e.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:e.pipelineContext.services.entityService,listViewTemplateNames:()=>e.pipelineContext.services.listViewTemplateNames()},e.pipelineContext.routeRegistry,e.pipelineContext.entityDisplay,{visibilityScope:"public",...e.publishedOnly!==void 0&&{publishedOnly:e.publishedOnly}}).generateEntityRoutes()}var Usa=E(()=>{J8()});function $sa(e,t,n){let r=t.getProfile(),i=n.getNavigationItems("primary"),o=n.getNavigationItems("secondary");return{...e,represents:e.represents??"anchor",...e.represents!=="brain"&&r.socialLinks!==void 0&&{socialLinks:r.socialLinks},...e.represents!=="brain"&&r.photo!==void 0&&{photo:r.photo},navigation:{primary:i,secondary:o},copyright:e.copyright??"Powered by Rizom"}}async function Zsa(e,t){return Qwr(e,t,new MT(t.pipelineContext.entityDisplay))}async function Qwr(e,t,n){if(e===null||e===void 0)return e;if(Array.isArray(e))return Promise.all(e.map((S)=>Qwr(S,t,n)));if(typeof e!=="object")return e;let r={},i=Object.entries(e),o=await Promise.all(i.map(([,S])=>Qwr(S,t,n)));for(let S=0;S<i.length;S++){let k=i[S];if(k)r[k[0]]=o[S]}let s=tjd.safeParse(e);if(!s.success)return r;let a=s.data,c=a.entityType,l=a.metadata.slug,d=t.pipelineContext.entityDisplay?.[c],p=d?d.label:c.charAt(0).toUpperCase()+c.slice(1),f=d?d.pluralName??d.label.toLowerCase()+"s":t3(c),m=`/${f}`,h=f.charAt(0).toUpperCase()+f.slice(1),g=pEt(a),x=await rjd(g,t),y=fEt(a)??g,v=await ijd(y,t);return{...r,...a,url:n.generateUrl(c,l),typeLabel:p,listUrl:m,listLabel:h,...x,...v&&{ogImageUrl:v}}}async function rjd(e,t){let n=e?t.imageBuildService?.get(e):void 0;if(n)return{coverImageUrl:n.src,coverImageWidth:n.width,coverImageHeight:n.height,...n.alt&&{coverImageAlt:n.alt},...n.srcset&&{coverImageSrcset:n.srcset,coverImageSizes:n.sizes}};let r=await Wsa(e,t.pipelineContext.services.entityService);if(!r)return{};return{coverImageUrl:r.url,...r.width&&{coverImageWidth:r.width},...r.height&&{coverImageHeight:r.height},...r.alt&&{coverImageAlt:r.alt}}}async function ijd(e,t){if(!e)return;let n=t.imageBuildService?.get(e);if(n)return Hsa(n.src,t.siteUrl);let r=await Wsa(e,t.pipelineContext.services.entityService);if(!r)return;if(r.url.startsWith("data:"))return;return Hsa(r.url,t.siteUrl)}function Hsa(e,t){if(/^https?:\/\//i.test(e)||e.startsWith("data:"))return e;if(!t)return e;return`${t.replace(/\/$/,"")}/${e.replace(/^\//,"")}`}async function Wsa(e,t){if(!e)return;let n=await t.getEntity({entityType:"image",id:e}),r=njd.safeParse(n);if(!r.success)return;let i=await dEt(t,r.data);if(!i)return;let o=Fze(r.data.metadata);return{url:i,...o&&{alt:o},...r.data.metadata.width&&{width:r.data.metadata.width},...r.data.metadata.height&&{height:r.data.metadata.height}}}async function Vsa(e,t){let n=new Set;try{let r=e.getEntityTypes();for(let i of r){if(i==="image")continue;await Qsa(e,i,(o)=>o.forEach((s)=>{let a=pEt(s);if(a)n.add(a);let c=fEt(s);if(c)n.add(c);if(s.content.includes("entity://image/"))mEt(s.content,(l)=>{let d=/^entity:\/\/image\/(.+)$/.exec(l);if(d?.[1])n.add(d[1]);return l})}))}}catch(r){t.warn("Failed to collect image IDs for pre-resolution",{error:Re(r)})}return[...n]}function Jwr(e){if(typeof e==="string")return[e];if(Array.isArray(e))return e.flatMap(Jwr);if(e!==null&&typeof e==="object")return Object.values(e).flatMap(Jwr);return[]}function ojd(e){if(!e.includes("entity://image/"))return[];let t=[];return mEt(e,(n)=>{let r=/^entity:\/\/image\/(.+)$/.exec(n);if(r?.[1])t.push(r[1]);return n}),t}function Ksa(e){return[...new Set(e.flatMap((t)=>t.sections??[]).flatMap((t)=>Jwr(t.content)).flatMap(ojd))]}async function Qsa(e,t,n,r=0){let i=await e.listEntities({entityType:t,options:{limit:Gsa,offset:r,sortFields:[{field:"id",direction:"asc"}],source:!0}});if(n(i),i.length<Gsa)return;await Qsa(e,t,n,r+i.length)}var tjd,njd,Gsa=1000;var Ywr=E(()=>{Pf();Su();or();oe();tjd=u.looseObject({id:u.string(),entityType:u.string(),content:u.string(),metadata:u.looseObject({slug:u.string()})}),njd=u.looseObject({content:u.string(),metadata:u.looseObject({width:u.number().optional(),height:u.number().optional()})})});async function Xwr(e,t,n,r,i){if(!e.template)return e.content??null;let o=e.template,s={entityType:"site-content",entityId:`${t.id}:${e.id}`},{services:a}=i.pipelineContext,c=t.copy==="brain"&&await a.isCopyStarted(s.entityId)?void 0:e.content,l=e.dataQuery?{dataParams:e.dataQuery,savedContent:s,fallback:c,publishedOnly:n,visibilityScope:r}:{savedContent:s,fallback:c,visibilityScope:r},d=await a.resolveTemplateContent(o,l);if(!d){if(c===void 0&&e.dataQuery===void 0&&await a.hasSavedContent(s.entityId))throw Error(`The saved text ${s.entityId} does not fit its section`);return null}let p=Zte(d);return Zsa(p,{pipelineContext:i.pipelineContext,imageBuildService:i.imageBuildService,siteUrl:i.siteUrl})}var Jsa=E(()=>{J8();Ywr()});function eEr(e,t,n){return i3.parse({id:e,path:`/${e}`,title:"Layout",description:"The words of the site's menu and footer",copy:"brain",navigation:{show:!1},sections:[{id:sjd,template:t,content:n}]})}function tEr(e){return e?[eEr(iZt,e.template,e.content)]:[]}function oZt(e,t){if(!e)return[];let[,...n]=t??[];return[...tEr(e),...n.flatMap((r)=>{let i=Object.entries(e.translations??{}).find(([o])=>o.toLowerCase()===r.toLowerCase())?.[1];return i?[eEr(`${r.toLowerCase()}:${iZt}`,e.template,i)]:[]})]}function Ysa(e,t,n){let i=(t?.[0]??n).toLowerCase()===n.toLowerCase()?iZt:`${n.toLowerCase()}:${iZt}`;return oZt(e,t).find((s)=>s.id===i)??(e?eEr(i,e.template,void 0):void 0)}var iZt="layout",sjd="copy";var nEr=E(()=>{Su()});import{randomUUID as ajd}from"crypto";function eaa(e){return _o(sZt(e))}function taa(e){let{buildId:t,preparedAt:n,...r}=e.envelope,i=[...new Set(e.templates)].sort();return _o(sZt({version:4,rendererIdentity:e.rendererIdentity,preparedInput:{...r,routes:e.routeDigests},layouts:Object.fromEntries(Object.entries(e.layouts).sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>[o,String(s)])),rendererRuntime:{staticSiteBuilderFactory:String(e.staticSiteBuilderFactory),stagingMessageSender:String(e.command)},templates:Object.fromEntries(i.map((o)=>{let s=e.getViewTemplate(o);return[o,s?{renderer:String(s.renderers.web),fullscreen:s.fullscreen??!1,runtimeScripts:s.runtimeScripts??[],staticAssets:s.staticAssets??{}}:null]}))}))}function sZt(e,t=new Set){if(e===null)return"null";if(typeof e==="string"||typeof e==="boolean")return JSON.stringify(e);if(typeof e==="number"){if(!Number.isFinite(e))throw Error("Cannot fingerprint non-finite number");return JSON.stringify(e)}if(typeof e==="function")return JSON.stringify(String(e));if(typeof e!=="object")throw Error(`Cannot fingerprint ${typeof e} value`);if(t.has(e))throw Error("Cannot fingerprint circular site inputs");let n=new Set(t).add(e);if(Array.isArray(e))return`[${e.map((r)=>sZt(r,n)).join(",")}]`;if(!Cr(e))throw Error("Cannot fingerprint non-plain site input objects");return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>`${JSON.stringify(r)}:${sZt(i,n)}`).join(",")}}`}var Xsa;var rEr=E(()=>{Oo();Xc();Xsa=ajd()});import{promises as aZt}from"fs";import{join as cjd,relative as ljd,sep as ujd}from"path";async function naa(e,t,n=djd){t.throwIfAborted();try{await aZt.access(e)}catch(i){if(bx(i))return{};throw i}let r={};return await raa(e,e,r,t,{totalBytes:0,maxTotalBytes:n}),r}async function raa(e,t,n,r,i){r.throwIfAborted();let o=await aZt.readdir(t,{withFileTypes:!0});o.sort((s,a)=>s.name.localeCompare(a.name));for(let s of o){r.throwIfAborted();let a=cjd(t,s.name),c=ljd(e,a).split(ujd).join("/");if(s.isSymbolicLink())throw Error(`Public asset cannot be a symbolic link: ${c}`);if(s.isDirectory()){await raa(e,a,n,r,i);continue}if(!s.isFile())continue;let{size:l}=await aZt.stat(a);if(i.totalBytes+=l,i.totalBytes>i.maxTotalBytes)throw Error(`App public assets exceed the ${i.maxTotalBytes} byte snapshot budget at "${c}". Large files belong in the shared image cache or behind a CDN rather than in public/.`);n[c]=(await aZt.readFile(a)).toString("base64")}}var djd=67108864;var iaa=E(()=>{Xc()});async function aaa(e){e.signal.throwIfAborted();let t=(x)=>e.pipelineContext.services.getViewTemplate(x),n=e.parsedOptions.environment==="production",r=[],i={};try{i=await naa(e.publicDir,e.signal)}catch(x){e.signal.throwIfAborted();let y={severity:"error",code:"public-asset-snapshot-failed",message:`Failed to snapshot app public assets: ${Re(x)}`,path:e.publicDir};e.pipelineContext.logger.error(y.message,{error:x}),r.push(y)}let o=Ezn({...Lzn(e.routes,{getViewTemplate:t}),...e.buildOptions.staticAssets},Object.keys(i)),s=$sa(e.siteMetadata,e.pipelineContext.profileService,e.pipelineContext.routeRegistry),a=new Set(Object.keys(i));for(let x of Object.keys(o)){let y=x.startsWith("/")?x.slice(1):x;if(!a.has(y))continue;r.push({severity:"warning",code:"static-asset-collision",message:`Static asset "${x}" overrides app public asset "${y}"`,path:x})}e.signal.throwIfAborted();let c=Ozn({buildId:e.buildId,preparedAt:e.preparedAt,environment:e.parsedOptions.environment,site:s,...e.parsedOptions.themeCSS!==void 0&&{themeCSS:e.parsedOptions.themeCSS},images:e.imageBuildService.getMap(),links:Tzn(e.routes),staticAssets:o,publicAssets:i,globalHeadScripts:e.buildOptions.headScripts??[],...e.siteUrl!==void 0&&{siteUrl:e.siteUrl}}),l=[],d=[],p=[],f=new Set,m=new Map,h=(x)=>{let y=x.toLowerCase(),v=m.get(y);if(v)return v;let w=Ysa(e.parsedOptions.layoutCopy,e.parsedOptions.languages,x),S=w?.sections[0],k=w&&S?Xwr(S,w,n,"public",{pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteMetadata.url}).then((C)=>C?qh.parse(C):void 0):Promise.resolve(void 0);return m.set(y,k),k},g={count:e.routes.length,each:(x,y)=>jzn(e.routes.map((v,w)=>({route:v,index:w})),async({route:v,index:w})=>{let S=await pjd({route:v,siteTitle:e.siteMetadata.title,publishedOnly:n,getViewTemplate:t,staticAssets:o,pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteMetadata.url,layoutCopyOf:h,signal:y});if(p[w]=S.diagnostics,S.diagnostics.some(({severity:C})=>C==="error"))return;let k=Fzn(S.route);l[w]={id:k.id,path:k.path,headScripts:k.headScripts},d[w]=eaa(k);for(let C of k.sections)f.add(C.template);await x(k)},y)};return{envelope:c,diagnostics:r,routes:g,pages:()=>({routes:l.filter((x)=>x!==void 0),digests:d.filter((x)=>x!==void 0),templates:[...f].sort(),diagnostics:p.flat()})}}async function pjd(e){e.signal.throwIfAborted();let t=[],n=[];for(let i of e.route.sections){if(e.signal.throwIfAborted(),i.template==="footer")continue;let o=await fjd(e,i);if(o.section)n.push(o.section);if(o.diagnostic)t.push(o.diagnostic)}let r;try{r=await e.layoutCopyOf(e.route.language)}catch(i){e.signal.throwIfAborted(),t.push({severity:"error",code:"section-content-resolution-failed",message:`Failed to resolve the layout's words in ${e.route.language}: ${Re(i)}`,routeId:e.route.id})}return{route:{id:e.route.id,path:e.route.path,language:e.route.language,alternates:e.route.alternates,...e.route.siteNavigation!==void 0&&{siteNavigation:e.route.siteNavigation},...e.route.siteTranslation!==void 0&&{siteTranslation:e.route.siteTranslation},title:e.route.title,...e.route.pageLabel!==void 0&&{pageLabel:e.route.pageLabel},description:e.route.description,layout:e.route.layout,...r!==void 0&&{layoutCopy:r},fullscreen:e.route.sections.some((i)=>e.getViewTemplate(i.template)?.fullscreen===!0),sections:n,headScripts:Nzn(e.route,{getViewTemplate:e.getViewTemplate},e.staticAssets)},diagnostics:t}}async function fjd(e,t){e.signal.throwIfAborted();let n=e.getViewTemplate(t.template),r=n?.renderers.web;if(!n||!r||typeof r!=="function")return{};let i;try{i=await Xwr(t,e.route,e.publishedOnly,"public",{pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteUrl}),e.signal.throwIfAborted()}catch(o){e.signal.throwIfAborted();let s=saa(o),a={severity:"error",code:"section-content-resolution-failed",message:`Failed to resolve content for route "${e.route.id}" section "${t.id}": ${s.summary}`,routeId:e.route.id,sectionId:t.id,template:t.template};return e.pipelineContext.logger.error("Failed to resolve site section content",{routeId:e.route.id,sectionId:t.id,template:t.template,...s.issues?{issues:s.issues}:{},...!s.issues?{error:s.summary}:{}}),{diagnostic:a}}if(!i)return{};e.signal.throwIfAborted();try{let o=oaa.parse(i),s=n.schema.parse({...o,pageTitle:e.route.title||e.siteTitle,...e.route.pageLabel!==void 0&&{pageLabel:e.route.pageLabel}}),a=Zte(s),c=oaa.parse(a);return{section:{id:t.id,template:t.template,data:qh.parse(c)}}}catch(o){let s=saa(o),a={severity:"warning",code:"invalid-section-content",message:`Route "${e.route.id}" section "${t.id}" has invalid content for template "${t.template}": ${s.summary}`,routeId:e.route.id,sectionId:t.id,template:t.template};return e.pipelineContext.logger.error("Invalid site section content",{routeId:e.route.id,sectionId:t.id,template:t.template,...s.issues?{issues:s.issues}:{},...!s.issues?{error:s.summary}:{}}),{diagnostic:a}}}function saa(e){if(!(e instanceof u.ZodError))return{summary:Re(e)};let t=e.issues.map((n)=>({code:n.code,path:n.path.map(String).join("."),message:n.message}));return{summary:t.map((n)=>`${n.path||"<root>"}: ${n.message}`).join("; "),issues:t}}var oaa;var caa=E(()=>{J8();oe();Jsa();nEr();rEr();iaa();oaa=u.record(u.string(),u.unknown())});async function laa(e){e.signal.throwIfAborted();let t=new R9t(e.pipelineContext.services.entityService,e.pipelineContext.logger,e.sharedImagesDir),n=[...new Set([...await Vsa(e.pipelineContext.services.entityService,e.pipelineContext.logger),...Ksa(e.routes)])];if(e.signal.throwIfAborted(),n.length>0)await t.resolveAll(n,e.signal);return e.signal.throwIfAborted(),t}var uaa=E(()=>{J8();Ywr()});async function daa(e){let t=e.reporter?.createSub({scale:{start:85,end:95}});e.signal.throwIfAborted(),await e.staticSiteBuilder.build(e.buildContext,(n)=>{t?.report(n).catch(()=>{})},e.signal),e.signal.throwIfAborted()}function mjd(e,t){let n=t.replace(/\/+$/u,""),r=(i)=>i.startsWith("/")&&!i.startsWith("//")?`${n}${i}`:i;return e.replace(/\b(href|src)="([^"]*)"/gu,(i,o,s)=>`${o}="${r(s)}"`).replace(/\bsrcset="([^"]*)"/gu,(i,o)=>`srcset="${o.split(",").map((a)=>{let[c="",...l]=a.trim().split(/\s+/u);return[r(c),...l].join(" ")}).join(", ")}"`)}function paa(e){let t=uQe(e.links),n=Tme(e.images);return(r)=>mjd(R2(r,{imageRenderer:n,wikiLinkResolver:t}),e.siteUrl)}var faa=E(()=>{J8();cc()});function iEr(e){return{success:!0,outputDir:e.outputDir,filesGenerated:e.filesGenerated,routesBuilt:e.routesBuilt,...e.skipped&&{skipped:!0},...e.warnings.length>0&&{warnings:e.warnings},...e.diagnostics&&e.diagnostics.length>0&&{diagnostics:e.diagnostics}}}function maa(e){return{success:!1,cancelled:!0,outputDir:e.outputDir,filesGenerated:0,routesBuilt:0,errors:[e.message],diagnostics:e.diagnostics}}function jot(e){return{success:!1,outputDir:e.outputDir,filesGenerated:0,routesBuilt:0,errors:e.errorMessages,...e.diagnostics&&e.diagnostics.length>0&&{diagnostics:e.diagnostics}}}function AK(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function haa(e,t){if(!e)return[];let n=[];for(let r of Object.keys(e)){let i=rZt(r,"asset");if(!i)continue;n.push(AK("error","unsafe-static-asset-path",`Static asset path "${r}" is unsafe: ${i}`,{...t,path:r}))}return n}function hjd(e,t){if(e!==void 0&&e.trim().length>0)return[];return[t==="production"?AK("error","missing-site-url","Production build has no configured site URL; staged sitemap, robots, and feed links would be published against a placeholder domain"):AK("warning","missing-site-url","Preview build has no configured site URL; staged sitemap, robots, and feed links fall back to a placeholder domain")]}function gaa(e){let t=haa(e.staticAssets,{});t.push(...hjd(e.siteUrl,e.environment));let n=new Set,r=new Map;for(let i of e.routes){let o=rZt(i.path,"route");if(o)t.push(AK("error","unsafe-route-path",`Route "${i.id}" path "${i.path}" is unsafe: ${o}`,{routeId:i.id,path:i.path}));if(typeof e.layouts[i.layout]!=="function")t.push(AK("error","missing-layout",`Route "${i.id}" references missing layout "${i.layout}"`,{routeId:i.id,path:i.path}));for(let s of i.sections){let a=e.getViewTemplate(s.template),c={routeId:i.id,sectionId:s.id,template:s.template,path:i.path};if(!a){t.push(AK("warning","missing-template",`Route "${i.id}" section "${s.id}" references missing template "${s.template}"`,c));continue}if(!a.renderers.web||typeof a.renderers.web!=="function")t.push(AK("warning","missing-web-renderer",`Template "${s.template}" has no callable web renderer`,c));if(n.has(s.template))continue;n.add(s.template),t.push(...haa(a.staticAssets,{template:s.template}));for(let[l,d]of Object.entries(a.staticAssets??{})){let p=r.get(l);if(!p){r.set(l,{template:s.template,content:d});continue}if(p.content===d)continue;t.push(AK("warning","static-asset-collision",`Static asset path "${l}" is declared by templates "${p.template}" and "${s.template}"; "${p.template}" wins by route order`,{template:s.template,path:l}))}}}for(let[i,o]of Object.entries(e.staticAssets??{})){let s=r.get(i);if(!s||s.content===o)continue;t.push(AK("warning","static-asset-collision",`Site-package static asset "${i}" overrides template "${s.template}"`,{template:s.template,path:i}))}return{diagnostics:t,errors:t.filter(({severity:i})=>i==="error"),warnings:t.filter(({severity:i})=>i==="warning")}}function Mxe(e){return`[${e.code}] ${e.message}`}var xaa=E(()=>{Oot()});import{promises as yaa}from"fs";function baa(e,t){return Object.keys(e).some((n)=>n.replace(/^\/+/,"")===t)}async function vaa(e){e.signal.throwIfAborted();let t=e.siteUrl??e.preparedBuild.site.url??"https://example.com";if(!baa(e.preparedBuild.staticAssets,"robots.txt")){let n=zzn(t,e.preparedBuild.environment);await yaa.writeFile(vK(e.outputDir,"robots.txt"),n,{encoding:"utf8",signal:e.signal}),e.signal.throwIfAborted()}if(!baa(e.preparedBuild.staticAssets,"sitemap.xml")){let n=qzn(e.preparedBuild.routes,t,e.preparedBuild.preparedAt);await yaa.writeFile(vK(e.outputDir,"sitemap.xml"),n,{encoding:"utf8",signal:e.signal}),e.signal.throwIfAborted()}e.logger.info(`Generated staged SEO files with ${e.preparedBuild.routes.length} URLs`)}var Aaa=E(()=>{J8();Oot()});import{createHash as gjd}from"crypto";import{createReadStream as xjd,promises as oEr}from"fs";import{dirname as yjd,join as bjd,relative as vjd,sep as Ajd}from"path";async function waa(e){let t=e.preparedBuild.routes.map((p)=>({routeId:p.id,urlPath:p.path,outputFile:wjd(p.path)})),n=new Set(t.map((p)=>p.outputFile)),r=Object.keys(e.preparedBuild.staticAssets).map(Ejd).sort(),i=Object.keys(e.preparedBuild.publicAssets).sort(),o=new Set(r),s=await Eaa(e.generationDir),a=new Set(s.map((p)=>p.path));for(let p of t)if(!a.has(p.outputFile))throw Error(`Expected route artifact is missing: ${p.routeId} (${p.outputFile})`);if(!a.has("styles/main.css"))throw Error("Expected CSS artifact is missing: styles/main.css");for(let p of["robots.txt","sitemap.xml"])if(!a.has(p))throw Error(`Expected SEO artifact is missing: ${p}`);for(let p of r)if(!a.has(p))throw Error(`Expected static asset is missing: ${p}`);for(let p of i)if(!a.has(p))throw Error(`Expected public asset is missing: ${p}`);let c=s.map((p)=>({...p,kind:Sjd(p.path,n,o)})),l=Bme.parse({version:1,buildId:e.preparedBuild.buildId,environment:e.preparedBuild.environment,...e.inputFingerprint&&{inputFingerprint:e.inputFingerprint},routes:t,files:c,images:e.preparedBuild.images,staticAssets:r,publicAssets:i,scripts:{global:e.preparedBuild.globalHeadScripts,byRoute:Object.fromEntries(e.preparedBuild.routes.map((p)=>[p.id,p.headScripts]))},warnings:e.warnings}),d=vK(e.generationDir,gT);return await oEr.mkdir(yjd(d),{recursive:!0}),await oEr.writeFile(d,`${JSON.stringify(l,null,2)}
|
|
12588
|
+
<link rel="alternate" hreflang="${br(i)}" href="${br(r+o)}">`).join("")}function KFd(e,t){if(!t)return e;return{...e,...t.title!==void 0&&{title:t.title},...t.description!==void 0&&{description:t.description},...t.copyright!==void 0&&{copyright:t.copyright},...t.cta!==void 0&&{cta:t.cta}}}var Kwr=E(()=>{Oo();or();Su();cc();J8();Isa();Oot()});var Osa,QFd,JFd,FRg;var Msa=E(()=>{Su();oe();Osa=u.object({environment:u.enum(["preview","production"]),outputDir:u.string(),workingDir:u.string().optional(),sharedImagesDir:u.string().default("./dist/images"),enableContentGeneration:u.boolean().default(!1),cleanBeforeBuild:u.boolean().default(!0),siteConfig:PT,layouts:u.record(u.string(),u.custom()),themeCSS:u.string().optional(),languages:u.array(YE).min(1).optional(),layoutCopy:Bce.optional()}),QFd=u.enum(["build-failed","build-cancelled","output-commit-failed","unsafe-route-path","missing-layout","missing-template","missing-web-renderer","unsafe-static-asset-path","static-asset-collision","public-asset-snapshot-failed","section-content-resolution-failed","invalid-section-content","missing-site-url","staged-artifact-failed"]),JFd=u.object({severity:u.enum(["warning","error"]),code:QFd,message:u.string(),routeId:u.string().optional(),sectionId:u.string().optional(),template:u.string().optional(),path:u.string().optional()}),FRg=u.object({success:u.boolean(),cancelled:u.boolean().optional(),superseded:u.boolean().optional(),skipped:u.boolean().optional(),outputDir:u.string(),filesGenerated:u.number(),routesBuilt:u.number(),errors:u.array(u.string()).optional(),warnings:u.array(u.string()).optional(),diagnostics:u.array(JFd).optional()})});function Fot(e,t){let n=t.toLowerCase();return Object.entries(e??{}).find(([r])=>r.toLowerCase()===n)?.[1]}function Fsa(e,t=[]){return{list:()=>{let n=e.list(),r=new Set(n.map((i)=>i.path));return[...n,...t.filter((i)=>!r.has(i.path))]},getNavigationItems:(n)=>e.getNavigationItems(n)}}async function jsa(e,t){let n=e.list(),r=n.length===0?["No routes registered for site build"]:[],[i=YFd,...o]=t.languages??[],s=o.filter((p)=>Fot(t.siteTranslations,p)!==void 0),a=n.filter((p)=>XFd(p)||p.languages!==void 0),c=await Promise.all(s.map(async(p)=>({language:p,byRouteId:new Map((await Promise.all(a.map(async(f)=>{let m=await ejd(f,p,i,t.hasSavedCopy);return m?[f.id,m]:null}))).filter((f)=>f!==null))}))),l=(p)=>[{language:i,path:p.path},...c.flatMap(({language:f,byRouteId:m})=>{let h=m.get(p.id);return h?[{language:f,path:h.path}]:[]})],d=({language:p,byRouteId:f})=>{let m=new Map(n.flatMap((g)=>{let x=f.get(g.id),y=Fot(g.translations,p);return x?[[g.path,{href:x.path,label:y?.navigationLabel??y?.title}]]:[]})),h=(g)=>g.flatMap((x)=>{let y=m.get(x.href);return y?[{...x,href:y.href,label:y.label??x.label}]:[]});return{primary:h(e.getNavigationItems("primary")),secondary:h(e.getNavigationItems("secondary"))}};return{routes:[...n.map((p)=>({...p,language:i,alternates:l(p)})),...c.flatMap((p)=>{let f=d(p),m=Fot(t.siteTranslations,p.language);return n.flatMap((h)=>{let g=p.byRouteId.get(h.id);return g?[{...g,alternates:l(h),siteNavigation:f,siteTranslation:m}]:[]})})],warnings:r}}function XFd(e){return e.sections.length>0&&e.sections.every((t)=>t.template!==""&&t.dataQuery===void 0)}async function ejd(e,t,n,r){let i=`${t.toLowerCase()}:${e.id}`,o=Fot(e.translations,t);if(e.languages!==void 0)return e.languages.some((a)=>a.toLowerCase()===t.toLowerCase())?{...e,id:i,title:o?.title??"",description:o?.description??"",path:c7e(t,n,e.path),language:t}:void 0;if(!(await Promise.all(e.sections.map((a)=>r(`${i}:${a.id}`)))).every(Boolean))return;return{...e,id:i,title:o?.title??"",description:o?.description??"",path:c7e(t,n,e.path),language:t,sections:e.sections.map(({content:a,...c})=>c)}}var YFd="en";var Nsa=E(()=>{Su()});function Lsa(e){let t=[...new Set(e.definitions.flatMap((r)=>r.sections).map((r)=>r.template))],n=Object.fromEntries(t.flatMap((r)=>{let i=e.pipelineContext.services.getViewTemplate(r);return i?[[r,i]]:[]}));return{preparedBuild:e.envelope,routes:e.routes,viewTemplates:n,layouts:e.layouts,...e.slots&&{slots:e.slots}}}async function zsa(e){e.signal.throwIfAborted();let t=e.staticSiteBuilderFactory({logger:e.logger.child("StaticSiteBuilder"),workingDir:e.workingDir,outputDir:e.outputDir});if(e.cleanBeforeBuild)await t.clean();return e.signal.throwIfAborted(),t}async function qsa(e){await new P9t({logger:e.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:e.pipelineContext.services.entityService,listViewTemplateNames:()=>e.pipelineContext.services.listViewTemplateNames()},e.pipelineContext.routeRegistry,e.pipelineContext.entityDisplay,{visibilityScope:"public",...e.publishedOnly!==void 0&&{publishedOnly:e.publishedOnly}}).generateEntityRoutes()}var Usa=E(()=>{J8()});function $sa(e,t,n){let r=t.getProfile(),i=n.getNavigationItems("primary"),o=n.getNavigationItems("secondary");return{...e,represents:e.represents??"anchor",...e.represents!=="brain"&&r.socialLinks!==void 0&&{socialLinks:r.socialLinks},...e.represents!=="brain"&&r.photo!==void 0&&{photo:r.photo},navigation:{primary:i,secondary:o},copyright:e.copyright??"Powered by Rizom"}}async function Zsa(e,t){return Qwr(e,t,new MT(t.pipelineContext.entityDisplay))}async function Qwr(e,t,n){if(e===null||e===void 0)return e;if(Array.isArray(e))return Promise.all(e.map((S)=>Qwr(S,t,n)));if(typeof e!=="object")return e;let r={},i=Object.entries(e),o=await Promise.all(i.map(([,S])=>Qwr(S,t,n)));for(let S=0;S<i.length;S++){let k=i[S];if(k)r[k[0]]=o[S]}let s=tjd.safeParse(e);if(!s.success)return r;let a=s.data,c=a.entityType,l=a.metadata.slug,d=t.pipelineContext.entityDisplay?.[c],p=d?d.label:c.charAt(0).toUpperCase()+c.slice(1),f=d?d.pluralName??d.label.toLowerCase()+"s":t3(c),m=`/${f}`,h=f.charAt(0).toUpperCase()+f.slice(1),g=pEt(a),x=await rjd(g,t),y=fEt(a)??g,v=await ijd(y,t);return{...r,...a,url:n.generateUrl(c,l),typeLabel:p,listUrl:m,listLabel:h,...x,...v&&{ogImageUrl:v}}}async function rjd(e,t){let n=e?t.imageBuildService?.get(e):void 0;if(n)return{coverImageUrl:n.src,coverImageWidth:n.width,coverImageHeight:n.height,...n.alt&&{coverImageAlt:n.alt},...n.srcset&&{coverImageSrcset:n.srcset,coverImageSizes:n.sizes}};let r=await Wsa(e,t.pipelineContext.services.entityService);if(!r)return{};return{coverImageUrl:r.url,...r.width&&{coverImageWidth:r.width},...r.height&&{coverImageHeight:r.height},...r.alt&&{coverImageAlt:r.alt}}}async function ijd(e,t){if(!e)return;let n=t.imageBuildService?.get(e);if(n)return Hsa(n.src,t.siteUrl);let r=await Wsa(e,t.pipelineContext.services.entityService);if(!r)return;if(r.url.startsWith("data:"))return;return Hsa(r.url,t.siteUrl)}function Hsa(e,t){if(/^https?:\/\//i.test(e)||e.startsWith("data:"))return e;if(!t)return e;return`${t.replace(/\/$/,"")}/${e.replace(/^\//,"")}`}async function Wsa(e,t){if(!e)return;let n=await t.getEntity({entityType:"image",id:e}),r=njd.safeParse(n);if(!r.success)return;let i=await dEt(t,r.data);if(!i)return;let o=Fze(r.data.metadata);return{url:i,...o&&{alt:o},...r.data.metadata.width&&{width:r.data.metadata.width},...r.data.metadata.height&&{height:r.data.metadata.height}}}async function Vsa(e,t){let n=new Set;try{let r=e.getEntityTypes();for(let i of r){if(i==="image")continue;await Qsa(e,i,(o)=>o.forEach((s)=>{let a=pEt(s);if(a)n.add(a);let c=fEt(s);if(c)n.add(c);if(s.content.includes("entity://image/"))mEt(s.content,(l)=>{let d=/^entity:\/\/image\/(.+)$/.exec(l);if(d?.[1])n.add(d[1]);return l})}))}}catch(r){t.warn("Failed to collect image IDs for pre-resolution",{error:Re(r)})}return[...n]}function Jwr(e){if(typeof e==="string")return[e];if(Array.isArray(e))return e.flatMap(Jwr);if(e!==null&&typeof e==="object")return Object.values(e).flatMap(Jwr);return[]}function ojd(e){if(!e.includes("entity://image/"))return[];let t=[];return mEt(e,(n)=>{let r=/^entity:\/\/image\/(.+)$/.exec(n);if(r?.[1])t.push(r[1]);return n}),t}function Ksa(e){return[...new Set(e.flatMap((t)=>t.sections??[]).flatMap((t)=>Jwr(t.content)).flatMap(ojd))]}async function Qsa(e,t,n,r=0){let i=await e.listEntities({entityType:t,options:{limit:Gsa,offset:r,sortFields:[{field:"id",direction:"asc"}],source:!0}});if(n(i),i.length<Gsa)return;await Qsa(e,t,n,r+i.length)}var tjd,njd,Gsa=1000;var Ywr=E(()=>{Pf();Su();or();oe();tjd=u.looseObject({id:u.string(),entityType:u.string(),content:u.string(),metadata:u.looseObject({slug:u.string()})}),njd=u.looseObject({content:u.string(),metadata:u.looseObject({width:u.number().optional(),height:u.number().optional()})})});async function Xwr(e,t,n,r,i){if(!e.template)return e.content??null;let o=e.template,s={entityType:"site-content",entityId:`${t.id}:${e.id}`},{services:a}=i.pipelineContext,c=await a.isCopyStarted(s.entityId)?void 0:e.content,l=e.dataQuery?{dataParams:e.dataQuery,savedContent:s,fallback:c,publishedOnly:n,visibilityScope:r}:{savedContent:s,fallback:c,visibilityScope:r},d=await a.resolveTemplateContent(o,l);if(!d){if(c===void 0&&e.dataQuery===void 0&&await a.hasSavedContent(s.entityId))throw Error(`The saved text ${s.entityId} does not fit its section`);return null}let p=Zte(d);return Zsa(p,{pipelineContext:i.pipelineContext,imageBuildService:i.imageBuildService,siteUrl:i.siteUrl})}var Jsa=E(()=>{J8();Ywr()});function eEr(e,t,n){return i3.parse({id:e,path:`/${e}`,title:"Layout",description:"The words of the site's menu and footer",navigation:{show:!1},sections:[{id:sjd,template:t,content:n}]})}function tEr(e){return e?[eEr(iZt,e.template,e.content)]:[]}function oZt(e,t){if(!e)return[];let[,...n]=t??[];return[...tEr(e),...n.flatMap((r)=>{let i=Object.entries(e.translations??{}).find(([o])=>o.toLowerCase()===r.toLowerCase())?.[1];return i?[eEr(`${r.toLowerCase()}:${iZt}`,e.template,i)]:[]})]}function Ysa(e,t,n){let i=(t?.[0]??n).toLowerCase()===n.toLowerCase()?iZt:`${n.toLowerCase()}:${iZt}`;return oZt(e,t).find((s)=>s.id===i)??(e?eEr(i,e.template,void 0):void 0)}var iZt="layout",sjd="copy";var nEr=E(()=>{Su()});import{randomUUID as ajd}from"crypto";function eaa(e){return _o(sZt(e))}function taa(e){let{buildId:t,preparedAt:n,...r}=e.envelope,i=[...new Set(e.templates)].sort();return _o(sZt({version:4,rendererIdentity:e.rendererIdentity,preparedInput:{...r,routes:e.routeDigests},layouts:Object.fromEntries(Object.entries(e.layouts).sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>[o,String(s)])),rendererRuntime:{staticSiteBuilderFactory:String(e.staticSiteBuilderFactory),stagingMessageSender:String(e.command)},templates:Object.fromEntries(i.map((o)=>{let s=e.getViewTemplate(o);return[o,s?{renderer:String(s.renderers.web),fullscreen:s.fullscreen??!1,runtimeScripts:s.runtimeScripts??[],staticAssets:s.staticAssets??{}}:null]}))}))}function sZt(e,t=new Set){if(e===null)return"null";if(typeof e==="string"||typeof e==="boolean")return JSON.stringify(e);if(typeof e==="number"){if(!Number.isFinite(e))throw Error("Cannot fingerprint non-finite number");return JSON.stringify(e)}if(typeof e==="function")return JSON.stringify(String(e));if(typeof e!=="object")throw Error(`Cannot fingerprint ${typeof e} value`);if(t.has(e))throw Error("Cannot fingerprint circular site inputs");let n=new Set(t).add(e);if(Array.isArray(e))return`[${e.map((r)=>sZt(r,n)).join(",")}]`;if(!Cr(e))throw Error("Cannot fingerprint non-plain site input objects");return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>`${JSON.stringify(r)}:${sZt(i,n)}`).join(",")}}`}var Xsa;var rEr=E(()=>{Oo();Xc();Xsa=ajd()});import{promises as aZt}from"fs";import{join as cjd,relative as ljd,sep as ujd}from"path";async function naa(e,t,n=djd){t.throwIfAborted();try{await aZt.access(e)}catch(i){if(bx(i))return{};throw i}let r={};return await raa(e,e,r,t,{totalBytes:0,maxTotalBytes:n}),r}async function raa(e,t,n,r,i){r.throwIfAborted();let o=await aZt.readdir(t,{withFileTypes:!0});o.sort((s,a)=>s.name.localeCompare(a.name));for(let s of o){r.throwIfAborted();let a=cjd(t,s.name),c=ljd(e,a).split(ujd).join("/");if(s.isSymbolicLink())throw Error(`Public asset cannot be a symbolic link: ${c}`);if(s.isDirectory()){await raa(e,a,n,r,i);continue}if(!s.isFile())continue;let{size:l}=await aZt.stat(a);if(i.totalBytes+=l,i.totalBytes>i.maxTotalBytes)throw Error(`App public assets exceed the ${i.maxTotalBytes} byte snapshot budget at "${c}". Large files belong in the shared image cache or behind a CDN rather than in public/.`);n[c]=(await aZt.readFile(a)).toString("base64")}}var djd=67108864;var iaa=E(()=>{Xc()});async function aaa(e){e.signal.throwIfAborted();let t=(x)=>e.pipelineContext.services.getViewTemplate(x),n=e.parsedOptions.environment==="production",r=[],i={};try{i=await naa(e.publicDir,e.signal)}catch(x){e.signal.throwIfAborted();let y={severity:"error",code:"public-asset-snapshot-failed",message:`Failed to snapshot app public assets: ${Re(x)}`,path:e.publicDir};e.pipelineContext.logger.error(y.message,{error:x}),r.push(y)}let o=Ezn({...Lzn(e.routes,{getViewTemplate:t}),...e.buildOptions.staticAssets},Object.keys(i)),s=$sa(e.siteMetadata,e.pipelineContext.profileService,e.pipelineContext.routeRegistry),a=new Set(Object.keys(i));for(let x of Object.keys(o)){let y=x.startsWith("/")?x.slice(1):x;if(!a.has(y))continue;r.push({severity:"warning",code:"static-asset-collision",message:`Static asset "${x}" overrides app public asset "${y}"`,path:x})}e.signal.throwIfAborted();let c=Ozn({buildId:e.buildId,preparedAt:e.preparedAt,environment:e.parsedOptions.environment,site:s,...e.parsedOptions.themeCSS!==void 0&&{themeCSS:e.parsedOptions.themeCSS},images:e.imageBuildService.getMap(),links:Tzn(e.routes),staticAssets:o,publicAssets:i,globalHeadScripts:e.buildOptions.headScripts??[],...e.siteUrl!==void 0&&{siteUrl:e.siteUrl}}),l=[],d=[],p=[],f=new Set,m=new Map,h=(x)=>{let y=x.toLowerCase(),v=m.get(y);if(v)return v;let w=Ysa(e.parsedOptions.layoutCopy,e.parsedOptions.languages,x),S=w?.sections[0],k=w&&S?Xwr(S,w,n,"public",{pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteMetadata.url}).then((C)=>C?qh.parse(C):void 0):Promise.resolve(void 0);return m.set(y,k),k},g={count:e.routes.length,each:(x,y)=>jzn(e.routes.map((v,w)=>({route:v,index:w})),async({route:v,index:w})=>{let S=await pjd({route:v,siteTitle:e.siteMetadata.title,publishedOnly:n,getViewTemplate:t,staticAssets:o,pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteMetadata.url,layoutCopyOf:h,signal:y});if(p[w]=S.diagnostics,S.diagnostics.some(({severity:C})=>C==="error"))return;let k=Fzn(S.route);l[w]={id:k.id,path:k.path,headScripts:k.headScripts},d[w]=eaa(k);for(let C of k.sections)f.add(C.template);await x(k)},y)};return{envelope:c,diagnostics:r,routes:g,pages:()=>({routes:l.filter((x)=>x!==void 0),digests:d.filter((x)=>x!==void 0),templates:[...f].sort(),diagnostics:p.flat()})}}async function pjd(e){e.signal.throwIfAborted();let t=[],n=[];for(let i of e.route.sections){if(e.signal.throwIfAborted(),i.template==="footer")continue;let o=await fjd(e,i);if(o.section)n.push(o.section);if(o.diagnostic)t.push(o.diagnostic)}let r;try{r=await e.layoutCopyOf(e.route.language)}catch(i){e.signal.throwIfAborted(),t.push({severity:"error",code:"section-content-resolution-failed",message:`Failed to resolve the layout's words in ${e.route.language}: ${Re(i)}`,routeId:e.route.id})}return{route:{id:e.route.id,path:e.route.path,language:e.route.language,alternates:e.route.alternates,...e.route.siteNavigation!==void 0&&{siteNavigation:e.route.siteNavigation},...e.route.siteTranslation!==void 0&&{siteTranslation:e.route.siteTranslation},title:e.route.title,...e.route.pageLabel!==void 0&&{pageLabel:e.route.pageLabel},description:e.route.description,layout:e.route.layout,...r!==void 0&&{layoutCopy:r},fullscreen:e.route.sections.some((i)=>e.getViewTemplate(i.template)?.fullscreen===!0),sections:n,headScripts:Nzn(e.route,{getViewTemplate:e.getViewTemplate},e.staticAssets)},diagnostics:t}}async function fjd(e,t){e.signal.throwIfAborted();let n=e.getViewTemplate(t.template),r=n?.renderers.web;if(!n||!r||typeof r!=="function")return{};let i;try{i=await Xwr(t,e.route,e.publishedOnly,"public",{pipelineContext:e.pipelineContext,imageBuildService:e.imageBuildService,siteUrl:e.siteUrl}),e.signal.throwIfAborted()}catch(o){e.signal.throwIfAborted();let s=saa(o),a={severity:"error",code:"section-content-resolution-failed",message:`Failed to resolve content for route "${e.route.id}" section "${t.id}": ${s.summary}`,routeId:e.route.id,sectionId:t.id,template:t.template};return e.pipelineContext.logger.error("Failed to resolve site section content",{routeId:e.route.id,sectionId:t.id,template:t.template,...s.issues?{issues:s.issues}:{},...!s.issues?{error:s.summary}:{}}),{diagnostic:a}}if(!i)return{};e.signal.throwIfAborted();try{let o=oaa.parse(i),s=n.schema.parse({...o,pageTitle:e.route.title||e.siteTitle,...e.route.pageLabel!==void 0&&{pageLabel:e.route.pageLabel}}),a=Zte(s),c=oaa.parse(a);return{section:{id:t.id,template:t.template,data:qh.parse(c)}}}catch(o){let s=saa(o),a={severity:"warning",code:"invalid-section-content",message:`Route "${e.route.id}" section "${t.id}" has invalid content for template "${t.template}": ${s.summary}`,routeId:e.route.id,sectionId:t.id,template:t.template};return e.pipelineContext.logger.error("Invalid site section content",{routeId:e.route.id,sectionId:t.id,template:t.template,...s.issues?{issues:s.issues}:{},...!s.issues?{error:s.summary}:{}}),{diagnostic:a}}}function saa(e){if(!(e instanceof u.ZodError))return{summary:Re(e)};let t=e.issues.map((n)=>({code:n.code,path:n.path.map(String).join("."),message:n.message}));return{summary:t.map((n)=>`${n.path||"<root>"}: ${n.message}`).join("; "),issues:t}}var oaa;var caa=E(()=>{J8();oe();Jsa();nEr();rEr();iaa();oaa=u.record(u.string(),u.unknown())});async function laa(e){e.signal.throwIfAborted();let t=new R9t(e.pipelineContext.services.entityService,e.pipelineContext.logger,e.sharedImagesDir),n=[...new Set([...await Vsa(e.pipelineContext.services.entityService,e.pipelineContext.logger),...Ksa(e.routes)])];if(e.signal.throwIfAborted(),n.length>0)await t.resolveAll(n,e.signal);return e.signal.throwIfAborted(),t}var uaa=E(()=>{J8();Ywr()});async function daa(e){let t=e.reporter?.createSub({scale:{start:85,end:95}});e.signal.throwIfAborted(),await e.staticSiteBuilder.build(e.buildContext,(n)=>{t?.report(n).catch(()=>{})},e.signal),e.signal.throwIfAborted()}function mjd(e,t){let n=t.replace(/\/+$/u,""),r=(i)=>i.startsWith("/")&&!i.startsWith("//")?`${n}${i}`:i;return e.replace(/\b(href|src)="([^"]*)"/gu,(i,o,s)=>`${o}="${r(s)}"`).replace(/\bsrcset="([^"]*)"/gu,(i,o)=>`srcset="${o.split(",").map((a)=>{let[c="",...l]=a.trim().split(/\s+/u);return[r(c),...l].join(" ")}).join(", ")}"`)}function paa(e){let t=uQe(e.links),n=Tme(e.images);return(r)=>mjd(R2(r,{imageRenderer:n,wikiLinkResolver:t}),e.siteUrl)}var faa=E(()=>{J8();cc()});function iEr(e){return{success:!0,outputDir:e.outputDir,filesGenerated:e.filesGenerated,routesBuilt:e.routesBuilt,...e.skipped&&{skipped:!0},...e.warnings.length>0&&{warnings:e.warnings},...e.diagnostics&&e.diagnostics.length>0&&{diagnostics:e.diagnostics}}}function maa(e){return{success:!1,cancelled:!0,outputDir:e.outputDir,filesGenerated:0,routesBuilt:0,errors:[e.message],diagnostics:e.diagnostics}}function jot(e){return{success:!1,outputDir:e.outputDir,filesGenerated:0,routesBuilt:0,errors:e.errorMessages,...e.diagnostics&&e.diagnostics.length>0&&{diagnostics:e.diagnostics}}}function AK(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function haa(e,t){if(!e)return[];let n=[];for(let r of Object.keys(e)){let i=rZt(r,"asset");if(!i)continue;n.push(AK("error","unsafe-static-asset-path",`Static asset path "${r}" is unsafe: ${i}`,{...t,path:r}))}return n}function hjd(e,t){if(e!==void 0&&e.trim().length>0)return[];return[t==="production"?AK("error","missing-site-url","Production build has no configured site URL; staged sitemap, robots, and feed links would be published against a placeholder domain"):AK("warning","missing-site-url","Preview build has no configured site URL; staged sitemap, robots, and feed links fall back to a placeholder domain")]}function gaa(e){let t=haa(e.staticAssets,{});t.push(...hjd(e.siteUrl,e.environment));let n=new Set,r=new Map;for(let i of e.routes){let o=rZt(i.path,"route");if(o)t.push(AK("error","unsafe-route-path",`Route "${i.id}" path "${i.path}" is unsafe: ${o}`,{routeId:i.id,path:i.path}));if(typeof e.layouts[i.layout]!=="function")t.push(AK("error","missing-layout",`Route "${i.id}" references missing layout "${i.layout}"`,{routeId:i.id,path:i.path}));for(let s of i.sections){let a=e.getViewTemplate(s.template),c={routeId:i.id,sectionId:s.id,template:s.template,path:i.path};if(!a){t.push(AK("warning","missing-template",`Route "${i.id}" section "${s.id}" references missing template "${s.template}"`,c));continue}if(!a.renderers.web||typeof a.renderers.web!=="function")t.push(AK("warning","missing-web-renderer",`Template "${s.template}" has no callable web renderer`,c));if(n.has(s.template))continue;n.add(s.template),t.push(...haa(a.staticAssets,{template:s.template}));for(let[l,d]of Object.entries(a.staticAssets??{})){let p=r.get(l);if(!p){r.set(l,{template:s.template,content:d});continue}if(p.content===d)continue;t.push(AK("warning","static-asset-collision",`Static asset path "${l}" is declared by templates "${p.template}" and "${s.template}"; "${p.template}" wins by route order`,{template:s.template,path:l}))}}}for(let[i,o]of Object.entries(e.staticAssets??{})){let s=r.get(i);if(!s||s.content===o)continue;t.push(AK("warning","static-asset-collision",`Site-package static asset "${i}" overrides template "${s.template}"`,{template:s.template,path:i}))}return{diagnostics:t,errors:t.filter(({severity:i})=>i==="error"),warnings:t.filter(({severity:i})=>i==="warning")}}function Mxe(e){return`[${e.code}] ${e.message}`}var xaa=E(()=>{Oot()});import{promises as yaa}from"fs";function baa(e,t){return Object.keys(e).some((n)=>n.replace(/^\/+/,"")===t)}async function vaa(e){e.signal.throwIfAborted();let t=e.siteUrl??e.preparedBuild.site.url??"https://example.com";if(!baa(e.preparedBuild.staticAssets,"robots.txt")){let n=zzn(t,e.preparedBuild.environment);await yaa.writeFile(vK(e.outputDir,"robots.txt"),n,{encoding:"utf8",signal:e.signal}),e.signal.throwIfAborted()}if(!baa(e.preparedBuild.staticAssets,"sitemap.xml")){let n=qzn(e.preparedBuild.routes,t,e.preparedBuild.preparedAt);await yaa.writeFile(vK(e.outputDir,"sitemap.xml"),n,{encoding:"utf8",signal:e.signal}),e.signal.throwIfAborted()}e.logger.info(`Generated staged SEO files with ${e.preparedBuild.routes.length} URLs`)}var Aaa=E(()=>{J8();Oot()});import{createHash as gjd}from"crypto";import{createReadStream as xjd,promises as oEr}from"fs";import{dirname as yjd,join as bjd,relative as vjd,sep as Ajd}from"path";async function waa(e){let t=e.preparedBuild.routes.map((p)=>({routeId:p.id,urlPath:p.path,outputFile:wjd(p.path)})),n=new Set(t.map((p)=>p.outputFile)),r=Object.keys(e.preparedBuild.staticAssets).map(Ejd).sort(),i=Object.keys(e.preparedBuild.publicAssets).sort(),o=new Set(r),s=await Eaa(e.generationDir),a=new Set(s.map((p)=>p.path));for(let p of t)if(!a.has(p.outputFile))throw Error(`Expected route artifact is missing: ${p.routeId} (${p.outputFile})`);if(!a.has("styles/main.css"))throw Error("Expected CSS artifact is missing: styles/main.css");for(let p of["robots.txt","sitemap.xml"])if(!a.has(p))throw Error(`Expected SEO artifact is missing: ${p}`);for(let p of r)if(!a.has(p))throw Error(`Expected static asset is missing: ${p}`);for(let p of i)if(!a.has(p))throw Error(`Expected public asset is missing: ${p}`);let c=s.map((p)=>({...p,kind:Sjd(p.path,n,o)})),l=Bme.parse({version:1,buildId:e.preparedBuild.buildId,environment:e.preparedBuild.environment,...e.inputFingerprint&&{inputFingerprint:e.inputFingerprint},routes:t,files:c,images:e.preparedBuild.images,staticAssets:r,publicAssets:i,scripts:{global:e.preparedBuild.globalHeadScripts,byRoute:Object.fromEntries(e.preparedBuild.routes.map((p)=>[p.id,p.headScripts]))},warnings:e.warnings}),d=vK(e.generationDir,gT);return await oEr.mkdir(yjd(d),{recursive:!0}),await oEr.writeFile(d,`${JSON.stringify(l,null,2)}
|
|
12589
12589
|
`,"utf8"),l}function wjd(e){if(e==="/")return"index.html";return`${e.slice(1).replace(/\/$/,"")}/index.html`}function Ejd(e){return e.startsWith("/")?e.slice(1):e}function Sjd(e,t,n){if(n.has(e))return"static";if(t.has(e))return"route";if(e==="styles/main.css")return"css";if(e==="robots.txt"||e==="sitemap.xml"||e==="feed.xml")return"seo";return"public"}async function Eaa(e,t=e){let n=await oEr.readdir(t,{withFileTypes:!0});n.sort((i,o)=>i.name.localeCompare(o.name));let r=[];for(let i of n){let o=bjd(t,i.name);if(i.isSymbolicLink())throw Error(`Artifact generation contains an unsupported symbolic link: ${i.name}`);if(i.isDirectory()){r.push(...await Eaa(e,o));continue}if(!i.isFile())continue;let s=vjd(e,o).split(Ajd).join("/");if(s===gT)continue;r.push({path:s,...await kjd(o)})}return r}async function kjd(e){let t=gjd("sha256");return{size:await Array.fromAsync(xjd(e),(r)=>(t.update(r),r.byteLength)).then((r)=>r.reduce((i,o)=>i+o,0)),sha256:t.digest("hex")}}var sEr=E(()=>{J8();lt();Oot();lt()});import{promises as Pq}from"fs";import{basename as Cjd,dirname as cZt,join as jP,relative as Ijd,resolve as Oq}from"path";class cEr{logger;retainedGenerations;staleGenerationAgeMs;fs;constructor(e,t=3,n=86400000,r=_jd){this.logger=e.child("SiteBuildOutput"),this.retainedGenerations=Math.max(1,t),this.staleGenerationAgeMs=Math.max(0,n),this.fs=r}async getCurrentManifest(e){try{let t=await this.fs.readFile(jP(Oq(e),gT),"utf8");return Bme.parse(JSON.parse(t))}catch(t){if(bx(t))return null;return this.logger.warn("Ignoring unreadable active site build manifest",{error:t}),null}}async begin(e){Mjd(e.buildId);let t=Oq(e.outputDir),n=jP(cZt(t),".site-builds",e.environment),r=jP(n,e.buildId),i=e.configuredWorkingDir?`${Oq(e.configuredWorkingDir)}-${e.buildId}`:jP(cZt(t),".site-build-work",e.environment,e.buildId);await this.fs.mkdir(n,{recursive:!0});let o=await Djd(this.fs,n,r,this.staleGenerationAgeMs);if(o>0)this.logger.debug(`Removed ${o} stale uncommitted site generation(s)`);return await this.fs.rm(r,{recursive:!0,force:!0}),await this.fs.rm(i,{recursive:!0,force:!0}),await this.fs.mkdir(r,{recursive:!0}),{activeOutputDir:t,generationDir:r,workingDir:i,environmentDir:n,buildId:e.buildId}}async commit(e){let t=await waa({generationDir:e.target.generationDir,preparedBuild:e.preparedBuild,inputFingerprint:e.inputFingerprint,warnings:e.warnings});await Tjd(this.fs,e.target);try{await this.fs.rm(e.target.workingDir,{recursive:!0,force:!0}),await Ojd(this.fs,e.target.environmentDir,e.target.generationDir,this.retainedGenerations)}catch(n){this.logger.warn("Published site but failed to clean old build data",{error:n})}return{filesGenerated:t.files.length+1,manifestPath:jP(e.target.activeOutputDir,gT),manifest:t}}async abort(e){await Promise.allSettled([this.fs.rm(e.generationDir,{recursive:!0,force:!0}),this.fs.rm(e.workingDir,{recursive:!0,force:!0})])}}async function Tjd(e,t){let n=cZt(t.activeOutputDir);await e.mkdir(n,{recursive:!0});let r=jP(n,`.${Cjd(t.activeOutputDir)}.next-${t.buildId}`);await e.rm(r,{force:!0}),await e.symlink(Ijd(n,t.generationDir),r,"dir");let i=await Rjd(e,t.activeOutputDir);if(!i)try{await e.rename(r,t.activeOutputDir),await aEr(e,t);return}catch(s){throw await e.rm(r,{force:!0}),await e.rm(t.activeOutputDir,{force:!0}),s}if(i.isSymbolicLink()){let s=await e.readlink(t.activeOutputDir);try{await e.rename(r,t.activeOutputDir),await aEr(e,t);return}catch(a){throw await Bjd(e,t.activeOutputDir,s),await e.rm(r,{force:!0}),a}}let o=jP(t.environmentDir,`.migrating-${t.buildId}`);await e.rm(o,{recursive:!0,force:!0}),await e.rename(t.activeOutputDir,o);try{await e.rename(r,t.activeOutputDir),await aEr(e,t)}catch(s){throw await e.rm(t.activeOutputDir,{recursive:!0,force:!0}),await e.rename(o,t.activeOutputDir),await e.rm(r,{force:!0}),s}await e.rm(o,{recursive:!0,force:!0})}async function Bjd(e,t,n){let r=`${t}.rollback`;await e.rm(r,{force:!0}),await e.symlink(n,r,"dir"),await e.rename(r,t)}async function aEr(e,t){let n=await e.readlink(t.activeOutputDir),r=Oq(cZt(t.activeOutputDir),n);if(r!==Oq(t.generationDir))throw Error(`Active site output points to unexpected generation: ${r}`);await e.access(jP(t.activeOutputDir,gT))}async function Rjd(e,t){try{return await e.lstat(t)}catch(n){if(bx(n))return;throw n}}async function Djd(e,t,n,r){let i=await e.readdir(t,{withFileTypes:!0}),o=Date.now(),s=[];for(let a of i){if(!a.isDirectory())continue;let c=jP(t,a.name);if(Oq(c)===Oq(n))continue;if(await Pjd(e,c))continue;let l=await e.stat(c);if(o-l.mtimeMs<r)continue;s.push(c)}return await Promise.all(s.map((a)=>e.rm(a,{recursive:!0,force:!0}))),s.length}async function Pjd(e,t){try{return await e.access(jP(t,gT)),!0}catch(n){if(bx(n))return!1;throw n}}async function Ojd(e,t,n,r){let i=await e.readdir(t,{withFileTypes:!0}),s=(await Promise.all(i.filter((c)=>c.isDirectory()).map(async(c)=>{let l=jP(t,c.name);try{await e.access(jP(l,gT));let d=await e.stat(l);return{path:l,modifiedAt:d.mtimeMs}}catch{return}}))).filter((c)=>c!==void 0);s.sort((c,l)=>l.modifiedAt-c.modifiedAt);let a=new Set([Oq(n)]);for(let c of s){if(a.size>=r)break;a.add(Oq(c.path))}await Promise.all(s.filter((c)=>!a.has(Oq(c.path))).map((c)=>e.rm(c.path,{recursive:!0,force:!0})))}function Mjd(e){if(!/^[A-Za-z0-9._-]+$/.test(e)||e==="."||e==="..")throw Error(`Unsafe site build id: ${e}`)}var _jd;var Saa=E(()=>{J8();Xc();sEr();_jd={mkdir:(e,t)=>Pq.mkdir(e,t),rm:(e,t)=>Pq.rm(e,t),readdir:(e,t)=>Pq.readdir(e,t),stat:(e)=>Pq.stat(e),access:(e)=>Pq.access(e),symlink:(e,t,n)=>Pq.symlink(e,t,n),rename:(e,t)=>Pq.rename(e,t),readlink:(e)=>Pq.readlink(e),lstat:(e)=>Pq.lstat(e),readFile:(e,t)=>Pq.readFile(e,t)}});import{randomUUID as Fjd}from"crypto";import{join as jjd}from"path";async function Caa(e){let t=Osa.parse(e.buildOptions),n=rD.from(e.progress),r=[],i=[],o=e.outputLifecycle??new cEr(e.pipelineContext.logger),s,a="build-failed",c=!1;try{e.signal.throwIfAborted(),await n?.report({message:"Starting site build",progress:0,total:100}),await n?.report({message:"Generating dynamic routes",progress:10,total:100}),e.signal.throwIfAborted(),await qsa({pipelineContext:e.pipelineContext,publishedOnly:t.environment==="production"}),e.signal.throwIfAborted();let l=await jsa(Fsa(e.pipelineContext.routeRegistry,e.buildOptions.pages),{languages:t.languages,siteTranslations:t.siteConfig.translations,hasSavedCopy:e.pipelineContext.services.hasSavedContent});r.push(...l.warnings);let{routes:d}=l,p=e.buildOptions.siteUrl??t.siteConfig.url,f=gaa({routes:d,layouts:t.layouts,getViewTemplate:e.pipelineContext.services.getViewTemplate,environment:t.environment,siteUrl:p,staticAssets:e.buildOptions.staticAssets});if(i.push(...f.diagnostics),r.push(...f.warnings.map(Mxe)),f.errors.length>0)return jot({outputDir:t.outputDir,errorMessages:f.errors.map(Mxe),diagnostics:i});await n?.report({message:`Preparing ${d.length} routes`,progress:20,total:100}),await n?.report({message:"Resolving images",progress:25,total:100});let m=await laa({pipelineContext:e.pipelineContext,routes:d,sharedImagesDir:t.sharedImagesDir,signal:e.signal}),h=await aaa({buildId:Fjd(),preparedAt:new Date().toISOString(),routes:d,parsedOptions:t,buildOptions:e.buildOptions,pipelineContext:e.pipelineContext,imageBuildService:m,siteMetadata:t.siteConfig,siteUrl:p,publicDir:jjd(process.cwd(),"public"),signal:e.signal}),{envelope:g}=h,x=kaa(h.diagnostics,i,r);if(x.length>0)return jot({outputDir:t.outputDir,errorMessages:x,diagnostics:i});e.signal.throwIfAborted();let y=Lsa({envelope:g,routes:h.routes,definitions:d,layouts:t.layouts,slots:e.buildOptions.slots,pipelineContext:e.pipelineContext});s=await o.begin({outputDir:t.outputDir,environment:t.environment,buildId:g.buildId,configuredWorkingDir:t.workingDir}),e.signal.throwIfAborted();let v=await zsa({logger:e.pipelineContext.logger,outputDir:s.generationDir,workingDir:s.workingDir,cleanBeforeBuild:t.cleanBeforeBuild,staticSiteBuilderFactory:e.staticSiteBuilderFactory,signal:e.signal});e.signal.throwIfAborted(),await n?.report({message:"Preparing site extension artifacts",progress:82,total:100});let w=[],S={outputDir:s.generationDir,environment:g.environment,routesBuilt:d.length,siteConfig:{...g.site,url:p},generateEntityUrl:(L,H)=>new MT(e.pipelineContext.entityDisplay).generateUrl(L,H),renderMarkdown:paa({links:g.links??{},images:g.images,siteUrl:p??""}),reportFailure:(L)=>{w.push(L)}};if(await e.pipelineContext.services.command(jse,S),e.signal.throwIfAborted(),w.length>0)throw a="staged-artifact-failed",Error(w.join("; "));await daa({staticSiteBuilder:v,buildContext:y,reporter:n,signal:e.signal});let k=h.pages(),C=kaa(k.diagnostics,i,r);if(C.length>0)return await lEr(o,s,e.pipelineContext.logger),s=void 0,jot({outputDir:t.outputDir,errorMessages:C,diagnostics:i});e.signal.throwIfAborted();let I=taa({envelope:g,routeDigests:k.digests,templates:k.templates,layouts:t.layouts,getViewTemplate:e.pipelineContext.services.getViewTemplate,staticSiteBuilderFactory:e.staticSiteBuilderFactory,command:e.pipelineContext.services.command,rendererIdentity:e.rendererIdentity??Xsa}),B=await o.getCurrentManifest?.(t.outputDir);if(e.signal.throwIfAborted(),!e.buildOptions.publishUnchanged&&B?.inputFingerprint===I)return await lEr(o,s,e.pipelineContext.logger),s=void 0,e.pipelineContext.logger.info("Skipping site publication because inputs are unchanged",{environment:t.environment,inputFingerprint:I}),await n?.report({message:"Site inputs unchanged",progress:100,total:100}),iEr({outputDir:t.outputDir,filesGenerated:B.files.length+1,routesBuilt:d.length,warnings:r,diagnostics:i,skipped:!0});let R={...g,routes:k.routes};await n?.report({message:"Generating SEO artifacts",progress:96,total:100}),await vaa({outputDir:s.generationDir,preparedBuild:R,logger:e.pipelineContext.logger,siteUrl:p,signal:e.signal}),await n?.report({message:"Validating and publishing site generation",progress:97,total:100}),e.signal.throwIfAborted(),a="output-commit-failed",c=!0;let P=await o.commit({target:s,preparedBuild:R,inputFingerprint:I,warnings:r});return s=void 0,await n?.report({message:"Site build complete",progress:100,total:100}).catch(()=>{}),iEr({outputDir:t.outputDir,filesGenerated:P.filesGenerated,routesBuilt:d.length,warnings:r,diagnostics:i})}catch(l){if(s)await lEr(o,s,e.pipelineContext.logger);if(e.signal.aborted&&!c){let h={severity:"error",code:"build-cancelled",message:`Site build cancelled: ${Re(e.signal.reason??l)}`};return e.pipelineContext.logger.info(h.message),maa({outputDir:t.outputDir,message:Mxe(h),diagnostics:[...i,h]})}let p={severity:"error",code:a,message:`${a==="output-commit-failed"?"Site output commit failed":a==="staged-artifact-failed"?"Staged site artifact failed":"Site build process failed"}: ${Re(l)}`},f=Error(p.message);return e.pipelineContext.logger.error("Site build failed",{error:f,originalError:l}),jot({outputDir:t.outputDir,errorMessages:[Mxe(p)],diagnostics:[...i,p]})}}function kaa(e,t,n){return t.push(...e),n.push(...e.filter((r)=>r.severity==="warning").map(Mxe)),e.filter((r)=>r.severity==="error").map(Mxe)}async function lEr(e,t,n){try{await e.abort(t)}catch(r){n.warn("Failed to clean aborted site build output",{error:r})}}var Iaa=E(()=>{lt();Su();Msa();Nsa();Usa();caa();uaa();faa();rEr();xaa();Aaa();Saa()});var uEr,Fxe;var dEr=E(()=>{Kwr();Iaa();uEr=class uEr extends Error{constructor(e){super(`Superseded by a newer ${e} site build`)}};Fxe=class Fxe{static defaultStaticSiteBuilderFactory=Vwr;pipelineContext;staticSiteBuilderFactory;outputLifecycle;activeBuilds=new Map;static setDefaultStaticSiteBuilderFactory(e){Fxe.defaultStaticSiteBuilderFactory=e}static createFresh(e,t,n,r,i,o=void 0,s){return new Fxe(e,i??Fxe.defaultStaticSiteBuilderFactory,t,n,r,o,s)}constructor(e,t,n,r,i,o,s){this.pipelineContext={logger:e,services:n,routeRegistry:r,profileService:i,entityDisplay:o},this.staticSiteBuilderFactory=t,this.outputLifecycle=s}async build(e,t){let n=e.environment;this.activeBuilds.get(n)?.controller.abort(new uEr(n));let i=new AbortController,o=e.signal?AbortSignal.any([i.signal,e.signal]):i.signal,s=Caa({buildOptions:e,progress:t,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory,...this.outputLifecycle&&{outputLifecycle:this.outputLifecycle},signal:o}),a={controller:i,promise:s};this.activeBuilds.set(n,a);try{let c=await s;return c.cancelled&&i.signal.reason instanceof uEr?{...c,superseded:!0}:c}finally{if(this.activeBuilds.get(n)===a)this.activeBuilds.delete(n)}}async cancelActiveBuilds(e=Error("Site builder is shutting down")){let t=[...this.activeBuilds.values()];for(let n of t)n.controller.abort(e);await Promise.allSettled(t.map((n)=>n.promise))}}});class pEr{fn;delayMs;timeout;pending=!1;constructor(e,t){this.fn=e,this.delayMs=t}trigger(){if(!this.timeout){this.fn(),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs);return}this.pending=!0,clearTimeout(this.timeout),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs)}dispose(){if(this.timeout)clearTimeout(this.timeout),this.timeout=void 0;this.pending=!1}}class fEr{config;context;pluginId;logger;statusService;debounces=new Map;enqueueRetries=new Map;activeTasks=new Set;disposePromise=null;disposed=!1;constructor(e,t,n,r,i){this.config=e,this.context=t,this.pluginId=n,this.logger=r,this.statusService=i}requestBuild(e){if(this.disposed)return;let t=e??(this.config.previewOutputDir?"preview":"production");if(this.statusService)this.runTrackedTask("mark build requested",()=>this.statusService?.markRequested(t)??Promise.resolve());let n=this.debounces.get(t);if(!n)n=new pEr(()=>{this.runTrackedTask(`enqueue ${t} build`,()=>this.enqueueBuild(t))},this.config.rebuildDebounce),this.debounces.set(t,n);n.trigger()}async requestAutomaticBuild(e){if(this.disposed)return;let t=e??(this.config.previewOutputDir?"preview":"production");await this.statusService?.markRequested(t),await this.enqueueBuild(t,!0)}setupAutoRebuild(){if(this.disposed)return;let e=new Set(["note"]),t=async(n)=>{if([...new Set([...n.sourceTypes,...n.changedTargetTypes])].some((i)=>!e.has(i)))this.logger.debug(`Projection wave ${n.waveId} will trigger rebuild`),await this.requestAutomaticBuild();return{}};this.context.answer(l3e,({request:n})=>t(n),{everyProcess:!0}),this.logger.debug(`Wave-end auto-rebuild enabled, excluding types: ${[...e].join(", ")}`)}dispose(){if(this.disposePromise)return this.disposePromise;return this.disposed=!0,this.disposePromise=this.disposeOnce(),this.disposePromise}async disposeOnce(){let e=[];for(let t of this.debounces.values())try{t.dispose()}catch(n){e.push(n)}this.debounces.clear();for(let t of this.enqueueRetries.values())t.abort();if(this.enqueueRetries.clear(),await Promise.all([...this.activeTasks]),e.length>0)throw e[0]}runTrackedTask(e,t){let n=t().catch((r)=>{this.logger.error(`Failed to ${e}`,{error:r})});this.activeTasks.add(n),n.then(()=>{this.activeTasks.delete(n)})}async enqueueBuild(e,t=!1){this.logger.debug(`Triggering ${e} site rebuild`);try{let n=await this.enqueueBuildJob(e);this.cancelEnqueueRetry(e),await this.statusService?.markQueued(e,n),this.logger.debug("Site rebuild enqueued")}catch(n){if(t||this.disposed){if(await this.statusService?.clearActive(e),this.logger.error("Failed to enqueue site rebuild",{error:n}),t)throw n;return}this.retryEnqueue(e,n)}}enqueueBuildJob(e){return this.context.jobs.enqueue({type:"site-build",data:{environment:e,outputDir:e==="production"?this.config.productionOutputDir:this.config.previewOutputDir,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:Njd,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip",deduplicationKey:`site-build:${e}`}})}retryEnqueue(e,t){this.cancelEnqueueRetry(e);let n=new AbortController;this.enqueueRetries.set(e,n),this.runTrackedTask(`retry ${e} build`,async()=>{let r=await CMe(()=>this.enqueueBuildJob(e),t,{firstDelayMs:this.config.rebuildDebounce,maxDelayMs:IMe,signal:n.signal,onRetry:(i,o)=>{this.logger.warn(`Failed to enqueue ${e} site rebuild; retrying in ${o}ms`,{error:i})}});if(this.enqueueRetries.get(e)===n)this.enqueueRetries.delete(e);if(r.kind==="succeeded")await this.statusService?.markQueued(e,r.value),this.logger.debug("Site rebuild enqueued")})}cancelEnqueueRetry(e){this.enqueueRetries.get(e)?.abort(),this.enqueueRetries.delete(e)}}var Njd=-10;var _aa=E(()=>{lt();dAe()});function Ljd(e,t){return e.map((n)=>({...n,template:n.template.includes(":")?n.template:`${t}:${n.template}`}))}function lZt(e,t,n){for(let r of e)n.register({...r,pluginId:t,sections:r.sections?Ljd(r.sections,t):[]})}function Taa(e,t,n){let[r,...i]=t??[],o=i.find((l)=>n.startsWith(`${l.toLowerCase()}:`)),s=o===void 0?n:n.slice(o.length+1),a=e.flatMap((l)=>l.sections.map((d)=>({route:l,section:d}))).find(({route:l,section:d})=>`${l.id}:${d.id}`===s&&d.template!==""&&d.dataQuery===void 0)?.section;if(!a)return null;let c=o??r;return{template:a.template,...c!==void 0&&{language:c},original:s}}function Baa(e,t,n){let[r,...i]=t??[],o=i.find((l)=>n.startsWith(`${l.toLowerCase()}:`)),s=o===void 0?n:n.slice(o.length+1),a=e.find((l)=>l.id===s);if(!a)return null;let c=o??r;return{...c!==void 0&&{language:c},isDefault:o===void 0,texts:a.sections.filter((l)=>l.template!==""&&l.dataQuery===void 0).map((l)=>`${n}:${l.id}`)}}function Raa(e,t,n,r,i=[]){e.answer(d7e,async({request:{routes:o,pluginId:s}})=>{try{lZt(o,s,t)}catch(a){throw n.error("Failed to register routes",{error:a}),Error("Failed to register routes",{cause:a})}},{everyProcess:!0}),e.answer(p7e,async()=>t.list(),{everyProcess:!0}),e.answer(Mse,async({request:{id:o}})=>Taa([...t.list(),...i],r,o)),e.answer(a3e,async({request:{page:o}})=>Baa([...t.list(),...i],r,o))}var Daa=E(()=>{Su();lt()});var Paa;var Oaa=E(()=>{Su();oe();Paa=u.object({environment:u.enum(["preview","production"]).optional(),outputDir:u.string(),workingDir:u.string().optional(),enableContentGeneration:u.boolean().optional(),siteConfig:PT.optional()})});async function jxe(e,t){let n=await e.request(Rce,{});if(n.status!=="answered")return t;return PT.parse({...t,...n.data})}var uZt=E(()=>{Su()});function Maa(e,t,n){return Kg({type:"site-build",input:Paa,exclusive:!0,executionTimeoutMs:1800000,summarize:(r)=>({environment:r.environment,outputDir:r.outputDir}),process:({input:r,jobId:i,progress:o})=>new Faa(e,t,n).process(r,i,o)})}class Faa{logger;messaging;cfg;constructor(e,t,n){this.logger=e,this.messaging=t,this.cfg=n}async process(e,t,n){let r=e.environment??"preview",i=e.enableContentGeneration??!1,o=await this.lastBuildFailed(r);await this.recordStatus(()=>this.cfg.statusService?.markBuilding(r,t),"building");try{this.logger.debug("Starting site build job",{jobId:t,environment:r,outputDir:e.outputDir}),await n.report({progress:0,total:100,message:`Starting site build for ${r} environment`});let s=n.createSub({scale:{start:10,end:90}}),a=await jxe(this.messaging,e.siteConfig??this.cfg.defaultSiteConfig),c=r==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl,l=this.cfg.preferLocalUrls?this.cfg.localSiteUrl??c:c,d=await this.cfg.siteBuilder.build({outputDir:e.outputDir,workingDir:e.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:i,environment:r,cleanBeforeBuild:!0,siteConfig:a,siteUrl:l,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:await this.cfg.getSlots?.(),headScripts:await this.cfg.getHeadScripts?.(),pages:await this.cfg.getPages?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets},...this.cfg.languages&&{languages:this.cfg.languages},...this.cfg.layoutCopy&&{layoutCopy:this.cfg.layoutCopy},publishUnchanged:o},s.toCallback());if(d.success&&d.skipped)await this.recordStatus(()=>this.cfg.statusService?.markSkipped(r,t,d.routesBuilt),"skipped");else if(d.success)await this.recordStatus(()=>this.cfg.statusService?.markSuccess(r,t,d.routesBuilt,d.warnings??[]),"success");else if(d.cancelled)await this.recordStatus(()=>this.cfg.statusService?.markCancelled(r,t,d.errors?.join("; ")??"Site build cancelled"),"cancelled");else await this.recordStatus(()=>this.cfg.statusService?.markFailure(r,t,d.errors?.join("; ")??"Site build failed"),"failure");await n.report({progress:100,total:100,message:d.cancelled?"Site build cancelled":`Site build completed: ${d.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:t,environment:r,routesBuilt:d.routesBuilt,success:d.success,cancelled:d.cancelled??!1});let p=d.success||d.superseded===!0;return{success:p,...!p&&{error:d.errors?.join("; ")??"Site build failed"},...d.cancelled&&{cancelled:!0},...d.skipped&&{skipped:!0},routesBuilt:d.routesBuilt,outputDir:e.outputDir,environment:r,...d.errors&&{errors:d.errors},...d.warnings&&{warnings:d.warnings},...d.diagnostics&&{diagnostics:d.diagnostics}}}catch(s){throw await this.recordStatus(()=>this.cfg.statusService?.markFailure(r,t,Re(s,"Site build failed")),"failure"),this.logger.error("Site build job failed",s),s}}async lastBuildFailed(e){try{return await this.cfg.statusService?.hasUnresolvedFailure(e)??!1}catch(t){return this.logger.error("Failed to read the last site build outcome",{error:t}),!1}}async recordStatus(e,t){try{await e()}catch(n){this.logger.error(`Failed to record site build ${t} state`,{error:n})}}}var jaa=E(()=>{wn();Oaa();uZt()});function Naa(e,t){return t.debug("NavigationDataSource initialized"),{id:"site:navigation",name:"Site Navigation DataSource",description:"Provides navigation items for site menus",fetch:async(n)=>{let r=zjd.parse(n??{});t.debug("NavigationDataSource fetch called",{params:r});let i=e.getNavigationItems(r.slot),o=r.limit?i.slice(0,r.limit):i,s=o.map((a)=>({label:a.label,href:a.href}));return t.debug("NavigationDataSource returning",{slot:r.slot,itemCount:o.length,items:s}),{navigation:s}}}}var zjd;var Laa=E(()=>{oe();Su();zjd=u.object({slot:u.enum(u7e).optional().default("primary"),limit:u.number().optional()})});function zaa(e,t){return[ph(e,"build-site","Build a static site from registered routes. Call this immediately whenever the user asks to build, rebuild, publish, or build the website/site again; every repeated request such as 'build it again' or 'one more build' needs a fresh call. Never say a build was started, queued, or requested unless this turn called this tool.",qjd,async(n)=>(t(n.environment),{success:!0,message:`Site build requested${n.environment?` for ${n.environment}`:""} (debounced)`,data:{}}),{sideEffects:"external",cli:{name:"build"}})]}var qjd;var qaa=E(()=>{wn();oe();qjd=u.object({environment:u.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")})});class gEr{store;jobs;constructor(e,t){this.store=new $H({runtimeState:e,namespace:Qjd,key:Kjd,schema:Zjd,createEmpty:()=>structuredClone(Vjd)}),this.jobs=t}async initialize(){await this.store.mutate((e)=>this.reconcile(e,!0))}async reconcile(e,t=!1){let n=["preview","production"];for(let r of n){let i=e[r],o=i.active;if(!o)continue;if(!o.jobId){if(t)delete i.active;continue}let s=await this.jobs.getStatus(o.jobId);if(!s){delete i.active;continue}if(s.status==="pending"){i.active={...o,state:"queued"};continue}if(s.status==="processing"){i.active={...o,state:"building",...s.startedAt?{startedAt:new Date(s.startedAt).toISOString()}:{}};continue}this.applyTerminalJob(e,r,s)}await this.reconcileFromQueue(e)}async reconcileFromQueue(e){let t=await this.jobs.getRecentJobs(Jjd,Yjd),n=["preview","production"];for(let r of n){let i=t.find((s)=>this.jobEnvironment(s)===r);if(!i)continue;if(i.status==="pending"||i.status==="processing"){e[r].active??={jobId:i.id,state:i.status==="processing"?"building":"queued",requestedAt:new Date(i.createdAt).toISOString(),...i.startedAt?{startedAt:new Date(i.startedAt).toISOString()}:{}};continue}if(e.recentBuilds.some((s)=>s.jobId===i.id))continue;let o=i.completedAt??i.startedAt??i.createdAt;if(this.hasNewerRecordedOutcome(e[r],o))continue;this.applyTerminalJob(e,r,i)}}jobEnvironment(e){let t=Uaa.safeParse(e.result);if(t.success)return t.data.environment;try{let n=Uaa.safeParse(JSON.parse(e.data));return n.success?n.data.environment:void 0}catch{return}}hasNewerRecordedOutcome(e,t){return[e.lastSuccess,e.lastFailure,e.lastCancellation].some((n)=>n!==void 0&&Date.parse(n.completedAt)>=t)}applyTerminalJob(e,t,n){let r=new Date(n.completedAt??n.startedAt??n.createdAt).toISOString();if(n.status==="failed"){this.applyFailure(e,t,n.id,r,n.lastError??"Site build failed");return}let i=Wjd.safeParse(n.result);if(i.success&&i.data.cancelled)this.applyCancellation(e,t,n.id,r,i.data.errors?.join("; ")??"Site build cancelled");else if(i.success&&i.data.success&&i.data.skipped)this.applySkipped(e,t,n.id,r,i.data.routesBuilt);else if(i.success&&i.data.success)this.applySuccess(e,t,n.id,r,i.data.routesBuilt,i.data.warnings??[]);else{let o=i.success?i.data.errors?.join("; ")??"Site build failed":"Site build completed without a readable result";this.applyFailure(e,t,n.id,r,o)}}markRequested(e,t=new Date().toISOString()){return this.mutate((n)=>{let r=n[e].active;if(r?.state==="queued"||r?.state==="building")return;n[e].active={state:"debouncing",requestedAt:t}})}markQueued(e,t){return this.mutate((n)=>{let r=n[e].active;n[e].active={jobId:t,state:"queued",requestedAt:r?.requestedAt??new Date().toISOString()}})}markBuilding(e,t,n=new Date().toISOString()){return this.mutate((r)=>{let i=r[e].active;r[e].active={jobId:t,state:"building",requestedAt:i?.requestedAt??n,startedAt:n}})}markSuccess(e,t,n,r,i=new Date().toISOString()){return this.mutate((o)=>{this.applySuccess(o,e,t,i,n,r)})}markSkipped(e,t,n,r=new Date().toISOString()){return this.mutate((i)=>{this.applySkipped(i,e,t,r,n)})}markCancelled(e,t,n,r=new Date().toISOString()){return this.mutate((i)=>{this.applyCancellation(i,e,t,r,n)})}markFailure(e,t,n,r=new Date().toISOString()){return this.mutate((i)=>{this.applyFailure(i,e,t,r,n)})}async hasUnresolvedFailure(e){return(await this.store.snapshot())[e].lastFailure!==void 0}clearActive(e){return this.mutate((t)=>{delete t[e].active})}async getSnapshot(){await this.store.mutate((t)=>this.reconcile(t));let e=await this.store.snapshot();return{environments:[{environment:"preview",...e.preview},{environment:"production",...e.production}],recentBuilds:e.recentBuilds}}mutate(e){return this.store.mutate(e)}applySuccess(e,t,n,r,i,o){let s={jobId:n,completedAt:r,routesBuilt:i,warnings:o};e[t].lastSuccess=s,delete e[t].lastFailure,delete e[t].lastCancellation,this.clearMatchingActive(e,t,n),this.prependRecent(e,{jobId:n,environment:t,outcome:"succeeded",completedAt:r,routesBuilt:i,warnings:o})}applySkipped(e,t,n,r,i){this.clearMatchingActive(e,t,n),this.prependRecent(e,{jobId:n,environment:t,outcome:"skipped",completedAt:r,routesBuilt:i,message:"Site inputs were unchanged; no render was published"})}applyFailure(e,t,n,r,i){let o={jobId:n,completedAt:r,message:i};e[t].lastFailure=o,delete e[t].lastCancellation,this.clearMatchingActive(e,t,n),this.prependRecent(e,{jobId:n,environment:t,outcome:"failed",completedAt:r,message:i})}applyCancellation(e,t,n,r,i){e[t].lastCancellation={jobId:n,completedAt:r,message:i},delete e[t].lastFailure,this.clearMatchingActive(e,t,n),this.prependRecent(e,{jobId:n,environment:t,outcome:"cancelled",completedAt:r,message:i})}clearMatchingActive(e,t,n){if(e[t].active?.jobId===n)delete e[t].active}prependRecent(e,t){e.recentBuilds=[t,...e.recentBuilds.filter((n)=>n.jobId!==t.jobId)].slice(0,5)}}var dZt,Ujd,$jd,Hjd,Gjd,mEr,$aa,hEr,Zjd,Wjd,Vjd,Kjd="current",Qjd="site-builder.build-status",Jjd,Yjd=10,Uaa;var xEr=E(()=>{wn();oe();dZt=u.enum(["preview","production"]),Ujd=u.object({jobId:u.string().optional(),state:u.enum(["debouncing","queued","building"]),requestedAt:u.string().datetime(),startedAt:u.string().datetime().optional()}),$jd=u.object({jobId:u.string(),completedAt:u.string().datetime(),routesBuilt:u.number().int().nonnegative(),warnings:u.array(u.string())}),Hjd=u.object({jobId:u.string(),completedAt:u.string().datetime(),message:u.string()}),Gjd=u.object({jobId:u.string(),completedAt:u.string().datetime(),message:u.string()}),mEr=u.object({active:Ujd.optional(),lastSuccess:$jd.optional(),lastFailure:Hjd.optional(),lastCancellation:Gjd.optional()}),$aa=u.object({...mEr.shape,environment:dZt}),hEr=u.object({jobId:u.string(),environment:dZt,outcome:u.enum(["succeeded","failed","cancelled","skipped"]),completedAt:u.string().datetime(),routesBuilt:u.number().int().nonnegative().optional(),warnings:u.array(u.string()).optional(),message:u.string().optional()}),Zjd=u.object({preview:mEr,production:mEr,recentBuilds:u.array(hEr).max(5)}),Wjd=u.object({success:u.boolean(),cancelled:u.boolean().optional(),skipped:u.boolean().optional(),routesBuilt:u.number().int().nonnegative(),warnings:u.array(u.string()).optional(),errors:u.array(u.string()).optional()}),Vjd={preview:{},production:{},recentBuilds:[]},Jjd=["site-builder:site-build"],Uaa=u.object({environment:u.enum(["preview","production"])})});import{readFile as Xjd,stat as eNd}from"fs/promises";import{join as tNd,resolve as nNd}from"path";async function yEr(e,t){let n=tNd(nNd(e),gT);try{let[r,i]=await Promise.all([Xjd(n,"utf8"),eNd(n)]),o=Bme.parse(JSON.parse(r));if(o.environment!==t)throw Error(`Active manifest environment mismatch: expected ${t}, found ${o.environment}`);return{state:"published",buildId:o.buildId,publishedAt:i.mtime.toISOString(),routesBuilt:o.routes.length,warnings:o.warnings}}catch(r){if(bx(r))return{state:"not-published"};return{state:"unreadable",message:`Unable to read the published ${t} generation: ${Re(r)}`}}}var pZt;var bEr=E(()=>{J8();Xc();oe();sEr();pZt=u.discriminatedUnion("state",[u.object({state:u.literal("not-published")}),u.object({state:u.literal("published"),buildId:u.string(),publishedAt:u.string().datetime(),routesBuilt:u.number().int().nonnegative(),warnings:u.array(u.string())}),u.object({state:u.literal("unreadable"),message:u.string()})])});function Haa(e){if(e.state==="published")return[{label:"Published at",value:e.publishedAt},{label:"Pages",value:String(e.routesBuilt)}];if(e.state==="unreadable")return[{label:"Why",value:e.message}];return[]}function Gaa(e){return[...e.publication.state==="published"?[{label:"Published build",value:e.publication.buildId}]:[],{label:"Last successful render",value:e.lastSuccess?.completedAt??"\u2014"},{label:"Rendered result",value:e.lastSuccess?`${e.lastSuccess.routesBuilt} routes \xB7 ${e.lastSuccess.jobId}`:"no successful render"},...e.lastFailure?[{label:"Last failed attempt",value:e.lastFailure.completedAt},{label:"Failed job",value:e.lastFailure.jobId}]:[]]}function Zaa(e,t){if(t===void 0)return{total:0,entries:[]};let n=Date.parse(t),r=e.filter((i)=>Date.parse(i.updated)>n).sort((i,o)=>Date.parse(o.updated)-Date.parse(i.updated));return{total:r.length,entries:r.slice(0,5).map((i)=>({entityType:i.entityType,id:i.id,title:i.title,change:Date.parse(i.created)>n?"new":"edited"}))}}function Waa(e,t){let n=(a)=>{let c=e.find((l)=>l.environment===a)?.publishedAt;return c===void 0?void 0:Date.parse(c)},r=e.some((a)=>a.environment==="production"),i=e.some((a)=>a.environment==="preview"),o=n("preview"),s=n("production");if(r&&s===void 0)return"Your site is not live yet.";if(i&&o===void 0)return"Build a preview to see your site before it goes live.";if(t>0)return`The preview is ${t} ${t===1?"change":"changes"} ahead of your live site.`;if(o!==void 0&&s!==void 0&&o>s)return"The preview has changes your live site does not have yet.";return"Your live site matches the preview."}function iNd(e){let t=e.routesBuilt===void 0?"":` \xB7 ${e.routesBuilt} pages`,n=e.environment==="production";switch(e.outcome){case"succeeded":return n?`Published${t}`:`Preview built${t}`;case"failed":return n?"Publishing failed":"Preview failed";case"cancelled":return n?"Publishing cancelled":"Preview cancelled";case"skipped":return n?"Publishing skipped":"Preview skipped"}}function Vaa(e){return e.filter((t)=>t.outcome!=="skipped").sort((t,n)=>Date.parse(n.completedAt)-Date.parse(t.completedAt)).slice(0,rNd).map((t)=>({id:t.jobId,title:iNd(t),at:t.completedAt,tone:t.outcome==="succeeded"?"good":t.outcome==="failed"?"error":"neutral",...t.outcome==="failed"&&t.message?{description:t.message}:{}}))}var rNd=6;function aNd(e){return{type:"progress",id:`${e.environment}-build`,label:`${e.environment} build`,state:e.active?.state??"active",startedAt:e.active?.startedAt??e.active?.requestedAt,tone:"neutral"}}function cNd(e){let t=e.lastFailure;if(!t)return[];let n=Date.parse(t.completedAt);if(e.lastSuccess&&Date.parse(e.lastSuccess.completedAt)>=n)return[];if(e.lastCancellation&&Date.parse(e.lastCancellation.completedAt)>=n)return[];return[{type:"notice",id:`${e.environment}-failure`,tone:"warn",title:"The latest completed build failed",text:e.publication.state==="published"?"The published generation is shown separately below.":"Review the build diagnostics before trying again.",details:[`Completed: ${t.completedAt}
|
|
12590
12590
|
Job: ${t.jobId}`,t.message]}]}class kEr{options;registered=!1;constructor(e){this.options=e}siteEntryTypes(){let{entityReads:e}=this.options;return e.getEntityTypes().filter((t)=>{let n=e.getEntityTypeConfig(t);return n.classification!=="system"&&!n.binaryStorage})}async changeCandidates(){let{entityReads:e,displayTitle:t}=this.options;return(await Promise.all(this.siteEntryTypes().map((r)=>e.listEntities({entityType:r,options:{limit:lNd,sortFields:[{field:"updated",direction:"desc"}],filter:{visibility:"public"}}}).catch(()=>[])))).flat().map((r)=>({entityType:r.entityType,id:r.id,title:t(r)??r.id,created:r.created,updated:r.updated}))}async getSnapshot(){let{messaging:e,previewUrl:t,siteUrl:n,config:r,routeRegistry:i,statusService:o}=this.options,[s,a,c,l,d]=await Promise.all([jxe(e,r.siteInfo),o.getSnapshot(),yEr(r.previewOutputDir,"preview"),yEr(r.productionOutputDir,"production"),this.changeCandidates()]);return Qaa.parse({site:{title:s.title,...t?{previewUrl:t}:{},...n?{liveUrl:n}:{}},automation:{autoRebuild:r.autoRebuild,debounceMs:r.rebuildDebounce,defaultEnvironment:r.previewOutputDir?"preview":"production"},environments:a.environments.map((p)=>({...p,publication:p.environment==="preview"?c:l})),recentBuilds:a.recentBuilds,routes:i.list().map((p)=>({id:p.id,path:p.path,title:p.title})),changes:Zaa(d,l.state==="published"?l.publishedAt:void 0)})}async registerStudioWorkspace(){let{studio:e}=this.options;if(!e.isAvailable())return;let t=e.source({definition:AEr,bind:(r)=>AEr.bind(r,{authorize:({caller:i,permissions:o})=>i?.permission==="admin"||o.allows(SEr,"update"),listEntityTypes:()=>this.siteEntryTypes(),load:()=>this.getSnapshot(),actions:[wEr.bind(r,({permissions:i})=>{if(!i.allows(SEr,"update"))throw Error("Preview site build requires update permission");return this.options.requestBuild("preview"),{accepted:!0,environment:"preview"}}),EEr.bind(r,()=>(this.options.requestBuild("production"),{accepted:!0,environment:"production"}))]})}),n=await e.register(t);return this.registered=n!==void 0,n}async unregisterStudioWorkspace(){if(!this.registered)return;await this.options.studio.unregister(`site-builder:${AEr.id}`),this.registered=!1}}var m6g,oNd,sNd,Kaa,Qaa,Jaa,wEr,EEr,vEr=8,SEr,AEr,lNd=20;var Yaa=E(()=>{Zo();Jr();oe();xEr();bEr();uZt();m6g=u.discriminatedUnion("type",[u.object({type:u.literal("build-preview")}),u.object({type:u.literal("build-production"),confirmed:u.literal(!0)})]),oNd=u.object({...$aa.shape,publication:pZt}),sNd=u.object({total:u.number().int().nonnegative(),entries:u.array(u.object({entityType:u.string().min(1),id:u.string().min(1),title:u.string(),change:u.enum(["new","edited"])}))}),Kaa=p3({id:"site-entries",label:"Site entries"}),Qaa=u.object({site:u.object({title:u.string().min(1),previewUrl:u.string().url().optional(),liveUrl:u.string().url().optional()}),automation:u.object({autoRebuild:u.boolean(),debounceMs:u.number().int().nonnegative(),defaultEnvironment:dZt}),environments:u.array(oNd),recentBuilds:u.array(hEr),routes:u.array(u.object({id:u.string().min(1),path:u.string(),title:u.string()})),changes:sNd}),Jaa=u.object({accepted:u.literal(!0),environment:u.enum(["preview","production"])}),wEr=La({name:"build-preview",label:"Build preview",permission:"trusted",palette:!0,input:u.object({}),output:Jaa}),EEr=La({name:"build-production",label:"Build production",permission:"admin",confirmation:{kind:"static",message:"Build and publish the production site now?"},input:u.object({}),output:Jaa}),SEr=Vr({type:"site-info",purpose:"Site identity and navigation settings",metadata:u.object({})});AEr=Sf({id:"site",label:"Site",permission:"trusted",section:"publish",entityCatalog:Kaa,data:Qaa,actions:[wEr,EEr],refresh:({data:e})=>e.environments.some((t)=>t.active)?1000:void 0,view:({data:e})=>{let t=e.environments.some((d)=>d.active),n=e.environments.some((d)=>d.environment==="preview"),r=e.environments.some((d)=>d.environment==="production"),i=e.site.previewUrl??e.site.liveUrl,o=Waa(e.environments.map((d)=>({environment:d.environment,publishedAt:d.publication.state==="published"?d.publication.publishedAt:void 0})),e.changes.total),s=e.environments.find((d)=>d.environment==="production")?.publication,a=s?.state==="published"?`Last published ${new Date(s.publishedAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}.`:"Publishing puts the preview on your live site.",c=[...e.site.previewUrl?[{label:"Open preview",target:{external:e.site.previewUrl}}]:[],...e.site.liveUrl?[{label:"Open live site",target:{external:e.site.liveUrl}}]:[],{label:"Edit site settings",target:{entity:SEr,id:"site-info"}}],l={type:"table",id:"routes",empty:"No site routes are configured.",columns:[{key:"title",label:"Route"},{key:"path",label:"Path"}],rows:e.routes.slice(0,vEr).map((d)=>({id:d.id,cells:{title:d.title,path:d.path},compact:{title:d.title,metadata:[d.path]}}))};return{title:"Site",...e.site.liveUrl?{facts:[{label:new URL(e.site.liveUrl).host}]}:{},...r?{primaryAction:{action:EEr,label:"Publish site",input:{},disabled:t}}:{},blocks:[{type:"columns",id:"site-hero",primary:i?[{type:"webpage",id:"site-page",title:`${e.site.previewUrl?"Preview":"Live site"} of ${e.site.title}`,url:i,caption:new URL(i).hostname,tag:e.site.previewUrl?"Preview":"Live"}]:[],aside:[{type:"notice",id:"site-headline",title:o,text:a},...e.changes.entries.length>0?[{type:"list",id:"site-changes",presentation:"activity",empty:"Nothing has changed since the live site.",items:e.changes.entries.map((d)=>({id:`${d.entityType}:${d.id}`,title:d.title,metadata:[d.change==="new"?`new ${d.entityType}`:"edited"],tone:d.change==="new"?"good":"neutral",link:{catalog:Kaa,entityType:d.entityType,id:d.id}}))}]:[],{type:"links",id:"site-links",items:c},...n?[{type:"actions",id:"site-preview-actions",items:[{action:wEr,input:{},disabled:t}]}]:[]]},...e.environments.flatMap((d)=>[...cNd(d),...d.active?[aNd(d)]:[]]),{type:"card",id:"site-builds",label:"Builds",blocks:[{type:"list",id:"site-build-history",presentation:"activity",empty:"No site builds have completed yet.",items:Vaa(e.recentBuilds)}]},{type:"card",id:"site-technical",label:"Technical",presentation:"disclosure",metadata:["Routes, automatic rebuild, environments"],blocks:[...e.environments.map((d)=>({type:"key-values",id:`${d.environment}-render-details`,items:[{label:"Environment",value:d.environment==="preview"?"Preview":"Live site"},...Haa(d.publication),...Gaa(d)]})),{type:"key-values",id:"automation",items:[{label:"Automatic rebuild",value:e.automation.autoRebuild},{label:"Debounce",value:`${e.automation.debounceMs} ms`},{label:"Default environment",value:e.automation.defaultEnvironment}]},l,...e.routes.length>vEr?[{type:"notice",id:"routes-remainder",text:`${e.routes.length-vEr} further routes are configured.`}]:[]]}]}}})});import{createElement as b6g}from"react";function CEr(e){return e.length<=500?e:`${e.slice(0,497)}\u2026`}function pNd(e){let t=e.lastFailure?.jobId?` \xB7 ${e.lastFailure.jobId}`:"";return`${e.environment}${t}`}function fNd(e){if(e.length===0)return[];return[{type:"notice",id:"build-failures",title:"Previous build failures",text:e.map((t)=>{let n=t.lastFailure,r=n?.completedAt?` \xB7 ${n.completedAt}`:"";return`${pNd(t)}${r}: ${CEr(n?.message??"Build failed without details.")}`}).join(`
|
|
12591
12591
|
`),tone:"error"}]}function mNd(e){return{type:"links",items:[...e.site.previewUrl?[{label:"Open preview",target:{external:e.site.previewUrl}}]:[],...e.site.liveUrl?[{label:"Open live",target:{external:e.site.liveUrl}}]:[],{label:"Open Site",target:{launch:{target:"site"}}}]}}function hNd(e){let t=e.environments.find((s)=>s.environment==="preview"),n=e.environments.find((s)=>s.environment==="production"),r=e.environments.filter((s)=>s.lastFailure!==void 0).length,i=fZt(t),o=fZt(n);return{items:[{label:"Preview",value:i.state,tone:i.tone},{label:"Live",value:o.state,tone:o.tone}],attention:r}}function fZt(e){if(!e)return{state:"unavailable",detail:"Unavailable",tone:"good"};if(e.active)return{state:e.active.state,detail:[e.active.state,e.active.jobId].filter((t)=>t!==void 0).join(" \xB7 "),tone:"good"};if(e.publication?.state==="unreadable")return{state:"unknown",detail:e.publication.message,tone:"warn"};if(e.lastCancellation)return{state:"cancelled",detail:e.lastCancellation.message,tone:"good"};if(e.lastFailure){let t=e.publication?.state==="published"?" The last published version is still live.":"";return{state:"failed",detail:`${e.lastFailure.message}${t}`,tone:"warn"}}if(e.publication?.state==="published"){let t=e.publication;return{state:"published",detail:`${t.routesBuilt} published routes \xB7 ${t.buildId} \xB7 ${t.publishedAt}`,tone:"good"}}if(e.lastSuccess){let t=e.lastSuccess.warnings.length>0?` \xB7 ${e.lastSuccess.warnings.length} warning`:"";return{state:"rendered",detail:`${e.lastSuccess.routesBuilt} routes rendered${t}`,tone:"good"}}return{state:"not built",detail:"No published generation",tone:"good"}}function Xaa(e,t){e.dashboardWidget({definition:gNd,load:async({signal:n})=>{n.throwIfAborted();let r=await t.getSnapshot();return n.throwIfAborted(),r}})}var uNd,dNd,gNd;var eca=E(()=>{Zo();oe();bEr();uNd=u.object({environment:u.enum(["preview","production"]),publication:pZt.optional(),active:u.object({jobId:u.string().optional(),state:u.enum(["debouncing","queued","building"]),requestedAt:u.string().optional(),startedAt:u.string().optional()}).optional(),lastSuccess:u.object({completedAt:u.string(),routesBuilt:u.number(),warnings:u.array(u.string())}).optional(),lastFailure:u.object({jobId:u.string().optional(),completedAt:u.string(),message:u.string()}).optional(),lastCancellation:u.object({completedAt:u.string(),message:u.string()}).optional()}),dNd=u.object({site:u.object({title:u.string(),previewUrl:u.string().optional(),liveUrl:u.string().optional()}),environments:u.array(uNd),managementUrl:u.string().optional()});gNd=zd({id:"site-health",title:"Site health",description:"Preview and live build status",group:"publishing",placement:"sidebar",priority:50,permission:"admin",data:dNd,digest:({data:e})=>hNd(e),view:({data:e})=>{let t=e.environments.find((s)=>s.environment==="preview"),n=e.environments.find((s)=>s.environment==="production"),r=e.environments.filter((s)=>s.lastFailure!==void 0),i=fZt(t),o=fZt(n);return{blocks:[{type:"stats",items:[{label:"Preview",value:i.state,tone:i.tone},{label:"Live",value:o.state,tone:o.tone}]},{type:"key-values",items:[{label:"Preview detail",value:CEr(i.detail)},{label:"Live detail",value:CEr(o.detail)}]},...fNd(r),mNd(e)]}}})});var tca;var nca=E(()=>{oe();Su();tca=u.object({previewOutputDir:u.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:u.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:u.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:u.string().optional().describe("Working directory for builds").default("./.react-work"),siteInfo:PT.default({represents:"anchor",title:"Brain",description:"A knowledge management system"}),themeCSS:u.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:u.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),headScripts:u.array(u.string()).default([]).describe("Global scripts to inject into every rendered page head"),templates:u.custom().optional().describe("Template definitions to register"),routes:u.array(i3).optional().describe("Routes to register"),layouts:u.record(u.string(),u.custom()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:u.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:u.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),staticAssets:u.record(u.string(),u.string()).optional().describe("Static files to write to the output directory at build time. Keys are output paths (e.g. '/canvases/tree.js'), values are file contents as strings. Typically supplied by a SitePackage via text imports."),languages:u.array(YE).min(1).optional().describe("The site's languages, the first its default. Every other language is built under its lowercased tag from copy saved for it."),layoutCopy:Bce.optional().describe("The layout's own words, kept in the brain per language and handed to the layout. Supplied by a SitePackage.")})});import{access as xNd}from"fs/promises";import{join as yNd}from"path";async function IEr(e,t){let n=[["production",e.productionOutputDir],["preview",e.previewOutputDir]],r=await Promise.all(n.map(async([i,o])=>({environment:i,exists:await xNd(yNd(o,"index.html")).then(()=>!0,()=>!1)})));for(let{environment:i,exists:o}of r)if(o)t.requestBuild(i)}function bNd(e,t){return{instructions:async()=>{let n=await jxe(e.messaging,t.siteInfo);return`## Your Site
|