@rizom/brain 0.2.0-alpha.865 → 0.2.0-alpha.866

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 CHANGED
@@ -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 g8i}from"react";import{jsx as Sde,jsxs as c1n}from"react/jsx-runtime";function x8i({messages:e,height:t,scrollOffset:n=0}){let r=new a1n,{stdout:i}=EX(),o=i.rows||24,s=t??Math.max(o-4,10),a=g8i(()=>{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=g8i(()=>{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 c1n(Go,{flexDirection:"column",overflow:"visible",children:[l&&Sde(Go,{justifyContent:"center",children:c1n(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 Sde(Go,{marginBottom:0,children:Sde(bo,{bold:!0,color:m.role==="user"?"blue":m.role==="assistant"?"green":m.role==="error"?"red":"gray",children:p.content})},f);else return Sde(Go,{paddingLeft:p.content.trim()?2:0,children:Sde(bo,{children:p.content})},f)}),d&&Sde(Go,{justifyContent:"center",marginTop:1,children:c1n(bo,{dimColor:!0,italic:!0,children:["\u2193 ",n," more lines (Shift+\u2193 or PgDn to scroll)"]})}),Sde(Dqe,{})]})}var y8i=E(async()=>{h8i();await eO()});import cIc,{useState as lIc,useEffect as uIc}from"react";function dIc({value:e,placeholder:t="",focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:o=!0,onChange:s,onSubmit:a}){let[c,l]=lIc({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:d,cursorWidth:p}=c;uIc(()=>{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}),cIc.createElement(bo,null,t?m.length>0?h:g:h)}var b8i;var v8i=E(async()=>{F1e();await eO();b8i=dIc});import{useState as A8i,useCallback as w8i}from"react";import{jsx as l1n,jsxs as E8i}from"react/jsx-runtime";function S8i({onSubmit:e,placeholder:t="Type a message or /help for commands...",isLoading:n=!1,history:r}){let[i,o]=A8i(""),[s,a]=A8i();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=w8i((d)=>{if(d.trim())r.add(d),e(d),o(""),a(void 0)},[e,r]),l=w8i((d)=>{if(o(d),s!==void 0&&d!==s)a(void 0)},[s]);if(n)return l1n(Go,{children:l1n(bo,{color:"gray",children:"Processing..."})});return E8i(Go,{children:[E8i(bo,{bold:!0,color:"green",children:["\u276F"," "]}),l1n(b8i,{value:i,onChange:l,onSubmit:c,placeholder:t})]})}var k8i=E(async()=>{await A6([eO(),v8i()])});import{jsx as C8i,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," "]}),C8i(bo,{color:c,children:g}),C8i(bo,{color:"gray",children:x}),o&&NSt(bo,{color:"gray",children:[" ",e,"/",t]}),i&&NSt(bo,{color:f===100?"green":"yellow",children:[" ",f,"%"]})]})}var Nqe=E(async()=>{await eO()});import{useState as pIc,useEffect as I8i,useRef as _8i}from"react";import{jsx as s8,jsxs as LSt}from"react/jsx-runtime";function T8i({messageCount:e,isConnected:t,progressEvents:n}){let[i,o]=pIc([]),s=_8i(new Map),a=_8i(new Map);I8i(()=>()=>{a.current.forEach((p)=>clearTimeout(p)),a.current.clear()},[]),I8i(()=>{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 B8i=E(async()=>{await A6([eO(),Nqe()])});import{useMemo as fIc}from"react";import{jsx as rO,jsxs as GI,Fragment as R8i}from"react/jsx-runtime";function D8i({progressEvents:e,maxLines:t=5}){let{batchEvents:n,jobEvents:r}=fIc(()=>{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 rO(Go,{flexDirection:"column",children:rO(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:[rO(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(R8i,{children:[rO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})]})]}),l.batchDetails&&l.batchDetails.totalOperations>0&&rO(Go,{marginLeft:2,children:rO(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:[rO(Go,{children:GI(bo,{color:"blue",children:["\u2022 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),rO(Go,{children:l.progress&&GI(R8i,{children:[GI(bo,{color:"gray",children:[l.progress.current,"/",l.progress.total]}),rO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})})]}),l.progress&&l.progress.total>0&&rO(Go,{marginLeft:2,children:rO(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 P8i=E(async()=>{await A6([eO(),Nqe()])});class u1n{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 N8i={};fi(N8i,{default:()=>j8i});import{useState as H1e,useCallback as O8i,useEffect as M8i,useMemo as mIc}from"react";import{jsx as a8,jsxs as F8i}from"react/jsx-runtime";function j8i({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=mIc(()=>new u1n,[]);M8i(()=>{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=O8i((P)=>{m(P)},[]);M8i(()=>(t(k),()=>{n()}),[t,n,k]);let C=O8i(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 F8i(Go,{flexDirection:"column",height:I,children:[a8(Go,{flexGrow:1,height:R,overflow:"hidden",children:a8(x8i,{messages:s,height:R,scrollOffset:x})}),h&&f.length>0&&a8(Go,{flexShrink:0,marginTop:1,marginBottom:1,children:a8(D8i,{progressEvents:f,maxLines:4})}),a8(Go,{flexShrink:0,marginTop:1,children:c?F8i(Go,{children:[a8(bo,{color:"green",children:a8(RSt,{type:"dots"})}),a8(bo,{color:"gray",children:" Processing..."})]}):a8(S8i,{onSubmit:C,isLoading:c,history:S})}),a8(Go,{flexShrink:0,marginTop:1,children:a8(T8i,{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 L8i=E(async()=>{await A6([eO(),KSn(),y8i(),k8i(),B8i(),P8i()])});var hIc,gIc,xIc,z8i;var q8i=E(()=>{_a();QH();tEn();YIi();hIc=uk({id:"cli",config:kEt,setup:(e)=>(If(e).logger.debug("CLI interface registered with AgentService"),QIi())}),gIc=NT(hIc,(e)=>{let{state:t}=e,n=If(e),{logger:r,messages:i}=n,o=JIi(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([eO().then(() => GRi),import("react"),L8i().then(() => N8i)]),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=Zze(["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()}}}}}),xIc=QJ(gIc,({state:e})=>({send:({message:t})=>{let n=typeof t==="string"?t:t.fallbackText??"";if(!n)return;(e.systemMessageCallback??e.responseCallback)?.(n)}})),z8i=xIc});import{jsx as ZI,jsxs as MD}from"react/jsx-runtime";function U8i({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 MD(Go,{flexDirection:"column",marginY:1,children:[ZI(Go,{marginBottom:1,children:MD(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&&MD(Go,{marginBottom:1,children:[ZI(bo,{color:"green",children:ZI(RSt,{type:"dots"})}),MD(bo,{color:"gray",children:[" ",s]})]}),t&&MD(Go,{flexDirection:"column",marginLeft:2,children:[f>0&&MD(Go,{children:[ZI(bo,{color:"green",children:"\u2713 "}),MD(bo,{color:"gray",children:[f," successful"]})]}),o>0&&MD(Go,{children:[ZI(bo,{color:"red",children:"\u2717 "}),MD(bo,{color:"gray",children:[o," failed"]})]}),a.length>0&&MD(Go,{flexDirection:"column",marginTop:1,children:[ZI(bo,{color:"red",bold:!0,children:"Errors:"}),a.slice(0,3).map((m,h)=>MD(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:MD(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 $8i=E(async()=>{await A6([eO(),KSn(),Nqe()])});var H8i={};fi(H8i,{BatchProgress:()=>U8i,ProgressBar:()=>yN,cliConfigSchema:()=>kEt,default:()=>z8i});var G8i=E(async()=>{q8i();tEn();await A6([Nqe(),$8i()])});var Z8i=j(function(mIf,yIc){yIc.exports={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.865",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 W8i(e){let[{default:t},{default:n}]=await Promise.all([G8i().then(() => H8i),Promise.resolve().then(() => yn(Z8i(),1))]);return lA(t,e??{},{name:n.name,version:n.version},{pluginId:"cli"})}var V8i=E(()=>{Ki()});function kde(e="admin"){return{interfaceType:"cli",actor:Lqe,userPermissionLevel:e}}var Lqe,zqe;var zSt=E(()=>{Lqe={kind:"service",serviceId:"brain-cli"},zqe=`${Lqe.kind}:${Lqe.serviceId}`});var bIc,qqe,Uqe;var qSt=E(()=>{oe();lt();bIc=u.enum(["eval"]),qqe=u.enum(["person","team","organization"]),Uqe=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 d1n,USt;var G1e=E(()=>{oe();Ki();ade();ade();qSt();qSt();d1n=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:d1n.optional(),logLevel:pk.optional(),logFile:u.string().optional(),profileKind:u.string().trim().min(1).optional(),plugins:u.array(KLe).default([]),spaces:u.array(u.string()).default([]),identity:G7e.optional(),agentInstructions:u.array(u.string()).optional(),deployment:Uqe.prefault({}),http:aX.prefault({})})});function AIc(){return process.env[vIc]}function p1n(){return AIc()==="production"}function K8i(){return!p1n()}var vIc="NODE_ENV";function EIc(){return Object.fromEntries(AI.map((e)=>[e,wIc]))}function Q8i(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 SIc(n),kIc(e,n),CIc(e,n,t),IIc(e,n),_Ic(e,n),TIc(e,n),BIc(e,n),RIc(e,n),PIc(e,n),DIc(e,n),n}function SIc(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??=VIi(),e.gitBrokerCheckout??=WIi()}function kIc(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function CIc(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&&EIc(),...t.ai?.providerKeys,...i},...o}}function IIc(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 _Ic(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((r)=>r.pattern===zqe)?n:[{pattern:zqe,level:"admin"},...n]}}function TIc(e,t){if(e.spaces)t.spaces=e.spaces}function BIc(e,t){if(e.identity)t.identity=e.identity}function RIc(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function DIc(e,t){t.http??={...Ar(e.http),port:e.deployment.ports.production}}function PIc(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=K8i(),t.production=p1n()}var wIc="startup-check";var f1n=E(()=>{ade();zSt();G1e();SEt()});var J8i={};fi(J8i,{App:()=>Z1e});class Z1e{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(e,t){return new Z1e(Q8i(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 Gze(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=Hze.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 W8i(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=Zze(["SIGINT"],t),i=Zze(["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=g8i(()=>{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 c1n(Go,{flexDirection:"column",overflow:"visible",children:[l&&Sde(Go,{justifyContent:"center",children:c1n(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 Sde(Go,{marginBottom:0,children:Sde(bo,{bold:!0,color:m.role==="user"?"blue":m.role==="assistant"?"green":m.role==="error"?"red":"gray",children:p.content})},f);else return Sde(Go,{paddingLeft:p.content.trim()?2:0,children:Sde(bo,{children:p.content})},f)}),d&&Sde(Go,{justifyContent:"center",marginTop:1,children:c1n(bo,{dimColor:!0,italic:!0,children:["\u2193 ",n," more lines (Shift+\u2193 or PgDn to scroll)"]})}),Sde(Dqe,{})]})}var y8i=E(async()=>{h8i();await eO()});import cIc,{useState as lIc,useEffect as uIc}from"react";function dIc({value:e,placeholder:t="",focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:o=!0,onChange:s,onSubmit:a}){let[c,l]=lIc({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:d,cursorWidth:p}=c;uIc(()=>{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}),cIc.createElement(bo,null,t?m.length>0?h:g:h)}var b8i;var v8i=E(async()=>{F1e();await eO();b8i=dIc});import{useState as A8i,useCallback as w8i}from"react";import{jsx as l1n,jsxs as E8i}from"react/jsx-runtime";function S8i({onSubmit:e,placeholder:t="Type a message or /help for commands...",isLoading:n=!1,history:r}){let[i,o]=A8i(""),[s,a]=A8i();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=w8i((d)=>{if(d.trim())r.add(d),e(d),o(""),a(void 0)},[e,r]),l=w8i((d)=>{if(o(d),s!==void 0&&d!==s)a(void 0)},[s]);if(n)return l1n(Go,{children:l1n(bo,{color:"gray",children:"Processing..."})});return E8i(Go,{children:[E8i(bo,{bold:!0,color:"green",children:["\u276F"," "]}),l1n(b8i,{value:i,onChange:l,onSubmit:c,placeholder:t})]})}var k8i=E(async()=>{await A6([eO(),v8i()])});import{jsx as C8i,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," "]}),C8i(bo,{color:c,children:g}),C8i(bo,{color:"gray",children:x}),o&&NSt(bo,{color:"gray",children:[" ",e,"/",t]}),i&&NSt(bo,{color:f===100?"green":"yellow",children:[" ",f,"%"]})]})}var Nqe=E(async()=>{await eO()});import{useState as pIc,useEffect as I8i,useRef as _8i}from"react";import{jsx as s8,jsxs as LSt}from"react/jsx-runtime";function T8i({messageCount:e,isConnected:t,progressEvents:n}){let[i,o]=pIc([]),s=_8i(new Map),a=_8i(new Map);I8i(()=>()=>{a.current.forEach((p)=>clearTimeout(p)),a.current.clear()},[]),I8i(()=>{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 B8i=E(async()=>{await A6([eO(),Nqe()])});import{useMemo as fIc}from"react";import{jsx as rO,jsxs as GI,Fragment as R8i}from"react/jsx-runtime";function D8i({progressEvents:e,maxLines:t=5}){let{batchEvents:n,jobEvents:r}=fIc(()=>{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 rO(Go,{flexDirection:"column",children:rO(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:[rO(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(R8i,{children:[rO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})]})]}),l.batchDetails&&l.batchDetails.totalOperations>0&&rO(Go,{marginLeft:2,children:rO(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:[rO(Go,{children:GI(bo,{color:"blue",children:["\u2022 ",l.metadata.operationType,l.metadata.operationTarget?`: ${l.metadata.operationTarget}`:""]})}),rO(Go,{children:l.progress&&GI(R8i,{children:[GI(bo,{color:"gray",children:[l.progress.current,"/",l.progress.total]}),rO(bo,{color:"gray",children:" \u2022 "}),GI(bo,{color:"green",children:[l.progress.percentage,"%"]})]})})]}),l.progress&&l.progress.total>0&&rO(Go,{marginLeft:2,children:rO(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 P8i=E(async()=>{await A6([eO(),Nqe()])});class u1n{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 N8i={};fi(N8i,{default:()=>j8i});import{useState as H1e,useCallback as O8i,useEffect as M8i,useMemo as mIc}from"react";import{jsx as a8,jsxs as F8i}from"react/jsx-runtime";function j8i({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=mIc(()=>new u1n,[]);M8i(()=>{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=O8i((P)=>{m(P)},[]);M8i(()=>(t(k),()=>{n()}),[t,n,k]);let C=O8i(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 F8i(Go,{flexDirection:"column",height:I,children:[a8(Go,{flexGrow:1,height:R,overflow:"hidden",children:a8(x8i,{messages:s,height:R,scrollOffset:x})}),h&&f.length>0&&a8(Go,{flexShrink:0,marginTop:1,marginBottom:1,children:a8(D8i,{progressEvents:f,maxLines:4})}),a8(Go,{flexShrink:0,marginTop:1,children:c?F8i(Go,{children:[a8(bo,{color:"green",children:a8(RSt,{type:"dots"})}),a8(bo,{color:"gray",children:" Processing..."})]}):a8(S8i,{onSubmit:C,isLoading:c,history:S})}),a8(Go,{flexShrink:0,marginTop:1,children:a8(T8i,{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 L8i=E(async()=>{await A6([eO(),KSn(),y8i(),k8i(),B8i(),P8i()])});var hIc,gIc,xIc,z8i;var q8i=E(()=>{_a();QH();tEn();YIi();hIc=uk({id:"cli",config:kEt,setup:(e)=>(If(e).logger.debug("CLI interface registered with AgentService"),QIi())}),gIc=NT(hIc,(e)=>{let{state:t}=e,n=If(e),{logger:r,messages:i}=n,o=JIi(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([eO().then(() => GRi),import("react"),L8i().then(() => N8i)]),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=Zze(["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()}}}}}),xIc=QJ(gIc,({state:e})=>({send:({message:t})=>{let n=typeof t==="string"?t:t.fallbackText??"";if(!n)return;(e.systemMessageCallback??e.responseCallback)?.(n)}})),z8i=xIc});import{jsx as ZI,jsxs as MD}from"react/jsx-runtime";function U8i({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 MD(Go,{flexDirection:"column",marginY:1,children:[ZI(Go,{marginBottom:1,children:MD(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&&MD(Go,{marginBottom:1,children:[ZI(bo,{color:"green",children:ZI(RSt,{type:"dots"})}),MD(bo,{color:"gray",children:[" ",s]})]}),t&&MD(Go,{flexDirection:"column",marginLeft:2,children:[f>0&&MD(Go,{children:[ZI(bo,{color:"green",children:"\u2713 "}),MD(bo,{color:"gray",children:[f," successful"]})]}),o>0&&MD(Go,{children:[ZI(bo,{color:"red",children:"\u2717 "}),MD(bo,{color:"gray",children:[o," failed"]})]}),a.length>0&&MD(Go,{flexDirection:"column",marginTop:1,children:[ZI(bo,{color:"red",bold:!0,children:"Errors:"}),a.slice(0,3).map((m,h)=>MD(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:MD(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 $8i=E(async()=>{await A6([eO(),KSn(),Nqe()])});var H8i={};fi(H8i,{BatchProgress:()=>U8i,ProgressBar:()=>yN,cliConfigSchema:()=>kEt,default:()=>z8i});var G8i=E(async()=>{q8i();tEn();await A6([Nqe(),$8i()])});var Z8i=j(function(mIf,yIc){yIc.exports={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.866",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 W8i(e){let[{default:t},{default:n}]=await Promise.all([G8i().then(() => H8i),Promise.resolve().then(() => yn(Z8i(),1))]);return lA(t,e??{},{name:n.name,version:n.version},{pluginId:"cli"})}var V8i=E(()=>{Ki()});function kde(e="admin"){return{interfaceType:"cli",actor:Lqe,userPermissionLevel:e}}var Lqe,zqe;var zSt=E(()=>{Lqe={kind:"service",serviceId:"brain-cli"},zqe=`${Lqe.kind}:${Lqe.serviceId}`});var bIc,qqe,Uqe;var qSt=E(()=>{oe();lt();bIc=u.enum(["eval"]),qqe=u.enum(["person","team","organization"]),Uqe=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 d1n,USt;var G1e=E(()=>{oe();Ki();ade();ade();qSt();qSt();d1n=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:d1n.optional(),logLevel:pk.optional(),logFile:u.string().optional(),profileKind:u.string().trim().min(1).optional(),plugins:u.array(KLe).default([]),spaces:u.array(u.string()).default([]),identity:G7e.optional(),agentInstructions:u.array(u.string()).optional(),deployment:Uqe.prefault({}),http:aX.prefault({})})});function AIc(){return process.env[vIc]}function p1n(){return AIc()==="production"}function K8i(){return!p1n()}var vIc="NODE_ENV";function EIc(){return Object.fromEntries(AI.map((e)=>[e,wIc]))}function Q8i(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 SIc(n),kIc(e,n),CIc(e,n,t),IIc(e,n),_Ic(e,n),TIc(e,n),BIc(e,n),RIc(e,n),PIc(e,n),DIc(e,n),n}function SIc(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??=VIi(),e.gitBrokerCheckout??=WIi()}function kIc(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function CIc(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&&EIc(),...t.ai?.providerKeys,...i},...o}}function IIc(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 _Ic(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((r)=>r.pattern===zqe)?n:[{pattern:zqe,level:"admin"},...n]}}function TIc(e,t){if(e.spaces)t.spaces=e.spaces}function BIc(e,t){if(e.identity)t.identity=e.identity}function RIc(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function DIc(e,t){t.http??={...Ar(e.http),port:e.deployment.ports.production}}function PIc(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=K8i(),t.production=p1n()}var wIc="startup-check";var f1n=E(()=>{ade();zSt();G1e();SEt()});var J8i={};fi(J8i,{App:()=>Z1e});class Z1e{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(e,t){return new Z1e(Q8i(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 Gze(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=Hze.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 W8i(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=Zze(["SIGINT"],t),i=Zze(["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 m1n=E(()=>{ade();ly();eEn();V8i();f1n();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 h1n=E(()=>{G1e()});var X8i={};fi(X8i,{aggregateUsage:()=>FIc,parseUsageLine:()=>Y8i});function Y8i(e){try{let t=MIc.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 FIc(e){let t=[];for(let o of e.trim().split(`
1175
1175
  `)){let s=Y8i(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 OIc,MIc;var e5i=E(()=>{oe();OIc=u.looseObject({operation:u.string(),provider:u.string(),model:u.string(),inputTokens:u.number(),outputTokens:u.number()}),MIc=u.looseObject({msg:u.literal("ai:usage"),ts:u.unknown().optional(),data:u.array(OIc).min(1)})});function jIc(e){process.on("uncaughtException",(t)=>{console.error(C4(`\u274C ${e} crashed:`),t),process.exit(1)}),process.on("unhandledRejection",(t)=>{console.error(C4(`\u274C ${e} unhandled rejection:`),t),process.exit(1)})}async function NIc(e){let{App:t}=await Promise.resolve().then(() => (m1n(),J8i));return jIc(e.name),{argv:process.argv.slice(2),env:process.env,log:console.log,error:console.error,exit:process.exit,app:t}}function t5i(e,t){let n=e.indexOf(t);return n!==-1?e[n+1]:void 0}function n5i(e,t,n){let r=t5i(e.argv,t);if(r===void 0)e.error(n),e.exit(1);return r}function g1n(e,t,n,r){let i=t5i(e,t);return i?r.parse(JSON.parse(i)):n}function i5i(e){return{...e,plugins:(e.plugins??[]).filter((t)=>t.type!=="interface"),http:{...e.http,enabled:!1}}}async function qIc(){let{ConsoleLogger:e}=await Promise.resolve().then(() => (ly(),unn));e.getInstance().setUseStderr(!0)}async function x1n(e,t,n){await qIc();let r=t.app.create(i5i(e));return await r.initialize(n),r}function UIc(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 M1n=E(()=>{N5i()});var KSt,z5i;var QSt=E(()=>{Su();l7e();Xc();oe();KSt=u.custom((e)=>hln.safeParse(e).success),z5i=u.custom((e)=>Cr(e)&&ZUr.safeParse(e).success)});function L_c(e){if(!e)return[];return Array.isArray(e)?e:[e]}class U5i{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){upn(e,this.packageName,ij(this.site),this.runtimeConfig);let t=(r)=>`${this.packageName}:${r}`,n=e.getDataSourceRegistry();for(let r of this.site.dataSources??[]){if(!opn(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 L_c(this.site.sections))e.registerTemplates(ght(r,{dataSourceId:t}),r.namespace);return{tools:[],resources:[]}}}function $5i(e,t,n,r=!1){if(!e||!r&&!Gqe(n,"site-builder"))return[];let i=[];if(e.sections||e.dataSources||ij(e)!==void 0)i.push(new U5i(t?.site?.package??"@rizom/site-package",e,{entityDisplay:e.entityDisplay,...w5i(t?.site)}));return i}function H_c(e,t){return t?zwe(e,t):e}function G_c(e,t){if(!t.site)return;let n=$_c.safeParse(e);if(!n.success)return;let{pluginConfig:r,...i}=n.data,o=_J(t.site,i);return H_c(o,r)}function Z_c(e,t,n){if(e===r2){let i=G_c(t,n);if(i)return i}let r=KSt.safeParse(t);return r.success?r.data:void 0}function H5i(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=Z_c(n,tG(n),e);if(r)return r;throw Error(`Package "${n}" is not a valid SitePackage`)}function q5i(e){if(nG(e)){let t=tG(e),n=xht.safeParse(t);if(!n.success)throw Error(`Package "${e}" does not export theme CSS`);return n.data}return e}function G5i(e,t,n){let r=t?.site?.theme?q5i(t.site.theme):e.theme,i=n?.themeOverride,o=t?.site?.themeOverride?q5i(t.site.themeOverride):void 0,s=[r,i,o].filter(Boolean).join(`
1731
1731
 
1732
1732
  `);if(!s)return;return VSt(s)}var z_c,q_c,U_c,$_c;var Z5i=E(()=>{Ki();M1n();oe();IX();QSt();Su();kX();P1n();z_c=u.looseObject({id:u.string().min(1)}),q_c=u.looseObject({label:u.string().min(1)}),U_c=u.looseObject({layouts:u.record(u.string(),u.unknown()).optional(),pluginConfig:u.record(u.string(),u.unknown()).optional(),routes:u.array(z_c).optional(),entityDisplay:u.record(u.string(),q_c).optional(),content:u.unknown().optional(),themeOverride:u.string().optional(),headScripts:u.array(u.string()).optional(),staticAssets:u.record(u.string(),u.string()).optional()}),$_c=u.custom((e)=>U_c.safeParse(e).success)});function W_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 V_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 K_c(e,t,n,r,i){let o=[];for(let[s,a,c]of e.capabilities){if(!Gqe(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(!Qht(h)||!Kht(h))throw h;i?.warn(`Skipping capability "${s}": missing required config`)}}return o}function Q_c(e,t,n,r,i){let o=[];for(let[s,a,c]of e.interfaces){if(!Gqe(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(!Qht(h)||!Kht(h))throw h;i?.warn(`Skipping interface "${s}": missing required config`)}}return o}function J_c(e){return e.identity?{name:e.identity.characterName,role:e.identity.role,purpose:e.identity.purpose,values:e.identity.values}:void 0}function Y_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 X_c(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 eTc(e,t){if(t.extra)Object.assign(e,t.extra)}function tTc(e,t){if(t?.enabled===void 0)return;e.shellConfig={...e.shellConfig,embedding:{...e.shellConfig?.embedding,enabled:t.enabled}}}function nTc(e,t){if(t===void 0)return;e.shellConfig={...e.shellConfig,themeCSS:t}}function rTc(e,t){if(!t)return;let n=e.shellConfig??{},r=n.entityDisplay??{};e.shellConfig={...n,entityDisplay:{...t.entityDisplay,...r}}}function iTc(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 oTc(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 sTc(e,t,n,r){iTc(e,n);let i=k5i(e,n);oTc(e,n,r);let o=i.activeIds,s=D5i(i.bundleDefinitions,i.resolution.permissionContributions),a=_5i(A5i(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??V_c(e,i,n),m=C5i(e,o,"site-builder"),h=H5i(e,n),g=G5i(e,n,h);W_c(a,{httpEnabled:f,site:h,theme:g,anchor:d,accountSettingsEncryptionKey:t.ACCOUNT_SETTINGS_ENCRYPTION_KEY});let x=[...$5i(h,n,o,i.bundleDefinitions.length===0),...K_c(e,t,i,a,r)],y=Q_c(e,t,i,a,r),v=J_c(e),w=Y_c(e,n),S=[...e.agentInstructions??[],...i.resolution.agentInstructions],k={name:n?.name??e.name,version:e.version,plugins:[...x,...y],ai:E5i(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}:{},...M5i(e.permissions,s,n,x),...n?.spaces?{spaces:n.spaces}:{},deployment:w,http:{...n?.http,enabled:f,preview:n?.http?.preview??m},...X_c(t,n)};return eTc(k,e),tTc(k,n?.embedding),nTc(k,g),rTc(k,h),HSt(k)}function W5i(e,t,n,r){let i=Ide(e)?WSt(e):e;return sTc(i,t,n,r)}var F1n=E(()=>{Ki();B1n();IX();S5i();h1n();G1e();P1n();I5i();T5i();P5i();j5i();Z5i()});import{existsSync as K5i,readFileSync as Q5i}from"fs";import{dirname as J5i,join as j1n}from"path";function aTc(e,t){return e===t||e.startsWith(`${t}/`)}function N1n(e){let t=J5i(e);return t===e?[e]:[e,...N1n(t)]}function e6i(e,t){return Object.freeze({name:e.name,version:e.version,dependencies:Object.freeze({...e.dependencies??{}}),peerDependencies:Object.freeze({...e.peerDependencies??{}}),directory:t})}function t6i(e){let t=N1n(e).find((o)=>K5i(j1n(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=j1n(t,"package.json"),r=JSON.parse(Q5i(n,"utf8")),i=Y5i.safeParse(r);if(!i.success)throw Error(`"${n}" must declare non-empty name and version fields`);return e6i(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 N1n(J5i(n))){let i=j1n(r,"package.json");if(!K5i(i))continue;let o=JSON.parse(Q5i(i,"utf8")),s=Y5i.safeParse(o);if(s.success&&aTc(e,s.data.name))return e6i(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 V5i(e,t){let n=e.peerDependencies["@rizom/brain"];if(!n||!Bun.semver.satisfies(t,n))throw new X5i(e,t,n)}function JSt(e,t){let n=sG(e,t);if(n.name==="@rizom/brain")return[];let r=sG("@rizom/brain",t);V5i(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)V5i(o,r.version);return i}var Y5i,X5i;var Zqe=E(()=>{oe();Y5i=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()});X5i=class X5i 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(()=>{F1n()});import{existsSync as L1n}from"fs";import{relative as cTc,sep as lTc}from"path";function z1n(e,t){let n=cTc(e,t).split(lTc).join("/");return n.startsWith(".")?n:`./${n}`}function uTc(e,t){return`import * as __pkg${t} from "${e}";`}function dTc(e,t){let n=e.version?`, { version: ${JSON.stringify(e.version)} }`:"";return`registerPackage("${e.ref}", __pkg${t}.default ?? __pkg${t}${n});`}function pTc(e){return{importLines:e.map(({ref:t},n)=>uTc(t,n)),registrationLines:e.map(dTc)}}function n6i(e,t){if(!t)return;try{return sG(e,t)}catch{return}}function fTc(e,t){if(!t||e==="@rizom/brain/model")return[];return JSt(e,t)}function mTc(e){let t=["resolve","handleCLI","parseInstanceOverrides"];if(e.hasRefs)t.push("registerPackage");if(e.hasConventions)t.push("applyConventionalSiteRefs","registerConventionalSitePackage");return t}function hTc(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 gTc(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(L1n(s)){let d=t.site?.package;o({packageRef:r2,importLine:`import __pkg${i} from "${z1n(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&&L1n(a))o({packageRef:iO,importLine:`import __pkg${i} from "${z1n(e,a)}" with { type: "text" };`,arg:`themeOverrideRef: "${iO}"`});let c=`${e}/src/site-content.ts`;if(t.plugins?.["site-content"]?.definitions===void 0&&L1n(c))o({packageRef:rG,importLine:`import __pkg${i} from "${z1n(e,c)}";`,arg:`siteContentDefinitionsRef: "${rG}"`});return r}function r6i(e,t={}){let n;try{n=_de(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=fTc(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=pTc(s.map((m)=>({ref:m,version:o.get(m)?.version??n6i(m,t.cwd)?.version}))),c=n6i(r,t.cwd),l=c?`registerPackage(${JSON.stringify(c.name)}, definition, { version: ${JSON.stringify(c.version)} });`:void 0,d=gTc(t.cwd,n,s.length),p=d.args.length>0,f=mTc({hasRefs:l!==void 0||s.length>0||d.registrations.length>0,hasConventions:p});return hTc({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 i6i=E(()=>{Zqe();YSt();IX()});async function o6i(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{}FD(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 s6i=E(()=>{YSt();kX();Zqe();ly()});async function a6i(e,t,n,r=xTc){let i=sG(e,n);FD(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`);FD(s.name,c??a,{version:s.version})}))}var xTc=async(e)=>import(e);var c6i=E(()=>{Ki();Zqe();kX()});import{existsSync as q1n,readFileSync as yTc}from"fs";import{join as U1n}from"path";import{pathToFileURL as l6i}from"url";function bTc(e,t){return t?zwe(e,t):e}function $1n(e,t){if(!t){FD(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,z5i.parse(i));FD(r2,bTc(o,r))}async function XSt(e,t){let n=t,r=U1n(e,"src/site.tsx");if(q1n(r)){let a=await import(l6i(r).href);if(a.default===void 0)throw Error(`Conventional site file ${r} must default-export a SitePackage or site overrides`);$1n(a.default,t.site?.package),n=Q1e(n,{sitePackageRef:r2})}let i=U1n(e,"src/theme.css");if(!t.site?.themeOverride&&q1n(i))FD(iO,yTc(i,"utf-8")),n=Q1e(n,{themeOverrideRef:iO});let o=U1n(e,"src/site-content.ts");if(n.plugins?.["site-content"]?.definitions===void 0&&q1n(o)){let a=await import(l6i(o).href);if(a.default===void 0)throw Error(`Conventional site-content file ${o} must default-export site content definitions`);FD(rG,a.default),n=Q1e(n,{siteContentDefinitionsRef:rG})}return n}var u6i=E(()=>{IX();Ki();kX();QSt();IX()});var Wqe={};fi(Wqe,{App:()=>Z1e,CLI_OPERATOR_ACTOR:()=>Lqe,CLI_OPERATOR_PRINCIPAL:()=>zqe,CONVENTIONAL_SITE_CONTENT_PACKAGE_REF:()=>rG,CONVENTIONAL_SITE_PACKAGE_REF:()=>r2,CONVENTIONAL_THEME_PACKAGE_REF:()=>iO,InstanceOverridesParseError:()=>K1e,MigrationManager:()=>Gze,SeedDataManager:()=>y1n,applyConventionalSiteRefs:()=>Q1e,brainAnchorConfigKindSchema:()=>qqe,buildShellConfig:()=>$St,collectOverridePackageRefs:()=>J1e,createCliOperatorContext:()=>kde,defineBrain:()=>ZSt,defineBundle:()=>WI,defineConfig:()=>HSt,deploymentConfigSchema:()=>Uqe,extendSite:()=>_J,findPackageManifest:()=>t6i,generateEntrypoint:()=>r6i,getPackage:()=>tG,getPackageMetadata:()=>x5i,handleCLI:()=>s5i,hasPackage:()=>nG,isConfiguredPluginDefinition:()=>GSt,isDeclarativeBrainDefinition:()=>Ide,isScopedPackageRef:()=>oG,logLevelSchema:()=>pk,normalizeDeclarativeBrainDefinition:()=>WSt,parseInstanceOverrides:()=>_de,pluginOverrideEntrySchema:()=>D1n,reasoningEffortSchema:()=>rR,registerBrainDefinitionPackages:()=>a6i,registerConventionalSitePackage:()=>$1n,registerConventionalSiteTheme:()=>XSt,registerOverridePackages:()=>o6i,registerPackage:()=>FD,resolve:()=>W5i,resolveBrainPackageName:()=>_X,resolveBundleSelection:()=>$qe,resolveStandardConfig:()=>wEt,resolveStandardConfigWithDirectories:()=>EEt,resolveStandardPaths:()=>y1e,use:()=>l5i});var bN=E(()=>{m1n();f1n();h1n();a5i();zSt();c5i();eEn();SEt();G1e();b1n();v1n();E1n();C1n();B1n();F1n();Zqe();kX();YSt();i6i();s6i();c6i();IX();u6i();QSt()});async function vTc(e){let{normalizeDeclarativeBrainDefinition:t}=await Promise.resolve().then(() => (bN(),Wqe)),n=t(e);return e.plugins.some(({definition:r})=>r.family==="interface")?{...n,http:!0}:n}function d6i(e){Tde=e}async function ATc(){if(!Tde)throw Error("Canonical brain definition is not registered");if(typeof Tde==="function")Tde=await Tde();return Tde}function e1t(){return Tde!==void 0}function wTc(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 ATc();let{isDeclarativeBrainDefinition:t,registerBrainDefinitionPackages:n}=await Promise.resolve().then(() => (bN(),Wqe)),i=(await import(e)).default;if(!wTc(i)&&!t(i))throw Error(`Brain definition package "${e}" has no valid default definition export`);return await n(e,i,process.cwd()),t(i)?vTc(i):i}var Tde;var t1t;var H1n=E(()=>{oe();t1t=u.object({type:u.literal("peer-event"),event:u.object({type:u.string(),payload:u.unknown()})})});var Z1n={};fi(Z1n,{bootBrain:()=>ETc,resetBootFn:()=>STc,setBootFn:()=>G1n});function G1n(e){n1t=e}async function ETc(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 STc(){n1t=void 0}var n1t;var mk="BRAIN_GIT_BROKER_SOCKET",aG="BRAIN_GIT_BROKER_CHECKOUT";import{tmpdir as kTc}from"os";import{join as W1n,resolve as f6i}from"path";function TX(e){return W1n(e,".brain-runtime")}function cG(e){let t=W1n(e,"git-broker.sock");if(Buffer.byteLength(t)<=CTc)return t;let n=_o(f6i(e)).slice(0,24);return W1n(kTc(),`brain-git-broker-${n}.sock`)}function X1e(e){return f6i(e.cwd,e.syncPath??e.dataDir)}var CTc=107;var Bde=E(()=>{Oo()});var r1t=E(()=>{Bde()});function m6i(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 ITc}from"child_process";function vN(e){let t=e.spawnImpl??ITc,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 h6i,Pw;var lG=E(()=>{h6i=process,Pw={env:process.env,kill:(e,t)=>t===void 0?process.kill(e):process.kill(e,t),on:(e,t)=>h6i.on(e,t),removeListener:(e,t)=>h6i.removeListener(e,t)}});function g6i(e,t){try{return e(-t,0),!1}catch(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ESRCH"}}function x6i(e,t,n){if(e)return{kind:"replace"};if(t>=n)return{kind:"give-up"};return{kind:"probe-again"}}function y6i(e,t,n){return e.filter((r)=>t-r<n)}function b6i(e,t){if(e===0)return 0;let n=Math.min(e-1,10);return t*2**n}function v6i(e,t){return e>=t}import{spawn as _Tc}from"child_process";function E6i(e,t=DTc){let n=t.setInterval(e,w6i);return()=>t.clearInterval(n)}function S6i(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 Vqe(e,t){return typeof e==="object"&&e!==null&&"type"in e&&e.type===t}function PTc(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 OTc(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 MTc(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:A6i,intervalMs:e.workerHeartbeatIntervalMs}),y(O,"SIGKILL")},e.workerHeartbeatIntervalMs*A6i)},w=(O,F=1)=>{if(n||r||o)return;let V=x6i(g6i((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=m6i(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=y6i(f,O,e.workerRestartWindowMs);if(f.length=0,f.push(...F),v6i(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=b6i(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(PTc(O,F)),S();return}if(O.role==="web"){k(OTc(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"&&Vqe(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"&&Vqe(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"&&Vqe(X,"runtime-ready")){if(Y.ready)return;Y.ready=!0,h(Y),e.reportReady(O),R();return}if(O==="worker"&&Vqe(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&&Vqe(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 k6i(e,t,n={}){return MTc({cwd:e,entrypointPath:t,spawnImpl:n.spawnImpl??_Tc,processImpl:n.processImpl??Pw,clock:n.clock??RTc,startupTimeoutMs:n.startupTimeoutMs??30000,shutdownGraceMs:n.shutdownGraceMs??15000,workerRestartBaseMs:n.workerRestartBaseMs??1000,workerRestartBudget:n.workerRestartBudget??3,workerRestartWindowMs:n.workerRestartWindowMs??3600000,workerHeartbeatIntervalMs:n.workerHeartbeatIntervalMs??w6i,brokerGroupProbeIntervalMs:n.brokerGroupProbeIntervalMs??TTc,brokerGroupProbeAttempts:n.brokerGroupProbeAttempts??BTc,gitBroker:n.gitBroker,reportIncident:n.reportIncident??((r)=>{console.error(JSON.stringify(r))}),reportReady:n.reportReady??((r)=>{console.log(`Brain ${r} runtime ready`)})})}var w6i=5000,A6i=3,TTc=500,BTc=20,RTc,DTc;var V1n=E(()=>{r1t();H1n();lG();RTc={now:Date.now,setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},DTc={setInterval:(e,t)=>setInterval(e,t),clearInterval:(e)=>clearInterval(e)}});var jD;var o1t=E(()=>{jD={name:"@rizom/brain",version:"0.2.0-alpha.865",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 F6i}from"fs";import{dirname as M6i,join as j6i}from"path";function Q1n(e){let t=e,n=M6i(t);while(t!==n){if(F6i(j6i(t,"bun.lock")))return t;t=n,n=M6i(t)}return}function BX(e){let t=Q1n(e);if(t){let n=j6i(t,"shell","app","src","runner.ts");if(F6i(n))return{path:n}}return}function tke(e){if(e1t())return"builtin";if(BX(e))return"monorepo";return}function Rde(e){return tke(e)==="monorepo"?BX(e):void 0}var s1t=()=>{};var L6i={};fi(L6i,{MCPClient:()=>N6i});import{Client as UTc,StreamableHTTPClientTransport as $Tc}from"@modelcontextprotocol/client";class N6i{client;transport;constructor(e,t){let n={};if(t)n.Authorization=`Bearer ${t}`;this.transport=new $Tc(new URL(e),{requestInit:{headers:n}}),this.client=new UTc({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 z6i=()=>{};var b1t=`ARG BUN_VERSION=1.4.0
1733
+ `)}function gTc(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(L1n(s)){let d=t.site?.package;o({packageRef:r2,importLine:`import __pkg${i} from "${z1n(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&&L1n(a))o({packageRef:iO,importLine:`import __pkg${i} from "${z1n(e,a)}" with { type: "text" };`,arg:`themeOverrideRef: "${iO}"`});let c=`${e}/src/site-content.ts`;if(t.plugins?.["site-content"]?.definitions===void 0&&L1n(c))o({packageRef:rG,importLine:`import __pkg${i} from "${z1n(e,c)}";`,arg:`siteContentDefinitionsRef: "${rG}"`});return r}function r6i(e,t={}){let n;try{n=_de(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=fTc(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=pTc(s.map((m)=>({ref:m,version:o.get(m)?.version??n6i(m,t.cwd)?.version}))),c=n6i(r,t.cwd),l=c?`registerPackage(${JSON.stringify(c.name)}, definition, { version: ${JSON.stringify(c.version)} });`:void 0,d=gTc(t.cwd,n,s.length),p=d.args.length>0,f=mTc({hasRefs:l!==void 0||s.length>0||d.registrations.length>0,hasConventions:p});return hTc({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 i6i=E(()=>{Zqe();YSt();IX()});async function o6i(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{}FD(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 s6i=E(()=>{YSt();kX();Zqe();ly()});async function a6i(e,t,n,r=xTc){let i=sG(e,n);FD(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`);FD(s.name,c??a,{version:s.version})}))}var xTc=async(e)=>import(e);var c6i=E(()=>{Ki();Zqe();kX()});import{existsSync as q1n,readFileSync as yTc}from"fs";import{join as U1n}from"path";import{pathToFileURL as l6i}from"url";function bTc(e,t){return t?zwe(e,t):e}function $1n(e,t){if(!t){FD(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,z5i.parse(i));FD(r2,bTc(o,r))}async function XSt(e,t){let n=t,r=U1n(e,"src/site.tsx");if(q1n(r)){let a=await import(l6i(r).href);if(a.default===void 0)throw Error(`Conventional site file ${r} must default-export a SitePackage or site overrides`);$1n(a.default,t.site?.package),n=Q1e(n,{sitePackageRef:r2})}let i=U1n(e,"src/theme.css");if(!t.site?.themeOverride&&q1n(i))FD(iO,yTc(i,"utf-8")),n=Q1e(n,{themeOverrideRef:iO});let o=U1n(e,"src/site-content.ts");if(n.plugins?.["site-content"]?.definitions===void 0&&q1n(o)){let a=await import(l6i(o).href);if(a.default===void 0)throw Error(`Conventional site-content file ${o} must default-export site content definitions`);FD(rG,a.default),n=Q1e(n,{siteContentDefinitionsRef:rG})}return n}var u6i=E(()=>{IX();Ki();kX();QSt();IX()});var Wqe={};fi(Wqe,{App:()=>Z1e,CLI_OPERATOR_ACTOR:()=>Lqe,CLI_OPERATOR_PRINCIPAL:()=>zqe,CONVENTIONAL_SITE_CONTENT_PACKAGE_REF:()=>rG,CONVENTIONAL_SITE_PACKAGE_REF:()=>r2,CONVENTIONAL_THEME_PACKAGE_REF:()=>iO,InstanceOverridesParseError:()=>K1e,MigrationManager:()=>Gze,SeedDataManager:()=>y1n,applyConventionalSiteRefs:()=>Q1e,brainAnchorConfigKindSchema:()=>qqe,buildShellConfig:()=>$St,collectOverridePackageRefs:()=>J1e,createCliOperatorContext:()=>kde,defineBrain:()=>ZSt,defineBundle:()=>WI,defineConfig:()=>HSt,deploymentConfigSchema:()=>Uqe,extendSite:()=>_J,findPackageManifest:()=>t6i,generateEntrypoint:()=>r6i,getPackage:()=>tG,getPackageMetadata:()=>x5i,handleCLI:()=>s5i,hasPackage:()=>nG,isConfiguredPluginDefinition:()=>GSt,isDeclarativeBrainDefinition:()=>Ide,isScopedPackageRef:()=>oG,logLevelSchema:()=>pk,normalizeDeclarativeBrainDefinition:()=>WSt,parseInstanceOverrides:()=>_de,pluginOverrideEntrySchema:()=>D1n,reasoningEffortSchema:()=>rR,registerBrainDefinitionPackages:()=>a6i,registerConventionalSitePackage:()=>$1n,registerConventionalSiteTheme:()=>XSt,registerOverridePackages:()=>o6i,registerPackage:()=>FD,resolve:()=>W5i,resolveBrainPackageName:()=>_X,resolveBundleSelection:()=>$qe,resolveStandardConfig:()=>wEt,resolveStandardConfigWithDirectories:()=>EEt,resolveStandardPaths:()=>y1e,use:()=>l5i});var bN=E(()=>{m1n();f1n();h1n();a5i();zSt();c5i();eEn();SEt();G1e();b1n();v1n();E1n();C1n();B1n();F1n();Zqe();kX();YSt();i6i();s6i();c6i();IX();u6i();QSt()});async function vTc(e){let{normalizeDeclarativeBrainDefinition:t}=await Promise.resolve().then(() => (bN(),Wqe)),n=t(e);return e.plugins.some(({definition:r})=>r.family==="interface")?{...n,http:!0}:n}function d6i(e){Tde=e}async function ATc(){if(!Tde)throw Error("Canonical brain definition is not registered");if(typeof Tde==="function")Tde=await Tde();return Tde}function e1t(){return Tde!==void 0}function wTc(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 ATc();let{isDeclarativeBrainDefinition:t,registerBrainDefinitionPackages:n}=await Promise.resolve().then(() => (bN(),Wqe)),i=(await import(e)).default;if(!wTc(i)&&!t(i))throw Error(`Brain definition package "${e}" has no valid default definition export`);return await n(e,i,process.cwd()),t(i)?vTc(i):i}var Tde;var t1t;var H1n=E(()=>{oe();t1t=u.object({type:u.literal("peer-event"),event:u.object({type:u.string(),payload:u.unknown()})})});var Z1n={};fi(Z1n,{bootBrain:()=>ETc,resetBootFn:()=>STc,setBootFn:()=>G1n});function G1n(e){n1t=e}async function ETc(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 STc(){n1t=void 0}var n1t;var mk="BRAIN_GIT_BROKER_SOCKET",aG="BRAIN_GIT_BROKER_CHECKOUT";import{tmpdir as kTc}from"os";import{join as W1n,resolve as f6i}from"path";function TX(e){return W1n(e,".brain-runtime")}function cG(e){let t=W1n(e,"git-broker.sock");if(Buffer.byteLength(t)<=CTc)return t;let n=_o(f6i(e)).slice(0,24);return W1n(kTc(),`brain-git-broker-${n}.sock`)}function X1e(e){return f6i(e.cwd,e.syncPath??e.dataDir)}var CTc=107;var Bde=E(()=>{Oo()});var r1t=E(()=>{Bde()});function m6i(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 ITc}from"child_process";function vN(e){let t=e.spawnImpl??ITc,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 h6i,Pw;var lG=E(()=>{h6i=process,Pw={env:process.env,kill:(e,t)=>t===void 0?process.kill(e):process.kill(e,t),on:(e,t)=>h6i.on(e,t),removeListener:(e,t)=>h6i.removeListener(e,t)}});function g6i(e,t){try{return e(-t,0),!1}catch(n){return typeof n==="object"&&n!==null&&"code"in n&&n.code==="ESRCH"}}function x6i(e,t,n){if(e)return{kind:"replace"};if(t>=n)return{kind:"give-up"};return{kind:"probe-again"}}function y6i(e,t,n){return e.filter((r)=>t-r<n)}function b6i(e,t){if(e===0)return 0;let n=Math.min(e-1,10);return t*2**n}function v6i(e,t){return e>=t}import{spawn as _Tc}from"child_process";function E6i(e,t=DTc){let n=t.setInterval(e,w6i);return()=>t.clearInterval(n)}function S6i(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 Vqe(e,t){return typeof e==="object"&&e!==null&&"type"in e&&e.type===t}function PTc(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 OTc(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 MTc(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:A6i,intervalMs:e.workerHeartbeatIntervalMs}),y(O,"SIGKILL")},e.workerHeartbeatIntervalMs*A6i)},w=(O,F=1)=>{if(n||r||o)return;let V=x6i(g6i((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=m6i(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=y6i(f,O,e.workerRestartWindowMs);if(f.length=0,f.push(...F),v6i(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=b6i(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(PTc(O,F)),S();return}if(O.role==="web"){k(OTc(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"&&Vqe(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"&&Vqe(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"&&Vqe(X,"runtime-ready")){if(Y.ready)return;Y.ready=!0,h(Y),e.reportReady(O),R();return}if(O==="worker"&&Vqe(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&&Vqe(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 k6i(e,t,n={}){return MTc({cwd:e,entrypointPath:t,spawnImpl:n.spawnImpl??_Tc,processImpl:n.processImpl??Pw,clock:n.clock??RTc,startupTimeoutMs:n.startupTimeoutMs??30000,shutdownGraceMs:n.shutdownGraceMs??15000,workerRestartBaseMs:n.workerRestartBaseMs??1000,workerRestartBudget:n.workerRestartBudget??3,workerRestartWindowMs:n.workerRestartWindowMs??3600000,workerHeartbeatIntervalMs:n.workerHeartbeatIntervalMs??w6i,brokerGroupProbeIntervalMs:n.brokerGroupProbeIntervalMs??TTc,brokerGroupProbeAttempts:n.brokerGroupProbeAttempts??BTc,gitBroker:n.gitBroker,reportIncident:n.reportIncident??((r)=>{console.error(JSON.stringify(r))}),reportReady:n.reportReady??((r)=>{console.log(`Brain ${r} runtime ready`)})})}var w6i=5000,A6i=3,TTc=500,BTc=20,RTc,DTc;var V1n=E(()=>{r1t();H1n();lG();RTc={now:Date.now,setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},DTc={setInterval:(e,t)=>setInterval(e,t),clearInterval:(e)=>clearInterval(e)}});var jD;var o1t=E(()=>{jD={name:"@rizom/brain",version:"0.2.0-alpha.866",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 F6i}from"fs";import{dirname as M6i,join as j6i}from"path";function Q1n(e){let t=e,n=M6i(t);while(t!==n){if(F6i(j6i(t,"bun.lock")))return t;t=n,n=M6i(t)}return}function BX(e){let t=Q1n(e);if(t){let n=j6i(t,"shell","app","src","runner.ts");if(F6i(n))return{path:n}}return}function tke(e){if(e1t())return"builtin";if(BX(e))return"monorepo";return}function Rde(e){return tke(e)==="monorepo"?BX(e):void 0}var s1t=()=>{};var L6i={};fi(L6i,{MCPClient:()=>N6i});import{Client as UTc,StreamableHTTPClientTransport as $Tc}from"@modelcontextprotocol/client";class N6i{client;transport;constructor(e,t){let n={};if(t)n.Authorization=`Bearer ${t}`;this.transport=new $Tc(new URL(e),{requestInit:{headers:n}}),this.client=new UTc({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 z6i=()=>{};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"
@@ -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=vgl.safeParse(JSON.parse(d.slice(6)));if(!y.success)continue;p=y.data}catch{return await dOn(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 dOn(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:ygl(a)}}}s=await ndo(r,t,n)}return{success:!1,error:"Stream ended without a terminal event"}}async function _gl(e,t,n,r,i){return lOn((o)=>e(t,{...n,signal:o}),{timeoutMs:r,onTimeout:()=>new fOn(r),signal:i})}async function ndo(e,t,n){try{return await lOn(()=>e.read(),{timeoutMs:t,onTimeout:()=>new $We(t),signal:n})}catch(r){if(r instanceof $We||n?.aborted)await dOn(e,r);throw r}}async function dOn(e,t){try{await e.cancel(t)}catch{}}function Tgl(e){if(e instanceof fOn||e instanceof $We)return!1;return e instanceof Error}function uOn(e,t){let n=t>1?` after ${t} attempts`:"";if(e instanceof $We)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??Agl,streamIdleTimeoutMs:t.streamIdleTimeoutMs??wgl,maxNetworkAttempts:t.maxNetworkAttempts??Egl},s=Cgl(e.agent),a=Ui(n.userPermissionLevel);if(!s.ok){let p=t.entityService?await Xuo(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&&!edo(c)){let p=await Xuo(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(!edo(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 tdo(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 tdo(d.card.url,e.message,r,t.requestSigner,o,i)}function ido(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:Sgl,visibility:"trusted",sideEffects:"external",handler:async(t,n)=>{let r=kgl.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 kkm,pOn,ggl,rdo,xgl,Ckm,Ikm,_km,Tkm,bgl,vgl,Agl=30000,wgl=60000,Egl=2,Sgl,kgl,fOn,$We;var mOn=E(()=>{oe();_a();Yuo();lt();v8t();kkm=u.object({kind:u.literal("text"),text:u.string()}),pOn=u.array(u.looseObject({kind:u.string()})),ggl=u.object({kind:u.literal("data"),data:u.object({sources:u.array(u.unknown())})}),rdo=u.looseObject({name:u.string().optional(),parts:pOn}),xgl=u.array(rdo);Ckm=u.object({error:u.object({message:u.string()})}),Ikm=u.object({kind:u.literal("message"),parts:pOn}),_km=u.object({kind:u.literal("task"),id:u.string().optional(),status:u.object({state:u.string(),message:u.object({parts:pOn}).optional()}),artifacts:xgl.optional()}),Tkm=u.object({result:u.unknown()}),bgl=u.looseObject({kind:u.string(),text:u.string().optional()}),vgl=u.looseObject({result:u.looseObject({kind:u.string().optional(),final:u.boolean().optional(),artifact:rdo.optional(),status:u.looseObject({state:u.string().optional(),message:u.looseObject({parts:u.array(bgl).optional()}).optional()}).optional()}).optional()}),Sgl={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")},kgl=u.object({agent:u.string(),message:u.string()});fOn=class fOn extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}};$We=class $We extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}});function sM(e,t){return{status:"refused",code:e,error:t}}async function odo(e,t,n){let r=e.trim().toLowerCase(),i=await n.entityService?.getEntity({entityType:"agent",id:r,visibilityScope:Ui("admin")});if(!i)return sM("agent_not_saved",`Agent ${r} is not saved.`);if(i.metadata.status==="archived")return sM("agent_archived",`Agent ${r} is archived.`);if(!await n.isContactApproved?.(r))return sM("agent_not_approved",`Agent ${r} is not approved yet. Approve it first.`);let{requestSigner:o}=n;if(!o)return sM("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??Bgl,c=await t2(r,{fetch:s,timeoutMs:a});if(!c.ok)return sM("agent_card_unavailable",c.error);if(!c.card.extensions.includes(PU))return sM("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 sM("peer_failed",Re(m,`${r} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return sM("peer_failed",`${r} answered HTTP ${p.status}`);let f=Rgl.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 sdo(e,t){let n=await odo(e.agent,{op:"list"},t);if(n.status!=="answered")return n;let r=n.data.map((i)=>mut.safeParse(i)).find((i)=>i.success)?.data;return r?{status:"found",entities:r.entities}:sM("unreadable_answer",`${n.agentId} did not answer with a list.`)}async function ado(e,t){let n=await odo(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)=>hut.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return sM("unreadable_answer",`${r} did not answer with the entity asked for.`);let a=sM("unverified",`${r} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ur(s.markdown))return a;try{if((await Euo(V4e(s),s.attestation.signature,s.attestation.keyId,new zWe({fetch:(l)=>i(l,{signal:AbortSignal.timeout(o)})}))).domain!==r)return a}catch{return a}return{status:"found",entity:s}}var Bgl=30000,Rgl;var cdo=E(()=>{lt();y8t();Oo();_a();oe();Rgl=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})})});function udo(e,t){let n="code"in e&&Dgl.has(e.code??"")?"permission_denied":"handler_failed",r="error"in e?e.error:t;return new gr(n,{publicMessage:Dse(r)})}function Pgl(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 ldo(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 udo(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 ddo(e,t,n={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(U4e,({request:{agent:r,question:i}})=>ldo(t,r,Pgl(i),n.networkAskTimeoutMs),w8t),e.answer($4e,({request:{agent:r,message:i}})=>ldo(t,r,i,n.turnTimeoutMs),w8t),e.answer(K4e,({request:r})=>ado(r,t),w8t),e.answer(Q4e,({request:r})=>sdo(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 udo(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 Dgl,w8t;var pdo=E(()=>{lt();cdo();_a();lt();mOn();Dgl=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);w8t={everyProcess:!0}});var mdo;var fdo=E(()=>{mdo={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.865",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 Fgl(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 vuo(r,i.privateJwk,i.keyId)}}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();return{keyId:i.keyId,signature:wuo(r,i.privateJwk)}}}function hOn(e,t,n){let r=Fgl(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 Ngl(e,t,n){if(!n.cardReady)return;return Muo({character:e.identity.get(),profile:e.identity.getProfile(),version:mdo.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 Lgl(e,t,n,r){let i=new URL(n.url),o=new URL(`${i.pathname}${i.search}`,r8(n)),s=await Auo({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 zgl(e,t,n){let r=new Tze,i=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await Ngl(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 juo(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 Lgl(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=Uuo.safeParse(c);if(!l.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(luo(o.req.raw.headers)){let p=l.data.method==="message/send"?uuo(l.data.params):void 0,f=p?.op==="list"?await fuo(e.entityReads,a.permissionLevel):await puo(e.entityReads,a.permissionLevel,p,jgl(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=Vuo.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=Kuo(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 Guo(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 gOn(e={}){let t=uk({id:"a2a",config:Puo,setup:(o)=>{let{config:s}=o,a=If(o),{servesHttp:c}=a,l=hOn(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new aOn,turnSupervisor:new cOn,jwksResolver:new zWe(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new oOn(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",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);ddo(s,hOn(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=zgl(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=()=>ido(hOn(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var Mgl,c_=(e)=>_1t(e,Mgl);var xOn=E(()=>{muo();lt();_a();QH();y8t();ZAn();Ouo();Fuo();Nuo();v8t();Luo();Juo();mOn();pdo();sOn();fdo();Mgl={"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 qgl,hdo;var gdo=E(()=>{xOn();xOn();qgl=gOn(),hdo=qgl});function E9(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 S9(e){return Ugl.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 Lfe(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 Ugl;var zfe=E(()=>{Ugl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"})});function bOn(e){let t=$gl[e];if(t)return t;let n=e.replaceAll(/[._-]+/g," ").trim();return n.length===0?e:np(n)}function ydo(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 bdo(e,t){return e?t.get(e)??"Former Admin":"System"}function vdo(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 Ado(e){let t=e.studio.source({definition:yOn,bind:(n)=>yOn.bind(n,{load:async({query:r})=>{let i=N8(e),o=r.get(vOn),[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(ydo),...s.selectedEvent?{selectedEvent:ydo(s.selectedEvent)}:{},users:E8t(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:bOn(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return dte(t,yOn.actions)}var $gl,vOn,xdo,Hgl,Ggl,yOn;var wdo=E(()=>{Zo();or();oe();zfe();$gl={"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"};vOn=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(E9,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(E9,u.number().int().min(1).max(100)).default(25)}),xdo=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()}),Hgl=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),Ggl=u.strictObject({query:vOn,events:u.array(xdo),selectedEvent:xdo.optional(),users:u.array(Hgl),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()});yOn=Sf({id:"audit",label:"Audit",priority:90,permission:"admin",query:vOn,data:Ggl,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:bOn(n.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:bdo(n.actorUserId,t)},{label:"Action",value:n.action},{label:"Target",value:vdo(n,t)},{label:"Occurred",value:S9(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:bOn(o.action),description:`${bdo(o.actorUserId,t)} \u2192 ${vdo(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 aM,S8t,k8t;var T8t=E(()=>{oe();aM=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 Zgl}from"crypto";function SOn(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 AOn(e,t){let n=SOn(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 Bdo(e,t){let n=SOn(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")?[AOn(e,"create-invitation-unavailable")]:[],i=SOn(e,"invitations");if(i.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=AOn(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,AOn(e,"invitation-filters"),i,{...o,presentation:"disclosure",blocks:[...o.blocks,n,...s]}]}}function Jgl(e){if(Wgl.has(e.state))return[];return[...e.deliveryAttemptId?[{action:_On,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:COn,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:Rdo}]:[],...e.state!=="expired"?[{action:IOn,input:{invitationId:e.id}}]:[]]}function kdo(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return np(e.state)}function Cdo(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 Ddo(e){let t=N8(e),n=new Map,r=e.studio.source({definition:wOn,bind:(i)=>{let o=EOn.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 Cdo(p)}),s=COn.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 Cdo(p)}),a=IOn.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=_On.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 wOn.bind(i,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(kOn),[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&&!Edo.has(k.invitation.state)),x=h.filter((k)=>k.invitation&&Edo.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:Zgl(),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,wOn.actions)}var Edo,Wgl,kOn,Ido,Vgl,_do,Kgl,Tdo,EOn,COn,IOn,_On,Sdo,Qgl,Rdo,wOn;var Pdo=E(()=>{Zo();T8t();or();oe();zfe();Edo=new Set(["claimed","expired","cancelled"]),Wgl=new Set(["claimed","cancelled"]),kOn=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(E9,u.number().int().min(0)).optional().default(0),limit:u.preprocess(E9,u.number().int().min(1).max(100)).optional().default(25)}),Ido=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),Vgl=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"])}),_do=u.strictObject({invitationId:u.string().min(1)}),Kgl=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),Tdo=u.strictObject({invitationId:u.string(),state:u.string()}),EOn=La({name:"create-invitation",label:"Add a person",permission:"admin",input:Vgl,output:Ido}),COn=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:_do,output:Ido}),IOn=La({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:_do,output:Tdo}),_On=La({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:Kgl,output:Tdo}),Sdo=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),Qgl=u.strictObject({query:kOn,idempotencyKey:u.string(),channels:u.array(k8t),invitations:u.array(Sdo),selectedInvitation:Sdo.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});Rdo=tTe("Invitation setup");wOn=Sf({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:kOn,data:Qgl,actions:[EOn,COn,IOn,_On],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:EOn,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:Rdo};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 ${kdo(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:kdo(i)},{label:"Destination",value:i.destination},{label:"Updated",value:S9(i.updatedAt)}]},{type:"actions",id:"invitation-actions",items:Jgl(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 POn(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 Odo(e){let t=N8(e),n=e.studio.source({definition:TOn,bind:(r)=>{let i=BOn.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=ROn.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 TOn.bind(r,{actions:[i,o],load:async({query:s})=>{let a=s.get(DOn),[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,TOn.actions)}var DOn,Ygl,Xgl,BOn,ROn,e0l,t0l,TOn;var Mdo=E(()=>{Zo();or();oe();T8t();zfe();DOn=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),Ygl=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"])}),Xgl=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),BOn=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:Ygl,output:S8t}),ROn=La({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:Xgl,output:aM}),e0l=u.strictObject({query:DOn,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)});t0l=tTe("Peer invitation setup"),TOn=Sf({id:"peers",label:"Peers",priority:12,permission:"admin",query:DOn,data:e0l,actions:[BOn,ROn],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:BOn,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:t0l}]});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:ROn,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:Lfe(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:S9(r.createdAt)},compact:{title:Lfe(r.peerId),metadata:[r.displayName,np(r.role),S9(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 OOn(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 Fdo(e,t,n){let r=OOn(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let i=OOn(e,"people");if(i.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=OOn(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 i0l(e){return e.revokedAt===void 0&&e.type!=="passkey"}function o0l(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}function f0l(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function MOn(e){return{type:"notice",tone:"warn",text:e}}function m0l(e){return{type:"action",action:ZOn,input:{userId:e},result:p0l}}function h0l(e,t){return{type:"action",action:WOn,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 g0l(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 x0l(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function jdo(e){let t=N8(e),n=e.studio.source({definition:FOn,bind:(r)=>{let i=jOn.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=NOn.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=LOn.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=zOn.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=ZOn.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=qOn.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=WOn.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=UOn.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=$On.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 FOn.bind(r,{actions:[i,o,s,a,c,l,d,p,f],load:async({query:m,caller:h})=>{let g=m.get(HOn),[x,y,v]=await Promise.all([x0l(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??g0l(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:o0l(R),createdAt:R.createdAt})),identities:B.identities.filter(i0l).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,FOn.actions)}var HOn,GOn,n0l,r0l,s0l,a0l,c0l,l0l,jOn,NOn,LOn,zOn,ZOn,qOn,WOn,UOn,$On,u0l,d0l,p0l,FOn;var Ndo=E(()=>{Zo();or();oe();T8t();zfe();HOn=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),GOn=u.strictObject({userId:u.string().min(1)}),n0l=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),r0l=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});s0l=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),a0l=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()}),c0l=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),l0l=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),jOn=La({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:n0l,output:aM}),NOn=La({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:r0l,output:aM}),LOn=La({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:GOn,output:aM}),zOn=La({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:s0l,output:aM}),ZOn=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:GOn,output:S8t}),qOn=La({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:GOn,output:aM}),WOn=La({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:a0l,output:aM}),UOn=La({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:c0l,output:aM}),$On=La({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:l0l,output:aM}),u0l=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"])}))}),d0l=u.strictObject({query:HOn,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(u0l),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()}))}),p0l=tTe("Passkey setup");FOn=Sf({id:"people",label:"People",priority:10,permission:"admin",query:HOn,data:d0l,actions:[jOn,NOn,LOn,zOn,ZOn,qOn,WOn,UOn,$On],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:jOn,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:NOn,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},...t.status==="active"&&!t.isSelf?[{action:qOn,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:LOn,input:{userId:t.userId}}]:[]]},...t.isSelf?[f0l()]:[],...s&&t.status==="active"?[MOn(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:S9(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${S9(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:zOn,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[m0l(t.userId)]:[MOn("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:UOn,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[h0l(t.userId,e.channelTypes)]:[MOn("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:Lfe(a.peerId),description:`Vouched in by ${Lfe(a.peerId)} \xB7 ${a.peerId}`,metadata:[np(a.verificationStatus)],actions:[{action:$On,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 ${Lfe(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 b0l(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function v0l(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 A0l(e,t){if(!v0l(e))throw Error(`${t} tab returned invalid workspace data`);return e}function Ldo(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 VOn(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function HWe(e,t,n,r){return A0l(await e.dataProvider(t,n,r),e.label)}async function w0l(e,t,n,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,n,r)}function E0l(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 zdo(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 S0l(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 qdo(e){if(!e.studio.isAvailable())return;let t=jdo(e),n=Ddo(e),r=Odo(e),i=Ado(e),o=E0l([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:l3,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=y0l.parse(p??{}),h,g=VOn("People"),x=VOn("Invitations"),y=VOn("Audit");if(m.tab==="people"){let[v,w]=await Promise.all([HWe(s,d,{...m.selected?{selected:m.selected}:{}},f),HWe(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=POn(w.view.blocks);g=[...Fdo(Ldo(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([HWe(a,d,{...m.state?{state:m.state}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f),HWe(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=POn(w.view.blocks),k=Bdo(v.view.blocks,S.invitations);h=v.view.primaryAction,x=[...k.blocks]}else{let v=await HWe(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=Ldo(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=b0l(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 w0l(h,d,p,f)},badgeProvider:async()=>{let d=zdo(await N8(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>S0l(zdo(await N8(e).listAdminUsers()))})}var y0l;var Udo=E(()=>{wn();lt();oe();wdo();Pdo();Mdo();Ndo();zfe();y0l=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(E9,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(E9,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 _0l(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+k0l)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 Hdo(e,t){t.throwIfAborted();let n=await N8(e).listAdminUsers();return t.throwIfAborted(),_0l(n,Date.now())}var k0l=259200000,C0l,I0l,$do;var Gdo=E(()=>{Zo();zfe();C0l=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),I0l=u.strictObject({invitations:u.array(C0l),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),$do=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:I0l,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 ${S9(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})})});var T0l,B0l,KOn;var Zdo=E(()=>{Zo();wn();Udo();Gdo();T0l=u.strictObject({}),B0l=$i({id:"admin",config:T0l},{subscriptions:(e)=>{let t=ni(e);return t.registered(async()=>{await qdo(t)}),[]},dashboardWidgets:(e)=>{let t=ni(e);return[$do.bind(e,({signal:n})=>Hdo(t,n))]}}),KOn=B0l});var Wdo=E(()=>{Zdo()});var Jr=E(()=>{oe();Ki();Ki()});var Du="agent",Vdo="agent-network",Kdo="agent-proximity",QOn="agent-discovery:entities",Qdo="agent-discovery:proximity-map",JOn="proximity-map",YOn="agent-list",XOn="agent-detail",Gw="skill",Jdo=30,Ydo=120,D8t="skill-derivation",Xdo="skill-derivation",eMn="skill:skill-derivation",epo="skills";var R0l,tMn,pte,GWe,fte;var _L=E(()=>{oe();_n();R0l=u.string().trim().min(1).max(Ydo),tMn=u.array(R0l).max(Jdo),pte=u.object({name:u.string(),description:u.string(),tags:tMn,examples:u.array(u.string())}),GWe=pte,fte=Qp.extend({entityType:u.literal(Gw),metadata:GWe})});var P8t,kZ,D0l,cM,ZWe,Op,P0l,WWe,O0l,M0l;var Zw=E(()=>{oe();_L();wn();_n();P8t=u.object({name:u.string(),description:u.string(),tags:tMn}),kZ=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),D0l=HH,cM=u.object({name:u.string(),kind:D0l,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"})}),ZWe=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:ZWe}),P0l=Vs.extend({entityType:u.literal(Du),metadata:ZWe}),WWe=P0l.extend({frontmatter:cM,about:u.string(),skills:u.array(P8t),notes:u.string()}),O0l=WWe.extend({url:u.string().optional(),typeLabel:u.string().optional()}),M0l=WWe.extend({url:u.string(),typeLabel:u.string()})});function j0l(e){try{return As(e,F0l).content}catch{return e}}function nMn(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:$Ae(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 tpo(e){return lh(Du,e,cM)}function VWe(e){return{content:e,metadata:nMn(tpo(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 KWe(e){return r1e(j0l(e))}function Ux(e){return{frontmatter:tpo(e.content),body:KWe(e.content)}}function rMn(e){return na("",e)}var F0l;var Rk=E(()=>{wn();_n();or();oe();Zw();_L();F0l=u.record(u.string(),u.unknown())});function N0l(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function npo(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=KWe(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(N0l).slice(0,i)}function rpo(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 udo(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 Dgl,w8t;var pdo=E(()=>{lt();cdo();_a();lt();mOn();Dgl=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);w8t={everyProcess:!0}});var mdo;var fdo=E(()=>{mdo={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.866",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 Fgl(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 vuo(r,i.privateJwk,i.keyId)}}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();return{keyId:i.keyId,signature:wuo(r,i.privateJwk)}}}function hOn(e,t,n){let r=Fgl(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 Ngl(e,t,n){if(!n.cardReady)return;return Muo({character:e.identity.get(),profile:e.identity.getProfile(),version:mdo.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 Lgl(e,t,n,r){let i=new URL(n.url),o=new URL(`${i.pathname}${i.search}`,r8(n)),s=await Auo({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 zgl(e,t,n){let r=new Tze,i=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await Ngl(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 juo(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 Lgl(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=Uuo.safeParse(c);if(!l.success)return c_(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(luo(o.req.raw.headers)){let p=l.data.method==="message/send"?uuo(l.data.params):void 0,f=p?.op==="list"?await fuo(e.entityReads,a.permissionLevel):await puo(e.entityReads,a.permissionLevel,p,jgl(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=Vuo.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=Kuo(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 Guo(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 gOn(e={}){let t=uk({id:"a2a",config:Puo,setup:(o)=>{let{config:s}=o,a=If(o),{servesHttp:c}=a,l=hOn(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new aOn,turnSupervisor:new cOn,jwksResolver:new zWe(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new oOn(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",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);ddo(s,hOn(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=zgl(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=()=>ido(hOn(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var Mgl,c_=(e)=>_1t(e,Mgl);var xOn=E(()=>{muo();lt();_a();QH();y8t();ZAn();Ouo();Fuo();Nuo();v8t();Luo();Juo();mOn();pdo();sOn();fdo();Mgl={"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 qgl,hdo;var gdo=E(()=>{xOn();xOn();qgl=gOn(),hdo=qgl});function E9(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 S9(e){return Ugl.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 Lfe(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 Ugl;var zfe=E(()=>{Ugl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"})});function bOn(e){let t=$gl[e];if(t)return t;let n=e.replaceAll(/[._-]+/g," ").trim();return n.length===0?e:np(n)}function ydo(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 bdo(e,t){return e?t.get(e)??"Former Admin":"System"}function vdo(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 Ado(e){let t=e.studio.source({definition:yOn,bind:(n)=>yOn.bind(n,{load:async({query:r})=>{let i=N8(e),o=r.get(vOn),[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(ydo),...s.selectedEvent?{selectedEvent:ydo(s.selectedEvent)}:{},users:E8t(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:bOn(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return dte(t,yOn.actions)}var $gl,vOn,xdo,Hgl,Ggl,yOn;var wdo=E(()=>{Zo();or();oe();zfe();$gl={"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"};vOn=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(E9,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(E9,u.number().int().min(1).max(100)).default(25)}),xdo=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()}),Hgl=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),Ggl=u.strictObject({query:vOn,events:u.array(xdo),selectedEvent:xdo.optional(),users:u.array(Hgl),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()});yOn=Sf({id:"audit",label:"Audit",priority:90,permission:"admin",query:vOn,data:Ggl,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:bOn(n.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:bdo(n.actorUserId,t)},{label:"Action",value:n.action},{label:"Target",value:vdo(n,t)},{label:"Occurred",value:S9(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:bOn(o.action),description:`${bdo(o.actorUserId,t)} \u2192 ${vdo(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 aM,S8t,k8t;var T8t=E(()=>{oe();aM=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 Zgl}from"crypto";function SOn(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 AOn(e,t){let n=SOn(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 Bdo(e,t){let n=SOn(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")?[AOn(e,"create-invitation-unavailable")]:[],i=SOn(e,"invitations");if(i.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=AOn(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,AOn(e,"invitation-filters"),i,{...o,presentation:"disclosure",blocks:[...o.blocks,n,...s]}]}}function Jgl(e){if(Wgl.has(e.state))return[];return[...e.deliveryAttemptId?[{action:_On,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:COn,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:Rdo}]:[],...e.state!=="expired"?[{action:IOn,input:{invitationId:e.id}}]:[]]}function kdo(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return np(e.state)}function Cdo(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 Ddo(e){let t=N8(e),n=new Map,r=e.studio.source({definition:wOn,bind:(i)=>{let o=EOn.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 Cdo(p)}),s=COn.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 Cdo(p)}),a=IOn.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=_On.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 wOn.bind(i,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(kOn),[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&&!Edo.has(k.invitation.state)),x=h.filter((k)=>k.invitation&&Edo.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:Zgl(),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,wOn.actions)}var Edo,Wgl,kOn,Ido,Vgl,_do,Kgl,Tdo,EOn,COn,IOn,_On,Sdo,Qgl,Rdo,wOn;var Pdo=E(()=>{Zo();T8t();or();oe();zfe();Edo=new Set(["claimed","expired","cancelled"]),Wgl=new Set(["claimed","cancelled"]),kOn=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(E9,u.number().int().min(0)).optional().default(0),limit:u.preprocess(E9,u.number().int().min(1).max(100)).optional().default(25)}),Ido=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),Vgl=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"])}),_do=u.strictObject({invitationId:u.string().min(1)}),Kgl=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),Tdo=u.strictObject({invitationId:u.string(),state:u.string()}),EOn=La({name:"create-invitation",label:"Add a person",permission:"admin",input:Vgl,output:Ido}),COn=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:_do,output:Ido}),IOn=La({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:_do,output:Tdo}),_On=La({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:Kgl,output:Tdo}),Sdo=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),Qgl=u.strictObject({query:kOn,idempotencyKey:u.string(),channels:u.array(k8t),invitations:u.array(Sdo),selectedInvitation:Sdo.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});Rdo=tTe("Invitation setup");wOn=Sf({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:kOn,data:Qgl,actions:[EOn,COn,IOn,_On],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:EOn,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:Rdo};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 ${kdo(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:kdo(i)},{label:"Destination",value:i.destination},{label:"Updated",value:S9(i.updatedAt)}]},{type:"actions",id:"invitation-actions",items:Jgl(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 POn(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 Odo(e){let t=N8(e),n=e.studio.source({definition:TOn,bind:(r)=>{let i=BOn.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=ROn.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 TOn.bind(r,{actions:[i,o],load:async({query:s})=>{let a=s.get(DOn),[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,TOn.actions)}var DOn,Ygl,Xgl,BOn,ROn,e0l,t0l,TOn;var Mdo=E(()=>{Zo();or();oe();T8t();zfe();DOn=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),Ygl=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"])}),Xgl=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),BOn=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:Ygl,output:S8t}),ROn=La({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:Xgl,output:aM}),e0l=u.strictObject({query:DOn,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)});t0l=tTe("Peer invitation setup"),TOn=Sf({id:"peers",label:"Peers",priority:12,permission:"admin",query:DOn,data:e0l,actions:[BOn,ROn],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:BOn,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:t0l}]});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:ROn,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:Lfe(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:S9(r.createdAt)},compact:{title:Lfe(r.peerId),metadata:[r.displayName,np(r.role),S9(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 OOn(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 Fdo(e,t,n){let r=OOn(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let i=OOn(e,"people");if(i.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=OOn(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 i0l(e){return e.revokedAt===void 0&&e.type!=="passkey"}function o0l(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}function f0l(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function MOn(e){return{type:"notice",tone:"warn",text:e}}function m0l(e){return{type:"action",action:ZOn,input:{userId:e},result:p0l}}function h0l(e,t){return{type:"action",action:WOn,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 g0l(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 x0l(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function jdo(e){let t=N8(e),n=e.studio.source({definition:FOn,bind:(r)=>{let i=jOn.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=NOn.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=LOn.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=zOn.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=ZOn.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=qOn.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=WOn.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=UOn.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=$On.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 FOn.bind(r,{actions:[i,o,s,a,c,l,d,p,f],load:async({query:m,caller:h})=>{let g=m.get(HOn),[x,y,v]=await Promise.all([x0l(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??g0l(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:o0l(R),createdAt:R.createdAt})),identities:B.identities.filter(i0l).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,FOn.actions)}var HOn,GOn,n0l,r0l,s0l,a0l,c0l,l0l,jOn,NOn,LOn,zOn,ZOn,qOn,WOn,UOn,$On,u0l,d0l,p0l,FOn;var Ndo=E(()=>{Zo();or();oe();T8t();zfe();HOn=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),GOn=u.strictObject({userId:u.string().min(1)}),n0l=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),r0l=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});s0l=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),a0l=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()}),c0l=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),l0l=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),jOn=La({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:n0l,output:aM}),NOn=La({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:r0l,output:aM}),LOn=La({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:GOn,output:aM}),zOn=La({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:s0l,output:aM}),ZOn=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:GOn,output:S8t}),qOn=La({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:GOn,output:aM}),WOn=La({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:a0l,output:aM}),UOn=La({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:c0l,output:aM}),$On=La({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:l0l,output:aM}),u0l=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"])}))}),d0l=u.strictObject({query:HOn,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(u0l),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()}))}),p0l=tTe("Passkey setup");FOn=Sf({id:"people",label:"People",priority:10,permission:"admin",query:HOn,data:d0l,actions:[jOn,NOn,LOn,zOn,ZOn,qOn,WOn,UOn,$On],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:jOn,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:NOn,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},...t.status==="active"&&!t.isSelf?[{action:qOn,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:LOn,input:{userId:t.userId}}]:[]]},...t.isSelf?[f0l()]:[],...s&&t.status==="active"?[MOn(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:S9(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${S9(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:zOn,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[m0l(t.userId)]:[MOn("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:UOn,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[h0l(t.userId,e.channelTypes)]:[MOn("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:Lfe(a.peerId),description:`Vouched in by ${Lfe(a.peerId)} \xB7 ${a.peerId}`,metadata:[np(a.verificationStatus)],actions:[{action:$On,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 ${Lfe(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 b0l(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function v0l(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 A0l(e,t){if(!v0l(e))throw Error(`${t} tab returned invalid workspace data`);return e}function Ldo(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 VOn(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function HWe(e,t,n,r){return A0l(await e.dataProvider(t,n,r),e.label)}async function w0l(e,t,n,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,n,r)}function E0l(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 zdo(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 S0l(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 qdo(e){if(!e.studio.isAvailable())return;let t=jdo(e),n=Ddo(e),r=Odo(e),i=Ado(e),o=E0l([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:l3,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=y0l.parse(p??{}),h,g=VOn("People"),x=VOn("Invitations"),y=VOn("Audit");if(m.tab==="people"){let[v,w]=await Promise.all([HWe(s,d,{...m.selected?{selected:m.selected}:{}},f),HWe(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=POn(w.view.blocks);g=[...Fdo(Ldo(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([HWe(a,d,{...m.state?{state:m.state}:{},...m.selected?{selected:m.selected}:{},...Ar({offset:m.offset,limit:m.limit})},f),HWe(c,d,{...m.peerId?{peerId:m.peerId}:{},...m.displayName?{displayName:m.displayName}:{}},f)]),S=POn(w.view.blocks),k=Bdo(v.view.blocks,S.invitations);h=v.view.primaryAction,x=[...k.blocks]}else{let v=await HWe(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=Ldo(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=b0l(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 w0l(h,d,p,f)},badgeProvider:async()=>{let d=zdo(await N8(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>S0l(zdo(await N8(e).listAdminUsers()))})}var y0l;var Udo=E(()=>{wn();lt();oe();wdo();Pdo();Mdo();Ndo();zfe();y0l=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(E9,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(E9,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 _0l(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+k0l)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 Hdo(e,t){t.throwIfAborted();let n=await N8(e).listAdminUsers();return t.throwIfAborted(),_0l(n,Date.now())}var k0l=259200000,C0l,I0l,$do;var Gdo=E(()=>{Zo();zfe();C0l=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),I0l=u.strictObject({invitations:u.array(C0l),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),$do=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:I0l,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 ${S9(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})})});var T0l,B0l,KOn;var Zdo=E(()=>{Zo();wn();Udo();Gdo();T0l=u.strictObject({}),B0l=$i({id:"admin",config:T0l},{subscriptions:(e)=>{let t=ni(e);return t.registered(async()=>{await qdo(t)}),[]},dashboardWidgets:(e)=>{let t=ni(e);return[$do.bind(e,({signal:n})=>Hdo(t,n))]}}),KOn=B0l});var Wdo=E(()=>{Zdo()});var Jr=E(()=>{oe();Ki();Ki()});var Du="agent",Vdo="agent-network",Kdo="agent-proximity",QOn="agent-discovery:entities",Qdo="agent-discovery:proximity-map",JOn="proximity-map",YOn="agent-list",XOn="agent-detail",Gw="skill",Jdo=30,Ydo=120,D8t="skill-derivation",Xdo="skill-derivation",eMn="skill:skill-derivation",epo="skills";var R0l,tMn,pte,GWe,fte;var _L=E(()=>{oe();_n();R0l=u.string().trim().min(1).max(Ydo),tMn=u.array(R0l).max(Jdo),pte=u.object({name:u.string(),description:u.string(),tags:tMn,examples:u.array(u.string())}),GWe=pte,fte=Qp.extend({entityType:u.literal(Gw),metadata:GWe})});var P8t,kZ,D0l,cM,ZWe,Op,P0l,WWe,O0l,M0l;var Zw=E(()=>{oe();_L();wn();_n();P8t=u.object({name:u.string(),description:u.string(),tags:tMn}),kZ=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),D0l=HH,cM=u.object({name:u.string(),kind:D0l,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"})}),ZWe=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:ZWe}),P0l=Vs.extend({entityType:u.literal(Du),metadata:ZWe}),WWe=P0l.extend({frontmatter:cM,about:u.string(),skills:u.array(P8t),notes:u.string()}),O0l=WWe.extend({url:u.string().optional(),typeLabel:u.string().optional()}),M0l=WWe.extend({url:u.string(),typeLabel:u.string()})});function j0l(e){try{return As(e,F0l).content}catch{return e}}function nMn(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:$Ae(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 tpo(e){return lh(Du,e,cM)}function VWe(e){return{content:e,metadata:nMn(tpo(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 KWe(e){return r1e(j0l(e))}function Ux(e){return{frontmatter:tpo(e.content),body:KWe(e.content)}}function rMn(e){return na("",e)}var F0l;var Rk=E(()=>{wn();_n();or();oe();Zw();_L();F0l=u.record(u.string(),u.unknown())});function N0l(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function npo(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=KWe(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(N0l).slice(0,i)}function rpo(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 qfe=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:$Ae(e.url)},anchorName:n}}var O8t=E(()=>{Rk();or();qfe()});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 ipo(e){return{input:L0l,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 L0l;var opo=E(()=>{wn();oe();O8t();L0l=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 iMn(e){let t=Op.parse(e),n=q0l(t);return n?{entity:t,parsed:n}:void 0}function cpo(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:n})=>(await n.list()).flatMap((r)=>{let i=iMn(r);return i?[i]:[]}).sort((r,i)=>i.parsed.frontmatter.discoveredAt.localeCompare(r.parsed.frontmatter.discoveredAt)).slice(0,z0l).map(({entity:r,parsed:i})=>U0l(r,i)),resolveDetail:async(n,{records:r,signal:i})=>{i.throwIfAborted();let o=iMn(await r.get(n));if(i.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=H0l(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,spo),truncated:s.length>spo}},act:async(n,r,{records:i,edits:o})=>{if(r!==oMn&&r!==apo)throw Error("Invalid agent sighting Inbox action");let s=await i.get(n),a=s?iMn(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=r===oMn?"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 q0l(e){let t=Ux(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function U0l(e,t){let n=lM(t.frontmatter.name),r=lM(e.id),i=lpo(n===r?n:`${n} \xB7 ${r}`,160);return{id:e.id,title:i,summary:$0l(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Du,entityId:e.id},actions:[{id:oMn,label:"Connect",confirm:!0},{id:apo,label:"Dismiss",confirm:!0}]}}function $0l(e){let t=e.frontmatter.introducedBy??[],n=`Introduced by ${sMn(t.map(lM))}.`,r=lM(e.body.about),i=e.body.skills.map((s)=>lM(s.name)).filter(Boolean).slice(0,4),o=i.length>0?` Declared skills: ${sMn(i)}.`:"";return lpo(`${n}${r?` ${r}`:""}${o}`,1000)}function H0l(e,t){let n=[`Agent: ${lM(t.frontmatter.name)}`,`Domain: ${lM(e.id)}`,`Introduced by: ${sMn((t.frontmatter.introducedBy??[]).map(lM))}`],r=lM(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=lM(i.description);return`- ${lM(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 MPd="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 vbr=E(()=>{rot();lt();Jr();_n();dbr();mbr();QHt();wea();VHt();rot();bbr();sDe=uu(xgt(Vr({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:ZHt,markdown:WHt,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:MPd,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:pbr(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:ybr},generation:fbr,create:{fromUpload:Aea},jobs:{"upload-import":vea(()=>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:ubr}),[ggt(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 FPd,Sea;var kea=E(()=>{Jr();lbr();vbr();vbr();dbr();rot();lbr();mbr();QHt();bbr();FPd=qc({id:"note",config:cbr,entities:[sDe]}),Sea=FPd});var jPd,NPd,LPd,Cea;var Iea=E(()=>{lt();Zo();wn();jPd=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),NPd=u.looseObject({defaultRecipient:jPd.or(_ut).optional()}),LPd=$i({id:"notifications",config:NPd},{subscriptions:(e)=>{let{config:t}=e,n=ni(e),{logger:r}=n;return n.answer(v4,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=Tut.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}),[]}}),Cea=LPd});function HPd(e){return e.toLowerCase().includes("no data found for this memberid")}function GPd(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 iot{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===_ea)throw Error(`LinkedIn snapshot exceeded ${_ea} 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,GPd(r,t),n+1)]}async fetchPage(e,t){let n=new URL(`${qPd}/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":UPd}});if(r.ok)return zPd.parse(await r.json());let i=await r.text();if(r.status<500&&HPd(i))return null;throw new JHt(r.status,i.slice(0,$Pd))}}var Tea,zPd,qPd="https://api.linkedin.com/rest",UPd="202312",_ea=1000,$Pd=1000,JHt;var oot=E(()=>{oe();Tea=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],zPd=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()});JHt=class JHt extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}});class Abr{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:ZPd})}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 wbr(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var ZPd;var Ebr=E(()=>{Zo();oe();ZPd=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 YPd(e){try{return await e.json()}catch{return null}}class sot{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(WPd);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",Bea),t}async exchange(e,t){let n=await this.fetchFn(VPd,{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 YPd(n);if(!n.ok){let o=JPd.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,KPd)}`:""}`)}let i=QPd.parse(r);if(i.scope!==void 0&&i.scope!==Bea)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 Rea(e){return new KJ({...Wgt,now:e})}var WPd="https://www.linkedin.com/oauth/v2/authorization",VPd="https://www.linkedin.com/oauth/v2/accessToken",Bea="r_dma_portability_3rd_party",KPd=500,QPd,JPd;var Sbr=E(()=>{Vgt();oe();QPd=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),JPd=u.looseObject({error:u.string().optional(),error_description:u.string().optional()})});function kbr(e,t={}){let n=(i)=>new sot({...e,redirectUri:i},t.fetch),r=t.now??Date.now;return{id:YHt,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 Cbr{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(qse.authorizations,{provider:YHt,brainState:e},"the connection");return new URL(Hen.parse(t).authorizationUrl)}async redeem(e){let t=Zen.parse(await this.post(qse.redeem,{provider:YHt,grant:e},"grant redemption"));if(t.provider!==YHt)throw Error("OAuth broker redeemed a grant for another provider");return XPd.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 YHt="linkedin",XPd;var Ibr=E(()=>{lt();oe();Sbr();XPd=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()})});function e4d(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function Axe(e,t){return e.map((n)=>e4d(n[t])).find(Boolean)}function Dea(e){let t=[Axe(e,"First Name"),Axe(e,"Last Name")].filter(Boolean).join(" ")||void 0,n=Axe(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:Axe(e,"Headline"),industry:Axe(e,"Industry"),location:Axe(e,"Geo Location"),website:n,story:Axe(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}function Pea(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 _br{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 Pea(await this.messaging.request(Mbe,{fields:t,revision:n}))}async previewFields(e){return Pea(await this.messaging.request(Obe,{fields:e}))}async imported(e){let t=new iot(e,this.fetchFn);return Dea(await t.fetchProfile())}}var Oea=E(()=>{lt();oot()});function Mea(e){return e?.permissionLevel==="admin"&&e.isAnchor}function aot(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function Fea(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return aot(303,`${l}${d}connection=${c}`)},n=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&Mea(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 aot(401);if(!Mea(l))return aot(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return aot(302,p.oauth.authorizationUrl(d).toString());try{return aot(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=Wen.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:Tbr,method:"GET",public:!0,handler:i},a.kind==="direct"?{path:cot,method:"GET",public:!0,handler:o(a.oauth)}:{path:lot,method:"GET",public:!0,handler:s(a.broker)}]}var Tbr="/linkedin/oauth/start",cot="/linkedin/oauth/callback",lot="/linkedin/oauth/broker/return";var jea=E(()=>{lt()});function zea(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 Nea(e){if(typeof e!=="string")return`<${zea(e)}>`;let t=e.trim();return n4d.find(([n])=>n.test(t))?.[1]??"<string>"}function r4d(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(Nea))].sort();return Nea(e)}function Lea([e],[t]){return e.localeCompare(t)}function i4d(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])=>zea(a)))].sort(),presentCount:s.length}}),i=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(Lea).map(([a,c])=>[a,r4d(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...i].sort(Lea).map(([,o])=>o)}}async function qea(e){let t=await Promise.all(Tea.map(async(n)=>[n,i4d(await e.fetchDomain(n))]));return Object.fromEntries(t)}var t4d,n4d;var Uea=E(()=>{oot();t4d=/^(?: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,n4d=[[/^$/,"<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>"],[t4d,"<month-year>"]]});function Hea(e){if(e===null)return"\u2014";return e.length>$ea?`${e.slice(0,$ea-1)}\u2026`:e}function Gea(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function Zea(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Rbr(e){let t=e.connection?s4d[e.connection]:null;return t?[{type:"notice",...t}]:[]}function Dbr(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 l4d(e){if(e instanceof JHt&&[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 Kea(e,t){if(!e.isAvailable())return;let n=async(i)=>{let o=await t.connections.get(Dbr(i));if(!o||wbr(o))throw new gr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:Wea,bind:(i)=>Wea.bind(i,{load:async({caller:o,query:s})=>{let a=Dbr(o),{connection:c}=s.get(Mbr),l=await t.connections.get(a);if(!l||wbr(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:l4d(d),startUrl:t.startUrl,connection:c}}},actions:[Pbr.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)=>Vea[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 ${Gea(c)} from LinkedIn?${l.length>0?` Your ${Gea(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Obr.bind(i,async({caller:o})=>{let s=await qea(t.clientFor((await n(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),XHt.bind(i,async({caller:o})=>(await t.connections.forget(Dbr(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(i)=>i.isAnchor&&await r.accessHandler(i)})}var Vea,o4d,s4d,$ea=200,Pbr,XHt,Obr,Mbr,a4d,Bbr,c4d,Wea;var Qea=E(()=>{Zo();lt();oe();oot();Ebr();Uea();Vea={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},o4d={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},s4d={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."}},Pbr=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())})}),XHt=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()})}),Obr=La({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Mbr=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),a4d=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Bbr=Mbr.shape.connection,c4d=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Bbr}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Bbr}),u.object({status:u.literal("ready"),fields:u.array(a4d),connection:Bbr})]);Wea=Sf({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:Mbr,data:c4d,actions:[Pbr,XHt,Obr],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:[...Rbr(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],Zea(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Rbr(e),{type:"notice",tone:"warn",text:e.message},Zea(e.startUrl,"Connect LinkedIn again"),{type:"action",action:XHt,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:Pbr,input:{}}}:{},blocks:[...Rbr(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:Vea[n.field],current:Hea(n.current),imported:Hea(n.imported),outcome:o4d[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:Obr,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:XHt,input:{}}]}}})});var Yea;var Jea=E(()=>{Yea={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.865",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 m4d(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!==cot)throw Error(`linkedin-import: oauth.redirectUri must end at ${cot}`);if(r&&new URL(r.returnUri).pathname!==lot)throw Error(`linkedin-import: broker.returnUri must end at ${lot}`);if(n)return{kind:"direct",oauth:new sot(n,t.fetch)};if(r)return{kind:"broker",broker:new Cbr(r,t.fetch)};return null}function eta(e={}){let t=$i({id:"linkedin-import",config:Xea,setup:(n)=>{let{config:r}=n,i=m4d(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!i||!o)return{routes:[]};let s=ni(n),a=new Abr(s.accountSettings,{pluginId:s.pluginId,packageName:Yea.name}),c=d4d;return s.registered(async()=>{let l=await Kea(s.studio,{profileImport:new _br(s.messaging,e.fetch),clientFor:(d)=>new iot(d,e.fetch),connections:a,startUrl:new URL(Tbr,o).toString()});if(l)c=l}),{routes:Fea({mode:i,states:Rea(),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 d4d="/studio",p4d,f4d,Xea,Fbr;var tta=E(()=>{Zo();wn();oe();oot();Ebr();Ibr();Sbr();Oea();jea();Qea();Jea();p4d=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 ${cot}, registered with the LinkedIn app`)}),f4d=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 ${lot}, registered with the broker`)}),Xea=u.object({oauth:p4d.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:f4d.optional().describe("The managed broker holding the shared LinkedIn app")});Fbr=eta()});var nta=E(()=>{tta()});var rta=E(()=>{Ibr()});import{createHash as h4d,timingSafeEqual as g4d}from"crypto";function ita(e){return h4d("sha256").update(e).digest()}function x4d(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 jbr{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ita(t.secret)}]))}authenticate(e){let t=x4d(e.headers.get("authorization")),n=t?this.instances.get(t.id):void 0;if(!t||!n)return null;return g4d(ita(t.secret),n.secretHash)?{id:n.id,returnUris:n.returnUris}:null}}var ota=()=>{};function Kie(e,t=200){return Response.json(e,{status:t,headers:Nbr})}function sta(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Nbr,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function ata(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function eGt(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:{...Nbr,Location:n.toString()}})}function cta(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-b4d),p=d.length<y4d;return n.set(c,p?[...d,l]:d),p},i=(c)=>new URL(Rut(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return sta();let d=$en.safeParse(await ata(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 sta();let d=Gen.safeParse(await ata(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 eGt(p,{error:"provider_denied"});let f=d.get("code")?.trim();if(!f)return eGt(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 eGt(p,{grant:h})}catch(m){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Re(m)}`),eGt(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:Rut(c.id),method:"GET",public:!0,handler:a(c)}))]}var y4d=10,b4d=600000,Nbr;var lta=E(()=>{lt();Nbr={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"}});function S4d(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 Lbr(e){let t=$i({id:"oauth-broker",config:dta,setup:(n)=>{let{config:r}=n,i=S4d(r,e);if(r.instances.length===0||i.length===0)return{routes:[]};return{routes:cta({publicUrl:r.publicUrl,providers:i,instances:new jbr(r.instances),authorizations:new KJ({ttlMs:v4d,maxPending:uta,now:e.now}),grants:new KJ({ttlMs:A4d,maxPending:uta,now:e.now}),now:e.now??Date.now,logger:ni(n).logger})}}});return Cf(t,({state:n})=>n.routes)}var v4d=600000,A4d=120000,uta=1000,w4d,E4d,dta;var pta=E(()=>{lt();Zo();wn();Vgt();oe();ota();lta();w4d=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),E4d=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")}),dta=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record($U,w4d).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(E4d).default([])})});var fta=E(()=>{pta()});function mta(e,t){let n=(r)=>r!==void 0&&t()-r.usedAt<k4d;return{get:async(r,i)=>{let o=await e.get(uot(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(uot(r,i),{hash:o,usedAt:t()})},conflictKept:async(r,i,o,s)=>{let a=await e.get(uot(r,i));if(!n(a))return;await e.set(uot(r,i),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(r,i)=>{await e.delete(uot(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 hta(e=Date.now){let t=new Map;return mta({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 gta(e,t=Date.now){let n=e.scoped({namespace:C4d,schema:I4d});return mta({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 k4d=2592000000,uot=(e,t)=>Ur(`${e}
12190
+ 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`})});var MPd="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 vbr=E(()=>{rot();lt();Jr();_n();dbr();mbr();QHt();wea();VHt();rot();bbr();sDe=uu(xgt(Vr({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:ZHt,markdown:WHt,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:MPd,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:pbr(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:ybr},generation:fbr,create:{fromUpload:Aea},jobs:{"upload-import":vea(()=>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:ubr}),[ggt(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 FPd,Sea;var kea=E(()=>{Jr();lbr();vbr();vbr();dbr();rot();lbr();mbr();QHt();bbr();FPd=qc({id:"note",config:cbr,entities:[sDe]}),Sea=FPd});var jPd,NPd,LPd,Cea;var Iea=E(()=>{lt();Zo();wn();jPd=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),NPd=u.looseObject({defaultRecipient:jPd.or(_ut).optional()}),LPd=$i({id:"notifications",config:NPd},{subscriptions:(e)=>{let{config:t}=e,n=ni(e),{logger:r}=n;return n.answer(v4,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=Tut.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}),[]}}),Cea=LPd});function HPd(e){return e.toLowerCase().includes("no data found for this memberid")}function GPd(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 iot{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===_ea)throw Error(`LinkedIn snapshot exceeded ${_ea} 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,GPd(r,t),n+1)]}async fetchPage(e,t){let n=new URL(`${qPd}/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":UPd}});if(r.ok)return zPd.parse(await r.json());let i=await r.text();if(r.status<500&&HPd(i))return null;throw new JHt(r.status,i.slice(0,$Pd))}}var Tea,zPd,qPd="https://api.linkedin.com/rest",UPd="202312",_ea=1000,$Pd=1000,JHt;var oot=E(()=>{oe();Tea=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],zPd=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()});JHt=class JHt extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}});class Abr{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:ZPd})}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 wbr(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var ZPd;var Ebr=E(()=>{Zo();oe();ZPd=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 YPd(e){try{return await e.json()}catch{return null}}class sot{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(WPd);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",Bea),t}async exchange(e,t){let n=await this.fetchFn(VPd,{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 YPd(n);if(!n.ok){let o=JPd.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,KPd)}`:""}`)}let i=QPd.parse(r);if(i.scope!==void 0&&i.scope!==Bea)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 Rea(e){return new KJ({...Wgt,now:e})}var WPd="https://www.linkedin.com/oauth/v2/authorization",VPd="https://www.linkedin.com/oauth/v2/accessToken",Bea="r_dma_portability_3rd_party",KPd=500,QPd,JPd;var Sbr=E(()=>{Vgt();oe();QPd=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),JPd=u.looseObject({error:u.string().optional(),error_description:u.string().optional()})});function kbr(e,t={}){let n=(i)=>new sot({...e,redirectUri:i},t.fetch),r=t.now??Date.now;return{id:YHt,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 Cbr{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(qse.authorizations,{provider:YHt,brainState:e},"the connection");return new URL(Hen.parse(t).authorizationUrl)}async redeem(e){let t=Zen.parse(await this.post(qse.redeem,{provider:YHt,grant:e},"grant redemption"));if(t.provider!==YHt)throw Error("OAuth broker redeemed a grant for another provider");return XPd.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 YHt="linkedin",XPd;var Ibr=E(()=>{lt();oe();Sbr();XPd=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()})});function e4d(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function Axe(e,t){return e.map((n)=>e4d(n[t])).find(Boolean)}function Dea(e){let t=[Axe(e,"First Name"),Axe(e,"Last Name")].filter(Boolean).join(" ")||void 0,n=Axe(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:Axe(e,"Headline"),industry:Axe(e,"Industry"),location:Axe(e,"Geo Location"),website:n,story:Axe(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0))}function Pea(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 _br{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 Pea(await this.messaging.request(Mbe,{fields:t,revision:n}))}async previewFields(e){return Pea(await this.messaging.request(Obe,{fields:e}))}async imported(e){let t=new iot(e,this.fetchFn);return Dea(await t.fetchProfile())}}var Oea=E(()=>{lt();oot()});function Mea(e){return e?.permissionLevel==="admin"&&e.isAnchor}function aot(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function Fea(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return aot(303,`${l}${d}connection=${c}`)},n=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&Mea(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 aot(401);if(!Mea(l))return aot(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return aot(302,p.oauth.authorizationUrl(d).toString());try{return aot(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=Wen.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:Tbr,method:"GET",public:!0,handler:i},a.kind==="direct"?{path:cot,method:"GET",public:!0,handler:o(a.oauth)}:{path:lot,method:"GET",public:!0,handler:s(a.broker)}]}var Tbr="/linkedin/oauth/start",cot="/linkedin/oauth/callback",lot="/linkedin/oauth/broker/return";var jea=E(()=>{lt()});function zea(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 Nea(e){if(typeof e!=="string")return`<${zea(e)}>`;let t=e.trim();return n4d.find(([n])=>n.test(t))?.[1]??"<string>"}function r4d(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(Nea))].sort();return Nea(e)}function Lea([e],[t]){return e.localeCompare(t)}function i4d(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])=>zea(a)))].sort(),presentCount:s.length}}),i=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(Lea).map(([a,c])=>[a,r4d(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...i].sort(Lea).map(([,o])=>o)}}async function qea(e){let t=await Promise.all(Tea.map(async(n)=>[n,i4d(await e.fetchDomain(n))]));return Object.fromEntries(t)}var t4d,n4d;var Uea=E(()=>{oot();t4d=/^(?: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,n4d=[[/^$/,"<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>"],[t4d,"<month-year>"]]});function Hea(e){if(e===null)return"\u2014";return e.length>$ea?`${e.slice(0,$ea-1)}\u2026`:e}function Gea(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function Zea(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Rbr(e){let t=e.connection?s4d[e.connection]:null;return t?[{type:"notice",...t}]:[]}function Dbr(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 l4d(e){if(e instanceof JHt&&[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 Kea(e,t){if(!e.isAvailable())return;let n=async(i)=>{let o=await t.connections.get(Dbr(i));if(!o||wbr(o))throw new gr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:Wea,bind:(i)=>Wea.bind(i,{load:async({caller:o,query:s})=>{let a=Dbr(o),{connection:c}=s.get(Mbr),l=await t.connections.get(a);if(!l||wbr(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:l4d(d),startUrl:t.startUrl,connection:c}}},actions:[Pbr.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)=>Vea[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 ${Gea(c)} from LinkedIn?${l.length>0?` Your ${Gea(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Obr.bind(i,async({caller:o})=>{let s=await qea(t.clientFor((await n(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),XHt.bind(i,async({caller:o})=>(await t.connections.forget(Dbr(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(i)=>i.isAnchor&&await r.accessHandler(i)})}var Vea,o4d,s4d,$ea=200,Pbr,XHt,Obr,Mbr,a4d,Bbr,c4d,Wea;var Qea=E(()=>{Zo();lt();oe();oot();Ebr();Uea();Vea={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},o4d={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},s4d={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."}},Pbr=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())})}),XHt=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()})}),Obr=La({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Mbr=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),a4d=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Bbr=Mbr.shape.connection,c4d=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Bbr}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Bbr}),u.object({status:u.literal("ready"),fields:u.array(a4d),connection:Bbr})]);Wea=Sf({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:Mbr,data:c4d,actions:[Pbr,XHt,Obr],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:[...Rbr(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],Zea(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Rbr(e),{type:"notice",tone:"warn",text:e.message},Zea(e.startUrl,"Connect LinkedIn again"),{type:"action",action:XHt,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:Pbr,input:{}}}:{},blocks:[...Rbr(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:Vea[n.field],current:Hea(n.current),imported:Hea(n.imported),outcome:o4d[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:Obr,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:XHt,input:{}}]}}})});var Yea;var Jea=E(()=>{Yea={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.866",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 m4d(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!==cot)throw Error(`linkedin-import: oauth.redirectUri must end at ${cot}`);if(r&&new URL(r.returnUri).pathname!==lot)throw Error(`linkedin-import: broker.returnUri must end at ${lot}`);if(n)return{kind:"direct",oauth:new sot(n,t.fetch)};if(r)return{kind:"broker",broker:new Cbr(r,t.fetch)};return null}function eta(e={}){let t=$i({id:"linkedin-import",config:Xea,setup:(n)=>{let{config:r}=n,i=m4d(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!i||!o)return{routes:[]};let s=ni(n),a=new Abr(s.accountSettings,{pluginId:s.pluginId,packageName:Yea.name}),c=d4d;return s.registered(async()=>{let l=await Kea(s.studio,{profileImport:new _br(s.messaging,e.fetch),clientFor:(d)=>new iot(d,e.fetch),connections:a,startUrl:new URL(Tbr,o).toString()});if(l)c=l}),{routes:Fea({mode:i,states:Rea(),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 d4d="/studio",p4d,f4d,Xea,Fbr;var tta=E(()=>{Zo();wn();oe();oot();Ebr();Ibr();Sbr();Oea();jea();Qea();Jea();p4d=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 ${cot}, registered with the LinkedIn app`)}),f4d=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 ${lot}, registered with the broker`)}),Xea=u.object({oauth:p4d.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:f4d.optional().describe("The managed broker holding the shared LinkedIn app")});Fbr=eta()});var nta=E(()=>{tta()});var rta=E(()=>{Ibr()});import{createHash as h4d,timingSafeEqual as g4d}from"crypto";function ita(e){return h4d("sha256").update(e).digest()}function x4d(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 jbr{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ita(t.secret)}]))}authenticate(e){let t=x4d(e.headers.get("authorization")),n=t?this.instances.get(t.id):void 0;if(!t||!n)return null;return g4d(ita(t.secret),n.secretHash)?{id:n.id,returnUris:n.returnUris}:null}}var ota=()=>{};function Kie(e,t=200){return Response.json(e,{status:t,headers:Nbr})}function sta(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Nbr,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function ata(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function eGt(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:{...Nbr,Location:n.toString()}})}function cta(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-b4d),p=d.length<y4d;return n.set(c,p?[...d,l]:d),p},i=(c)=>new URL(Rut(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return sta();let d=$en.safeParse(await ata(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 sta();let d=Gen.safeParse(await ata(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 eGt(p,{error:"provider_denied"});let f=d.get("code")?.trim();if(!f)return eGt(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 eGt(p,{grant:h})}catch(m){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Re(m)}`),eGt(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:Rut(c.id),method:"GET",public:!0,handler:a(c)}))]}var y4d=10,b4d=600000,Nbr;var lta=E(()=>{lt();Nbr={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"}});function S4d(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 Lbr(e){let t=$i({id:"oauth-broker",config:dta,setup:(n)=>{let{config:r}=n,i=S4d(r,e);if(r.instances.length===0||i.length===0)return{routes:[]};return{routes:cta({publicUrl:r.publicUrl,providers:i,instances:new jbr(r.instances),authorizations:new KJ({ttlMs:v4d,maxPending:uta,now:e.now}),grants:new KJ({ttlMs:A4d,maxPending:uta,now:e.now}),now:e.now??Date.now,logger:ni(n).logger})}}});return Cf(t,({state:n})=>n.routes)}var v4d=600000,A4d=120000,uta=1000,w4d,E4d,dta;var pta=E(()=>{lt();Zo();wn();Vgt();oe();ota();lta();w4d=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),E4d=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")}),dta=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record($U,w4d).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(E4d).default([])})});var fta=E(()=>{pta()});function mta(e,t){let n=(r)=>r!==void 0&&t()-r.usedAt<k4d;return{get:async(r,i)=>{let o=await e.get(uot(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(uot(r,i),{hash:o,usedAt:t()})},conflictKept:async(r,i,o,s)=>{let a=await e.get(uot(r,i));if(!n(a))return;await e.set(uot(r,i),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(r,i)=>{await e.delete(uot(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 hta(e=Date.now){let t=new Map;return mta({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 gta(e,t=Date.now){let n=e.scoped({namespace:C4d,schema:I4d});return mta({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 k4d=2592000000,uot=(e,t)=>Ur(`${e}
12191
12191
  ${t}`),C4d="webdav.mount-base",I4d;var zbr=E(()=>{Oo();oe();I4d=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()})});function wxe(e){let[t]=e;return t!==void 0&&_4d.has(t)}function yta(){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 bta(e){let t=e.scoped({namespace:T4d,schema:B4d}),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 _4d,xta=33554432,T4d="webdav.kept",B4d;var qbr=E(()=>{Oo();oe();_4d=new Set([".obsidian"]);B4d=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()})});import{randomUUID as R4d}from"crypto";class Ubr{run=R4d().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??D4d}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 D4d=500;var vta=()=>{};function Eta(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 j4d(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,Iut)}}async function Sta(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:O4d},sources:i,confirmations:o};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function Cta(e,t){let n=M4d.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 j4d(e.tree,o),a=await e.ask?.({asker:Eta(e.grant),interfaceType:Ata,channelName:wta,question:r,...i!==void 0&&{conversationId:i},...s!==void 0&&{entry:s}});if(!a)return kta();if("message"in a)return new Response(a.message,{status:409});return Sta(e.tree,a.conversationId,a.response)}async function Ita(e,t){let n=F4d.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:Eta(e.grant),interfaceType:Ata,channelName:wta,conversationId:r,approvalId:i,confirmed:o});if(!s)return kta();if("message"in s)return new Response(s.message,{status:409});return Sta(e.tree,r,s.response)}var Ata="obsidian",wta="Obsidian",P4d=1024,O4d="Your brain could not answer this.",M4d,F4d,kta=()=>new Response("Nothing answers questions here right now.",{status:503});var _ta=E(()=>{lt();oe();M4d=u.object({question:u.string().min(1).max(8000),conversation:u.string().min(1).max(yQ).optional(),path:u.string().min(1).max(P4d).optional()}),F4d=u.object({conversation:u.string().min(1).max(yQ),approval:u.string().min(1).max(yQ),confirmed:u.boolean()})});function Hbr(e){return Bta.has(e)}class Gbr{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($br))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(Tta).map((r)=>({kind:"folder",segments:[...e,r]})),...n.sort((r,i)=>Tta(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(dot)?(await this.hierarchy(dot,[])).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:L4d,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)=>!Hbr(n)&&n!==N4d),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($br))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($br))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:z4d[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!Bta.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()=>q4d(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!==dot&&!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 Tta(e,t){return e<t?-1:e>t?1:0}function $br(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function q4d(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 N4d="conflict",dot="note",L4d=100,Bta,z4d;var Zbr=E(()=>{_n();ste();wn();Bta=new Set(["image","document"]);z4d={".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 U4d}from"crypto";import{posix as $4d}from"path";async function Vbr(e,t){let n=$4d.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Uw.includes(n))return Pta(e,t,n,K4d);if(rM.includes(n))return Pta(e,t,n,Q4d);let r=n===".yaml"?G4d(e,t):t;if(r===void 0)return await tGt(e,t)?Qie("No entry can be stored at this path"):nGt();if(n!==".md"&&n!==".yaml")return await tGt(e,r)?Qie("The drive stores notes, entries, images, PDFs and EPUBs"):nGt();if(r.bytes.byteLength>e.writes.maxFileBytes)return Lta();let i=await e.tree.entityAt(r.segments),o=i?.entity.entityType??e.tree.placementAt(r.segments,n)?.entityType;if(o!==void 0&&Hbr(o))return Qie(o===Ota?"An image is stored as its image file":"A document is stored as its PDF or EPUB file");return i?Z4d(e,r,i):V4d(e,r,n)}function G4d(e,t){let n=e.tree.placementAt(t.segments,".yaml")?.entityType;if(n===void 0||e.tree.textExtension(n)!==".yaml")return;let r=qta(t.bytes);if(r===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(R$(r),"utf8"))}}async function Z4d(e,t,{entity:n,file:r}){let{writes:i}=e,o=t.onlyIfAbsent===!0||!Kbr(t.ifMatch,r.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?rGt():Jie();let s=jta(i,t.bytes,n.entityType);if("status"in s)return s;if(W4d(i,s.parsed,n))return await e.mount.held(n.contentHash),{status:204,etag:await Nta(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 pot(e,t.grant,"update",l,z$(n.entityType,n,l,e.reader));if(d)return d;if(o)return Dta(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 Dta(e,t,{existing:n,base:m,text:s.text,declared:s.parsed.visibility})}let p=await iGt(()=>i.updateEntity({entity:l,options:{expectedContentHash:n.contentHash,eventContext:fot(t.grant)}}));if(!p.ok)return zta(p.error);if(p.value.skipReason==="content-conflict")return Jie();if(!p.value.skipped)await Exe(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 W4d(e,t,n){let r=Jbr(()=>e.deserializeEntity(n.content,n.entityType));return r.ok&&(t.visibility??n.visibility)===n.visibility&&Bun.deepEquals(t,r.value)}async function Dta(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 V4d(e,t,n){let{writes:r,tree:i}=e,{segments:o}=t;if(!await tGt(e,t))return nGt();let s=i.placementAt(o,n);if(!s)return Qie("No entry can be stored at this path");let a=jta(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=rj(s.entityType,void 0,l.status,e.reader)!=="non-publish",m=await pot(e,t.grant,"create",p,f?["create","publish"]:["create"]);if(m)return m;let h=await iGt(()=>r.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:fot(t.grant)}}));if(!h.ok)return Qbr(h.error);return await Exe(r,t.grant,"create","allowed",p),{status:201,etag:await Nta(e,t,a.text)}}async function Pta(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 tGt(e,t))return nGt();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 Lta();if(l&&t.onlyIfAbsent)return rGt();if(l&&!Kbr(t.ifMatch,l.file.etag))return Jie();let p=await r.describe({bytes:a,digest:U4d("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 pot(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:fot(c)},v=await iGt(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:Qbr(v.error);if(w)return await i.discardStagedAsset(g),w;await Exe(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 Mta(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!==Rta||s?.entityType!==Rta)return Qie("The drive renames notes only, to another note's name");if(await r.entityAt(t.to))return rGt();let a=await pot(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await iGt(()=>n.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:fot(t.grant)}}));if(!c.ok)return Qbr(c.error);if(!c.value.renamed)return Jie();return await Exe(n,t.grant,"rename","allowed",o),{status:201}}async function Fta(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(!Kbr(t.ifMatch,i.etag))return Jie();let o=await pot(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:fot(t.grant)}}))return Jie();return await e.mount.forget(),await Exe(e.writes,t.grant,"delete","allowed",r),{status:204}}function jta(e,t,n){let r=qta(t);if(r===void 0)return{status:422,message:"The file is not UTF-8 text"};let i=Jbr(()=>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 pot(e,t,n,r,i){let o=t.principal.permissionLevel,s=Jbr(()=>i.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(r.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await Exe(e.writes,t,n,"denied",r,"entity-action-policy"),Qie(Re(s.error,"Not allowed"));if(n!=="delete"&&!Pm(o,r.visibility))return await Exe(e.writes,t,n,"denied",r,"visibility-policy"),Qie(`Cannot set visibility to "${r.visibility}" at ${o} permission`);return}function Exe(e,t,n,r,i,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${Wbr}.entity.${n}.${r}`,targetType:"entity",targetId:i.id,metadata:{entityType:i.entityType,interfaceType:Wbr,outcome:r,...o?{reason:o}:{}}})}async function Nta(e,t,n){let r=await e.tree.entityAt(t.segments);return r?.entity.content===n?r.file.etag:void 0}function fot(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:Wbr}}function Kbr(e,t){return e===null||e==="*"||e===t}function tGt(e,t){return e.folderExists(t.segments.slice(0,-1))}function nGt(){return{status:409,message:"The folder does not exist"}}function Lta(){return{status:413,message:"The file is larger than the drive accepts"}}function rGt(){return{status:412,message:"An entry already exists at this path"}}function Qbr(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?rGt():zta(e)}function Qie(e){return{status:403,message:e}}function Jie(){return{status:412,message:"The file changed since it was opened"}}function zta(e){if(T$(e))return{status:422,message:Re(e,"The file cannot be saved")};throw e}function qta(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function Jbr(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function iGt(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}var Ota="image",H4d="document",Rta="note",Wbr="webdav",K4d,Q4d;var Uta=E(()=>{_n();Oo();_n();ste();Pf();YT();brt();Zbr();K4d={entityType:Ota,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 V3(ode(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}}}},Q4d={entityType:H4d,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=TWe(o.mimeType);if(s!==n)return{status:422,message:`These bytes are stored as ${s}; save the document under that extension`};if(_ue(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 J4d}from"path";function Hta(e){return e.startsWith(".")||!Y4d.has(J4d.extname(e).toLowerCase())}class Ybr{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=yta()){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=wxe(t);if([...r.values()].filter((l)=>wxe(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+n.byteLength>(s?xta:e3d))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&&wxe(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&&wxe(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)}),wxe(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($ta(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($ta(r,i.touched,n))t.delete(r)}),t.size===0)this.files.delete(e);return t}}var Y4d,X4d=600000,e3d=16777216,$ta=(e,t,n)=>!wxe(e.split("/"))&&n-t>=X4d;var Gta=E(()=>{ste();qbr();Y4d=new Set([".md",".yaml",...Uw,...rM])});class Xbr{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(Zta(e,t),n+30000)}take(e,t){let n=Zta(e,t),r=this.expected.get(n);if(r===void 0)return!1;return this.expected.delete(n),r>this.now()}}function Zta(e,t){return`${e}
12192
12192
  ${t.join("/")}`}import{createHash as t3d}from"crypto";class evr{held=new Map;now;capBytes;constructor(e=Date.now,t=r3d){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-${t3d("sha256").update(n.bytes).digest("hex")}"`,until:o+n3d});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 n3d=600000,r3d=16777216;var Wta=()=>{};import{randomUUID as i3d}from"crypto";class tvr{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,n){if(this.live(e))return;let r={token:`opaquelocktoken:${i3d()}`,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||!Kta(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||Kta(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 Kta(e,t,n){return e.userId===t&&n.includes(`<${e.token}>`)}function Qta(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):Vta,Vta)}var Vta=600;var Jta=()=>{};function o3d(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 s3d(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=o3d(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 nvr(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:s3d(n)}]})}var rvr=E(()=>{gce()});function Sxe(e){return e.replace(/[&<>]/g,(t)=>a3d[t]??t)}function c3d(e){return[`<D:supportedlock><D:lockentry>${Yta}</D:lockentry></D:supportedlock>`,`<D:displayname>${Sxe(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>${Sxe(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${Sxe(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function Xta(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((n)=>`<D:response><D:href>${Sxe(n.href)}</D:href><D:propstat><D:prop>${c3d(n)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function ena(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function tna(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${Yta}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${Sxe(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${Sxe(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function nna(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${Sxe(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var a3d,Yta="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";var rna=E(()=>{a3d={"&":"&amp;","<":"&lt;",">":"&gt;"}});function gna(e){let t={options:e,mounts:e.mounts??hta(e.now),scratch:new Ybr(e.now,e.kept),locks:new tvr(e.now),cleanups:new Xbr(e.now),holds:new evr(e.now)},n={GET:(r,i)=>dna(r,i,!0),HEAD:(r,i)=>dna(r,i,!1),PROPFIND:S3d,POST:R3d,PUT:k3d,DELETE:M3d,MOVE:N3d,COPY:async()=>cDe("The drive does not copy files"),PROPPATCH:F3d,MKCOL:j3d,LOCK:q3d,UNLOCK:U3d};return hna.map((r)=>({path:e.basePath,match:"prefix",method:r,public:!0,handler:async(i)=>{if(r==="OPTIONS")return mot(G3d());let o=await e.resolveAppPassword(i);if(!o)return mot(Z3d(e.realm));if(lna(r)&&o.access!=="write")return mot(cDe("This app password is read-only"));let s=i.headers.get("x-brain-sync")?.trim()==="1",a={request:i,grant:o,tree:new Gbr(e.reader,Ui(o.principal.permissionLevel),{everyType:s}),path:kna(e.basePath,new URL(i.url).pathname),sync:s};if(lna(r)&&r!=="LOCK"&&r!=="UNLOCK"&&a.path&&!xna(t,a,a.path.segments))return mot(lvr());await t.scratch.open(o.principal.userId);let c=await n[r](t,a);return await t.scratch.settle(),mot(c)}}))}function xna(e,t,n){return e.locks.permits(n,t.grant.principal.userId,t.request.headers.get("if"))}function lna(e){return mna.some((t)=>t===e)}function cGt(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&&(yna(e)||Hta(t))}function yna(e){return e.some((t)=>t.startsWith("."))}async function lGt(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 avr(e,t,n){return n.length===0||e.scratch.hasFolder(t.grant.principal.userId,n)||(await t.tree.resolve(n))?.kind==="folder"}async function cvr(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 bna(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 cvr(e,t,i):void 0)?.etag===r?null:r}async function w3d(e,t){let n=new URL(t.request.url).searchParams,r=Number(n.get("wait")??ina),i=Number.isFinite(r)?Math.min(Math.max(r,0),u3d):ina,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 E3d(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")??cna),i=Number.isInteger(r)&&r>0?Math.min(r,x3d):cna,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 una(e,t,n){let r=ovr(n,e.options.basePath),i=await cvr(e,t,n);return i?{...r,contentLength:i.bytes.byteLength,etag:i.etag,lastModified:i.savedAt}:r}function vna(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 uGt(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:vna(e,t),recordConflict:async(n)=>e.options.recordConflict?.(n),folderExists:(n)=>avr(e,t,n)}}async function dna(e,t,n){let{shapes:r,changes:i}=e.options;if(t.sync&&t.path?.segments.join("/")===g3d.join("/"))return E3d(t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===l3d.join("/"))return w3d(i,t);if(t.sync&&r!==void 0&&t.path?.segments.join("/")===y3d.join("/")){let c=JSON.stringify({shapes:nvr(r).filter((l)=>l.entityType===dot||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=cGt(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:Sna(o),"Last-Modified":o.modified.toUTCString()}});let s=await lGt(e,t);if(!s)return Z5();if(s.kind==="folder")return svr();let a=await cvr(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 vna(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 S3d(e,t){let n=t.request.headers.get("depth");if(n!=="0"&&n!=="1")return new Response(ena("propfind-finite-depth"),{status:403,headers:{"Content-Type":aGt}});let{basePath:r}=e.options,i=cGt(e,t);if(i)return ivr([fna(i,r)]);let o=await lGt(e,t);if(!o)return Z5();if(o.kind==="file"||n==="0")return ivr([await una(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 ivr([ovr(o,r),...await Promise.all(a.map((l)=>una(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>ovr({kind:"folder",segments:[...o.segments,l]},r)),...e.scratch.list(s,o.segments).map((l)=>fna(l,r))])}async function k3d(e,t){let{path:n}=t;if(!n)return Z5();if(n.asFolder||n.segments.length===0)return svr();let{maxFileBytes:r,maxAssetBytes:i}=e.options.writes,o=await Ena(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 avr(e,t,n.segments))return svr();return wna(e.scratch.put(s,n.segments,o))}let c=await Vbr(uGt(e,t),{segments:n.segments,bytes:o,ifMatch:await bna(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 C3d(e,t,n.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,n.segments);return await _3d(e,t,n.segments,o,c),got(e,t,n.segments,c)}async function C3d(e,t,n,r,i){if("message"in i)return got(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 I3d(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 I3d(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 _3d(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 T3d(e){let t=await Ena(e,p3d);if(!t)return Ana;try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}function B3d(){return new Response("The request is too large",{status:413})}async function R3d(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=[sna,ana,m3d.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 T3d(t.request);if(o===Ana)return B3d();if(n===sna)return Cta(r(),o);if(n===ana)return Ita(r(),o);return D3d(e,t,o)}async function D3d(e,t,n){let r=h3d.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 P3d(e){let[t,n,r,...i]=e;return t===ona[0]&&n===ona[1]&&r!==void 0&&i.length===0?r:void 0}async function O3d(e,t,n){return await e.options.resolveConflict?.({conflictId:n,action:"keep-current",userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel})?oGt():new Response("Conflicts cannot be settled here right now.",{status:503})}async function M3d(e,t){let{path:n}=t;if(!n)return Z5();let r=t.sync&&!n.asFolder?P3d(n.segments):void 0;if(r!==void 0)return O3d(e,t,r);let i=t.grant.principal.userId;if(e.scratch.removeFolder(i,n.segments))return oGt();if(!n.asFolder&&aDe(n.segments)){if(e.scratch.delete(i,n.segments))return oGt()}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 Fta(uGt(e,t),{segments:n.segments,ifMatch:await bna(e,t,n.segments),grant:t.grant});if(!("message"in o))e.holds.release(t.grant.appPasswordId,n.segments);return got(e,t,n.segments,o)}async function F3d(e,t){let n=cGt(e,t)??await lGt(e,t);if(!n||!t.path)return Z5();let r="kind"in n&&n.kind==="folder",i=hot(t.path.segments);return new Response(nna(`${e.options.basePath}/${i}${r&&i?"/":""}`),{status:207,headers:{"Content-Type":aGt}})}async function j3d(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 avr(e,t,r.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=r;if(!yna(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 N3d(e,t){let n=t.request.headers.get("destination");if(!n)return new Response("Destination required",{status:400});let r=$3d(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(!xna(e,t,r.segments))return lvr();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)?z3d(e,t,i.segments,r.segments,o):L3d(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 sGt("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 sGt("The destination exists");let c=await Vbr(uGt(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 got(e,t,r.segments,c)}async function L3d(e,t,n,r){let i=await Mta(uGt(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 got(e,t,r,i)}async function z3d(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 sGt("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return wna(e.scratch.put(s,r,a))}async function q3d(e,t){let{path:n}=t;if(!n||n.segments.length===0)return Z5();if(n.segments[0]===d3d)return cDe("There is nothing to lock here");let r=t.grant.principal.userId,i=Qta(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?pna(e,n.segments,l,200):sGt("No such lock to refresh")}let a=e.locks.acquire(n.segments,r,i);if(!a)return lvr();let c=cGt(e,t)!==void 0||await lGt(e,t)!==void 0;return pna(e,n.segments,a,c?200:201)}function pna(e,t,n,r){return new Response(tna({...n,href:`${e.options.basePath}/${hot(t)}`}),{status:r,headers:{"Content-Type":aGt,"Lock-Token":`<${n.token}>`}})}async function U3d(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)?oGt():new Response("No such lock",{status:409})}function got(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 wna(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function Ena(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 ovr(e,t){let n=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let r=hot(e.segments);return{href:r?`${t}/${r}/`:`${t}/`,displayName:n,collection:!0}}return{href:`${t}/${hot(e.segments)}`,displayName:n,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function fna(e,t){return{href:`${t}/${hot(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:Sna(e),lastModified:e.modified}}function Sna(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function hot(e){return e.map(encodeURIComponent).join("/")}function kna(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(H3d);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:r}:void 0}function $3d(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=kna(e,i.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function H3d(e){try{return decodeURIComponent(e)}catch{return}}function ivr(e){return new Response(Xta(e),{status:207,headers:{"Content-Type":aGt}})}function G3d(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:v3d,"MS-Author-Via":"DAV"}})}function Z3d(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function svr(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function oGt(){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 lvr(){return new Response("The file is locked",{status:423})}function sGt(e){return new Response(e,{status:412})}function mot(e){let t=new Headers(e.headers);return Object.entries(A3d).forEach(([n,r])=>t.set(n,r)),new Response(e.body,{status:e.status,headers:t})}var l3d,u3d=50,ina=25,ona,d3d=".brain",p3d=65536,f3d=1024,m3d,h3d,sna=".brain/ask",ana=".brain/ask/confirm",g3d,cna=10,x3d=25,y3d,b3d,mna,hna,v3d,aGt='application/xml; charset="utf-8"',A3d,Ana;var Cna=E(()=>{oe();_ta();zbr();wn();Uta();Gta();Wta();Jta();Oo();rvr();Zbr();rna();l3d=[".brain","changes"],ona=[".brain","conflicts"],m3d=[".brain","publish"],h3d=u.object({path:u.string().min(1).max(f3d)}),g3d=[".brain","related"],y3d=[".brain","vault-shapes.json"],b3d=["OPTIONS","GET","HEAD","PROPFIND"],mna=["POST","PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],hna=[...b3d,...mna],v3d=hna.filter((e)=>e!=="POST").join(", "),A3d={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};Ana=Symbol("too large")});var uvr="/dav",W3d=5242880,Ina,V3d,dvr;var pvr=E(()=>{lt();zbr();qbr();lt();Zo();wn();vta();Pf();oe();Cna();Ina=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(W3d)}),V3d=$i({id:"webdav",config:Ina,setup:(e)=>{let t=ni(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(nh))return;throw Error(`webdav needs the "${nh}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let n=new Ubr;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=gta(t.classRuntimeState);return t.ready(()=>r.sweep()),t.interaction({id:P3e,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${uvr}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:gna({basePath:uvr,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:bta(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:nh,id:i,visibilityScope:En("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),dvr=Cf(V3d,({state:e})=>e.routes)});var _na;var Tna=E(()=>{pvr();pvr();rvr();_na=dvr});async function fvr(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 Bna(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=Q3d.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 Bna(d)??d.status}`);return"registered"}async function Bna(e){let t=K3d.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var K3d,Q3d;var mvr=E(()=>{oe();K3d=u.object({errcode:u.string()}),Q3d=u.object({session:u.string()})});function dGt(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Iq(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function gvr(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
12193
12193
  server_name = ${Iq(e.serverName)}
@@ -14960,7 +14960,7 @@ ${pCr}`,FHd=Mma});var Nma={};fi(Nma,{CONVENTIONAL_SITE_PACKAGE_REF:()=>r2,CONVEN
14960
14960
  `,{flag:"wx"}),!0}catch(g){if(g instanceof Error&&"code"in g&&g.code==="EEXIST")return!1;throw g}}finally{await p1t(f,{force:!0})}},s=()=>(gkn.add(r),{release:async()=>{gkn.delete(r),await p1t(i,{force:!0})}}),a=(f)=>f===process.pid?gkn.has(r):O2c(f);if(await o())return s();let c=await xkn(i);if(c!==void 0&&a(c))return{heldBy:c};let l=`${i}.${ykn()}`;try{await h1t(i,l)}catch(f){if(!c8(f))throw f}let d=await xkn(l);if(d!==void 0&&d!==c)return await n(l,i).catch(async(f)=>{let m=f instanceof Error&&"code"in f?f.code:void 0;if(!oDi.has(String(m)))return;await f1t(i,`${d}
14961
14961
  `,{flag:"wx"}).catch(()=>{return})}),await p1t(l,{force:!0}),{heldBy:d};if(await p1t(l,{force:!0}),await o())return s();return{heldBy:await xkn(i)??0}}import{randomInt as M2c,randomUUID as fDi}from"crypto";var F2c=600000,mDi="ABCDEFGHJKMNPQRSTUVWXYZ23456789";function j2c(){let e=()=>mDi.charAt(M2c(mDi.length));return`${e()}${e()}${e()}-${e()}${e()}${e()}`}async function hDi(e,t){let n=fDi().replaceAll("-",""),r=`/start-${fDi().replaceAll("-","")}`,i=j2c(),o,s=new Promise((f)=>{o=f}),a=encodeURIComponent("studio:account"),c=`${e}/studio/workspaces/${a}?section=drive`,l="",d=Bun.serve({hostname:"127.0.0.1",port:0,fetch:async(f)=>{let{pathname:m}=new URL(f.url);if(f.method==="GET"&&m===r)return Response.redirect(l,302);if(f.method!=="POST")return new Response(null,{status:404});let h=await f.formData().catch(()=>{return}),g=(w)=>{let S=h?.get(w);return typeof S==="string"&&S!==""?S:void 0},x=g("username"),y=g("password");if(g("state")!==n||!x||!y)return new Response(null,{status:400});let v={username:x,password:y};if(t.verify&&!await t.verify(v))return new Response("The brain did not take that app password. brain vault waits on.",{status:400});return o?.(v),Response.redirect(c,303)}}),p;try{let f=`http://127.0.0.1:${d.port}/`,m=new URLSearchParams({connect:"vault",state:n,code:i,callback:f});l=`${c}&${m.toString()}`;let h=`http://127.0.0.1:${d.port}${r}`;t.out([`Confirm in your brain, in the browser: the Connect card there shows code ${i} and port ${d.port}. Connect only if both match.`,`If no browser opens, open ${h} yourself.`,"A brain from before Connect for brain vault shows no Connect card: create an app password in its Drive section and run brain vault on a terminal to enter it."].join(`
14962
14962
  `));let g=new Promise((y)=>{if(t.signal?.aborted)y(void 0);t.signal?.addEventListener("abort",()=>y(void 0),{once:!0})}),x=new Promise((y)=>{p=setTimeout(()=>y(void 0),t.waitMs??F2c)});return t.openUrl(h).catch(()=>{return}),await Promise.race([s,g,x])}finally{if(p!==void 0)clearTimeout(p);await d.stop(!0)}}async function gDi(e){let t=process.platform==="darwin"?["open",e]:process.platform==="win32"?["rundll32","url.dll,FileProtocolHandler",e]:["xdg-open",e];await Bun.spawn(t,{stdout:"ignore",stderr:"ignore"}).exited}oe();import{chmod as N2c,mkdir as L2c,readFile as z2c,writeFile as q2c}from"fs/promises";import{homedir as U2c}from"os";import{dirname as $2c,join as xDi}from"path";var H2c=u.object({username:u.string(),password:u.string()}),G2c=u.record(u.string(),H2c);function yDi(e){let t=e.XDG_CONFIG_HOME,n=t!==void 0&&t!==""?t:xDi(U2c(),".config");return xDi(n,"rizom-brain","credentials.json")}async function bDi(e){try{let t=G2c.safeParse(JSON.parse(await z2c(e,"utf8")));return t.success?t.data:{}}catch{return{}}}async function vDi(e,t){return(await bDi(e))[t]}async function ADi(e,t,n){await L2c($2c(e),{recursive:!0,mode:448});let r={...await bDi(e),[t]:n};await q2c(e,`${JSON.stringify(r,null,2)}
14963
- `,{mode:384}),await N2c(e,384)}var IDi=2,o2=(e)=>({success:!1,message:e,exitCode:IDi}),Ekn=20;function zD(e,t,n){if(n.length===0)return;e.out(`${t} (${n.length}):`);for(let r of n.slice(0,Ekn))e.out(` ${r}`);if(n.length>Ekn)e.out(` \u2026and ${n.length-Ekn} more`)}var _Di=(e)=>e.map((t)=>`${t.path}: ${t.reason}`);function W2c(e,t){if(e.events){e.events.plan(t);return}if(e.out("The first sync of this folder will:"),zD(e,"Download",t.download),zD(e,"Send up",t.upload),zD(e,"Replace with the brain's version, keeping this folder's in Conflicts/",t.replace),zD(e,"Keep in this folder only",_Di(t.localOnly)),t.agreed.length>0)e.out(`${t.agreed.length} files are the same in both already.`)}function V2c(e){switch(e.kind){case"conflict":return`${e.path} changed in both places: the brain's version is in the file, this folder's is in ${e.copy}${e.inInbox?", and the brain's Inbox has the conflict":""}.`;case"conflict-changed":return`${e.path} changed after its conflict was shown: nothing was replaced.`;case"rename-undone":return`${e.from} was moved back from ${e.to}: ${e.reason}`}}function Ckn(e,t){if(e.events){e.events.report(t);return}zD(e,"Downloaded",t.downloaded),zD(e,"Sent up",t.uploaded),zD(e,"Deleted in the brain",t.deletedInBrain),zD(e,"Moved to .rizom-brain/trash",t.trashed);for(let n of t.notices)e.out(V2c(n));if(zD(e,"Refused by the brain",_Di(t.issues)),t.localOnly.length>0)e.out(`${t.localOnly.length} files stay in this folder only.`)}function tUe(e,t){switch(e.status){case"offline":return{success:!1,message:`${t} cannot be reached. No files were changed.`,exitCode:1};case"unavailable":return{success:!1,message:`${t} is not answering for now. No files were changed; try again in a minute.`,exitCode:1};case"signed-out":return o2(`${t} refused the app password. Run brain vault with --connect to confirm a new one in the browser (:Brain connect in Neovim), or create one in Studio's Drive section and set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD.`);case"no-drive":return o2(`${t} has no drive. No files were changed.`);case"old-brain":return o2(`${t} is older than brain vault needs: it needs version ${rkn} or later. No files were changed.`);default:return}}async function K2c(e,t,n,r){let i=r.env.BRAIN_VAULT_USERNAME,o=r.env.BRAIN_VAULT_PASSWORD;if(i&&o)return{username:i,password:o};if(!n.connect){let l=await vDi(r.credentialsFile,e);if(l)return l}let s=r.io.interactive&&!r.io.events,{openUrl:a}=r;if(a!==void 0&&(n.connect===!0||s&&await r.io.confirm("Connect in the browser? No: type an app password instead.",r.signal,!0))){let l=await hDi(t,{openUrl:a,out:(d)=>r.io.out(d),verify:async(d)=>{try{return await new Qqe({address:t,...d},r.fetch).list(""),!0}catch{return!1}},...r.signal?{signal:r.signal}:{}});if(l)return l}if(!s||r.signal?.aborted)return;return r.io.askLogin(t)}var Skn=(e)=>a1t(e).href,wDi=(e)=>e.replace(/\/dav\/$/,"");function TDi(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"&&"syscall"in e}async function Q2c(e){try{return!(await CDi(e)).isDirectory()}catch(t){if(TDi(t)&&t.code==="ENOENT")return!1;throw t}}function EDi(e,t){if(TDi(e))return{success:!1,message:`Something in ${t} could not be written or read (${e.code}): ${e.message}`,exitCode:1};return{success:!1,message:`brain vault stopped: ${Re(e)}`,exitCode:1}}var J2c=130;async function BDi(e,t,n){let r=Z2c(e);if(await Q2c(r))return o2(`${r} is a file, not a folder.`);if(await uDi(r))return o2(`The sync record in ${r}/.rizom-brain/state.json cannot be read, so which brain this folder syncs with is not known. Move .rizom-brain aside and sync again: the first sync shows what it will do before it does it.`);let i=y1t(r),o=await i.load(),s=t.address??(o.address||void 0);if(s===void 0)return o2(`Name the brain this folder syncs with: brain vault ${e} --address <brain>`);let a=Skn(s),c=wDi(a);if(o.address!==""&&Skn(o.address)!==a)return o2(`This folder syncs with ${wDi(Skn(o.address))}, not ${c}. Use another folder for another brain.`);if(t.connect&&n.env.BRAIN_VAULT_USERNAME&&n.env.BRAIN_VAULT_PASSWORD)return o2("BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD are set, and an app password from them comes first: unset them to connect in the browser.");let l=await K2c(a,c,t,n);if(l===void 0){if(t.connect&&!n.signal?.aborted)return o2(`Nothing was confirmed in the browser for ${c}. A brain from before Connect for brain vault shows no Connect card: create an app password in its Drive section, then set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD, or run brain vault on a terminal to enter it.`);return o2(`No app password for ${c}. Run brain vault with --connect to confirm one in your brain, in the browser (:Brain connect in Neovim); or create one in Studio's Drive section, then set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD, or run brain vault on a terminal to enter it.`)}let d=await pDi(r).catch((y)=>EDi(y,r));if("heldBy"in d)return o2(`brain vault is already syncing ${r} (process ${d.heldBy}). Stop that one first.`);if(!("release"in d))return d;let p=new Akn(r),f=new Qqe({address:s,...l},n.fetch),m=new d1t({vault:p,drive:f,store:i}),h={folder:r,key:a,brain:c,credentials:l},g={savedEarly:new Set,syncEarly:!1,settleEarly:[]},x=n.io.listen?.({unsaved:(y)=>p.setUnsaved(y),saved:(y)=>{if(p.settled(y),g.saved)g.saved(y);else g.savedEarly.add(y)},sync:()=>{if(g.sync)g.sync();else g.syncEarly=!0},conflicts:(y)=>g.conflicts?.(y),settle:(y,v,w)=>{if(g.settle)g.settle(y,v,w);else g.settleEarly.push({copy:y,keep:v,...w?{seen:w}:{}})},related:(y,v,w)=>{m.related(y,w).catch(()=>({status:"unavailable"})).then((S)=>n.io.events?.related(S,v))}});try{n.io.events?.state("syncing");let y=await X2c(m,h,t,n);if(n.signal?.aborted&&!y.synced)return{success:!1,message:"Stopped before the sync was done. What was synced stays; the next run goes on from there.",exitCode:J2c};if(n.signal?.aborted&&!t.once)return n.io.out("Stopped."),{success:!0};if(t.once||!y.synced)return y.result;if(!y.result.success&&y.result.message)n.io.out(y.result.message);return await oBc({engine:m,drive:f,vault:p,...h,relay:g,...y.decided?{decided:y.decided}:{}},n)}catch(y){return EDi(y,r)}finally{x?.(),await d.release()}}function RDi(e){return{...e.localMissing.length>0?{localMissing:{paths:e.localMissing,action:"delete"}}:{},...e.remoteGone.length>0?{remoteGone:{paths:e.remoteGone,action:"trash"}}:{}}}var kkn="These deletions wait for a yes: run brain vault on a terminal to decide. Nothing was deleted.",DDi="Delete these in the other place as well?";function PDi(e,t){zD(e,"Gone from this folder, still in the brain",t.localMissing),zD(e,"Gone from the brain, still in this folder",t.remoteGone)}async function Y2c(e,t,n,r){let{io:i}=r,o=t.decision;if(!o)return;if(PDi(i,o),!(i.interactive&&await i.confirm(DDi,r.signal)))return o2(kkn);let a=await e.resolveDeletes(RDi(o)),c=tUe(a,n);if(c)return c;Ckn(i,a);return}async function X2c(e,t,n,r){let{io:i}=r,{folder:o,key:s,brain:a,credentials:c}=t,l=y1t(o),d=(g)=>({result:g,synced:!1}),p=await e.sync(),f=tUe(p,a);if(f)return d(f);if(!r.env.BRAIN_VAULT_PASSWORD)await ADi(r.credentialsFile,s,c);if(p.status==="first-sync"&&p.firstSync){if(W2c(i,p.firstSync),!(n.yes===!0||i.interactive&&await i.confirm("Make the first sync?",r.signal))){if(i.interactive)return i.out("No files were changed."),d({success:!0});return d(o2("The first sync waits for a yes: run brain vault again with --yes, or on a terminal."))}p=await e.applyFirstSync();let x=tUe(p,a);if(x)return d(x)}let m=await l.load();if(m.address!==s)await l.save({...m,address:s});Ckn(i,p);let h=await Y2c(e,p,a,r);if(h)return{result:h,synced:h.exitCode===IDi,...p.decision?{decided:p.decision}:{}};return i.out(`In step with ${a}.`),{result:{success:!0},synced:!0}}var eBc=30,tBc=1000,nBc=60000,rBc=5000,SDi=5000,iBc=60000,kDi=(e)=>JSON.stringify([e.localMissing,e.remoteGone]);async function oBc(e,t){let{engine:n,drive:r,vault:i,folder:o,key:s,brain:a}=e,c=y1t(o),l=[],d=!1,p={...t.io,out:(ve)=>{if(d)l.push(ve);else t.io.out(ve)}},f=()=>t.signal?.aborted===!0;p.out(`Following ${a}. Stop with Ctrl+C.`),t.io.events?.state("in-step");let m={},h=new Promise((ve)=>{m.done=ve}),g=(ve)=>{if(m.result)return;m.result=ve,m.done?.()},x=()=>m.result===void 0,y=Promise.resolve(),v=Date.now(),w,S=SDi,k=0,C=!1,I,B,R=new Set(e.decided?[kDi(e.decided)]:[]),P=(ve)=>{let Fe=kDi(ve);if(d||R.has(Fe))return;if(R.add(Fe),PDi(p,ve),!p.interactive){p.out(kkn);return}d=!0,p.confirm(DDi,t.signal).then((ke)=>{d=!1;for(let Me of l.splice(0))t.io.out(Me);if(m.result)return;if(!ke){p.out(kkn);return}D(async()=>{let Me=await n.resolveDeletes(RDi(ve));if(Me.status!=="synced")R.delete(Fe);return Me})})},L=()=>{if(B!==void 0)return;B=setTimeout(()=>{B=void 0,O()},nBc)},H=(ve,Fe)=>{if(w===void 0)S=SDi,C=!1;else S=Math.min(S*2,iBc);if(k=Date.now()+S,w!==ve.status)p.out(Fe);w=ve.status,t.io.events?.state("away")},z=(ve)=>{if(f())return;if(ve.status==="no-drive"){H(ve,`${a} does not show its drive for now. It is asked again shortly.`);return}if(ve.status==="offline"||ve.status==="unavailable"){H(ve,tUe(ve,a)?.message??"");return}let Fe=tUe(ve,a);if(Fe){g(Fe);return}if(w!==void 0){if(p.out(`${a} answers again.`),w=void 0,ve.scope!==void 0)O()}if(I=void 0,!p.events)zD(p,"Moved in the brain",ve.moved.map(({from:ke,to:Me})=>`${ke} \u2192 ${Me}`));if(Ckn(p,ve),ve.decision)P(ve.decision);e.relay.conflicts?.()},D=(ve)=>(y=y.then(async()=>{if(m.result)return;try{t.io.events?.state("syncing");let Fe=await ve();if(Fe)z(Fe);if(w===void 0&&x())t.io.events?.state("in-step")}catch(Fe){if(f())return;let ke=Re(Fe);if(ke!==I)p.out(`A sync failed (${ke}). It is tried again in a minute.`);t.io.events?.state("retrying"),I=ke,L()}}),y),O=()=>{v=Date.now(),F.follow(s),D(()=>n.sync())},F=new c1t({watch:(ve,Fe,ke)=>{let Me=new l1t({drive:r,onChange:Fe,onReset:ke,compareAtFirstCursor:!0});return Me.start(),Me},syncTypes:(ve)=>D(()=>n.syncTypes(ve)),fullSync:O});F.follow(s);let V,Y=()=>{if(V!==void 0)clearTimeout(V);V=setTimeout(()=>{V=void 0,O()},tBc)},X=async()=>CDi(o).then((ve)=>ve.isDirectory(),()=>!1),K=()=>g(o2(`${o} is gone. Stopped following ${a}.`)),ie=async(ve)=>{if(m.result)return;if(!await X()){K();return}if(await i.isFolder(ve))return;let Fe=(await c.load()).paths[ve];if(await i.exists(ve)){if(Fe!==void 0){await D(()=>n.syncFile(ve));return}Y();return}if(i.isOwnRemoval(ve))return;if(Fe!==void 0)await D(()=>n.noteDeleted(ve));Y()},pe=new Map,ne=dDi(o,{onPath:(ve)=>{let Fe=pe.get(ve);if(Fe!==void 0)clearTimeout(Fe);pe.set(ve,setTimeout(()=>{pe.delete(ve),ie(ve).catch((ke)=>{p.out(`A change in ${ve} could not be looked at (${Re(ke)}). It is compared again in a minute.`),L()})},x1t+500))},onRoot:()=>{X().then((ve)=>{if(!ve)K()})}}),ee=setInterval(()=>{let ve=Date.now(),Fe=F.state();if(w!==void 0){let ke=Fe==="watching"&&!C;if(ke||ve>=k)C||=ke,k=ve+S,O();return}if(hkn(ve,v,eBc,Fe))O()},rBc);e.relay.saved=(ve)=>{let Fe=pe.get(ve);if(Fe!==void 0)clearTimeout(Fe);pe.delete(ve),ie(ve).catch(()=>L())},e.relay.sync=O;let he=(ve)=>{if(!t.io.events)return;D(async()=>{let Fe=await n.openConflicts();t.io.events?.conflicts(Fe.map(({path:ke,copy:Me,flavor:Xe,seen:et})=>({path:ke,copy:Me,flavor:Xe,...et?{seen:et}:{}})),ve)})};e.relay.conflicts=he,e.relay.settle=(ve,Fe,ke)=>{D(async()=>{let Me=(await n.openConflicts()).find((St)=>St.copy===ve);if(!Me){t.io.events?.settled({copy:ve,keep:Fe,done:!1,reason:"gone"});return}let{path:Xe}=Me;if(Fe==="mine"&&i.holdsUnsaved(Xe)){t.io.events?.settled({path:Xe,copy:ve,keep:Fe,done:!1,reason:"unsaved"});return}let et=ke===void 0?Me:{...Me,seen:ke},He=await n.settleConflict(et,Fe),$e=He.notices.some((St)=>St.kind==="conflict-changed");return t.io.events?.settled({path:Xe,copy:ve,keep:Fe,done:!$e,...$e?{reason:"changed"}:{}}),He}),he()},he();for(let ve of e.relay.savedEarly)e.relay.saved(ve);e.relay.savedEarly.clear();for(let ve of e.relay.settleEarly)e.relay.settle(ve.copy,ve.keep,ve.seen);if(e.relay.settleEarly=[],e.relay.syncEarly)O();e.relay.syncEarly=!1;let fe=()=>g({success:!0});if(t.signal?.aborted)fe();t.signal?.addEventListener("abort",fe,{once:!0}),await h,delete e.relay.saved,delete e.relay.sync,delete e.relay.conflicts,delete e.relay.settle,ne.close(),F.stop(),clearInterval(ee);for(let ve of pe.values())clearTimeout(ve);if(V!==void 0)clearTimeout(V);if(B!==void 0)clearTimeout(B);t.signal?.removeEventListener("abort",fe),await y,d=!1;for(let ve of l.splice(0))t.io.out(ve);return t.io.events?.state("stopped"),t.io.out("Stopped."),m.result??{success:!0}}oe();var sBc=u.discriminatedUnion("type",[u.object({type:u.literal("answer"),id:u.number(),yes:u.boolean()}),u.object({type:u.literal("unsaved"),paths:u.array(u.string())}),u.object({type:u.literal("saved"),path:u.string()}),u.object({type:u.literal("sync")}),u.object({type:u.literal("conflicts"),id:u.number().optional()}),u.object({type:u.literal("settle"),copy:u.string(),keep:u.enum(["brain","mine"]),seen:u.string().optional()}),u.object({type:u.literal("related"),id:u.number(),path:u.string(),limit:u.number().int().positive().optional()}),u.object({type:u.literal("stop")})]);function ODi(e,t,n){let r=(l)=>t(JSON.stringify(l)),i=new Map,o=1,s,a=[],c=(l)=>{if(l.type==="answer"){i.get(l.id)?.(l.yes),i.delete(l.id);return}if(l.type==="stop"){n();return}if(!s){a.push(l);return}if(l.type==="unsaved")s.unsaved(l.paths);else if(l.type==="saved")s.saved(l.path);else if(l.type==="conflicts")s.conflicts(l.id);else if(l.type==="related")s.related(l.path,l.id,l.limit);else if(l.type==="settle")s.settle(l.copy,l.keep,l.seen);else s.sync()};return(async()=>{try{for await(let l of e){if(l.trim()==="")continue;let d=sBc.safeParse(aBc(l));if(d.success)c(d.data);else r({type:"refused",line:l})}}catch{}for(let l of i.values())l(!1);i.clear(),n()})(),{interactive:!0,out:(l)=>r({type:"message",text:l}),confirm:(l,d)=>new Promise((p)=>{if(d?.aborted){p(!1);return}let f=o++;i.set(f,p),d?.addEventListener("abort",()=>{i.delete(f),p(!1)},{once:!0}),r({type:"ask",id:f,question:l})}),askLogin:async()=>{return},events:{plan:(l)=>r({type:"plan",...l}),report:(l)=>r({type:"report",...l}),state:(l)=>r({type:"state",state:l}),conflicts:(l,d)=>r({type:"conflicts",conflicts:l,...d===void 0?{}:{id:d}}),settled:(l)=>r({type:"settled",...l}),related:(l,d)=>r({type:"related",id:d,...l})},listen:(l)=>{s=l;for(let d of a.splice(0))c(d);return()=>{s=void 0}}}}function aBc(e){try{return JSON.parse(e)}catch{return}}async function*MDi(e){let t=new TextDecoder,n="";for await(let r of e){n+=typeof r==="string"?r:t.decode(r,{stream:!0});let i=n.split(`
14963
+ `,{mode:384}),await N2c(e,384)}var IDi=2,o2=(e)=>({success:!1,message:e,exitCode:IDi}),Ekn=20;function zD(e,t,n){if(n.length===0)return;e.out(`${t} (${n.length}):`);for(let r of n.slice(0,Ekn))e.out(` ${r}`);if(n.length>Ekn)e.out(` \u2026and ${n.length-Ekn} more`)}var _Di=(e)=>e.map((t)=>`${t.path}: ${t.reason}`);function W2c(e,t){if(e.events){e.events.plan(t);return}if(e.out("The first sync of this folder will:"),zD(e,"Download",t.download),zD(e,"Send up",t.upload),zD(e,"Replace with the brain's version, keeping this folder's in Conflicts/",t.replace),zD(e,"Keep in this folder only",_Di(t.localOnly)),t.agreed.length>0)e.out(`${t.agreed.length} files are the same in both already.`)}function V2c(e){switch(e.kind){case"conflict":return`${e.path} changed in both places: the brain's version is in the file, this folder's is in ${e.copy}${e.inInbox?", and the brain's Inbox has the conflict":""}.`;case"conflict-changed":return`${e.path} changed after its conflict was shown: nothing was replaced.`;case"rename-undone":return`${e.from} was moved back from ${e.to}: ${e.reason}`}}function Ckn(e,t){if(e.events){e.events.report(t);return}zD(e,"Downloaded",t.downloaded),zD(e,"Sent up",t.uploaded),zD(e,"Deleted in the brain",t.deletedInBrain),zD(e,"Moved to .rizom-brain/trash",t.trashed);for(let n of t.notices)e.out(V2c(n));if(zD(e,"Refused by the brain",_Di(t.issues)),t.localOnly.length>0)e.out(`${t.localOnly.length} files stay in this folder only.`)}function tUe(e,t){switch(e.status){case"offline":return{success:!1,message:`${t} cannot be reached. No files were changed.`,exitCode:1};case"unavailable":return{success:!1,message:`${t} is not answering for now. No files were changed; try again in a minute.`,exitCode:1};case"signed-out":return o2(`${t} refused the app password. Run brain vault with --connect to confirm a new one in the browser (:Brain connect in Neovim), or create one in Studio's Drive section and set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD.`);case"no-drive":return o2(`${t} has no drive. No files were changed.`);case"old-brain":return o2(`${t} is older than brain vault needs: it needs version ${rkn} or later. No files were changed.`);default:return}}async function K2c(e,t,n,r){let i=r.env.BRAIN_VAULT_USERNAME,o=r.env.BRAIN_VAULT_PASSWORD;if(i&&o)return{username:i,password:o};if(!n.connect){let l=await vDi(r.credentialsFile,e);if(l)return l}let s=r.io.interactive&&!r.io.events,{openUrl:a}=r;if(a!==void 0&&(n.connect===!0||s&&await r.io.confirm("Connect in the browser? No: type an app password instead.",r.signal,!0))){let l=await hDi(t,{openUrl:a,out:(d)=>r.io.out(d),verify:async(d)=>{try{return await new Qqe({address:t,...d},r.fetch).list(""),!0}catch{return!1}},...r.signal?{signal:r.signal}:{}});if(l)return l}if(!s||r.signal?.aborted)return;return r.io.askLogin(t)}var Skn=(e)=>a1t(e).href,wDi=(e)=>e.replace(/\/dav\/$/,"");function TDi(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"&&"syscall"in e}async function Q2c(e){try{return!(await CDi(e)).isDirectory()}catch(t){if(TDi(t)&&t.code==="ENOENT")return!1;throw t}}function EDi(e,t){if(TDi(e))return{success:!1,message:`Something in ${t} could not be written or read (${e.code}): ${e.message}`,exitCode:1};return{success:!1,message:`brain vault stopped: ${Re(e)}`,exitCode:1}}var J2c=130;async function BDi(e,t,n){let r=Z2c(e);if(await Q2c(r))return o2(`${r} is a file, not a folder.`);if(await uDi(r))return o2(`The sync record in ${r}/.rizom-brain/state.json cannot be read, so which brain this folder syncs with is not known. Move .rizom-brain aside and sync again: the first sync shows what it will do before it does it.`);let i=y1t(r),o=await i.load(),s=t.address??(o.address||void 0);if(s===void 0)return o2(`Name the brain this folder syncs with: brain vault ${e} --address <brain>`);let a=Skn(s),c=wDi(a);if(o.address!==""&&Skn(o.address)!==a)return o2(`This folder syncs with ${wDi(Skn(o.address))}, not ${c}. Use another folder for another brain.`);if(t.connect&&n.env.BRAIN_VAULT_USERNAME&&n.env.BRAIN_VAULT_PASSWORD)return o2("BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD are set, and an app password from them comes first: unset them to connect in the browser.");let l=await K2c(a,c,t,n);if(l===void 0){if(t.connect&&!n.signal?.aborted)return o2(`Nothing was confirmed in the browser for ${c}. A brain from before Connect for brain vault shows no Connect card: create an app password in its Drive section, then set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD, or run brain vault on a terminal to enter it.`);return o2(`No app password for ${c}. Run brain vault with --connect to confirm one in your brain, in the browser (:Brain connect in Neovim); or create one in Studio's Drive section, then set BRAIN_VAULT_USERNAME and BRAIN_VAULT_PASSWORD, or run brain vault on a terminal to enter it.`)}let d=await pDi(r).catch((y)=>EDi(y,r));if("heldBy"in d)return o2(`brain vault is already syncing ${r} (process ${d.heldBy}). Stop that one first.`);if(!("release"in d))return d;let p=new Akn(r),f=new Qqe({address:s,...l},n.fetch),m=new d1t({vault:p,drive:f,store:i}),h={folder:r,key:a,brain:c,credentials:l},g={savedEarly:new Set,syncEarly:!1,settleEarly:[]},x=n.io.listen?.({unsaved:(y)=>p.setUnsaved(y),saved:(y)=>{if(p.settled(y),g.saved)g.saved(y);else g.savedEarly.add(y)},sync:()=>{if(g.sync)g.sync();else g.syncEarly=!0},conflicts:(y)=>g.conflicts?.(y),settle:(y,v,w)=>{if(g.settle)g.settle(y,v,w);else g.settleEarly.push({copy:y,keep:v,...w?{seen:w}:{}})},related:(y,v,w)=>{m.related(y,w).catch(()=>({status:"unavailable"})).then((S)=>n.io.events?.related(S,v))},question:(y,v)=>{m.ask(y).catch(()=>({status:"unavailable"})).then((w)=>n.io.events?.reply(w,v))},approval:(y,v)=>{m.answerAsk(y).catch(()=>({status:"unavailable"})).then((w)=>n.io.events?.reply(w,v))}});try{n.io.events?.state("syncing");let y=await X2c(m,h,t,n);if(n.signal?.aborted&&!y.synced)return{success:!1,message:"Stopped before the sync was done. What was synced stays; the next run goes on from there.",exitCode:J2c};if(n.signal?.aborted&&!t.once)return n.io.out("Stopped."),{success:!0};if(t.once||!y.synced)return y.result;if(!y.result.success&&y.result.message)n.io.out(y.result.message);return await oBc({engine:m,drive:f,vault:p,...h,relay:g,...y.decided?{decided:y.decided}:{}},n)}catch(y){return EDi(y,r)}finally{x?.(),await d.release()}}function RDi(e){return{...e.localMissing.length>0?{localMissing:{paths:e.localMissing,action:"delete"}}:{},...e.remoteGone.length>0?{remoteGone:{paths:e.remoteGone,action:"trash"}}:{}}}var kkn="These deletions wait for a yes: run brain vault on a terminal to decide. Nothing was deleted.",DDi="Delete these in the other place as well?";function PDi(e,t){zD(e,"Gone from this folder, still in the brain",t.localMissing),zD(e,"Gone from the brain, still in this folder",t.remoteGone)}async function Y2c(e,t,n,r){let{io:i}=r,o=t.decision;if(!o)return;if(PDi(i,o),!(i.interactive&&await i.confirm(DDi,r.signal)))return o2(kkn);let a=await e.resolveDeletes(RDi(o)),c=tUe(a,n);if(c)return c;Ckn(i,a);return}async function X2c(e,t,n,r){let{io:i}=r,{folder:o,key:s,brain:a,credentials:c}=t,l=y1t(o),d=(g)=>({result:g,synced:!1}),p=await e.sync(),f=tUe(p,a);if(f)return d(f);if(!r.env.BRAIN_VAULT_PASSWORD)await ADi(r.credentialsFile,s,c);if(p.status==="first-sync"&&p.firstSync){if(W2c(i,p.firstSync),!(n.yes===!0||i.interactive&&await i.confirm("Make the first sync?",r.signal))){if(i.interactive)return i.out("No files were changed."),d({success:!0});return d(o2("The first sync waits for a yes: run brain vault again with --yes, or on a terminal."))}p=await e.applyFirstSync();let x=tUe(p,a);if(x)return d(x)}let m=await l.load();if(m.address!==s)await l.save({...m,address:s});Ckn(i,p);let h=await Y2c(e,p,a,r);if(h)return{result:h,synced:h.exitCode===IDi,...p.decision?{decided:p.decision}:{}};return i.out(`In step with ${a}.`),{result:{success:!0},synced:!0}}var eBc=30,tBc=1000,nBc=60000,rBc=5000,SDi=5000,iBc=60000,kDi=(e)=>JSON.stringify([e.localMissing,e.remoteGone]);async function oBc(e,t){let{engine:n,drive:r,vault:i,folder:o,key:s,brain:a}=e,c=y1t(o),l=[],d=!1,p={...t.io,out:(ve)=>{if(d)l.push(ve);else t.io.out(ve)}},f=()=>t.signal?.aborted===!0;p.out(`Following ${a}. Stop with Ctrl+C.`),t.io.events?.state("in-step");let m={},h=new Promise((ve)=>{m.done=ve}),g=(ve)=>{if(m.result)return;m.result=ve,m.done?.()},x=()=>m.result===void 0,y=Promise.resolve(),v=Date.now(),w,S=SDi,k=0,C=!1,I,B,R=new Set(e.decided?[kDi(e.decided)]:[]),P=(ve)=>{let Fe=kDi(ve);if(d||R.has(Fe))return;if(R.add(Fe),PDi(p,ve),!p.interactive){p.out(kkn);return}d=!0,p.confirm(DDi,t.signal).then((ke)=>{d=!1;for(let Me of l.splice(0))t.io.out(Me);if(m.result)return;if(!ke){p.out(kkn);return}D(async()=>{let Me=await n.resolveDeletes(RDi(ve));if(Me.status!=="synced")R.delete(Fe);return Me})})},L=()=>{if(B!==void 0)return;B=setTimeout(()=>{B=void 0,O()},nBc)},H=(ve,Fe)=>{if(w===void 0)S=SDi,C=!1;else S=Math.min(S*2,iBc);if(k=Date.now()+S,w!==ve.status)p.out(Fe);w=ve.status,t.io.events?.state("away")},z=(ve)=>{if(f())return;if(ve.status==="no-drive"){H(ve,`${a} does not show its drive for now. It is asked again shortly.`);return}if(ve.status==="offline"||ve.status==="unavailable"){H(ve,tUe(ve,a)?.message??"");return}let Fe=tUe(ve,a);if(Fe){g(Fe);return}if(w!==void 0){if(p.out(`${a} answers again.`),w=void 0,ve.scope!==void 0)O()}if(I=void 0,!p.events)zD(p,"Moved in the brain",ve.moved.map(({from:ke,to:Me})=>`${ke} \u2192 ${Me}`));if(Ckn(p,ve),ve.decision)P(ve.decision);e.relay.conflicts?.()},D=(ve)=>(y=y.then(async()=>{if(m.result)return;try{t.io.events?.state("syncing");let Fe=await ve();if(Fe)z(Fe);if(w===void 0&&x())t.io.events?.state("in-step")}catch(Fe){if(f())return;let ke=Re(Fe);if(ke!==I)p.out(`A sync failed (${ke}). It is tried again in a minute.`);t.io.events?.state("retrying"),I=ke,L()}}),y),O=()=>{v=Date.now(),F.follow(s),D(()=>n.sync())},F=new c1t({watch:(ve,Fe,ke)=>{let Me=new l1t({drive:r,onChange:Fe,onReset:ke,compareAtFirstCursor:!0});return Me.start(),Me},syncTypes:(ve)=>D(()=>n.syncTypes(ve)),fullSync:O});F.follow(s);let V,Y=()=>{if(V!==void 0)clearTimeout(V);V=setTimeout(()=>{V=void 0,O()},tBc)},X=async()=>CDi(o).then((ve)=>ve.isDirectory(),()=>!1),K=()=>g(o2(`${o} is gone. Stopped following ${a}.`)),ie=async(ve)=>{if(m.result)return;if(!await X()){K();return}if(await i.isFolder(ve))return;let Fe=(await c.load()).paths[ve];if(await i.exists(ve)){if(Fe!==void 0){await D(()=>n.syncFile(ve));return}Y();return}if(i.isOwnRemoval(ve))return;if(Fe!==void 0)await D(()=>n.noteDeleted(ve));Y()},pe=new Map,ne=dDi(o,{onPath:(ve)=>{let Fe=pe.get(ve);if(Fe!==void 0)clearTimeout(Fe);pe.set(ve,setTimeout(()=>{pe.delete(ve),ie(ve).catch((ke)=>{p.out(`A change in ${ve} could not be looked at (${Re(ke)}). It is compared again in a minute.`),L()})},x1t+500))},onRoot:()=>{X().then((ve)=>{if(!ve)K()})}}),ee=setInterval(()=>{let ve=Date.now(),Fe=F.state();if(w!==void 0){let ke=Fe==="watching"&&!C;if(ke||ve>=k)C||=ke,k=ve+S,O();return}if(hkn(ve,v,eBc,Fe))O()},rBc);e.relay.saved=(ve)=>{let Fe=pe.get(ve);if(Fe!==void 0)clearTimeout(Fe);pe.delete(ve),ie(ve).catch(()=>L())},e.relay.sync=O;let he=(ve)=>{if(!t.io.events)return;D(async()=>{let Fe=await n.openConflicts();t.io.events?.conflicts(Fe.map(({path:ke,copy:Me,flavor:Xe,seen:et})=>({path:ke,copy:Me,flavor:Xe,...et?{seen:et}:{}})),ve)})};e.relay.conflicts=he,e.relay.settle=(ve,Fe,ke)=>{D(async()=>{let Me=(await n.openConflicts()).find((St)=>St.copy===ve);if(!Me){t.io.events?.settled({copy:ve,keep:Fe,done:!1,reason:"gone"});return}let{path:Xe}=Me;if(Fe==="mine"&&i.holdsUnsaved(Xe)){t.io.events?.settled({path:Xe,copy:ve,keep:Fe,done:!1,reason:"unsaved"});return}let et=ke===void 0?Me:{...Me,seen:ke},He=await n.settleConflict(et,Fe),$e=He.notices.some((St)=>St.kind==="conflict-changed");return t.io.events?.settled({path:Xe,copy:ve,keep:Fe,done:!$e,...$e?{reason:"changed"}:{}}),He}),he()},he();for(let ve of e.relay.savedEarly)e.relay.saved(ve);e.relay.savedEarly.clear();for(let ve of e.relay.settleEarly)e.relay.settle(ve.copy,ve.keep,ve.seen);if(e.relay.settleEarly=[],e.relay.syncEarly)O();e.relay.syncEarly=!1;let fe=()=>g({success:!0});if(t.signal?.aborted)fe();t.signal?.addEventListener("abort",fe,{once:!0}),await h,delete e.relay.saved,delete e.relay.sync,delete e.relay.conflicts,delete e.relay.settle,ne.close(),F.stop(),clearInterval(ee);for(let ve of pe.values())clearTimeout(ve);if(V!==void 0)clearTimeout(V);if(B!==void 0)clearTimeout(B);t.signal?.removeEventListener("abort",fe),await y,d=!1;for(let ve of l.splice(0))t.io.out(ve);return t.io.events?.state("stopped"),t.io.out("Stopped."),m.result??{success:!0}}oe();var sBc=u.discriminatedUnion("type",[u.object({type:u.literal("answer"),id:u.number(),yes:u.boolean()}),u.object({type:u.literal("unsaved"),paths:u.array(u.string())}),u.object({type:u.literal("saved"),path:u.string()}),u.object({type:u.literal("sync")}),u.object({type:u.literal("conflicts"),id:u.number().optional()}),u.object({type:u.literal("settle"),copy:u.string(),keep:u.enum(["brain","mine"]),seen:u.string().optional()}),u.object({type:u.literal("related"),id:u.number(),path:u.string(),limit:u.number().int().positive().optional()}),u.object({type:u.literal("question"),id:u.number(),question:u.string().min(1),conversation:u.string().optional(),path:u.string().optional()}),u.object({type:u.literal("approval"),id:u.number(),conversation:u.string(),approval:u.string(),confirmed:u.boolean()}),u.object({type:u.literal("stop")})]);function ODi(e,t,n){let r=(l)=>t(JSON.stringify(l)),i=new Map,o=1,s,a=[],c=(l)=>{if(l.type==="answer"){i.get(l.id)?.(l.yes),i.delete(l.id);return}if(l.type==="stop"){n();return}if(!s){a.push(l);return}if(l.type==="unsaved")s.unsaved(l.paths);else if(l.type==="saved")s.saved(l.path);else if(l.type==="conflicts")s.conflicts(l.id);else if(l.type==="related")s.related(l.path,l.id,l.limit);else if(l.type==="question"){let{id:d,question:p,conversation:f,path:m}=l;s.question({question:p,...f!==void 0&&{conversation:f},...m!==void 0&&{path:m}},d)}else if(l.type==="approval"){let{type:d,id:p,...f}=l;s.approval(f,p)}else if(l.type==="settle")s.settle(l.copy,l.keep,l.seen);else s.sync()};return(async()=>{try{for await(let l of e){if(l.trim()==="")continue;let d=sBc.safeParse(aBc(l));if(d.success)c(d.data);else r({type:"refused",line:l})}}catch{}for(let l of i.values())l(!1);i.clear(),n()})(),{interactive:!0,out:(l)=>r({type:"message",text:l}),confirm:(l,d)=>new Promise((p)=>{if(d?.aborted){p(!1);return}let f=o++;i.set(f,p),d?.addEventListener("abort",()=>{i.delete(f),p(!1)},{once:!0}),r({type:"ask",id:f,question:l})}),askLogin:async()=>{return},events:{plan:(l)=>r({type:"plan",...l}),report:(l)=>r({type:"report",...l}),state:(l)=>r({type:"state",state:l}),conflicts:(l,d)=>r({type:"conflicts",conflicts:l,...d===void 0?{}:{id:d}}),settled:(l)=>r({type:"settled",...l}),related:(l,d)=>r({type:"related",id:d,...l}),reply:(l,d)=>r({type:"reply",id:d,...l})},listen:(l)=>{s=l;for(let d of a.splice(0))c(d);return()=>{s=void 0}}}}function aBc(e){try{return JSON.parse(e)}catch{return}}async function*MDi(e){let t=new TextDecoder,n="";for await(let r of e){n+=typeof r==="string"?r:t.decode(r,{stream:!0});let i=n.split(`
14964
14964
  `);n=i.pop()??"",yield*i}if(n!=="")yield n}ike();Fkn();ike();import{existsSync as ZBc,readFileSync as r9i,writeFileSync as WBc}from"fs";import{basename as n9i,join as qkn}from"path";oe();Xc();import{spawn as FBc}from"child_process";import{basename as jBc,resolve as NBc}from"path";var k1t=u.looseObject({id:u.string(),name:u.string(),organizationId:u.string()}),jkn=u.looseObject({id:u.string(),key:u.string(),value:u.string(),note:u.string().optional(),organizationId:u.string(),projectId:u.string().nullable().optional()}),LBc=u.union([u.array(k1t),u.looseObject({data:u.array(k1t)})]),zBc=u.looseObject({data:k1t}),qBc=u.looseObject({secrets:u.array(jkn).nullable().optional()});function Nkn(e){return jBc(NBc(e))}class Lkn{runBwsCommand;secretWriter;constructor(e=HBc,t=new e9i){this.runBwsCommand=e,this.secretWriter=t}async pushSecrets(e,t){let{project:n,created:r}=await this.ensureProject(e),i=await this.secretWriter.listProjectSecrets(n),o=new Map;for(let l of i){if(o.has(l.key))throw Error(`Multiple Bitwarden secrets named ${l.key} found in project ${e}`);o.set(l.key,l)}let s=[],a=[],c=[];for(let[l,d]of t){let p=o.get(l);if(p){let m=await this.secretWriter.updateSecret(n,p,d);s.push({key:l,id:m.id}),c.push(l);continue}let f=await this.secretWriter.createSecret(n,l,d);s.push({key:l,id:f.id}),a.push(l)}return{projectName:e,projectId:n.id,createdProject:r,createdKeys:a,updatedKeys:c,mappings:s}}async ensureProject(e){let n=(await this.listProjects()).filter((r)=>r.name===e);if(n.length>1)throw Error(`Multiple Bitwarden projects named ${e} found`);if(n[0])return{project:n[0],created:!1};return{project:await this.createProject(e),created:!0}}async listProjects(){let e=LBc.parse(XDi(await this.runBwsCommand(["project","list"])));return Array.isArray(e)?e:e.data}async createProject(e){let t=XDi(await this.runBwsCommand(["project","create",e])),n=k1t.safeParse(t);if(n.success)return n.data;return zBc.parse(t).data}}class e9i{clientPromise;async listProjectSecrets(e){let t=await this.getClient();return(qBc.parse(await t.secrets().sync(e.organizationId)).secrets??[]).filter((r)=>r.projectId===e.id)}async createSecret(e,t,n){let r=await this.getClient();return jkn.parse(await r.secrets().create(e.organizationId,t,n,"",[e.id]))}async updateSecret(e,t,n){let r=await this.getClient();return jkn.parse(await r.secrets().update(e.organizationId,t.id,t.key,n,t.note??"",[e.id]))}getClient(){return this.clientPromise??=$Bc(),this.clientPromise}}function UBc(e){return Cr(e)&&typeof e.BitwardenClient==="function"}async function $Bc(){let e=process.env.BWS_ACCESS_TOKEN;if(!e)throw Error("Missing BWS_ACCESS_TOKEN. Create a Bitwarden Secrets Manager machine account token and export it before pushing.");let t="@bitwarden/sdk-napi",n=await import(t);if(!UBc(n))throw Error(`${t} did not export a BitwardenClient constructor; the installed SDK version is not supported.`);let r=new n.BitwardenClient(void 0,n.LogLevel?.Error);return await r.auth().loginAccessToken(e),r}function HBc(e){return new Promise((t,n)=>{let r=FBc("bws",["--output","json",...e],{stdio:["ignore","pipe","pipe"],env:process.env}),i="",o="";r.stdout.on("data",(s)=>{i+=String(s)}),r.stderr.on("data",(s)=>{o+=String(s)}),r.on("error",n),r.on("close",(s)=>{if(s===0){t(i);return}n(Error(`bws ${e.join(" ")} exited with code ${s??1}${o?`: ${o.trim()}`:""}`))})})}function XDi(e){try{return JSON.parse(e)}catch(t){throw Error(`Could not parse bws JSON output: ${Re(t)}`,{cause:t})}}I1t();or();var VBc=new Set(["CERTIFICATE_PEM","PRIVATE_KEY_PEM"]);async function i9i(e,t={}){try{let n=await KBc(e,t);return{success:!0,message:n.dryRun?`Dry run: would push ${n.pushedKeys.length} env-backed secrets to ${n.target}`:`Pushed ${n.pushedKeys.length} env-backed secrets to ${n.target}`}}catch(n){return{success:!1,message:Re(n,"Secret push failed")}}}async function KBc(e,t={}){let n=ske(t.pushTo);if(!n)throw Error("Missing --push-to value. Use --push-to gh or bitwarden");let r=t.logger??console.log,i=t.env??process.env,o=QBc(e),s=nUe(e),a=JBc(o,n),c=a.map((h)=>h.key),l=new Map(a.map((h)=>[h.key,h])),d=XBc(c,s,t.all??!1,YBc(t.only),n),{pushedKeys:p,skippedKeys:f}=rRc(d,i,s,e);if(p.length===0)throw Error(`No local secrets found in ${o?n9i(o):".env"}`);let m=p.map(([h])=>h);if(t.dryRun){if(n==="bitwarden"){let h=Nkn(e);r(`Dry run: would push ${m.length} secrets to Bitwarden project ${h}.`),r("Dry run: would update .env.schema with Bitwarden UUID references after push.")}else r(`Dry run: would push ${m.length} secrets to GitHub Secrets.`);if(m.length>0)r(`Secrets: ${m.join(", ")}`);return Ukn(r,f,l),{target:n,pushedKeys:m,skippedKeys:f,dryRun:!0}}if(n==="bitwarden"){if(!o||n9i(o)!==".env.schema")throw Error("Bitwarden secret push requires a .env.schema file");let h=Nkn(e),x=await(t.bitwardenClient??new Lkn).pushSecrets(h,p);return tRc(o,x.mappings),eRc(r,x),Ukn(r,f,l),{target:n,pushedKeys:m,skippedKeys:f,bitwarden:x}}return await oke(p,{runCommand:t.runCommand,logger:r}),Ukn(r,f,l),{target:n,pushedKeys:m,skippedKeys:f}}function QBc(e){let t=[qkn(e,".env.schema"),qkn(e,".env.example"),qkn(e,".env")];for(let n of t)if(ZBc(n))return n;return}function JBc(e,t){if(!e)return[];return Rkn(e,{skipSections:new Set([w1t])}).filter((n)=>o9i(n.key,t))}function YBc(e){if(!e)return[];let t=[],n=new Set;for(let r of e.split(",")){let i=r.trim().toUpperCase();if(!i||n.has(i))continue;n.add(i),t.push(i)}return t}function XBc(e,t,n,r,i){let o=[],s=new Set,a=(c)=>{if(o9i(c,i)&&!s.has(c))s.add(c),o.push(c)};if(r.length>0){for(let c of r)a(c);return o}for(let c of e)a(c);if(n)for(let c of Object.keys(t))a(c);return o}function o9i(e,t){if(E1t.has(e))return!1;if(t==="gh"&&VBc.has(e))return!1;return!0}function Ukn(e,t,n){t9i(e,t,(r)=>n.get(r)?.required??!1)}function eRc(e,t){if(e(`${t.createdProject?"Created":"Using"} Bitwarden project ${t.projectName} (${t.projectId})`),iUe(e,"Created Bitwarden secrets",t.createdKeys),iUe(e,"Updated Bitwarden secrets",t.updatedKeys),e("Updated .env.schema with Bitwarden UUID references."),t.mappings.length>0){e("Bitwarden schema references:");for(let n of t.mappings)e(`${n.key}=bitwarden("${n.id}")`)}}function tRc(e,t){let n=r9i(e,"utf-8");n=nRc(n);for(let r of t){let i=new RegExp(`^(${JE(r.key)}\\s*=).*$`,"m");if(!i.test(n))throw Error(`Could not find ${r.key} in .env.schema`);n=n.replace(i,`$1bitwarden("${r.id}")`)}WBc(e,n)}function nRc(e){let t=[];if(!S1t(e))t.push("# @plugin(@varlock/bitwarden-plugin@1.0.0)");if(!e.includes("@initBitwarden("))t.push("# @initBitwarden(accessToken=$BWS_ACCESS_TOKEN)");let n=!/^BWS_ACCESS_TOKEN\s*=.*$/m.test(e);if(t.length===0&&!n)return e;let r=e.split(`
14965
14965
  `),i=r.findIndex((s)=>/^#\s*-{3,}\s*$/.test(s)),o=i>=0?i:0;if(t.length>0)r.splice(o,0,...t);if(n){let s=r.findIndex((l)=>/^#\s*-{3,}\s*$/.test(l)),a=["","# Bitwarden bootstrap token supplied by shell/CI","# @required @sensitive @type=bitwardenAccessToken","BWS_ACCESS_TOKEN="],c=s>=0?s+1:o+t.length;r.splice(c,0,...a)}return r.join(`
14966
14966
  `)}function rRc(e,t,n,r){let i=[],o=[];for(let s of e){let a=`${s}_FILE`,c=RX(a,t,n),l=iRc(c,r)??RX(s,t,n);if(l===void 0||l.trim().length===0){o.push(s);continue}i.push([s,l])}return{pushedKeys:i,skippedKeys:o}}function iRc(e,t){if(!e||e.trim().length===0)return;return r9i(rUe(e,t),"utf-8")}oe();Pkn();I1t();zkn();import{execFileSync as s9i}from"child_process";import{chmodSync as aRc,existsSync as cRc,mkdirSync as lRc,readFileSync as a9i,writeFileSync as uRc}from"fs";import{dirname as dRc,join as pRc}from"path";import{homedir as fRc}from"os";var c9i=u.object({id:u.number(),name:u.string(),public_key:u.string()}),mRc=u.object({ssh_keys:u.array(c9i)}),hRc={createEd25519KeyPair(e,t){s9i("ssh-keygen",["-t","ed25519","-f",e,"-C",t,"-N",""],{stdio:"ignore"})},derivePublicKey(e){return s9i("ssh-keygen",["-y","-f",e],{encoding:"utf-8",stdio:["ignore","pipe","inherit"]}).trim()}};async function $kn(e,t={}){try{let n=await l9i(e,t);return{success:!0,message:n.createdLocalKey?`SSH deploy key ready at ${n.privateKeyPath}`:`SSH deploy key already ready at ${n.privateKeyPath}`}}catch(n){return{success:!1,message:Re(n,"SSH key bootstrap failed")}}}async function l9i(e,t={}){let n=t.env??process.env,r=nUe(e),i=t.logger??console.log,o=t.fetchImpl??fetch,s=t.sshKeygen??hRc,a=RX("HCLOUD_TOKEN",n,r);if(!a)throw Error("Missing HCLOUD_TOKEN");let c=RX("HCLOUD_SSH_KEY_NAME",n,r);if(!c)throw Error("Missing HCLOUD_SSH_KEY_NAME");let l=RX("KAMAL_SSH_PRIVATE_KEY_FILE",n,r),d=l?rUe(l,e):pRc(fRc(),".ssh",`${xRc(c)}_ed25519`),p=`${d}.pub`,f=!1;if(!cRc(d))lRc(dRc(d),{recursive:!0,mode:448}),s.createEd25519KeyPair(d,c),f=!0;aRc(d,384);let m;if(f)m=a9i(p,"utf-8").trim();else m=s.derivePublicKey(d),uRc(p,`${m}