@fungi.computer/spore 0.11.9 → 0.11.11

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.
@@ -1440,8 +1440,8 @@ ${p.comment}`:p.comment}this.doc.range[2]=p.offset;break}default:this.errors.pus
1440
1440
  `,n=A$e.byteLength(t,"utf8");if(n<=I$e)return t;if(e.event==="memory"){const r=JSON.stringify({...e,heap:{...e.heap,objectTypeCounts:Van(e.heap.objectTypeCounts),protectedObjectTypeCounts:Van(e.heap.protectedObjectTypeCounts)},omittedRecordBytes:n})+`
1441
1441
  `;if(A$e.byteLength(r,"utf8")<=I$e)return r}return JSON.stringify({source:"local-service",timestamp:e.timestamp,pid:e.pid,event:"record-omitted",recordEvent:e.event,encodedBytes:n})+`
1442
1442
  `}function I6r(e){let t,n=!1;return{start(){if(n)throw new Error("Cannot restart a disposed service log sampler");t===void 0&&(t=setInterval(()=>{let r;try{r=e.readMemory()}catch(i){ar("service-log.sample",i),e.emit({event:"memory-unavailable",failure:Qre("service-log.sample",i)});return}e.emit({event:"memory",...r})},S6r),t.unref())},close(){n=!0,t!==void 0&&clearInterval(t),t=void 0}}}function C6r(e){let t=!1,n=!1,r,i={state:"active"},o,s,a=!1;const u=()=>{if(!a){a=!0;try{s?.close()}catch(p){i.state==="active"&&(i={state:"failed",code:"sink-close-failed",since:new Date().toISOString()}),ar("service-log.close",p)}}},c=p=>{i.state!=="failed"&&(i={state:"failed",code:p,since:new Date().toISOString()},d.close(),u())},l=p=>{if(!(n||i.state==="failed"))try{if(s===void 0)throw new Error("Diagnostic writer did not open");s.writeLine(T6r({...p,source:"local-service",timestamp:new Date().toISOString(),pid:e.pid,version:e.version}))}catch(m){c("sink-write-failed"),ar("service-log.write",m)}},d=I6r({readMemory:e.readMemory,emit:l});try{s=(e.openWriter??Gan)(e.directory)}catch(p){c("sink-open-failed"),ar("service-log.open",p)}return l({event:"starting"}),{getStatus:()=>i.state==="failed"?i:o??i,ready(p){n||t||(l({event:"ready",serviceId:p}),t=!0,i.state==="active"&&d.start())},stopping(p){r===void 0&&(r=p,d.close(),l({event:"stopping",reason:r}))},failure(p){l({event:"failure",failure:p})},ruleMatch(p){l({event:"exec-rule-match",...p})},approvalDecision(p){l({event:"exec-approval-decision",...p})},recoveryDisabled(p){n||o!==void 0||(o={state:"recovery-disabled",code:p,since:new Date().toISOString()},l({event:"recovery-persistence-disabled",code:p}))},drainTimeout(p){l({event:"drain-timeout",deadlineMs:p.deadlineMs,phase:p.phase,unfinishedOwners:p.unfinishedOwners.slice(0,A6r),unfinishedOwnerCount:p.unfinishedOwners.length})},close(){n||(d.close(),r!==void 0&&l({event:"stopped",reason:r}),u(),n=!0)}}}import{isAbsolute as R6r,join as O6r,relative as P6r,resolve as M6r,sep as D6r}from"node:path";import{fileURLToPath as L6r}from"node:url";import{rmSync as C$e}from"node:fs";import{userInfo as N6r}from"node:os";import{lstatSync as R$e,mkdirSync as $6r,mkdtempSync as U6r,readFileSync as F6r,realpathSync as _ie,rmSync as Kan,writeFileSync as B6r}from"node:fs";import{createRequire as j6r}from"node:module";import{userInfo as W6r}from"node:os";import{dirname as wie,isAbsolute as Jan,join as uR,relative as q6r,resolve as bie,sep as z6r}from"node:path";import{fileURLToPath as H6r}from"node:url";import{createHash as G6r}from"node:crypto";import{lstatSync as V6r,readFileSync as xie,statSync as Qan}from"node:fs";import{createRequire as K6r}from"node:module";import{dirname as Xan,join as Sie}from"node:path";import{fileURLToPath as J6r}from"node:url";var Yan=Object.freeze({"linux-x64":{patch:"93d17ead57b33d2295cd3960603220b1c418084ab39bc8450a8fd90a258c7608",bwrap:"035ac5ddfc70dd7d4a9b575b351944d47aa9d0bbafeb433fb72b2afb02cef7f4",seccomp:"38112f9cf994bed2ed962fae63e803c41874732ab032088b2c1ea3d713e51c11",seccompWorkspace:"e46f1045f85fcf14f91fae8654bba6a0c87f57e3b92f60bfc16008dbf7dc87c8"},"linux-arm64":{patch:"ee2105027bcdd1c68e45b4708addb5e09683dd20f9f5396eef28ee8321713fcf",bwrap:"46d782ab80e7459a2a160b09ba6f3622a39fbc7ce4d09f091339149302abe26c",seccomp:"3acf1897053260251357e29cc3641cf07dff527101bc332326cf37af59097bc0",seccompWorkspace:"ff61645ff32c11ebee925ce677b3f127b4e0dce20597e7349404f04c44029bdb"},"darwin-arm64":{patch:"2381f4fb9aa737bd8eb8919e71fe6ab0f26ae881e20e118c2a6d881912f2cab0"},"darwin-x64":{patch:"fb561a2e11c7541007e0076bec48fea675c5a5ca0c64fb8bfaeffe079d31300d"}});xt();import{isUtf8 as Zan}from"node:buffer";import{spawnSync as eun}from"node:child_process";import{accessSync as Q6r,constants as X6r,lstatSync as Z_,mkdirSync as tun,realpathSync as Sd,statSync as cR}from"node:fs";import{userInfo as Y6r}from"node:os";import{basename as nun,dirname as yv,isAbsolute as p0,join as ho,posix as run,relative as O$e,resolve as lR,sep as uU}from"node:path";var _2=A.string().min(1).refine(e=>!run.isAbsolute(e)&&!e.includes("\\")&&!e.includes("\0")&&!e.split("/").includes(".."),"Agent folder must be a project-relative POSIX path without '..'").transform(e=>run.normalize(e));function cU(e,t){const n=Sd(e),r=Sd(lR(n,_2.parse(t))),i=O$e(n,r);if(p0(i)||i===".."||i.startsWith(`..${uU}`))throw new Error("Agent folder resolves outside the project");if(i===".fungi"||i.startsWith(`.fungi${uU}`))throw new Error("Agent folder cannot be inside protected project .fungi");if(!Z_(r).isDirectory())throw new Error("Agent folder must be a directory");return{folder:i.split(uU).join("/")||".",absolute:r}}function iun(e){if(!p0(e))return[];try{return cR(e).isDirectory()?[Sd(e)]:[]}catch(t){if(L$e(t))return[];throw t}}function lU(e,t){return dR(e,t)}function oun(e,t,n){const r=e.HOME??t,i=n==="linux"?[...new Set([r,t].map(o=>ho(o,".cache","fungi","tmp")).flatMap(iun))]:[];return[ho(r,".config","fungi"),ho(r,".fungi","service"),...i]}function Z6r(e,t,n,r,i,o="linux"){const s=r.HOME??i;if(!p0(s))throw new Error("Sandbox HOME must be absolute");if(!p0(i))throw new Error("Sandbox OS home must be absolute");const a=r.XDG_CACHE_HOME??ho(s,".cache"),u=r.XDG_DATA_HOME??ho(s,".local","share"),c=r.CARGO_HOME??ho(s,".cargo"),l=o==="darwin",d=r.PNPM_HOME??(l&&r.XDG_DATA_HOME===void 0?ho(s,"Library","pnpm"):ho(u,"pnpm")),p=l&&r.XDG_CACHE_HOME===void 0?[ho(s,"Library","Caches","pnpm")]:[],m=[a,ho(s,".npm"),ho(d,"store"),...p,ho(s,".bun","install","cache"),ho(c,"registry"),ho(c,"git"),r.GOMODCACHE??ho(s,"go","pkg","mod"),r.GOCACHE??ho(a,"go-build")],h=r.SSH_AUTH_SOCK,f=h&&p0(h)&&cR(h,{throwIfNoEntry:!1})?.isSocket()?h:void 0,g=[...new Set(m.flatMap(iun))].filter(b=>!lU(b,ho(s,".cargo","bin"))&&!lU(b,ho(s,".local","bin"))&&!lU(b,e.projectRoot)&&!lU(e.projectRoot,b)),y=t==="workspace"?[...new Set([e.writableRoot,...g])]:[],v=kie(ho(a,"fungi")),_=y.some(b=>lU(b,v))?v:void 0;return{...e,readOnly:_===void 0?e.readOnly:[...e.readOnly,_],mode:t,temporaryDirectory:n,fungiCache:_,writable:y,hidden:oun(r,i,o),sshAgentSocket:t==="workspace"?f:void 0,sshAgentMask:t==="read-only"?f:void 0}}function P$e(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("Invalid Local Agent ID for temporary directory");const n=Y6r().homedir,r=process.env.XDG_RUNTIME_DIR,i=r&&p0(r)?ho(r,"fungi","tmp"):ho(n,".cache","fungi","tmp"),o=Sd(t);if([lR(i),kie(i)].some(u=>dR(o,u)||Eie(u)))throw new Error("Agent temporary directory cannot live in the Agent project or Git administration");tun(i,{recursive:!0,mode:448});const s=ho(i,e);if(tun(s,{recursive:!0,mode:448}),dR(o,Sd(s)))throw new Error("Agent temporary directory resolved into the Agent project");const a=Z_(s);if(!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0)throw new Error("Local Agent temporary directory must be private");return Sd(s)}var m0=class extends Error{name="UnsafeNativePayload"},ew=class extends Error{name="UnsafeHostCode"},M$e=class extends Error{name="UnsafeSandboxFolder"},sun=class extends Error{name="UnsafeGitMarker"};function dR(e,t){const n=O$e(e,t);return!p0(n)&&n!==".."&&!n.startsWith(`..${uU}`)}function Eie(e){for(let t=yv(e);;t=yv(t)){if(nun(t)===".git"||Z_(ho(t,"HEAD"),{throwIfNoEntry:!1})?.isFile()&&(Z_(ho(t,"objects"),{throwIfNoEntry:!1})?.isDirectory()||Z_(ho(t,"commondir"),{throwIfNoEntry:!1})?.isFile()))return!0;if(t===yv(t))return!1}}function eTr(e,t,n){const r=Sd(e),i=[t,n,yv(t),yv(yv(t)),yv(n),yv(yv(n))];for(const o of i)try{const s=lR(o),a=Sd(s);if([s,a].some(u=>dR(r,u)||Eie(u)))throw new ew("Fungi host JavaScript is inside the Agent project or Git administration; install Fungi outside the project.")}catch(s){throw s instanceof ew?s:new ew("Fungi host JavaScript location cannot be verified; reinstall Fungi outside the project.",{cause:s})}for(const o of[t,n])try{const s=cR(o);if(!s.isFile()||s.nlink>1)throw new ew("Fungi host JavaScript is not an independent file (hardlinked or not regular); use a copying install outside the project (pnpm package-import-method=copy or npm global).")}catch(s){throw s instanceof ew?s:new ew("Fungi host JavaScript cannot be inspected; reinstall Fungi using a copying install outside the project.",{cause:s})}}function D$e(e,t){const n=lR(t),r=Sd(n),i=o=>Eie(o);if([n,r].some(o=>dR(e,o)||i(o)))throw new m0("Packaged native payload is inside the Agent project or a Git-admin folder; reinstall Fungi outside the project.")}function kie(e){return Z_(e,{throwIfNoEntry:!1})!==void 0?Sd(e):ho(kie(yv(e)),nun(e))}function pR(e){return[...new Set(e.flatMap(t=>{if(!p0(t))throw new Error("Sandbox protected paths must be absolute");const n=lR(t);return[n,kie(n)]}))]}var aun=16*1024,uun=3e4;function cun(e,t,n){for(const r of t.split(":")){if(!p0(r))continue;const i=ho(r,"git");try{Q6r(i,X6r.X_OK);const o=Sd(i);if(!cR(o).isFile())continue;if([i,o].some(s=>dR(e,s)||Eie(s))){if(n)return;continue}return i}catch(o){if(!L$e(o))throw o}}}function lun(){const e={};for(const[t,n]of Object.entries(process.env))t.startsWith("GIT_")||(e[t]=n);return{...e,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}}function L$e(e){if(!(e instanceof Error)||!("code"in e))return!1;switch(e.code){case"ENOENT":case"ENOTDIR":case"ELOOP":case"EACCES":case"EISDIR":return!0;default:return!1}}function dU(e,t,n){const r=cun(e,n??process.env.PATH??"",n!==void 0);if(r===void 0)return;const i=eun(r,["--no-pager","-c","core.fsmonitor=false","-c","core.untrackedCache=false","-C",t,"rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:t,env:lun(),maxBuffer:aun,timeout:uun,stdio:["ignore","pipe","ignore"]});if(i.error!==void 0||i.status!==0||!Zan(i.stdout))return;const o=i.stdout.toString("utf8").split(`
1443
- `);if(o.length!==3||o[2]!=="")return;const[s,a]=o;if(!(s===void 0||!p0(s)||!a))try{const u=Sd(s),c=Sd(lR(t,a));return!cR(u).isDirectory()||!cR(c).isDirectory()?void 0:{common:c,worktree:u}}catch(u){if(L$e(u))return;throw u}}function tTr(e,t,n){const r=cun(e,n,!0);if(r===void 0)return;const i=ho(t,"config"),o=Z_(i,{throwIfNoEntry:!1});if(o===void 0||!o.isFile()||o.nlink!==1)return;const s=eun(r,["config","--no-includes","--file",i,"--null","--name-only","--get-regexp","^remote\\..*\\.url$"],{cwd:e,env:lun(),maxBuffer:aun,timeout:uun,stdio:["ignore","pipe","ignore"]});if(s.error!==void 0||!Zan(s.stdout))return;if(s.status===1&&s.stdout.length===0)return new Set;if(s.status!==0||s.stdout.at(-1)!==0)return;const a=new Set;for(const u of s.stdout.toString("utf8").slice(0,-1).split("\0")){const c=/^remote\.([A-Za-z][A-Za-z0-9_.-]*)\.url$/u.exec(u)?.[1];c!==void 0&&a.add(c)}return a}function N$e(e,t){const n=Sd(e),r=Sd(t),i=O$e(n,r);if(p0(i)||i===".."||i.startsWith(`..${uU}`))throw new Error("Sandbox folder resolves outside the project.");if(!Z_(r).isDirectory())throw new Error("Sandbox folder must be a directory.");const o=ho(r,".git"),s=[...new Set([ho(n,".fungi"),ho(r,".fungi")])],a=Z_(o,{throwIfNoEntry:!1});if(a===void 0)return{projectRoot:n,writableRoot:r,readOnly:s};if(a.isSymbolicLink())throw new sun(`Agent folder ${o} is a symlink. Remove the .git symlink or select a different Agent folder before running sandboxed commands.`);s.push(o);const u=dU(n,r);return u!==void 0&&s.push(u.worktree,u.common),{projectRoot:n,writableRoot:r,readOnly:[...new Set(s)]}}var Wa=class extends Error{constructor(e,t,n){super(t,n),this.reason=e}reason;name="LocalBwrapUnavailable"};function nTr(e,t,n=xie){const r=Yan[`${process.platform}-${process.arch}`]?.patch;if(r===void 0)throw new Wa("install","No built native patch digest for this platform; reinstall Fungi.");return Aie(e,"fungi-apply-patch",t,r,n)}function rTr(e,t,n,r=xie){const i=Aie(e,"fungi-bwrap",t,n.bwrap,r);return{sourcePath:e,executableBytes:i,seccomp:Aie(Sie(Xan(e),"fungi-seccomp.bpf"),"fungi-seccomp.bpf",t,n.seccomp,r),seccompWorkspace:Aie(Sie(Xan(e),"fungi-seccomp-workspace.bpf"),"fungi-seccomp-workspace.bpf",t,n.seccompWorkspace,r)}}function Aie(e,t,n,r,i=xie){let o;try{if(D$e(n,e),!Qan(e).isFile())throw new Wa("install",`Packaged ${t} is not a regular file; reinstall Fungi.`);o=i(e)}catch(s){throw s instanceof Error&&"code"in s&&s.code==="ENOENT"?new Wa("install",`Packaged ${t} is missing; reinstall Fungi with optional dependencies enabled.`,{cause:s}):s instanceof m0||s instanceof Wa?s:new Wa("install",`Packaged ${t} cannot be read; reinstall Fungi. No command was started.`,{cause:s})}if(G6r("sha256").update(o).digest("hex")!==r)throw new Wa("install",`Packaged ${t} digest mismatch; reinstall Fungi. No command was started.`);return o}function iTr(e,t=xie){const n=Yan[`${process.platform}-${process.arch}`];if(n?.bwrap===void 0||n.seccomp===void 0||n.seccompWorkspace===void 0)throw new Wa("install","No built native Linux payload digest for this platform; reinstall Fungi.");let r;if(process.env.FUNGI_BUNDLED_CLI){const i=`@fungi.computer/spore-native-${process.platform}-${process.arch}`,o=`Packaged ${i}/bin/fungi-bwrap cannot be read; reinstall Fungi.`;let s;try{s=K6r(process.env.FUNGI_BUNDLED_CLI).resolve.paths(i)}catch(u){throw new Wa("install",o,{cause:u})}if(s===null)throw new Wa("install",o);let a;for(const u of s){const c=Sie(u,i);try{if(V6r(c,{throwIfNoEntry:!1})!==void 0){a=c;break}}catch(l){throw new Wa("install",o,{cause:l})}}if(a===void 0)throw new Wa("install",`Missing ${i}; reinstall Fungi with optional dependencies enabled.`);try{if(D$e(e,a),!Qan(a).isDirectory())throw new Wa("install",o)}catch(u){throw u instanceof m0||u instanceof Wa?u:new Wa("install",o,{cause:u})}r=Sie(a,"bin","fungi-bwrap")}else r=J6r(new URL("../native/bin/fungi-bwrap",import.meta.url));return rTr(r,e,{bwrap:n.bwrap,seccomp:n.seccomp,seccompWorkspace:n.seccompWorkspace},t)}function $$e(e,t){const n=q6r(e,t);return!Jan(n)&&n!==".."&&!n.startsWith(`..${z6r}`)}function dun(){if(process.env.FUNGI_BUNDLED_CLI){const e=`@fungi.computer/spore-native-${process.platform}-${process.arch}`;try{const n=j6r(process.env.FUNGI_BUNDLED_CLI).resolve.paths(e)?.map(r=>uR(r,e)).find(r=>R$e(r,{throwIfNoEntry:!1}));if(n!==void 0)return uR(n,"bin","fungi-apply-patch");throw new Error("Native package not installed")}catch(t){throw new Wa("install",`Missing ${e}/bin/fungi-apply-patch; reinstall Fungi.`,{cause:t})}}return H6r(new URL("../native/bin/fungi-apply-patch",import.meta.url))}function Tie(e,t=F6r){const n=dun();D$e(e,wie(wie(n)));const r=nTr(n,e,t),i=process.platform==="linux"?iTr(e,t):void 0,o=[wie(n),...i===void 0?[]:[wie(i.sourcePath)]].flatMap(p=>[bie(p),_ie(p)]),s=process.env.XDG_RUNTIME_DIR,a=s??uR(W6r().homedir,".local","state"),u=process.getuid?.();if(u===void 0||!Jan(a))throw new m0("Native staging needs an absolute runtime directory and POSIX user.");if(s!==void 0){const p=R$e(s,{throwIfNoEntry:!1});if(p===void 0||!p.isDirectory()||p.uid!==u||(p.mode&63)!==0)throw new m0("XDG_RUNTIME_DIR must be a private directory owned by this user.")}const c=uR(a,"fungi"),l=_ie(e);if($$e(l,bie(c)))throw new m0("Host native staging cannot live inside the Agent project.");let d;try{$6r(c,{recursive:!0,mode:448});const p=_ie(c);if($$e(l,p))throw new m0("Host native staging resolves inside the Agent project.");const m=R$e(p);if(!m.isDirectory()||m.uid!==u||(m.mode&63)!==0)throw new m0("Host native staging root must be private and owned by this user.");const h=U6r(uR(p,"native-"));d=h;const f=[h,...o],g=(x,k,T)=>{const C=uR(h,x);return B6r(C,k,{flag:"wx",mode:T}),C},y=g("fungi-apply-patch",r,320),v=i&&g("fungi-bwrap",i.executableBytes,320),_=i&&g("fungi-seccomp.bpf",i.seccomp,256),b=i&&g("fungi-seccomp-workspace.bpf",i.seccompWorkspace,256);let w=!1;return{admitProject:x=>{if(w)throw new Error("Native staging owner is closed");const k=_ie(x);for(const T of f)if($$e(k,T))throw new m0("Native files must be outside the Agent project.")},patch:x=>{if(w)throw new Error("Native staging owner is closed");if(bie(x)!==bie(n))throw new Wa("install","Native patch helper changed; restart Fungi.");return y},linux:x=>{if(w)throw new Error("Native staging owner is closed");if(i===void 0||v===void 0)throw new Wa("install","No packaged Linux sandbox; reinstall Fungi.");return{executable:v,seccompFilter:x.mode==="workspace"?i.seccompWorkspace:i.seccomp}},probeFilter:x=>{if(w)throw new Error("Native staging owner is closed");if(x===i?.seccomp&&_!==void 0)return _;if(x===i?.seccompWorkspace&&b!==void 0)return b;throw new Wa("install","Unknown native filter; restart Fungi.")},close:()=>{w||(w=!0,Kan(h,{recursive:!0}))}}}catch(p){throw d!==void 0&&Kan(d,{recursive:!0}),p instanceof m0||p instanceof Wa?p:new Wa("install","Cannot copy verified native files into the private runtime directory; reinstall Fungi.",{cause:p})}}xt();import{spawnSync as oTr}from"node:child_process";import{closeSync as sTr,openSync as aTr,realpathSync as uTr}from"node:fs";import{userInfo as cTr}from"node:os";import{existsSync as cA,lstatSync as lTr,mkdirSync as pun,realpathSync as pU,statSync as mU}from"node:fs";import{dirname as mun,isAbsolute as U$e,join as F$e,relative as B$e,sep as j$e}from"node:path";function dTr(e,t,n,r,i=process.env,o,s=[]){const a=e.writableRoot;for(const l of new Set([e.projectRoot,a]))pun(F$e(l,".fungi"),{recursive:!0});e.fungiCache!==void 0&&pun(e.fungiCache,{recursive:!0,mode:448});const u=[...e.mode==="read-only"?["--unshare-all"]:["--unshare-user","--unshare-pid","--unshare-ipc","--unshare-uts","--unshare-cgroup-try"],"--die-with-parent","--new-session","--seccomp","3","--ro-bind","/","/","--bind",e.temporaryDirectory,"/tmp","--tmpfs","/run",...cA("/var/run")&&pU("/var/run")!=="/run"?["--tmpfs",pU("/var/run")]:[],"--dev","/dev","--proc","/proc"];e.mode==="read-only"&&u.push("--ro-bind",a,a);for(const l of e.writable)u.push("--bind",l,l);if(e.mode==="workspace")for(const l of pR(e.readOnly))cA(l)&&u.push("--ro-bind",l,l);const c=i.XDG_RUNTIME_DIR;if(c&&U$e(c)&&cA(c)&&u.push("--tmpfs",pU(c)),e.mode==="workspace"&&cA("/etc/resolv.conf")){const l=pU("/etc/resolv.conf");l.startsWith("/run/")&&u.push("--ro-bind",l,l)}if(i.HOME&&U$e(i.HOME))for(const l of[F$e(i.HOME,".docker","run"),F$e(i.HOME,".docker","desktop")])cA(l)&&mU(l).isDirectory()&&u.push("--tmpfs",pU(l));for(const l of pTr(e.hidden,e.writable))u.push("--bind",l,l);for(const l of e.hidden){const d=B$e("/tmp",l),p=B$e(a,l);d!==".."&&!d.startsWith(`..${j$e}`)&&(p===".."||p.startsWith(`..${j$e}`))||cA(l)&&mU(l).isDirectory()&&u.push("--tmpfs",l)}if(e.sshAgentSocket!==void 0&&u.push("--bind",e.sshAgentSocket,e.sshAgentSocket),e.sshAgentMask!==void 0&&u.push("--ro-bind","/dev/null",e.sshAgentMask),o!==void 0){if(!mU(o).isFile())throw new Error("Local native helper must be a regular file");u.push("--ro-bind",o,o)}for(const l of s){if(!mU(l).isFile())throw new Error("Local sandbox payload must be a regular file");u.push("--ro-bind",l,l)}return u.push("--setenv","GIT_DISCOVERY_ACROSS_FILESYSTEM","1"),u.push("--setenv","FUNGI_SANDBOX",e.mode),e.mode==="read-only"&&u.push("--setenv","FUNGI_SANDBOX_NETWORK_DISABLED","1"),u.push("--chdir",n,"--",...r),{...t,args:u}}function hun(e,t){const n=B$e(e,t);return n!==""&&!U$e(n)&&n!==".."&&!n.startsWith(`..${j$e}`)}function pTr(e,t){const n=new Set;for(const r of e)for(const i of t){if(!hun(i,r))continue;const o=[];for(let s=mun(r);hun(i,s);s=mun(s))o.unshift(s);for(const s of o){if(!cA(s))break;if(lTr(s).isSymbolicLink())throw new M$e("Sandbox writable folder reaches a Fungi hidden record through a symlink.");if(!mU(s).isDirectory())break;n.add(s)}}return[...n]}import{readFileSync as mTr,realpathSync as Iie}from"node:fs";import{dirname as hTr,isAbsolute as fTr,relative as gTr,sep as yTr}from"node:path";var vTr="/usr/bin/sandbox-exec";function W$e(e,t){const n=gTr(e,t);return!fTr(n)&&n!==".."&&!n.startsWith(`..${yTr}`)}function _Tr(e,t){const n=pR(e.hidden),r=e.mode==="workspace"?[e.writableRoot,e.temporaryDirectory]:[e.temporaryDirectory];if(r.some(g=>n.some(y=>W$e(g,hTr(y))||W$e(y,g))))throw new M$e("Seatbelt writable folder or temp contains a Fungi hidden record or its parent.");const i=[],o=(g,y)=>(i.push("-D",`${g}=${y}`),`(param "${g}")`),s=n.flatMap((g,y)=>{const v=o(`HIDDEN_${String(y)}`,g);return[`(deny file-read* (literal ${v}))`,`(deny file-read* (subpath ${v}))`]}),a=n.flatMap((g,y)=>{const v=`(param "HIDDEN_${String(y)}")`;return[`(deny file-write* (literal ${v}))`,`(deny file-write* (subpath ${v}))`]}),c=pR(e.readOnly).map((g,y)=>{const v=o(`PROTECTED_${String(y)}`,g);return{path:g,rules:[`(require-not (literal ${v}))`,`(require-not (subpath ${v}))`]}}),l=Iie(e.temporaryDirectory),d=e.fungiCache!==void 0&&W$e(e.fungiCache,l)?new Set(pR([e.fungiCache])):void 0,p=r.map((g,y)=>{const v=o(`WRITABLE_ROOT_${String(y)}`,Iie(g)),_=c.filter(({path:b})=>!(e.mode==="workspace"&&y===1&&d?.has(b))).flatMap(({rules:b})=>b);return`(require-all (subpath ${v}) ${_.join(" ")})`}),m=[...new Set(r.map(g=>Iie(g)))].map((g,y)=>`(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal ${o(`ANCHOR_${String(y)}`,g)})))`),f=[mTr(new URL("./seatbelt/safe-base.sbpl",import.meta.url),"utf8"),"(allow file-read*)",...s,`(allow file-write* ${p.join(" ")})`,...a,...m,"(deny system-fcntl (fcntl-command 80 110))"].join(`
1444
- `);return{executable:vTr,args:["-p",f,...i,"--",...t],temporaryDirectory:Iie(e.temporaryDirectory)}}xt();var wTr=A.strictObject({kind:A.enum(["unsupported","install","folder","startup-refused"]),message:A.string()}),Vc=class extends Error{constructor(e){super(`Local sandbox unavailable: ${e.message}`),this.reason=e}reason;name="LocalSandboxUnavailable"};function mR(e){return e instanceof sun?{kind:"folder",message:e.message}:e instanceof M$e?{kind:"folder",message:e.message}:e instanceof ew?{kind:"install",message:e.message}:e instanceof m0?{kind:"install",message:e.message}:e instanceof Wa?{kind:e.reason,message:e.message}:{kind:"startup-refused",message:e instanceof Error?e.message:"Sandbox preparation failed."}}function fun(e,t,n){try{N$e(e.project,e.folder)}catch(o){return{state:"unavailable",reason:{kind:"folder",message:o instanceof Error?o.message:"Invalid sandbox folder."}}}const r=e.platform??process.platform;if(r!=="linux"&&r!=="darwin")return{state:"unavailable",reason:{kind:"unsupported",message:`${e.mode==="workspace"?"Workspace":"Read-only"} on ${r} needs a supported OS sandbox; use --yolo or run on macOS/Linux.`}};let i;try{i=t??(r==="linux"?Tie(e.project):void 0);const o=r==="linux"?"/tmp":e.temporaryDirectory;let s=!1;const a={command:(p,m,h,f)=>{if(s)throw new Vc({kind:"startup-refused",message:"Sandbox has been closed."});const g=N$e(e.project,e.folder);try{const y=Z6r(g,e.mode,e.temporaryDirectory,process.env,cTr().homedir,r),v=r==="linux"?i?.linux(y):void 0,_=h===void 0?void 0:i?.patch(h),b=_===void 0?m:[m[0]===h?_:m[0],...m.slice(1).map(k=>k===h?_:k)],w=v!==void 0?dTr(y,v,p,b,void 0,_,f):_Tr(y,b);let x={TMPDIR:o};return r==="linux"&&y.sshAgentSocket!==void 0&&(x={TMPDIR:o,SSH_AUTH_SOCK:y.sshAgentSocket}),{...w,environment:x}}catch(y){throw new Vc(mR(y))}},close:()=>{s||(s=!0,t===void 0&&i?.close())}},u=a.command(uTr(e.folder),["/usr/bin/true"]);let c;const l=()=>{if(u.seccompFilter!==void 0){const p=i?.probeFilter(u.seccompFilter);if(p===void 0)throw new Error("No Linux filter staging owner");c=aTr(p,"r")}return oTr(u.executable,[...u.args],{cwd:e.folder,env:{...u.environment},encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","pipe",...c===void 0?[]:[c]]})},d=(()=>{try{return n?.(u)??l()}finally{c!==void 0&&sTr(c)}})();if(d.status!==0){a.close();const p=d.error===void 0?d.stderr.trim():"";return{state:"unavailable",reason:{kind:"startup-refused",message:`${e.mode==="workspace"?"Workspace":"Read-only"} on this ${r==="darwin"?"Mac":"Linux host"} needs a working ${r==="darwin"?"sandbox-exec profile probe":"bwrap installation"}; use --yolo or ${r==="darwin"?"check the failed Seatbelt profile probe":"fix the sandbox installation"}. ${d.error?.message??(p.length>0?p:`Sandbox startup exited ${String(d.status)} (${String(d.signal)}).`)}`}}}return{state:"ready",sandbox:a}}catch(o){return t===void 0&&i?.close(),{state:"unavailable",reason:o instanceof Vc?o.reason:mR(o)}}}var bTr=A.strictObject({mode:A.enum(["full-access","workspace","read-only"]),available:A.boolean(),reason:wTr.optional()}),xTr=class extends Error{constructor(e){super(`Files write targets a protected Local path: ${e}`),this.path=e}path;name="ProtectedLocalFilesPath"};function gun(e,t){const n=P6r(e,t);return!R6r(n)&&n!==".."&&!n.startsWith(`..${D6r}`)}function yun(e){const t=e.mode(),n=cU(e.project,e.folder),r=e.agentId??`probe-${String(process.pid)}-${process.hrtime.bigint().toString(36)}`,i=()=>{try{const k=process.env.FUNGI_LAUNCHER,T=k===void 0?L6r(import.meta.url):process.env.FUNGI_BUNDLED_CLI;if(T===void 0)throw new ew("Packed CLI entry was not provided by the launcher; reinstall Fungi outside the project.");eTr(e.project,T,k??T)}catch(k){throw new Vc(k instanceof ew?mR(k):{kind:"install",message:`Fungi host JavaScript identity cannot be verified (${k instanceof Error?k.message:String(k)}); reinstall Fungi using a copying install outside the project.`})}};t!=="full-access"&&i();let o=t!=="full-access",s=t==="full-access"?void 0:P$e(r,e.project);const a=e.platform===void 0?{}:{platform:e.platform},u=(e.platform??process.platform)==="linux"||(e.platform??process.platform)==="darwin",c=()=>{try{return Tie(e.project,e.readNativePatchSource)}catch(k){throw new Vc(mR(k))}},l=k=>{try{k?.admitProject(e.project)}catch(T){throw new Vc(mR(T))}};let d,p=!1,m;try{t!=="full-access"&&(d=u?e.native??c():void 0,l(d),p=d!==void 0,m=fun({project:e.project,folder:n.absolute,mode:t,temporaryDirectory:s??P$e(r,e.project),...a},d,e.runProbe))}catch(k){try{e.native===void 0&&d?.close()}finally{s!==void 0&&C$e(s,{recursive:!0,force:!0})}throw k}let h=m?.state==="ready"?m.sandbox:void 0,f=h===void 0?void 0:t,g=m?.state==="unavailable"?m.reason:e.defaultReason;if(g!==void 0){if(s!==void 0&&C$e(s,{recursive:!0,force:!0}),g.kind==="folder")throw e.native===void 0&&d?.close(),new Error(g.message);if(t!=="full-access")throw e.native===void 0&&d?.close(),new Vc(g)}let y=!1;const v=()=>{if(y)throw new Error("Local sandbox owner is closed");try{if(cU(e.project,e.folder).absolute===n.absolute)return;throw new Error("Local Agent folder authority changed while open")}catch(k){throw g={kind:"folder",message:k instanceof Error?k.message:String(k)},new Vc(g)}};function _(k){if(h!==void 0&&f===k)return;h?.close(),h=void 0,o||(i(),o=!0),d??=e.native??c(),p||(l(d),p=!0),s??=P$e(r,e.project);const T=fun({project:e.project,folder:n.absolute,mode:k,temporaryDirectory:s,...a},d,e.runProbe);if(T.state==="ready")h=T.sandbox,f=k,g=void 0;else throw g=T.reason,new Vc(g)}function b(k,T,C,O){if(v(),e.mode()!=="full-access"){if(_(e.mode()==="read-only"?"read-only":"workspace"),h!==void 0)try{const P=h.command(k,T,C,O);return g=void 0,P}catch(P){throw g=P instanceof Vc?P.reason:mR(P),new Vc(g)}throw g===void 0?new Error("Local sandbox preparation produced no result"):g.kind==="folder"?new Error(g.message):new Vc(g)}}const w=()=>oun(process.env,N6r().homedir,e.platform??process.platform),x=()=>{e.mode()!=="full-access"&&b(n.absolute,["/usr/bin/true"])};return{launch:b,assertReady:x,assertModeReady:k=>{if(k!=="full-access"){if(v(),_(k),h===void 0)throw new Error("Local sandbox preparation produced no result");h.command(n.absolute,["/usr/bin/true"])}},hiddenRecords:()=>e.mode()==="full-access"?[]:pR(w()),assertWrite:k=>{if(e.mode()==="full-access")return;x();const T=N$e(e.project,n.absolute),C=pR([...T.readOnly,O6r(T.writableRoot,".git"),...w()]);for(const O of k){const P=M6r(O);if(!gun(T.writableRoot,P)||C.some($=>gun($,P)))throw new xTr(P)}},status:()=>{if(y)throw new Error("Local sandbox owner is closed");return g===void 0?{mode:e.mode(),available:!0}:{mode:e.mode(),available:!1,reason:g}},close:()=>{if(!y){y=!0;try{h?.close()}finally{e.native===void 0&&d?.close(),s!==void 0&&C$e(s,{recursive:!0})}}}}}function Cie(e,t,n){try{yun({project:e,folder:t,mode:()=>"workspace",native:n}).close();return}catch(r){if(r instanceof Vc)return r.reason;throw r}}var q$e=5;function STr(){return A.string().regex(/^[a-f0-9]{64}$/u).optional().parse(process.env.FUNGI_BUNDLED_BUILD_ID)??"source"}var vun=A.looseObject({protocol:A.number().int().positive(),version:A.string().min(1),serviceId:A.string().refine(e=>gan.service.is(e)),pid:A.number().int().positive(),startedAt:A.string().min(1)}),z$e=A.strictObject({...vun.shape,protocol:A.literal(q$e),baseUrl:A.url().refine(e=>{const t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"&&t.port!==""&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""})}),ETr=z$e.extend({diagnostics:E6r}),H$e=A.strictObject({uiAttachmentLifetime:aan.optional(),invocationRoot:A.string().min(1),clientPath:cie,mode:oU.optional(),databasePath:A.string().min(1).optional(),sessionId:A.string().min(1).optional(),fungiMcp:aie.optional()}),kTr=A.strictObject({uiAttachmentLifetime:aan.optional(),invocationRoot:A.string().min(1),clientPath:cie,mode:oU.optional(),databasePath:A.string().min(1),requestId:A.string().min(1),fungiMcp:aie.optional()}),ATr=H$e.omit({clientPath:!0,uiAttachmentLifetime:!0}).extend({sessionId:A.string().min(1),limit:A.number().int().min(1).max(200)}),MVr=A.strictObject({agentId:A.string().min(1),databasePath:A.string().min(1),sessionId:A.string().min(1),routePath:A.templateLiteral(["/agents/",A.uuid({version:"v4"})])}),TTr=A.strictObject({invocationRoot:A.string().min(1),archived:A.boolean().default(!1)}),ITr=A.strictObject({invocationRoot:A.string().min(1),agentId:A.string().min(1),archived:A.boolean()}),DVr=A.strictObject({code:A.literal("agent_archive_refused"),reason:A.enum(d6r),error:A.string()}),LVr=A.strictObject({root:A.string().min(1),agents:A.array(A.strictObject({agentId:A.string().min(1),name:A.string().optional(),createdBy:A.string().nullable().optional(),unreadable:A.string().optional(),databasePath:A.string().min(1),sessionCount:A.number().int().nonnegative(),updatedAt:A.number().optional()})),sessions:A.array(A.strictObject({databasePath:A.string().min(1),sessionId:A.string().min(1),title:A.string(),createdAt:A.number(),updatedAt:A.number()})),problems:A.array(A.strictObject({kind:A.enum(["corrupt","in_use","unreadable"])}))}),NVr=A.array(A.strictObject({providerId:A.string().min(1),providerName:A.string().min(1),id:A.string().min(1),name:A.string().min(1),reasoning:A.array(A.enum($ee))}));function CTr(e){return L5r(e??uA(N5r(),".fungi","service"))}async function _un(e){const t=CTr(e);return await man(t,{recursive:!0,mode:448}),await C5r(t,448),O5r(t)}var hU=e=>uA(e,"service.json");async function wun(e){let t;try{t=await R5r(hU(e),"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;throw i}let n;try{n=JSON.parse(t)}catch(i){if(i instanceof SyntaxError)return{kind:"unidentified"};throw i}const r=vun.safeParse(n);if(!r.success){const i=z$e.pick({serviceId:!0,baseUrl:!0}).safeParse(n);if(i.success)throw new RTr(e,i.data);return{kind:"unidentified"}}return r.data.protocol!==q$e?{kind:"other-protocol",lifecycle:r.data}:{kind:"current",record:z$e.parse(n)}}var RTr=class extends Error{name="LocalServiceRecordWithoutPid";constructor(e,t){super(`An older Fungi service (${t.serviceId} on port ${new URL(t.baseUrl).port}) is registered in ${hU(e)} without a process identity. Fungi cannot safely signal it. End the process whose command line contains \`--internal-service ${e}\`. If it is no longer running, move ${hU(e)} aside. Then retry; saved Sessions are kept.`)}};async function OTr(e,t){const n=await wun(e);(n?.kind==="current"&&n.record.serviceId===t||n?.kind==="other-protocol"&&n.lifecycle.serviceId===t)&&await die(hU(e),{force:!0})}var Rie=e=>uA(e,"owner.lock","sqlite-owner");async function G$e(e){try{return await M5r(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}}async function PTr(e){if(await G$e(uA(e,"owner.lock"))&&!await G$e(Rie(e)))throw new Error("A previous Fungi service may still own this directory. Stop that service before starting Fungi again; its owner lock was not released.")}async function bun(e,t){if(t==="startup")return I5r.default.lock(uA(e,t),{realpath:!1,lockfilePath:uA(e,`${t}.lock`),retries:{retries:100,minTimeout:100,maxTimeout:100},onCompromised(o){throw o}});const n=await H5r(e),r=uA(e,"owner.lock");let i=!1;try{await PTr(e),await G$e(Rie(e))&&await die(r,{recursive:!0}),await man(r),i=!0,await D5r(Rie(e),"",{flag:"wx",mode:384})}catch(o){try{i&&await die(r,{recursive:!0})}finally{n()}throw o}return async()=>{try{await die(Rie(e),{force:!0}),await P5r(r)}finally{n()}}}async function MTr(e){return await z5r(e)!==void 0}var DTr=A.looseObject({code:A.string().optional(),cause:A.looseObject({code:A.string().optional()}).optional()});async function LTr(e,t=2e3){try{const n=await fetch(`${e.baseUrl}/service/${e.serviceId}/status`,{redirect:"error",signal:AbortSignal.timeout(t)});if(!n.ok)return{kind:"unavailable"};const r=ETr.parse(await n.json());return r.serviceId===e.serviceId&&r.baseUrl===e.baseUrl&&r.pid===e.pid&&r.startedAt===e.startedAt&&r.version===e.version?{kind:"running",service:r}:{kind:"unavailable"}}catch(n){const r=DTr.safeParse(n);if(r.success){const i=[r.data.code,r.data.cause?.code];if(i.includes("ECONNREFUSED")||i.includes("ConnectionRefused"))return{kind:"not-running"}}return{kind:"unavailable"}}}var NTr=A.strictObject({credentialPath:A.string().min(1),endpoint:A.string().optional()}),xun=A.strictObject({kind:A.enum(["not-logged-in","removed","revoked"]),message:A.string(),unconfirmedComputers:A.array(A.strictObject({name:A.string(),url:A.string()}))});async function $Tr(e,t){const{clearOffline:n,directory:r,...i}=t,o=await _un(r),s=await bun(o,"startup");try{const a=await wun(o),u=await MTr(o);if(a?.kind!=="current"){if(u)throw new Error("The running Local account owner is unavailable");return await n(e,i)}const c=await LTr(a.record);if(c.kind!=="running"){if(u||c.kind==="unavailable")throw new Error("The running Local account owner is unavailable");return await n(e,i)}const l=c.service,d=new URL(`${l.baseUrl}/service/${l.serviceId}/auth`);d.protocol="ws:";const p=new WebSocket(d),m=Gft(p);try{const h={credentialPath:i.credentialPath};return e!==void 0&&(h.endpoint=e.toString()),xun.parse(await m.signOutFungi(h))}finally{m[Symbol.dispose](),p.close()}}finally{await s()}}var h0="fungi",Sun="openid profile email offline_access models:invoke git:tracker billing:read",Oie="127.0.0.1",V$e="/oauth/callback",Eun="/client-registration",UTr=`http://${Oie}${V$e}`,kun=A.object({teamId:A.string().min(1).max(256),handle:A.string().min(1).max(256),name:A.string().min(1).max(256)}),El=A.looseObject({type:A.literal("oauth"),access:A.string(),refresh:A.string(),expires:A.number(),clientId:A.string().min(1).optional(),issuer:A.url().optional(),clientInformation:A.json().optional(),tokens:A.json().optional(),codeVerifier:A.string().optional(),localBackends:A.array(NAr).max(16).optional(),team:kun.optional(),teamCount:A.number().int().min(0).max(1e3).optional()}).transform(e=>{const t={...e};return delete t.machineEnrollments,t});function Pie(e){const t=JSON.stringify(e),n=JSON.parse(t);return A.json().parse(n)}function FTr(e){return{client_name:"Fungi Local",redirect_uris:[e],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:Sun}}function f0(e){return _$e(e)}async function g0(e){const t=await f0(e).read(h0);if(t?.type!=="oauth")return;const n=El.safeParse(t);if(!n.success)throw new Error("Fungi Local credential data is invalid");return n.data}function Aun(e){return{read:async()=>{const t=await g0(e),n=await f0(e).readMachineEnrollments(),r=t?.issuer!==void 0&&t.access!==""?t.issuer:void 0,i=n.find(o=>o.origin===r&&Xsn(o)==="oauth");return[...r!==void 0?[{kind:"oauth",origin:r,enrollments:i?.enrollments??[]}]:[],...n.flatMap(o=>Xsn(o)==="oyster"?[{kind:"oyster",origin:o.origin,enrollments:o.enrollments}]:[])]},update:async(t,n)=>{const r=FAr.parse(t);if(r.kind==="oyster"){await f0(e).modifyMachineEnrollments(r.origin,n);return}await f0(e).modifyMachineEnrollments(r.origin,n,{providerId:h0,admit:i=>{const o=El.safeParse(i);if(!o.success||o.data.access===""||o.data.issuer!==r.origin)throw new Error("Fungi sign-in changed before machine enrollment was persisted")}})}}}async function hR(e,t){await f0(t).modify(h0,r=>{const i=El.safeParse(r),o=i.success?i.data:{type:"oauth",access:"",refresh:"",expires:0},s=El.parse(Object.fromEntries(Object.entries({...o,...e}).filter(([,a])=>a!==void 0)));return Promise.resolve(s)})}function BTr(e){return`fungi login --fungi-mcp ${e instanceof URL?e.href:e}`}function Tun(e){rie.stderr.write(`Open this URL to sign in to Fungi:
1443
+ `);if(o.length!==3||o[2]!=="")return;const[s,a]=o;if(!(s===void 0||!p0(s)||!a))try{const u=Sd(s),c=Sd(lR(t,a));return!cR(u).isDirectory()||!cR(c).isDirectory()?void 0:{common:c,worktree:u}}catch(u){if(L$e(u))return;throw u}}function tTr(e,t,n){const r=cun(e,n,!0);if(r===void 0)return;const i=ho(t,"config"),o=Z_(i,{throwIfNoEntry:!1});if(o===void 0||!o.isFile()||o.nlink!==1)return;const s=eun(r,["config","--no-includes","--file",i,"--null","--name-only","--get-regexp","^remote\\..*\\.url$"],{cwd:e,env:lun(),maxBuffer:aun,timeout:uun,stdio:["ignore","pipe","ignore"]});if(s.error!==void 0||!Zan(s.stdout))return;if(s.status===1&&s.stdout.length===0)return new Set;if(s.status!==0||s.stdout.at(-1)!==0)return;const a=new Set;for(const u of s.stdout.toString("utf8").slice(0,-1).split("\0")){const c=/^remote\.([A-Za-z][A-Za-z0-9_.-]*)\.url$/u.exec(u)?.[1];c!==void 0&&a.add(c)}return a}function N$e(e,t){const n=Sd(e),r=Sd(t),i=O$e(n,r);if(p0(i)||i===".."||i.startsWith(`..${uU}`))throw new Error("Sandbox folder resolves outside the project.");if(!Z_(r).isDirectory())throw new Error("Sandbox folder must be a directory.");const o=ho(r,".git"),s=[...new Set([ho(n,".fungi"),ho(r,".fungi")])],a=Z_(o,{throwIfNoEntry:!1});if(a===void 0)return{projectRoot:n,writableRoot:r,readOnly:s};if(a.isSymbolicLink())throw new sun(`Agent folder ${o} is a symlink. Remove the .git symlink or select a different Agent folder before running sandboxed commands.`);s.push(o);const u=dU(n,r);return u!==void 0&&s.push(u.worktree,u.common),{projectRoot:n,writableRoot:r,readOnly:[...new Set(s)]}}var Wa=class extends Error{constructor(e,t,n){super(t,n),this.reason=e}reason;name="LocalBwrapUnavailable"};function nTr(e,t,n=xie){const r=Yan[`${process.platform}-${process.arch}`]?.patch;if(r===void 0)throw new Wa("install","No built native patch digest for this platform; reinstall Fungi.");return Aie(e,"fungi-apply-patch",t,r,n)}function rTr(e,t,n,r=xie){const i=Aie(e,"fungi-bwrap",t,n.bwrap,r);return{sourcePath:e,executableBytes:i,seccomp:Aie(Sie(Xan(e),"fungi-seccomp.bpf"),"fungi-seccomp.bpf",t,n.seccomp,r),seccompWorkspace:Aie(Sie(Xan(e),"fungi-seccomp-workspace.bpf"),"fungi-seccomp-workspace.bpf",t,n.seccompWorkspace,r)}}function Aie(e,t,n,r,i=xie){let o;try{if(D$e(n,e),!Qan(e).isFile())throw new Wa("install",`Packaged ${t} is not a regular file; reinstall Fungi.`);o=i(e)}catch(s){throw s instanceof Error&&"code"in s&&s.code==="ENOENT"?new Wa("install",`Packaged ${t} is missing; reinstall Fungi with optional dependencies enabled.`,{cause:s}):s instanceof m0||s instanceof Wa?s:new Wa("install",`Packaged ${t} cannot be read; reinstall Fungi. No command was started.`,{cause:s})}if(G6r("sha256").update(o).digest("hex")!==r)throw new Wa("install",`Packaged ${t} digest mismatch; reinstall Fungi. No command was started.`);return o}function iTr(e,t=xie){const n=Yan[`${process.platform}-${process.arch}`];if(n?.bwrap===void 0||n.seccomp===void 0||n.seccompWorkspace===void 0)throw new Wa("install","No built native Linux payload digest for this platform; reinstall Fungi.");let r;if(process.env.FUNGI_BUNDLED_CLI){const i=`@fungi.computer/spore-native-${process.platform}-${process.arch}`,o=`Packaged ${i}/bin/fungi-bwrap cannot be read; reinstall Fungi.`;let s;try{s=K6r(process.env.FUNGI_BUNDLED_CLI).resolve.paths(i)}catch(u){throw new Wa("install",o,{cause:u})}if(s===null)throw new Wa("install",o);let a;for(const u of s){const c=Sie(u,i);try{if(V6r(c,{throwIfNoEntry:!1})!==void 0){a=c;break}}catch(l){throw new Wa("install",o,{cause:l})}}if(a===void 0)throw new Wa("install",`Missing ${i}; reinstall Fungi with optional dependencies enabled.`);try{if(D$e(e,a),!Qan(a).isDirectory())throw new Wa("install",o)}catch(u){throw u instanceof m0||u instanceof Wa?u:new Wa("install",o,{cause:u})}r=Sie(a,"bin","fungi-bwrap")}else r=J6r(new URL("../native/bin/fungi-bwrap",import.meta.url));return rTr(r,e,{bwrap:n.bwrap,seccomp:n.seccomp,seccompWorkspace:n.seccompWorkspace},t)}function $$e(e,t){const n=q6r(e,t);return!Jan(n)&&n!==".."&&!n.startsWith(`..${z6r}`)}function dun(){if(process.env.FUNGI_BUNDLED_CLI){const e=`@fungi.computer/spore-native-${process.platform}-${process.arch}`;try{const n=j6r(process.env.FUNGI_BUNDLED_CLI).resolve.paths(e)?.map(r=>uR(r,e)).find(r=>R$e(r,{throwIfNoEntry:!1}));if(n!==void 0)return uR(n,"bin","fungi-apply-patch");throw new Error("Native package not installed")}catch(t){throw new Wa("install",`Missing ${e}/bin/fungi-apply-patch; reinstall Fungi.`,{cause:t})}}return H6r(new URL("../native/bin/fungi-apply-patch",import.meta.url))}function Tie(e,t=F6r){const n=dun();D$e(e,wie(wie(n)));const r=nTr(n,e,t),i=process.platform==="linux"?iTr(e,t):void 0,o=[wie(n),...i===void 0?[]:[wie(i.sourcePath)]].flatMap(p=>[bie(p),_ie(p)]),s=process.env.XDG_RUNTIME_DIR,a=s??uR(W6r().homedir,".local","state"),u=process.getuid?.();if(u===void 0||!Jan(a))throw new m0("Native staging needs an absolute runtime directory and POSIX user.");if(s!==void 0){const p=R$e(s,{throwIfNoEntry:!1});if(p===void 0||!p.isDirectory()||p.uid!==u||(p.mode&63)!==0)throw new m0("XDG_RUNTIME_DIR must be a private directory owned by this user.")}const c=uR(a,"fungi"),l=_ie(e);if($$e(l,bie(c)))throw new m0("Host native staging cannot live inside the Agent project.");let d;try{$6r(c,{recursive:!0,mode:448});const p=_ie(c);if($$e(l,p))throw new m0("Host native staging resolves inside the Agent project.");const m=R$e(p);if(!m.isDirectory()||m.uid!==u||(m.mode&63)!==0)throw new m0("Host native staging root must be private and owned by this user.");const h=U6r(uR(p,"native-"));d=h;const f=[h,...o],g=(x,k,T)=>{const C=uR(h,x);return B6r(C,k,{flag:"wx",mode:T}),C},y=g("fungi-apply-patch",r,320),v=i&&g("fungi-bwrap",i.executableBytes,320),_=i&&g("fungi-seccomp.bpf",i.seccomp,256),b=i&&g("fungi-seccomp-workspace.bpf",i.seccompWorkspace,256);let w=!1;return{admitProject:x=>{if(w)throw new Error("Native staging owner is closed");const k=_ie(x);for(const T of f)if($$e(k,T))throw new m0("Native files must be outside the Agent project.")},patch:x=>{if(w)throw new Error("Native staging owner is closed");if(bie(x)!==bie(n))throw new Wa("install","Native patch helper changed; restart Fungi.");return y},linux:x=>{if(w)throw new Error("Native staging owner is closed");if(i===void 0||v===void 0)throw new Wa("install","No packaged Linux sandbox; reinstall Fungi.");return{executable:v,seccompFilter:x.mode==="workspace"?i.seccompWorkspace:i.seccomp}},probeFilter:x=>{if(w)throw new Error("Native staging owner is closed");if(x===i?.seccomp&&_!==void 0)return _;if(x===i?.seccompWorkspace&&b!==void 0)return b;throw new Wa("install","Unknown native filter; restart Fungi.")},close:()=>{w||(w=!0,Kan(h,{recursive:!0}))}}}catch(p){throw d!==void 0&&Kan(d,{recursive:!0}),p instanceof m0||p instanceof Wa?p:new Wa("install","Cannot copy verified native files into the private runtime directory; reinstall Fungi.",{cause:p})}}xt();import{spawnSync as oTr}from"node:child_process";import{closeSync as sTr,openSync as aTr,realpathSync as uTr}from"node:fs";import{userInfo as cTr}from"node:os";import{existsSync as cA,lstatSync as lTr,mkdirSync as pun,realpathSync as pU,statSync as mU}from"node:fs";import{dirname as mun,isAbsolute as U$e,join as F$e,relative as B$e,sep as j$e}from"node:path";function dTr(e,t,n,r,i=process.env,o,s=[]){const a=e.writableRoot;for(const l of new Set([e.projectRoot,a]))pun(F$e(l,".fungi"),{recursive:!0});e.fungiCache!==void 0&&pun(e.fungiCache,{recursive:!0,mode:448});const u=[...e.mode==="read-only"?["--unshare-all"]:["--unshare-user","--unshare-pid","--unshare-ipc","--unshare-uts","--unshare-cgroup-try"],"--die-with-parent","--new-session","--seccomp","3","--ro-bind","/","/","--bind",e.temporaryDirectory,"/tmp","--tmpfs","/run",...cA("/var/run")&&pU("/var/run")!=="/run"?["--tmpfs",pU("/var/run")]:[],"--dev","/dev","--proc","/proc"];e.mode==="read-only"&&u.push("--ro-bind",a,a);for(const l of e.writable)u.push("--bind",l,l);if(e.mode==="workspace")for(const l of pR(e.readOnly))cA(l)&&u.push("--ro-bind",l,l);const c=i.XDG_RUNTIME_DIR;if(c&&U$e(c)&&cA(c)&&u.push("--tmpfs",pU(c)),e.mode==="workspace"&&cA("/etc/resolv.conf")){const l=pU("/etc/resolv.conf");l.startsWith("/run/")&&u.push("--ro-bind",l,l)}if(i.HOME&&U$e(i.HOME))for(const l of[F$e(i.HOME,".docker","run"),F$e(i.HOME,".docker","desktop")])cA(l)&&mU(l).isDirectory()&&u.push("--tmpfs",pU(l));for(const l of pTr(e.hidden,e.writable))u.push("--bind",l,l);for(const l of e.hidden){const d=B$e("/tmp",l),p=B$e(a,l);d!==".."&&!d.startsWith(`..${j$e}`)&&(p===".."||p.startsWith(`..${j$e}`))||cA(l)&&mU(l).isDirectory()&&u.push("--tmpfs",l)}if(e.sshAgentSocket!==void 0&&u.push("--bind",e.sshAgentSocket,e.sshAgentSocket),e.sshAgentMask!==void 0&&u.push("--ro-bind","/dev/null",e.sshAgentMask),o!==void 0){if(!mU(o).isFile())throw new Error("Local native helper must be a regular file");u.push("--ro-bind",o,o)}for(const l of s){if(!mU(l).isFile())throw new Error("Local sandbox payload must be a regular file");u.push("--ro-bind",l,l)}return u.push("--setenv","GIT_DISCOVERY_ACROSS_FILESYSTEM","1"),u.push("--setenv","FUNGI_SANDBOX",e.mode),e.mode==="read-only"&&u.push("--setenv","FUNGI_SANDBOX_NETWORK_DISABLED","1"),u.push("--chdir",n,"--",...r),{...t,args:u}}function hun(e,t){const n=B$e(e,t);return n!==""&&!U$e(n)&&n!==".."&&!n.startsWith(`..${j$e}`)}function pTr(e,t){const n=new Set;for(const r of e)for(const i of t){if(!hun(i,r))continue;const o=[];for(let s=mun(r);hun(i,s);s=mun(s))o.unshift(s);for(const s of o){if(!cA(s))break;if(lTr(s).isSymbolicLink())throw new M$e("Sandbox writable folder reaches a Fungi hidden record through a symlink.");if(!mU(s).isDirectory())break;n.add(s)}}return[...n]}import{readFileSync as mTr,realpathSync as Iie}from"node:fs";import{dirname as hTr,isAbsolute as fTr,relative as gTr,sep as yTr}from"node:path";var vTr="/usr/bin/sandbox-exec";function W$e(e,t){const n=gTr(e,t);return!fTr(n)&&n!==".."&&!n.startsWith(`..${yTr}`)}function _Tr(e,t,n=!1){const r=pR(e.hidden),i=e.mode==="workspace"?[e.writableRoot,e.temporaryDirectory]:[e.temporaryDirectory];if(i.some(y=>r.some(v=>W$e(y,hTr(v))||W$e(v,y))))throw new M$e("Seatbelt writable folder or temp contains a Fungi hidden record or its parent.");const o=[],s=(y,v)=>(o.push("-D",`${y}=${v}`),`(param "${y}")`),a=r.flatMap((y,v)=>{const _=s(`HIDDEN_${String(v)}`,y);return[`(deny file-read* (literal ${_}))`,`(deny file-read* (subpath ${_}))`]}),u=r.flatMap((y,v)=>{const _=`(param "HIDDEN_${String(v)}")`;return[`(deny file-write* (literal ${_}))`,`(deny file-write* (subpath ${_}))`]}),l=pR(e.readOnly).map((y,v)=>{const _=s(`PROTECTED_${String(v)}`,y);return{path:y,rules:[`(require-not (literal ${_}))`,`(require-not (subpath ${_}))`]}}),d=Iie(e.temporaryDirectory),p=e.fungiCache!==void 0&&W$e(e.fungiCache,d)?new Set(pR([e.fungiCache])):void 0,m=i.map((y,v)=>{const _=s(`WRITABLE_ROOT_${String(v)}`,Iie(y)),b=l.filter(({path:w})=>!(e.mode==="workspace"&&v===1&&p?.has(w))).flatMap(({rules:w})=>w);return`(require-all (subpath ${_}) ${b.join(" ")})`}),h=[...new Set(i.map(y=>Iie(y)))].map((y,v)=>`(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal ${s(`ANCHOR_${String(v)}`,y)})))`),g=[mTr(new URL("./seatbelt/safe-base.sbpl",import.meta.url),"utf8"),...n?['(allow network-bind (local ip "localhost:*"))','(allow network-inbound (local ip "localhost:*"))']:[],"(allow file-read*)",...a,`(allow file-write* ${m.join(" ")})`,...u,...h,"(deny system-fcntl (fcntl-command 80 110))"].join(`
1444
+ `);return{executable:vTr,args:["-p",g,...o,"--",...t],temporaryDirectory:Iie(e.temporaryDirectory)}}xt();var wTr=A.strictObject({kind:A.enum(["unsupported","install","folder","startup-refused"]),message:A.string()}),Vc=class extends Error{constructor(e){super(`Local sandbox unavailable: ${e.message}`),this.reason=e}reason;name="LocalSandboxUnavailable"};function mR(e){return e instanceof sun?{kind:"folder",message:e.message}:e instanceof M$e?{kind:"folder",message:e.message}:e instanceof ew?{kind:"install",message:e.message}:e instanceof m0?{kind:"install",message:e.message}:e instanceof Wa?{kind:e.reason,message:e.message}:{kind:"startup-refused",message:e instanceof Error?e.message:"Sandbox preparation failed."}}function fun(e,t,n){try{N$e(e.project,e.folder)}catch(o){return{state:"unavailable",reason:{kind:"folder",message:o instanceof Error?o.message:"Invalid sandbox folder."}}}const r=e.platform??process.platform;if(r!=="linux"&&r!=="darwin")return{state:"unavailable",reason:{kind:"unsupported",message:`${e.mode==="workspace"?"Workspace":"Read-only"} on ${r} needs a supported OS sandbox; use --yolo or run on macOS/Linux.`}};let i;try{i=t??(r==="linux"?Tie(e.project):void 0);const o=r==="linux"?"/tmp":e.temporaryDirectory;let s=!1;const a={command:(p,m,h,f)=>{if(s)throw new Vc({kind:"startup-refused",message:"Sandbox has been closed."});const g=N$e(e.project,e.folder);try{const y=Z6r(g,e.mode,e.temporaryDirectory,process.env,cTr().homedir,r),v=r==="linux"?i?.linux(y):void 0,_=h===void 0?void 0:i?.patch(h),b=_===void 0?m:[m[0]===h?_:m[0],...m.slice(1).map(k=>k===h?_:k)],w=v!==void 0?dTr(y,v,p,b,void 0,_,f):_Tr(y,b,e.loopbackListener);let x={TMPDIR:o};return r==="linux"&&y.sshAgentSocket!==void 0&&(x={TMPDIR:o,SSH_AUTH_SOCK:y.sshAgentSocket}),{...w,environment:x}}catch(y){throw new Vc(mR(y))}},close:()=>{s||(s=!0,t===void 0&&i?.close())}},u=a.command(uTr(e.folder),["/usr/bin/true"]);let c;const l=()=>{if(u.seccompFilter!==void 0){const p=i?.probeFilter(u.seccompFilter);if(p===void 0)throw new Error("No Linux filter staging owner");c=aTr(p,"r")}return oTr(u.executable,[...u.args],{cwd:e.folder,env:{...u.environment},encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","pipe",...c===void 0?[]:[c]]})},d=(()=>{try{return n?.(u)??l()}finally{c!==void 0&&sTr(c)}})();if(d.status!==0){a.close();const p=d.error===void 0?d.stderr.trim():"";return{state:"unavailable",reason:{kind:"startup-refused",message:`${e.mode==="workspace"?"Workspace":"Read-only"} on this ${r==="darwin"?"Mac":"Linux host"} needs a working ${r==="darwin"?"sandbox-exec profile probe":"bwrap installation"}; use --yolo or ${r==="darwin"?"check the failed Seatbelt profile probe":"fix the sandbox installation"}. ${d.error?.message??(p.length>0?p:`Sandbox startup exited ${String(d.status)} (${String(d.signal)}).`)}`}}}return{state:"ready",sandbox:a}}catch(o){return t===void 0&&i?.close(),{state:"unavailable",reason:o instanceof Vc?o.reason:mR(o)}}}var bTr=A.strictObject({mode:A.enum(["full-access","workspace","read-only"]),available:A.boolean(),reason:wTr.optional()}),xTr=class extends Error{constructor(e){super(`Files write targets a protected Local path: ${e}`),this.path=e}path;name="ProtectedLocalFilesPath"};function gun(e,t){const n=P6r(e,t);return!R6r(n)&&n!==".."&&!n.startsWith(`..${D6r}`)}function yun(e){const t=e.mode(),n=cU(e.project,e.folder),r=e.agentId??`probe-${String(process.pid)}-${process.hrtime.bigint().toString(36)}`,i=()=>{try{const k=process.env.FUNGI_LAUNCHER,T=k===void 0?L6r(import.meta.url):process.env.FUNGI_BUNDLED_CLI;if(T===void 0)throw new ew("Packed CLI entry was not provided by the launcher; reinstall Fungi outside the project.");eTr(e.project,T,k??T)}catch(k){throw new Vc(k instanceof ew?mR(k):{kind:"install",message:`Fungi host JavaScript identity cannot be verified (${k instanceof Error?k.message:String(k)}); reinstall Fungi using a copying install outside the project.`})}};t!=="full-access"&&i();let o=t!=="full-access",s=t==="full-access"?void 0:P$e(r,e.project);const a=e.platform===void 0?{}:{platform:e.platform},u=(e.platform??process.platform)==="linux",c=()=>{try{return Tie(e.project,e.readNativePatchSource)}catch(k){throw new Vc(mR(k))}},l=k=>{try{k?.admitProject(e.project)}catch(T){throw new Vc(mR(T))}};let d,p=!1,m;try{t!=="full-access"&&(d=e.native??(u?c():void 0),l(d),p=d!==void 0,m=fun({project:e.project,folder:n.absolute,mode:t,temporaryDirectory:s??P$e(r,e.project),...a,loopbackListener:e.loopbackListener===!0},d,e.runProbe))}catch(k){try{e.native===void 0&&d?.close()}finally{s!==void 0&&C$e(s,{recursive:!0,force:!0})}throw k}let h=m?.state==="ready"?m.sandbox:void 0,f=h===void 0?void 0:t,g=m?.state==="unavailable"?m.reason:e.defaultReason;if(g!==void 0){if(s!==void 0&&C$e(s,{recursive:!0,force:!0}),g.kind==="folder")throw e.native===void 0&&d?.close(),new Error(g.message);if(t!=="full-access")throw e.native===void 0&&d?.close(),new Vc(g)}let y=!1;const v=()=>{if(y)throw new Error("Local sandbox owner is closed");try{if(cU(e.project,e.folder).absolute===n.absolute)return;throw new Error("Local Agent folder authority changed while open")}catch(k){throw g={kind:"folder",message:k instanceof Error?k.message:String(k)},new Vc(g)}};function _(k){if(h!==void 0&&f===k)return;h?.close(),h=void 0,o||(i(),o=!0),d??=e.native??(u?c():void 0),p||(l(d),p=!0),s??=P$e(r,e.project);const T=fun({project:e.project,folder:n.absolute,mode:k,temporaryDirectory:s,...a,loopbackListener:e.loopbackListener===!0},d,e.runProbe);if(T.state==="ready")h=T.sandbox,f=k,g=void 0;else throw g=T.reason,new Vc(g)}function b(k,T,C,O){if(v(),e.mode()!=="full-access"){if(C!==void 0&&d===void 0&&(o||(i(),o=!0),d=c(),p=!1,h?.close(),h=void 0),_(e.mode()==="read-only"?"read-only":"workspace"),h!==void 0)try{const P=h.command(k,T,C,O);return g=void 0,P}catch(P){throw g=P instanceof Vc?P.reason:mR(P),new Vc(g)}throw g===void 0?new Error("Local sandbox preparation produced no result"):g.kind==="folder"?new Error(g.message):new Vc(g)}}const w=()=>oun(process.env,N6r().homedir,e.platform??process.platform),x=()=>{e.mode()!=="full-access"&&b(n.absolute,["/usr/bin/true"])};return{launch:b,assertReady:x,assertModeReady:k=>{if(k!=="full-access"){if(v(),_(k),h===void 0)throw new Error("Local sandbox preparation produced no result");h.command(n.absolute,["/usr/bin/true"])}},hiddenRecords:()=>e.mode()==="full-access"?[]:pR(w()),assertWrite:k=>{if(e.mode()==="full-access")return;x();const T=N$e(e.project,n.absolute),C=pR([...T.readOnly,O6r(T.writableRoot,".git"),...w()]);for(const O of k){const P=M6r(O);if(!gun(T.writableRoot,P)||C.some($=>gun($,P)))throw new xTr(P)}},status:()=>{if(y)throw new Error("Local sandbox owner is closed");return g===void 0?{mode:e.mode(),available:!0}:{mode:e.mode(),available:!1,reason:g}},close:()=>{if(!y){y=!0;try{h?.close()}finally{e.native===void 0&&d?.close(),s!==void 0&&C$e(s,{recursive:!0})}}}}}function Cie(e,t,n){try{yun({project:e,folder:t,mode:()=>"workspace",native:n}).close();return}catch(r){if(r instanceof Vc)return r.reason;throw r}}var q$e=5;function STr(){return A.string().regex(/^[a-f0-9]{64}$/u).optional().parse(process.env.FUNGI_BUNDLED_BUILD_ID)??"source"}var vun=A.looseObject({protocol:A.number().int().positive(),version:A.string().min(1),serviceId:A.string().refine(e=>gan.service.is(e)),pid:A.number().int().positive(),startedAt:A.string().min(1)}),z$e=A.strictObject({...vun.shape,protocol:A.literal(q$e),baseUrl:A.url().refine(e=>{const t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"&&t.port!==""&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""})}),ETr=z$e.extend({diagnostics:E6r}),H$e=A.strictObject({uiAttachmentLifetime:aan.optional(),invocationRoot:A.string().min(1),clientPath:cie,mode:oU.optional(),databasePath:A.string().min(1).optional(),sessionId:A.string().min(1).optional(),fungiMcp:aie.optional()}),kTr=A.strictObject({uiAttachmentLifetime:aan.optional(),invocationRoot:A.string().min(1),clientPath:cie,mode:oU.optional(),databasePath:A.string().min(1),requestId:A.string().min(1),fungiMcp:aie.optional()}),ATr=H$e.omit({clientPath:!0,uiAttachmentLifetime:!0}).extend({sessionId:A.string().min(1),limit:A.number().int().min(1).max(200)}),MVr=A.strictObject({agentId:A.string().min(1),databasePath:A.string().min(1),sessionId:A.string().min(1),routePath:A.templateLiteral(["/agents/",A.uuid({version:"v4"})])}),TTr=A.strictObject({invocationRoot:A.string().min(1),archived:A.boolean().default(!1)}),ITr=A.strictObject({invocationRoot:A.string().min(1),agentId:A.string().min(1),archived:A.boolean()}),DVr=A.strictObject({code:A.literal("agent_archive_refused"),reason:A.enum(d6r),error:A.string()}),LVr=A.strictObject({root:A.string().min(1),agents:A.array(A.strictObject({agentId:A.string().min(1),name:A.string().optional(),createdBy:A.string().nullable().optional(),unreadable:A.string().optional(),databasePath:A.string().min(1),sessionCount:A.number().int().nonnegative(),updatedAt:A.number().optional()})),sessions:A.array(A.strictObject({databasePath:A.string().min(1),sessionId:A.string().min(1),title:A.string(),createdAt:A.number(),updatedAt:A.number()})),problems:A.array(A.strictObject({kind:A.enum(["corrupt","in_use","unreadable"])}))}),NVr=A.array(A.strictObject({providerId:A.string().min(1),providerName:A.string().min(1),id:A.string().min(1),name:A.string().min(1),reasoning:A.array(A.enum($ee))}));function CTr(e){return L5r(e??uA(N5r(),".fungi","service"))}async function _un(e){const t=CTr(e);return await man(t,{recursive:!0,mode:448}),await C5r(t,448),O5r(t)}var hU=e=>uA(e,"service.json");async function wun(e){let t;try{t=await R5r(hU(e),"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;throw i}let n;try{n=JSON.parse(t)}catch(i){if(i instanceof SyntaxError)return{kind:"unidentified"};throw i}const r=vun.safeParse(n);if(!r.success){const i=z$e.pick({serviceId:!0,baseUrl:!0}).safeParse(n);if(i.success)throw new RTr(e,i.data);return{kind:"unidentified"}}return r.data.protocol!==q$e?{kind:"other-protocol",lifecycle:r.data}:{kind:"current",record:z$e.parse(n)}}var RTr=class extends Error{name="LocalServiceRecordWithoutPid";constructor(e,t){super(`An older Fungi service (${t.serviceId} on port ${new URL(t.baseUrl).port}) is registered in ${hU(e)} without a process identity. Fungi cannot safely signal it. End the process whose command line contains \`--internal-service ${e}\`. If it is no longer running, move ${hU(e)} aside. Then retry; saved Sessions are kept.`)}};async function OTr(e,t){const n=await wun(e);(n?.kind==="current"&&n.record.serviceId===t||n?.kind==="other-protocol"&&n.lifecycle.serviceId===t)&&await die(hU(e),{force:!0})}var Rie=e=>uA(e,"owner.lock","sqlite-owner");async function G$e(e){try{return await M5r(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}}async function PTr(e){if(await G$e(uA(e,"owner.lock"))&&!await G$e(Rie(e)))throw new Error("A previous Fungi service may still own this directory. Stop that service before starting Fungi again; its owner lock was not released.")}async function bun(e,t){if(t==="startup")return I5r.default.lock(uA(e,t),{realpath:!1,lockfilePath:uA(e,`${t}.lock`),retries:{retries:100,minTimeout:100,maxTimeout:100},onCompromised(o){throw o}});const n=await H5r(e),r=uA(e,"owner.lock");let i=!1;try{await PTr(e),await G$e(Rie(e))&&await die(r,{recursive:!0}),await man(r),i=!0,await D5r(Rie(e),"",{flag:"wx",mode:384})}catch(o){try{i&&await die(r,{recursive:!0})}finally{n()}throw o}return async()=>{try{await die(Rie(e),{force:!0}),await P5r(r)}finally{n()}}}async function MTr(e){return await z5r(e)!==void 0}var DTr=A.looseObject({code:A.string().optional(),cause:A.looseObject({code:A.string().optional()}).optional()});async function LTr(e,t=2e3){try{const n=await fetch(`${e.baseUrl}/service/${e.serviceId}/status`,{redirect:"error",signal:AbortSignal.timeout(t)});if(!n.ok)return{kind:"unavailable"};const r=ETr.parse(await n.json());return r.serviceId===e.serviceId&&r.baseUrl===e.baseUrl&&r.pid===e.pid&&r.startedAt===e.startedAt&&r.version===e.version?{kind:"running",service:r}:{kind:"unavailable"}}catch(n){const r=DTr.safeParse(n);if(r.success){const i=[r.data.code,r.data.cause?.code];if(i.includes("ECONNREFUSED")||i.includes("ConnectionRefused"))return{kind:"not-running"}}return{kind:"unavailable"}}}var NTr=A.strictObject({credentialPath:A.string().min(1),endpoint:A.string().optional()}),xun=A.strictObject({kind:A.enum(["not-logged-in","removed","revoked"]),message:A.string(),unconfirmedComputers:A.array(A.strictObject({name:A.string(),url:A.string()}))});async function $Tr(e,t){const{clearOffline:n,directory:r,...i}=t,o=await _un(r),s=await bun(o,"startup");try{const a=await wun(o),u=await MTr(o);if(a?.kind!=="current"){if(u)throw new Error("The running Local account owner is unavailable");return await n(e,i)}const c=await LTr(a.record);if(c.kind!=="running"){if(u||c.kind==="unavailable")throw new Error("The running Local account owner is unavailable");return await n(e,i)}const l=c.service,d=new URL(`${l.baseUrl}/service/${l.serviceId}/auth`);d.protocol="ws:";const p=new WebSocket(d),m=Gft(p);try{const h={credentialPath:i.credentialPath};return e!==void 0&&(h.endpoint=e.toString()),xun.parse(await m.signOutFungi(h))}finally{m[Symbol.dispose](),p.close()}}finally{await s()}}var h0="fungi",Sun="openid profile email offline_access models:invoke git:tracker billing:read",Oie="127.0.0.1",V$e="/oauth/callback",Eun="/client-registration",UTr=`http://${Oie}${V$e}`,kun=A.object({teamId:A.string().min(1).max(256),handle:A.string().min(1).max(256),name:A.string().min(1).max(256)}),El=A.looseObject({type:A.literal("oauth"),access:A.string(),refresh:A.string(),expires:A.number(),clientId:A.string().min(1).optional(),issuer:A.url().optional(),clientInformation:A.json().optional(),tokens:A.json().optional(),codeVerifier:A.string().optional(),localBackends:A.array(NAr).max(16).optional(),team:kun.optional(),teamCount:A.number().int().min(0).max(1e3).optional()}).transform(e=>{const t={...e};return delete t.machineEnrollments,t});function Pie(e){const t=JSON.stringify(e),n=JSON.parse(t);return A.json().parse(n)}function FTr(e){return{client_name:"Fungi Local",redirect_uris:[e],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:Sun}}function f0(e){return _$e(e)}async function g0(e){const t=await f0(e).read(h0);if(t?.type!=="oauth")return;const n=El.safeParse(t);if(!n.success)throw new Error("Fungi Local credential data is invalid");return n.data}function Aun(e){return{read:async()=>{const t=await g0(e),n=await f0(e).readMachineEnrollments(),r=t?.issuer!==void 0&&t.access!==""?t.issuer:void 0,i=n.find(o=>o.origin===r&&Xsn(o)==="oauth");return[...r!==void 0?[{kind:"oauth",origin:r,enrollments:i?.enrollments??[]}]:[],...n.flatMap(o=>Xsn(o)==="oyster"?[{kind:"oyster",origin:o.origin,enrollments:o.enrollments}]:[])]},update:async(t,n)=>{const r=FAr.parse(t);if(r.kind==="oyster"){await f0(e).modifyMachineEnrollments(r.origin,n);return}await f0(e).modifyMachineEnrollments(r.origin,n,{providerId:h0,admit:i=>{const o=El.safeParse(i);if(!o.success||o.data.access===""||o.data.issuer!==r.origin)throw new Error("Fungi sign-in changed before machine enrollment was persisted")}})}}}async function hR(e,t){await f0(t).modify(h0,r=>{const i=El.safeParse(r),o=i.success?i.data:{type:"oauth",access:"",refresh:"",expires:0},s=El.parse(Object.fromEntries(Object.entries({...o,...e}).filter(([,a])=>a!==void 0)));return Promise.resolve(s)})}function BTr(e){return`fungi login --fungi-mcp ${e instanceof URL?e.href:e}`}function Tun(e){rie.stderr.write(`Open this URL to sign in to Fungi:
1445
1445
  ${e.href}
1446
1446
  `),jTr(e)}function jTr(e){if(rie.platform!=="darwin"&&rie.platform!=="linux")throw new Error("Fungi OAuth login supports macOS and Linux");const t=LAr(rie.platform==="darwin"?"open":"xdg-open",[e.href],{detached:!0,stdio:"ignore"});t.once("error",n=>{ar("fungi-account.open-browser",n)}),t.unref()}function fU(e,t,n){e.writeHead(t,{"Content-Type":"text/html; charset=utf-8"}),e.end(`<!doctype html><meta charset="utf-8"><title>Fungi Local</title><p>${n}</p>`)}function WTr(e={}){const t={...e,credentialPath:e.credentialPath??xa().credentialPath},n=t.interactive??!1,r=t.credentialPath,i=t.issuer??t.endpoint?.origin,o=t.redirectUrl??UTr,s=BTr(t.endpoint??`${i??"https://<hub>"}/api/teams/<team>/mcp`),a=(d,p)=>new Error(`Saved Fungi OAuth ${d} another issuer (${p??"unknown"}); run ${s} to replace it`);let u,c,l;return{get redirectUrl(){return o},get clientMetadata(){return FTr(o)},saveDiscoveryState(d){if(i!==void 0&&(new URL(d.authorizationServerUrl).origin!==i||d.authorizationServerMetadata?.issuer!==void 0&&new URL(d.authorizationServerMetadata.issuer).origin!==i))throw new Error("Fungi OAuth discovery belongs to another issuer");l=d},discoveryState(){return l},validateResourceURL(d,p){if(i===void 0)throw new Error("Fungi account issuer is required");const m=new URL("/api/teams",i);if(p!==void 0&&p!==m.href)throw new Error("Fungi OAuth resource did not match this account");return Promise.resolve(m)},state(){return c=qsn(32).toString("base64url"),c},async clientInformation(){const d=await g0(r),p=d?.clientId;if(p===void 0)return;if(i!==void 0&&d?.issuer!==i)throw a("client belongs to",d?.issuer);const m=A.looseObject({client_id:A.string().min(1)}).safeParse(d?.clientInformation??{client_id:p});return m.success?{...m.data,client_id:p,redirect_uris:[o],token_endpoint_auth_method:"none"}:void 0},async saveClientInformation(d){const m={clientId:A.looseObject({client_id:A.string().min(1)}).parse(d).client_id,clientInformation:Pie(d)};i!==void 0&&(m.issuer=i),await hR(m,r)},async tokens(){const d=await g0(r);if(i!==void 0&&d?.tokens!==void 0&&d.issuer!==i)throw a("tokens belong to",d.issuer);const p=A.looseObject({access_token:A.string().min(1),refresh_token:A.string().min(1),token_type:A.string().min(1)}).safeParse(d?.tokens);return p.success?{...p.data}:void 0},async saveTokens(d){const p=Pie(d),m=A.looseObject({access_token:A.string().min(1),refresh_token:A.string().min(1),token_type:A.string().min(1),expires_in:A.number().optional()}).parse(p);await hR({access:m.access_token,refresh:m.refresh_token,expires:Date.now()+(m.expires_in??0)*1e3,tokens:Pie(d),team:void 0,teamCount:void 0},r)},redirectToAuthorization(d){if(!n)throw new Error(`Fungi MCP sign-in is missing, expired or revoked; run ${s}`);return u=new URL(d),(t.openBrowser??Tun)(u),Promise.resolve()},async saveCodeVerifier(d){await hR({codeVerifier:d},r)},async codeVerifier(){const d=(await g0(r))?.codeVerifier;if(d===void 0)throw new Error("Fungi OAuth verifier is unavailable");return d},async invalidateCredentials(d){if(d==="all"){await f0(r).remove(h0,p=>{if((El.parse(p).localBackends??[]).length>0)throw new Error("Detach this machine's Computers before clearing Fungi account custody");return Promise.resolve()});return}d==="client"&&await hR({clientId:void 0,clientInformation:void 0},r),d==="tokens"&&await hR({tokens:void 0,access:"",refresh:"",expires:0},r),d==="verifier"&&await hR({codeVerifier:void 0},r)},expectedState(){return c},authorizationUrl(){return u}}}function w2(e){return oR(e)}var fR=new Map;function qTr(e,t){const n=iie(e);if(fR.has(n))throw new Error("Fungi account already has an in-process owner");return fR.set(n,t),()=>{fR.delete(n)}}function K$e(e,t,n=[]){const r=e==="not-logged-in"?`Fungi was not logged in${t?` to ${t}`:""}.`:e==="revoked"&&t!==void 0?`Fungi logged out of ${t}; the Hub revoked this login.`:"Signed out here. Couldn't confirm with Fungi; you can revoke this login under Connected logins.",i=n.map(({name:o,url:s})=>`Computer ${JSON.stringify(o)} may still be attached and serving commands. Detach it on the Hub Computers page (${s}) or press Ctrl-C in the terminal running fungi computer attach. Cleanup will retry after your next sign-in to this account.`);return{kind:e,message:[r,...i].join(`
1447
1447
  `),unconfirmedComputers:n}}async function Iun(e,t,n){try{const r=`/api/v1/teams/${encodeURIComponent(t.teamId)}/computers/${encodeURIComponent(t.computerId)}/backends/local/requests/${encodeURIComponent(t.requestId)}/detach`,i=await n(new URL(r,e),{method:"POST"});return i.ok?A.object({detached:A.boolean()}).safeParse(await i.json()).success:(await i.body?.cancel(),!1)}catch(r){return ar("fungi-account.logout-detach",r),!1}}function gU(e,t,n){const r=san(new URL(e),t);return(i,o)=>{if(new URL(i).origin!==e)throw new Error("Fungi OAuth refused an endpoint from another issuer");const s=new Headers(o?.headers);return s.set("Origin",e),r(i,{...o,headers:s,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(3e4),...n?[n]:[],...o?.signal?[o.signal]:[]])})}}async function Cun(e,t){const n=e.issuer,r=e.clientId;if(n===void 0||r===void 0||e.refresh==="")return!1;try{const i=gU(n,t),{authorizationServerMetadata:o}=await W$(new URL("/api/teams",n),{fetchFn:i}),s=A.looseObject({revocation_endpoint:A.url().optional()}).safeParse(o).data?.revocation_endpoint;return s===void 0||new URL(s).origin!==n?!1:(await i(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e.refresh,token_type_hint:"refresh_token",client_id:r}),redirect:"error"})).ok}catch(i){return ar("fungi-account.revoke",i),!1}}async function Run(e,t){const n=Wsn(t.credentialPath),r=[],i=AbortSignal.timeout(3e4),o=await f0(t.credentialPath).remove(h0,async u=>{const c=El.parse(u);if(c.issuer!==e.issuer)throw new Error("Fungi account changed during sign-out. Retry for the current account.");const l=c.issuer&&d$e(c.issuer,c.access);if(l)try{await n.remember(l,(c.localBackends??[]).map(({teamId:d,computerId:p,requestId:m})=>({teamId:d,computerId:p,requestId:m})))}catch(d){ar("fungi-account.pending-revoke-write",d)}if(c.issuer){const d=c.issuer,p=gU(d,t.fetch,i),m=(h,f)=>p(h,{...f,headers:{Authorization:`Bearer ${c.access}`}});for(const h of c.localBackends??[])if(await Iun(d,h,m)){if(l)try{await n.confirmed(l,h)}catch(f){ar("fungi-account.pending-detach-clear",f)}}else r.push({name:h.computerName,url:new URL(`/teams/${encodeURIComponent(h.teamId)}/computers`,d).href})}return c});if(await fR.get(iie(t.credentialPath))?.({type:"signed-out"}),o===void 0||o.refresh==="")return K$e("not-logged-in",e.issuer,r);let s=await Cun(o,t.fetch);s||(s=await Cun(o,t.fetch));const a=o.issuer&&d$e(o.issuer,o.access);if(s&&a)try{await n.confirmed(a)}catch(u){ar("fungi-account.pending-revoke-clear",u)}return K$e(s?"revoked":"removed",o.issuer,r)}async function zTr(e={}){const t={...e,credentialPath:e.credentialPath??xa().credentialPath},n=await g0(t.credentialPath);if(n?.issuer===void 0||n.access==="")return;const r={issuer:n.issuer,accessExpiresAt:new Date(n.expires)};return n.team!==void 0&&(r.team=n.team),n.teamCount!==void 0&&(r.teamCount=n.teamCount),r}async function HTr(e,t={}){const n=iie(t.credentialPath??xa().credentialPath);if(fR.has(n))return await Mie(e,{...t,credentialPath:n});const r=xa(p$e(p$e(p$e(n)))),i=t.serviceDirectory??(r.credentialPath===n?r.serviceDirectory:void 0);return i!==void 0?await $Tr(e,{...t,credentialPath:n,directory:i,clearOffline:Mie}):await Mie(e,{...t,credentialPath:n})}async function Mie(e,t={}){const n={...t,credentialPath:t.credentialPath??xa().credentialPath},r=await g0(n.credentialPath),i=e===void 0?r?.issuer:w2(e).origin,o=i!==void 0&&await f0(n.credentialPath).removeMachineEnrollments(i);return r===void 0||r.issuer!==i?(o&&await fR.get(iie(n.credentialPath))?.({type:"signed-out"}),K$e(o?"removed":"not-logged-in",i)):Run(r,n)}async function GTr(e,t){try{const n=await g0(t.credentialPath);if(n?.issuer!==e.origin)return;const r=d$e(n.issuer,n.access);if(r===void 0)return;const i=Wsn(t.credentialPath),o=await i.forAccount(r),s=AbortSignal.any([AbortSignal.timeout(3e4),...t.signal?[t.signal]:[]]),a=Lie(e,{...t,signal:s});for(const u of o){for(const l of u.detaches){if(s.aborted)return;await Iun(e.origin,l,a)&&await i.confirmed(u,l)}if(!u.revoke)continue;const c=await a(new URL("/api/local/oauth-logins/revoke",e.origin),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grantId:u.loginId})});if(await c.body?.cancel(),!c.ok)break;await i.confirmed(u)}}catch(n){ar("fungi-account.pending-revoke",n)}}async function VTr(e,t={}){const n={...t,credentialPath:t.credentialPath??xa().credentialPath};n.signal?.throwIfAborted();const r=w2(e),i=AbortSignal.any([AbortSignal.timeout(5e3),...n.signal===void 0?[]:[n.signal]]);try{const O=await(n.fetch??fetch)(r.origin,{method:"HEAD",redirect:"manual",signal:i});if(await O.body?.cancel(),O.status>=500)throw new Error("Hub unavailable")}catch{throw n.signal?.throwIfAborted(),new TypeError(`Can't reach ${r.host}. Check your connection and try again.`)}const o=await g0(n.credentialPath);if(o!==void 0&&(o.clientId!==void 0||o.tokens!==void 0)&&o.issuer!==r.origin){const O=o.issuer??"an earlier Fungi origin";if(!(await n.confirmReplace?.(O,r.origin)??!1))throw new Error(`Fungi MCP is logged in to ${O}. Run fungi logout --fungi-mcp ${o.issuer??"<url>"} first, or rerun this login in a terminal to replace it.`);const $=await Run(o,n);if($.unconfirmedComputers.length>0)throw new Error($.message)}const s=gU(r.origin,n.fetch,n.signal),a=n.openBrowser??Tun;let u,c;const l=new Promise((O,P)=>{u=O,c=P});let d,p;const m=new Promise((O,P)=>{d=O,p=P}),h=l.then(O=>({kind:"registered",clientId:O}),O=>({kind:"failed",cause:O})),f=m.then(O=>({kind:"authorized",params:O}),O=>({kind:"failed",cause:O})),g=qsn(32).toString("base64url");let y;const v=DAr();await new Promise((O,P)=>{v.once("error",P),v.listen(0,Oie,O)});const{port:_}=A.object({port:A.number().int().positive()}).parse(v.address()),b=`http://${Oie}:${String(_)}`,w=`${b}${V$e}`,x={interactive:!0,credentialPath:n.credentialPath,endpoint:r,redirectUrl:w,openBrowser:a},k=WTr(x);v.on("request",(O,P)=>{const $=new URL(O.url??"/",`http://${Oie}`);if($.pathname===Eun&&y===void 0){const B=$.searchParams.get("state"),q=$.searchParams.get("client_id");if(B!==g||!q){fU(P,400,"Local OAuth registration did not match this login. Return to the terminal and retry."),c(new Error("Local OAuth registration response was invalid"));return}y=q,u(q),fU(P,200,"Fungi Local is registered. Return to your terminal to continue sign in.");return}if($.pathname===V$e){const B=$.searchParams;if(B.get("state")!==k.expectedState()){fU(P,400,"OAuth state did not match. Return to the terminal and retry."),p(new Error("Fungi OAuth callback state did not match"));return}d(B),fU(P,200,"Fungi sign-in returned to Local. Continue in your terminal to choose a Team.");return}fU(P,404,"Fungi Local callback not found.")});const T=()=>{const O=new Error("Fungi sign-in cancelled",{cause:n.signal?.reason});c(O),p(O)};n.signal?.addEventListener("abort",T,{once:!0}),n.signal?.aborted&&T();const C=setTimeout(()=>{const O=new Error("Fungi OAuth login timed out");c(O),p(O)},5*6e4);try{const O=(await k.clientInformation())?.client_id,P=new URL("/oauth/local-client",r.origin);if(P.search=new URLSearchParams({redirect_uri:`${b}${Eun}`,state:g}).toString(),a(P),y=await Promise.race([h.then(J=>{if(J.kind==="failed")throw J.cause;return J.clientId}),f.then(J=>{if(J.kind==="failed")throw J.cause;return""})]),!y)throw new Error("OAuth callback arrived before Local registration");if(O!==void 0&&y!==O)throw new Error("Fungi Local registration belongs to another account. Use the browser account for your saved login, or detach its Computers and sign out before switching accounts.");await k.saveClientInformation({client_id:y,redirect_uris:[w],token_endpoint_auth_method:"none"});const $=new URL("/api/teams",r.origin),B=s;if(await m2(k,{serverUrl:$,scope:Sun,fetchFn:B,forceReauthorization:!0})==="REDIRECT"){const J=await f;if(J.kind==="failed")throw J.cause;const re=J.params.get("code");if(J.params.has("error")||re===null)throw new Error("Fungi sign-in was declined or did not return an authorization code");const ue=J.params.get("iss"),N={serverUrl:$,authorizationCode:re,fetchFn:B};ue!==null&&(N.iss=ue),await m2(k,N)}await GTr(r,n),await XTr(r,n)}finally{clearTimeout(C),n.signal?.removeEventListener("abort",T),await new Promise(O=>{v.close(()=>{O()})})}}var KTr=A.looseObject({kind:A.literal("accepted"),items:A.array(kun).max(100),nextCursor:A.string().min(1).max(4096).nullable()});async function JTr(e,t){const n=w2(e).origin,r=[];let i=null;for(let o=0;o<10;o+=1){const s=new URL("/api/v1/teams",n);s.searchParams.set("limit","100"),i!==null&&s.searchParams.set("cursor",i);const a=await Lie(n,t)(s,{redirect:"error",signal:AbortSignal.timeout(3e4)});if(!a.ok)throw new Error(a.status===401||a.status===403?"Sign in to Fungi again to choose a Team":"Fungi is unreachable or could not list your Teams. Retry.");const u=KTr.parse(await a.json());if(r.push(...u.items),u.nextCursor===null)return r;i=u.nextCursor}throw new Error("Your Team list is too large for this picker. Contact Fungi support.")}async function QTr(e,t,n,r){await f0(r).modify(h0,i=>{const o=El.parse(i);if(o.issuer!==e||o.access==="")throw new Error("Fungi account changed while choosing a Team. Sign in again.");return Promise.resolve(El.parse({...o,team:t,teamCount:n}))})}async function XTr(e,t){const n=w2(e).origin,r=await JTr(n,t);if(r.length===0)throw new Error(`Create or join a Team at ${n} before using Fungi models`);const i=r.length===1?r[0]?.teamId:await t.chooseTeam?.(r),o=r.find(s=>s.teamId===i);if(o===void 0)throw new Error("Choose a current Team to pay for Fungi models");await QTr(n,o,r.length,t.credentialPath)}var yU=A.object({amount:A.string().max(16).regex(/^(?:0|[1-9]\d*)$/u),currency:A.object({code:A.literal("USD"),base:A.literal(10),exponent:A.literal(2)}),scale:A.literal(5)}),$Vr=A.object({teamId:A.string().min(1).max(256),balance:yU,included:A.strictObject({granted:yU,remaining:yU,expiresAt:A.number().int().nonnegative()}).nullable(),reserved:yU,available:yU});async function Oun(e,t){const n=e.issuer,r=e.clientId;if(n===void 0||r===void 0||e.refresh==="")throw new aA;const i=new URL("/api/teams",w2(n)),o=gU(n,t.fetch,t.signal);try{const s=await W$(i,{fetchFn:o});if(new URL(s.authorizationServerUrl).origin!==n||s.resourceMetadata!==void 0&&s.resourceMetadata.resource!==i.href)throw new Error("Fungi OAuth discovery did not match the account issuer and resource");const a={clientInformation:{client_id:r,token_endpoint_auth_method:"none"},refreshToken:e.refresh,resource:i,fetchFn:o};s.authorizationServerMetadata!==void 0&&(a.metadata=s.authorizationServerMetadata);const u=await TNe(s.authorizationServerUrl,a);return El.parse({...e,access:u.access_token,refresh:u.refresh_token??e.refresh,expires:Date.now()+(u.expires_in??0)*1e3,tokens:Pie(u)})}catch(s){throw ar("fungi-account.refresh",s),s instanceof mv&&["invalid_grant","invalid_client","unauthorized_client"].includes(s.code)?new aA({cause:s}):new Error("Fungi is unreachable or could not refresh your sign-in. Retry or sign in again.",{cause:s})}}function Pun(e,t){return e.expires<=Date.now()||e.access===t}function YTr(e,t,n){if(!(e?.issuer!==t||e.access===""||Pun(e,n)))return e.access}async function Die(e,t={}){const n={...t,credentialPath:t.credentialPath??xa().credentialPath},r=w2(e).origin;n.signal?.throwIfAborted();const i=await g0(n.credentialPath),o=YTr(i,r,n.rejectedAccess);if(o!==void 0)return o;const s=await f0(n.credentialPath).modify(h0,async a=>{if(a?.type!=="oauth")throw new Error("Sign in to Fungi to use models and Computers");const u=El.parse(a);if(u.issuer!==r)throw new Error("Saved Fungi sign-in belongs to another issuer");if(u.access==="")throw new aA;return Pun(u,n.rejectedAccess)?Oun(u,n):u},n.signal===void 0?void 0:{signal:n.signal});return El.parse(s).access}function Lie(e,t={}){const n={...t,credentialPath:t.credentialPath??xa().credentialPath},r=w2(e).origin,i=gU(r,n.fetch,n.signal);return Object.assign(async(s,a)=>{const u=s instanceof Request?new Request(s,{...a,redirect:"error"}):new Request(String(s),{...a,redirect:"error"});if(new URL(u.url).origin!==r)throw new Error("Fungi refused a request to another issuer");const c=u.headers.get("Authorization"),l=c?.startsWith("Bearer ")?c.slice(7):await Die(r,n);u.headers.set("Authorization",`Bearer ${l}`);const d=u.clone(),p=await i(u.url,{method:u.method,headers:Object.fromEntries(u.headers),body:u.body,signal:u.signal,redirect:"error",duplex:"half"});if(p.status!==401)return p;await p.body?.cancel();const m=await Die(r,{...n,rejectedAccess:l});return d.headers.set("Authorization",`Bearer ${m}`),i(d.url,{method:d.method,headers:Object.fromEntries(d.headers),body:d.body,signal:d.signal,redirect:"error",duplex:"half"})},{preconnect:globalThis.fetch.preconnect})}function ZTr(e,t={}){const n={...t,credentialPath:t.credentialPath??xa().credentialPath};let r;return{token:async()=>(r=await Die(e,n),r),onUnauthorized:async({response:i})=>{const o=_5r(i)??r;if(o===void 0)throw new aA;await Die(e,{...n,rejectedAccess:o})}}}function Mun(e){const t=El.parse(e);if(t.team===void 0)throw new Error("Choose a Team with fungi login --provider fungi before using Fungi models");return t.team}function eIr(e={}){const t={...e,credentialPath:e.credentialPath??xa().credentialPath};return{name:"Fungi",loginLabel:"Sign in to Fungi",isSubscription:!0,async login(n){const r=await g0(t.credentialPath);await VTr(r?.issuer??"https://fungi.computer",{...t,signal:n.signal,openBrowser:o=>{n.notify({type:"auth_url",url:o.href})},chooseTeam:o=>n.prompt({type:"select",signal:n.signal,message:"Which Team pays for Fungi models?",options:o.map(s=>({id:s.teamId,label:s.name,description:s.handle}))})});const i=await g0(t.credentialPath);if(i===void 0||i.access==="")throw new Error("Fungi sign-in did not finish");return i},refresh:(n,r)=>Oun(El.parse(n),{...t,signal:r}),toAuth(n){const r=El.parse(n);if(r.issuer===void 0||r.access==="")throw new Error("Sign in to Fungi to use models");const i=Mun(n),o=w2(r.issuer).origin;if(o!==r.issuer)throw new Error("Saved Fungi account issuer is invalid");return Promise.resolve({apiKey:r.access,baseUrl:`${o}/api/v1/teams/${encodeURIComponent(i.teamId)}`})}}}function tIr(e={}){const t={...e,credentialPath:e.credentialPath??xa().credentialPath},n=f0(t.credentialPath);return{async read(r,i){const o=await n.read(r,i);if(r!==h0||o===void 0)return o;const s=El.parse(o);return s.access===""||s.team===void 0?void 0:s},async list(r){const i=await n.list(r),o=await n.read(h0,r),s=o===void 0?void 0:El.parse(o);return s!==void 0&&s.access!==""&&s.team!==void 0?i:i.filter(a=>a.providerId!==h0)},modify:(r,i,o)=>n.modify(r,i,o),async delete(r,i){if(r!==h0)return n.delete(r,i);i?.signal?.throwIfAborted();const o=await HTr(void 0,t);if(o.kind==="removed"||o.unconfirmedComputers.length>0)throw new Error(o.message)}}}vt();import{statSync as nIr}from"node:fs";import{readdir as rIr,realpath as Dun,stat as iIr}from"node:fs/promises";import{basename as oIr,dirname as sIr,join as aIr,resolve as Lun}from"node:path";xt(),xt();var Nie="private_local_model_settings",uIr=A.string().optional();function cIr(e){e.exec(`CREATE TABLE IF NOT EXISTS ${Nie} (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), model TEXT NOT NULL) STRICT`)}function lIr(e,t){e.prepare(`INSERT OR IGNORE INTO ${Nie} VALUES (1, ?)`).run(JSON.stringify(t))}function Nun(e){return uIr.parse(e.prepare(`SELECT model FROM ${Nie} WHERE singleton = 1`).get()?.model)}function dIr(e){return P8e(Nun(e))}function pIr(e,t){e.prepare(`UPDATE ${Nie} SET model = ? WHERE singleton = 1`).run(JSON.stringify(t))}function $un(e,t){return t.updatedAt-e.updatedAt||t.createdAt-e.createdAt||e.title.localeCompare(t.title)||e.databasePath.localeCompare(t.databasePath)||e.sessionId.localeCompare(t.sessionId)}var $ie=class extends Error{constructor(e,t){super("Local session store could not be read",t),this.kind=e}kind};function Uun(e){return e==="busy"||e==="locked"?"in_use":e==="corrupt"||e==="not_a_database"?"corrupt":"unreadable"}function mIr(e){return e instanceof $ie?e.kind:Uun(Jre(e))}async function hIr(e,t){const n=Lun(e,t);let r;try{r=await rIr(n,{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return Promise.all(r.filter(i=>(i.isDirectory()||i.isSymbolicLink())&&i.name.length>0).map(async i=>{const o=aIr(n,i.name,"agent.sqlite");try{return(await iIr(o)).isFile()?{path:o}:void 0}catch(s){if(s instanceof Error&&"code"in s&&s.code==="ENOENT")return;throw s}})).then(i=>i.filter(o=>o!==void 0))}function J$e(e){return`predates the current schema; move .fungi/agents/${e} aside to reset it`}function Fun(e){try{return tw(e).archived}catch(t){return t instanceof b2||ar("store-archived",t),!1}}async function gR(e,t="active"){const n=await hIr(e,".fungi/agents"),r=new Set;for(const i of n)try{const o=await Dun(i.path);(t==="all"||Fun(o)===(t==="archived"))&&r.add(o)}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")continue;throw o}return[...r]}var jun=A.strictObject({name:A.string().nullable(),createdBy:A.string().nullable(),archived:A.union([A.literal(0),A.literal(1)]),mode:oU,writableFolders:A.array(A.string()),folder:_2,model:A.string()}),b2=class extends Error{constructor(e,t){super(`Agent store ${e} is incompatible with this version of Fungi. To reset, stop the owning Fungi service, then move this database, its .owner.sqlite sidecar and any associated SQLite journal files aside together. Create a fresh Agent; existing Sessions are not migrated. Keep the moved files if you need their data.`,t),this.databasePath=e}databasePath;name="LocalStoreSchemaError"},fIr=1024,yR=new Map;function gIr(e){const t=n=>{const r=nIr(n,{bigint:!0,throwIfNoEntry:!1});return r===void 0?"-":`${String(r.dev)}:${String(r.ino)}:${String(r.size)}:${String(r.mtimeNs)}:${String(r.ctimeNs)}`};return`${t(e)}/${t(`${e}-wal`)}`}function tw(e){const t=gIr(e),n=yR.get(e);if(n?.version===t)return n.profile;const r=yIr(e);if(yR.delete(e),yR.set(e,{version:t,profile:r}),yR.size>fIr){const i=yR.keys().next().value;i!==void 0&&yR.delete(i)}return r}function yIr(e){const t=Xon(e);try{const n=t.prepare("PRAGMA table_info(private_local_identity)").all();if(!["name","created_by","archived","mode","writable_folders","folder"].every(s=>n.some(a=>a.name===s)))throw new b2(e);const r=t.prepare("SELECT name, created_by, archived, mode, writable_folders, folder FROM private_local_identity WHERE singleton = 1").get(),i=jun.shape.writableFolders.parse(JSON.parse(A.string().parse(r?.writable_folders))),o=jun.parse({name:r?.name,createdBy:r?.created_by,archived:r?.archived,mode:r?.mode,writableFolders:i,folder:r?.folder,model:Nun(t)});return Object.freeze({name:o.name??void 0,createdBy:o.createdBy,archived:o.archived===1,mode:o.mode,writableFolders:Object.freeze(o.writableFolders),folder:o.folder,model:P8e(o.model)})}finally{t.close()}}async function Wun(e){const t=Xon(e);try{t.exec("PRAGMA foreign_keys = ON");let n;const r=t$e(t,s=>{n=s}),i=[];let o;try{do{const s=await Ac(DEr(r,o));for(const a of s.sessions){if(a.kind==="unavailable")throw new $ie("corrupt");i.push({sessionId:a.sessionId,title:a.title,createdAt:a.createdAt,updatedAt:a.updatedAt,databasePath:e})}o=s.next}while(o!==void 0)}catch(s){throw s instanceof $ie?s:new $ie(Uun(n),{cause:s})}return i.sort($un)}finally{t.close()}}async function vIr(e,t={}){t.signal?.throwIfAborted();const n=await Dun(Lun(e)),r=await gR(n,t.archived===!0?"archived":"active"),i=[],o=[],s=new Map,a=[];for(const c of r){t.signal?.throwIfAborted();const l=oIr(sIr(c));try{const d=await Wun(c);i.push(...d);let p,m;try{p=tw(c),cU(n,p.folder),s.set(l,p)}catch(h){if(!(h instanceof b2))throw h;m=J$e(l)}o.push({agentId:l,name:p?.name,unreadable:m,databasePath:c,sessionCount:d.length,updatedAt:d[0]?.updatedAt})}catch(d){a.push({kind:mIr(d)}),o.push({agentId:l,databasePath:c,sessionCount:0})}}i.sort($un);const u=o.map(c=>{const l=s.get(c.agentId)?.createdBy;return l===void 0?c:{...c,createdBy:l}});return{root:n,agents:u,sessions:i,problems:a}}var Uie=A.string().min(1).max(256),qun=A.strictObject({origin:A.url(),invocationRoot:A.string().min(1).max(4096),machineLabel:A.string().trim().min(1).max(256),agents:A.array(Uie).max(256).refine(e=>new Set(e).size===e.length)}),zun=A.discriminatedUnion("kind",[qun.extend({kind:A.literal("oauth"),teamId:Uie}),qun.extend({kind:A.literal("oyster-key"),key:A.string().startsWith("oyk_").min(5).max(4096)})]),Hun=A.strictObject({kind:A.literal("joined"),deviceId:Uie,agents:A.array(Vsn).max(256)}),_Ir=Hun.extend({scopeId:Uie}),wIr=dy({family:"local-machine-enrollment",version:1,kinds:{join:{prefix:"machine_join"}}});function bIr(){const e=_Ar("ed25519"),t=A.object({x:A.string()}).parse(e.publicKey.export({format:"jwk"}));return{publicKey:vAr.from(t.x,"base64url").toString("base64"),privateKey:e.privateKey.export({format:"der",type:"pkcs8"}).toString("base64")}}async function xIr(e,t){const n=zun.parse(e),r=oR(n.origin);if(r.pathname!=="/")throw new Error("Mesh enrollment needs an origin");const i=r.origin,o={kind:n.kind==="oauth"?"oauth":"oyster",origin:i};if(n.kind==="oauth"&&!(await t.account.read()).some(w=>w.kind==="oauth"&&w.origin===i))throw new Error("Sign in to this Fungi issuer before joining a machine");const s=await wAr(kAr(n.invocationRoot)),a=await gR(s),u=n.agents.map(b=>{const w=a.find(T=>bAr(xAr(T))===b);if(w===void 0)throw new Error("The selected Agent is not active in this project");const x=SAr(s,w);if(EAr(x)||x===".."||x.startsWith("../"))throw new Error("The selected Agent is outside this project");const k=tw(w);return{localAgentId:b,databasePath:w,name:k.name??b}}),c={state:"pending",requestId:wIr.join.generate(),target:n.kind==="oauth"?{kind:"oauth",teamId:n.teamId}:{kind:"oyster"},invocationRoot:s,machineLabel:n.machineLabel,...bIr(),agents:u};let l;if(await t.account.update(o,b=>{const w=b.find(x=>JSON.stringify(x.target)===JSON.stringify(c.target));if(w!==void 0){if(w.invocationRoot!==s||w.machineLabel!==n.machineLabel||JSON.stringify(w.agents)!==JSON.stringify(u))throw new Error("This scope already has another machine enrollment intent");return l=w,[...b]}return l=c,[...b,c]}),l===void 0)throw new Error("The credential owner did not persist an enrollment");const d=l;if(d.state==="enrolled")return{state:"enrolled",deviceId:d.deviceId,agents:d.bindings};const p=new URL(n.kind==="oauth"?`/api/teams/${encodeURIComponent(n.teamId)}/local/mesh/join`:"/local/mesh/join",i),m=n.kind==="oauth"?Lie(i,t):t.fetch??globalThis.fetch,h=new Headers({"content-type":"application/json"});n.kind==="oyster-key"&&h.set("Authorization",`Bearer ${n.key}`);const f={method:"POST",headers:h,redirect:"error",body:JSON.stringify({requestId:d.requestId,machineLabel:d.machineLabel,publicKey:d.publicKey,agents:d.agents.map(({name:b})=>({name:b}))})};t.signal!==void 0&&(f.signal=t.signal);let g;try{g=await m(p,f)}finally{n.kind==="oyster-key"&&(h.delete("Authorization"),n.key="")}if(!g.ok)throw new Error(`Machine enrollment refused with HTTP ${String(g.status)}`);const y=JSON.parse(await AAr(g,64*1024,"Machine enrollment")),v=n.kind==="oauth"?{...Hun.parse(y),scopeId:n.teamId}:_Ir.parse(y);if(v.agents.length!==d.agents.length||v.agents.some((b,w)=>b.selection!==w)||new Set(v.agents.map(b=>b.agentId)).size!==v.agents.length)throw new Error("Machine enrollment does not match the selected Agent set");const _=Jsn.parse({...d,state:"enrolled",deviceId:v.deviceId,scopeId:v.scopeId,bindings:v.agents});return await t.account.update(o,b=>{const w=b.find(x=>x.requestId===d.requestId);if(w===void 0)throw new Error("Machine enrollment was removed before acknowledgment");if(w.state==="enrolled"&&(w.deviceId!==v.deviceId||w.scopeId!==v.scopeId||JSON.stringify(w.bindings)!==JSON.stringify(v.agents)))throw new Error("Home changed an acknowledged machine enrollment");return b.map(x=>x.requestId===d.requestId?_:x)}),{state:"enrolled",deviceId:v.deviceId,agents:v.agents}}xt();var jVr=A.strictObject({rootAgentId:A.string(),agents:A.array(A.discriminatedUnion("outcome",[A.strictObject({agentId:A.string(),name:A.string(),outcome:A.enum(["stopped","idle"])}),A.strictObject({agentId:A.string(),name:A.string(),outcome:A.literal("failed"),reason:A.string()})])),discoveryFailures:A.array(A.strictObject({agentId:A.string(),reason:A.string()}))}),SIr=A.strictObject({invocationRoot:A.string().min(1),agentId:A.string().min(1)});import{readFile as EIr}from"node:fs/promises";import{join as kIr}from"node:path";Dre();import{once as AIr}from"node:events";import{access as TIr}from"node:fs/promises";import{join as IIr}from"node:path";import{EventEmitter as vR}from"node:events";var _R=class{constructor(e,t={},n){this.pattern=e,this.separator=t.separator||".",this.segments=this._parse(e),this.data=n,this._hasDeepWildcard=this.segments.some(r=>r.type==="deep-wildcard"),this._hasAttributeCondition=this.segments.some(r=>r.attrName!==void 0),this._hasPositionSelector=this.segments.some(r=>r.position!==void 0)}_parse(e){const t=[];let n=0,r="";for(;n<e.length;)e[n]===this.separator?n+1<e.length&&e[n+1]===this.separator?(r.trim()&&(t.push(this._parseSegment(r.trim())),r=""),t.push({type:"deep-wildcard"}),n+=2):(r.trim()&&t.push(this._parseSegment(r.trim())),r="",n++):(r+=e[n],n++);return r.trim()&&t.push(this._parseSegment(r.trim())),t}_parseSegment(e){const t={type:"tag"};let n=null,r=e;const i=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){const c=i[2].slice(1,-1);c&&(n=c)}let o,s=r;if(r.includes("::")){const c=r.indexOf("::");if(o=r.substring(0,c).trim(),s=r.substring(c+2).trim(),!o)throw new Error(`Invalid namespace in pattern: ${e}`)}let a,u=null;if(s.includes(":")){const c=s.lastIndexOf(":"),l=s.substring(0,c).trim(),d=s.substring(c+1).trim();["first","last","odd","even"].includes(d)||/^nth\(\d+\)$/.test(d)?(a=l,u=d):a=s}else a=s;if(!a)throw new Error(`Invalid segment pattern: ${e}`);if(t.tag=a,o&&(t.namespace=o),n)if(n.includes("=")){const c=n.indexOf("=");t.attrName=n.substring(0,c).trim(),t.attrValue=n.substring(c+1).trim()}else t.attrName=n.trim();if(u){const c=u.match(/^nth\((\d+)\)$/);c?(t.position="nth",t.positionValue=parseInt(c[1],10)):t.position=u}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}},CIr=class{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._deepByTerminalTag=new Map,this._patterns=new Set,this._sealed=!1}add(e){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(e.pattern))return this;if(this._patterns.add(e.pattern),e.hasDeepWildcard()){const i=e.segments[e.segments.length-1];if(i&&i.type!=="deep-wildcard"&&i.tag!=="*"){const o=i.tag;this._deepByTerminalTag.has(o)||this._deepByTerminalTag.set(o,[]),this._deepByTerminalTag.get(o).push(e)}else this._deepWildcards.push(e);return this}const t=e.length,r=e.segments[e.segments.length-1]?.tag;if(!r||r==="*")this._wildcardByDepth.has(t)||this._wildcardByDepth.set(t,[]),this._wildcardByDepth.get(t).push(e);else{const i=`${t}:${r}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(e)}return this}addAll(e){for(const t of e)this.add(t);return this}has(e){return this._patterns.has(e.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(e){return this.findMatch(e)!==null}findMatch(e){const t=e.getDepth(),n=e.getCurrentTag(),r=`${t}:${n}`,i=this._byDepthAndTag.get(r);if(i){for(let a=0;a<i.length;a++)if(e.matches(i[a]))return i[a]}const o=this._wildcardByDepth.get(t);if(o){for(let a=0;a<o.length;a++)if(e.matches(o[a]))return o[a]}const s=this._deepByTerminalTag.get(n);if(s){for(let a=0;a<s.length;a++)if(e.matches(s[a]))return s[a]}for(let a=0;a<this._deepWildcards.length;a++)if(e.matches(this._deepWildcards[a]))return this._deepWildcards[a];return null}},RIr=class{constructor(e){this._matcher=e}get separator(){return this._matcher.separator}getCurrentTag(){const e=this._matcher.path;return e.length>0?e[e.length-1].tag:void 0}getCurrentNamespace(){const e=this._matcher.path;return e.length>0?e[e.length-1].namespace:void 0}getAttrValue(e){const t=this._matcher.path;if(t.length!==0)return t[t.length-1].values?.[e]}hasAttr(e){const t=this._matcher.path;if(t.length===0)return!1;const n=t[t.length-1];return n.values!==void 0&&e in n.values}getAnyParentAttr(e){return this._matcher.getAnyParentAttr(e)}hasAnyParentAttr(e){return this._matcher.hasAnyParentAttr(e)}getPosition(){const e=this._matcher.path;return e.length===0?-1:e[e.length-1].position??0}getCounter(){const e=this._matcher.path;return e.length===0?-1:e[e.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(e,t=!0){return this._matcher.toString(e,t)}toArray(){return this._matcher.path.map(e=>e.tag)}matches(e){return this._matcher.matches(e)}matchesAny(e){return e.matchesAny(this._matcher)}},Q$e=class{constructor(e={}){this.separator=e.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new RIr(this),this._keptAttrs=[]}push(e,t=null,n=null,r=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;let o=this.siblingStacks[i];o||(o={counts:new Map,total:0},this.siblingStacks[i]=o);const s=n?`${n}:${e}`:e,a=o.counts.get(s)||0,u=o.total;o.counts.set(s,a+1),o.total++;const c={tag:e,position:u,counter:a};n!=null&&(c.namespace=n),t!=null&&(c.values=t),this.path.push(c);const l=this.path.length,d=r!==null?r.keep:null;if(d!=null&&d.length>0&&t)for(let p=0;p<d.length;p++){const m=d[p];t[m]!==void 0&&this._keptAttrs.push({depth:l,name:m,value:t[m]})}}pop(){if(this.path.length===0)return;this._pathStringCache=null;const e=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);const t=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=t;)this._keptAttrs.pop();return e}updateCurrent(e){if(this.path.length>0){const t=this.path[this.path.length-1];e!=null&&(t.values=e)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(e){if(this.path.length!==0)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(this.path.length===0)return!1;const t=this.path[this.path.length-1];return t.values!==void 0&&e in t.values}getAnyParentAttr(e){const t=this._keptAttrs;for(let n=t.length-1;n>=0;n--)if(t[n].name===e)return t[n].value}hasAnyParentAttr(e){const t=this._keptAttrs;for(let n=t.length-1;n>=0;n--)if(t[n].name===e)return!0;return!1}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=!0){const n=e||this.separator;if(n===this.separator&&t===!0){if(this._pathStringCache!==null)return this._pathStringCache;const i=this.path.map(o=>o.namespace?`${o.namespace}:${o.tag}`:o.tag).join(n);return this._pathStringCache=i,i}return this.path.map(i=>t&&i.namespace?`${i.namespace}:${i.tag}`:i.tag).join(n)}toArray(){return this.path.map(e=>e.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}matches(e){const t=e.segments;return t.length===0?!1:e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t)}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(!this._matchSegment(e[t],this.path[t],t===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,n=e.length-1;for(;n>=0&&t>=0;){const r=e[n];if(r.type==="deep-wildcard"){if(n--,n<0)return!0;const i=e[n];let o=!1;for(let s=t;s>=0;s--)if(this._matchSegment(i,this.path[s],s===this.path.length-1)){t=s-1,n--,o=!0;break}if(!o)return!1}else{if(!this._matchSegment(r,this.path[t],t===this.path.length-1))return!1;t--,n--}}return n<0}_matchSegment(e,t,n){if(e.tag!=="*"&&e.tag!==t.tag||e.namespace!==void 0&&e.namespace!=="*"&&e.namespace!==t.namespace||e.attrName!==void 0&&(!n||!t.values||!(e.attrName in t.values)||e.attrValue!==void 0&&String(t.values[e.attrName])!==String(e.attrValue)))return!1;if(e.position!==void 0){if(!n)return!1;const r=t.counter??0;if(e.position==="first"&&r!==0)return!1;if(e.position==="odd"&&r%2!==1)return!1;if(e.position==="even"&&r%2!==0)return!1;if(e.position==="nth"&&r!==e.positionValue)return!1}return!0}matchesAny(e){return e.matchesAny(this)}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>e&&{counts:new Map(e.counts),total:e.total}),keptAttrs:this._keptAttrs.map(e=>({...e}))}}restore(e){this._pathStringCache=null,this.path=e.path.map(t=>({...t})),this.siblingStacks=e.siblingStacks.map(t=>t&&{counts:new Map(t.counts),total:t.total}),this._keptAttrs=(e.keptAttrs||[]).map(t=>({...t}))}readOnly(){return this._view}};function Ed(e){return typeof e=="number"&&Object.is(e,-0)?"-0":String(e)}function X$e(e){return Ed(e).replace(/--/g,"- -").replace(/--/g,"- -").replace(/-$/,"- ")}function Gun(e){return Ed(e).replace(/\]\]>/g,"]]]]><![CDATA[>")}function x2(e){return Ed(e).replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var Vun=":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",OIr=Vun+"\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040",Kun=":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}",PIr=Kun+"\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040",Y$e=(e,t,n="")=>{const r=e.replace(":",""),i=t.replace(":",""),o=`[${r}][${i}]*`;return{name:new RegExp(`^[${e}][${t}]*$`,n),ncName:new RegExp(`^${o}$`,n),qName:new RegExp(`^${o}(?::${o})?$`,n),nmToken:new RegExp(`^[${t}]+$`,n),nmTokens:new RegExp(`^[${t}]+(?:\\s+[${t}]+)*$`,n)}},MIr=Y$e(Vun,OIr),DIr=Y$e(Kun,PIr,"u"),Jun=":A-Za-z_",LIr=Jun+"\\-\\.\\d",NIr=Y$e(Jun,LIr),Qun=(e="1.0",t=!1)=>t?NIr:e==="1.1"?DIr:MIr,Xun=(e,{xmlVersion:t="1.0",asciiOnly:n=!1}={})=>Qun(t,n).qName.test(e),Yun=["name","ncName","qName","nmToken","nmTokens"],Zun=(e,{xmlVersion:t="1.0",asciiOnly:n=!1,maxCacheSize:r=2048}={})=>{if(!Yun.includes(e))throw new TypeError(`Unknown production "${e}". Must be one of: ${Yun.join(", ")}`);const i=Qun(t,n)[e];let o=new Map;const s=a=>{const u=o.get(a);if(u!==void 0)return u;const c=i.test(a);return o.size<r&&o.set(a,c),c};return s.reset=()=>{o=new Map},s},$Ir=`
@@ -1763,7 +1763,7 @@ data: ${JSON.stringify({...r,connectionId:n.id})}
1763
1763
 
1764
1764
  `))))))).pipe(d1t,n=>_1t(n,{strategy:{highWaterMark:1}}));return new Response(t,{headers:{"Cache-Control":"no-cache","Content-Encoding":"Identity","Content-Type":"text/event-stream"}})}function gUr(e){if(!(e instanceof x0))return Response.json({error:"Live App commands are unavailable"},{status:503});const t=e.code==="invalid_browser_wire"?400:503;return Response.json({error:e.message},{status:t})}async function Phn(e,t,n){const r=Bi({try:()=>e.json(),catch:()=>new x0("invalid_browser_wire",t)}).pipe(je(i=>It(()=>q$r.parse(i))),je(n));try{return Response.json(await uBe(r,e.signal))}catch(i){return gUr(i)}}function yUr(e=GS(sUr())){const t=qn.module({id:"knapsack-ui",name:"ui",description:"Live semantic commands from the connected browser",operations:{discover:qn.operation({replay:"safe",description:"Discover commands in the connected browser",input:A.object({}),output:uUr,execute:(r,i)=>uBe(dUr(e,{type:"discover"}).pipe(St(mUr)),i.signal)}),execute:qn.operation({replay:"unsafe",description:"Execute one discovered command in the connected browser",input:J$r,output:cUr,execute:(r,i)=>uBe(pUr(e,{type:"execute",...r}).pipe(St(hUr)),i.signal)})}});return Object.freeze({modules:[t],fetch:async r=>{const i=new URL(r.url);return r.method==="GET"&&i.pathname==="/browser/events"?fUr(e):r.method==="POST"&&i.pathname==="/browser/claims"?Phn(r,"Browser claim is invalid",e.claim):r.method==="POST"&&i.pathname==="/browser/results"?Phn(r,"Browser result is invalid",e.acceptResult):Response.json({error:"Not found"},{status:404})}})}var vUr=class{open;hasSession;generation=0;closed=!1;hosts=new Map;constructor(e,t){this.open=e,this.hasSession=t}async close(){this.closed=!0,this.generation+=1;const e=[...this.hosts.values()];this.hosts.clear(),await Promise.all(e.flatMap(t=>[...t.connections].map(n=>n())))}async fetch(e){if(this.closed)return new Response(null,{status:410});const t=this.generation,n=new URL(e.url).pathname,r=/^\/browser\/sessions\/([^/]+)\/browser\/(events|claims|results)$/u.exec(n);if(r===null)return new Response("Not found",{status:404});let i;try{i=decodeURIComponent(r[1]??"")}catch{return new Response("Not found",{status:404})}const o=r[2];if(!i||!o)return new Response("Not found",{status:404});let s=this.hosts.get(i);if(s===void 0){if(o!=="events")return new Response("Not found",{status:404});if(!await this.hasSession(i))return new Response("Not found",{status:404});if(t!==this.generation)return new Response(null,{status:404});s=this.hosts.get(i)??this.createHost(i)}const a=new URL(e.url);return a.pathname=`/browser/${o}`,o!=="events"?s.host.fetch(new Request(a,e)):this.openEvents(new Request(a,e),i,s,t)}async openEvents(e,t,n,r){n.browserConnections+=1;try{const i=await n.host.fetch(e);return r!==this.generation?(await i.body?.cancel(),this.releaseBrowserConnection(t,n),new Response(null,{status:404})):!i.ok||i.body===null?(this.releaseBrowserConnection(t,n),i):this.trackBrowserConnection(i,t,n)}catch(i){throw this.releaseBrowserConnection(t,n),i}}createHost(e){const t={host:this.open(e),activeRuns:0,browserConnections:0,connections:new Set};return this.hosts.set(e,t),t}acquire(e){if(this.closed)throw new Error("Browser host is closed");const t=this.hosts.get(e)??this.createHost(e);t.activeRuns+=1;let n=!1;return{modules:t.host.modules,release:()=>{n||(n=!0,t.activeRuns-=1,this.releaseIdleHost(e,t))}}}releaseBrowserConnection(e,t){t.browserConnections-=1,this.releaseIdleHost(e,t)}releaseIdleHost(e,t){t.activeRuns===0&&t.browserConnections===0&&this.hosts.get(e)===t&&this.hosts.delete(e)}trackBrowserConnection(e,t,n){const r=e.body?.getReader();if(r===void 0)return this.releaseBrowserConnection(t,n),e;let i=!1,o;const s=async()=>{i||(a(),o.close(),await r.cancel())},a=()=>{i||(i=!0,n.connections.delete(s),this.releaseBrowserConnection(t,n))};n.connections.add(s);const u=new ReadableStream({start:c=>{o=c},pull:async c=>{try{const l=await r.read();if(i)return;l.done?(c.close(),a()):c.enqueue(l.value)}catch(l){if(i)return;c.error(l),a()}},cancel:async c=>{a(),await r.cancel(c)}});return new Response(u,{status:e.status,statusText:e.statusText,headers:e.headers})}};function _Ur(e,t){if(t.signal.throwIfAborted(),t.session===void 0)return{snapshot:{version:"no-session",modules:[]},release:()=>Promise.resolve()};const n=t.session.sessionId,r=e.acquire(n);return{snapshot:{version:`session:${n}`,modules:r.modules},release:()=>(r.release(),Promise.resolve())}}function wUr(e){const t=new vUr(()=>yUr(),e.hasSession);return Object.freeze({source:{id:e.id,acquire:n=>new Promise(r=>{r(_Ur(t,n))})},fetch:n=>t.fetch(n),close:()=>t.close()})}var bUr=256,xUr=8,Mhn=1e4,SUr=new TextEncoder,Voe=A.json(),Dhn=A.lazy(()=>A.custom(e=>Voe.safeParse(e).success)),Lhn=A.lazy(()=>A.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),EUr=A.lazy(()=>A.strictObject({id:Lhn,name:Lhn,kind:A.string().min(1).max(128),description:A.string().min(1).max(2048),parameters:Dhn,output:Dhn.optional()})),kUr=A.lazy(()=>A.array(EUr).max(bUr));function AUr(e){return A.fromJSONSchema(e).pipe(Voe)}function TUr(e){return A.intersection(Voe,A.fromJSONSchema(e))}async function Nhn(e){const t=SUr.encode(e),n=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return`computer-${Array.from(n,r=>r.toString(16).padStart(2,"0")).join("")}`}var cBe=class extends Error{name="ComputerUnavailableError";computerId;reason;constructor(e,t,n){super(`Computer ${e} is unavailable: ${t}`,{cause:n}),this.computerId=e,this.reason=t}};function IUr(e,t){const n=kUr.parse(t),r={};for(const s of n){const a=s.output===void 0?Voe:TUr(s.output);r[s.id]=qn.operation({replay:"unsafe",confirm:e.confirmCalls===!0,description:s.description,input:AUr(s.parameters),output:a,execute:(u,c)=>e.computer.call(s.id,u,c)})}if(e.files!==void 0){if(r.files!==void 0)throw new Error("Computer advertisement reserves the files namespace");r.files=phn(e.files).module}const i=e.role===void 0?`Computer "${e.name}": capabilities advertised by this Computer.`:`Computer "${e.name}" (${e.role}): capabilities advertised by this Computer.`;return{module:qn.module({id:e.id,name:e.name,namespace:e.namespace??[],description:i,operations:r}),serialized:JSON.stringify(n)}}function $hn(e,t){return Bi({try:n=>e.computer.getCapabilities(n),catch:n=>new cBe(e.id,"rejected",n)}).pipe(s6({duration:t,orElse:()=>xe(new cBe(e.id,"timeout"))}),je(n=>It({try:()=>IUr(e,n),catch:r=>new cBe(e.id,"invalid-advertisement",r)})),je(({module:n,serialized:r})=>tm(()=>Nhn(r)).pipe(St(i=>({module:n,version:i})))))}async function Uhn(e,t){t.throwIfAborted();try{return await Ac(e,{signal:t})}catch(n){throw t.throwIfAborted(),n}}function CUr(e){return{id:e.id,acquire:async({signal:t})=>{const n=await Uhn(_h($hn(e,Mhn)),t);if(On(n))throw n.failure;return{snapshot:{version:n.success.version,modules:[n.success.module]},release:()=>Promise.resolve()}}}}function RUr(e){const t=e.describeTimeoutMillis??Mhn;return{id:e.id,acquire:async n=>{n.signal.throwIfAborted();const r=e.subscribe(n.invalidate);try{const i=e.read(),o=await Uhn(go(i.connections,u=>_h($hn(u,t)),{concurrency:xUr}),n.signal),s=[],a=[i.version];for(const u of o){if(On(u)){e.onUnavailable(u.failure),a.push(`unavailable:${u.failure.computerId}:${u.failure.reason}`);continue}s.push(u.success.module),a.push(u.success.version)}return{snapshot:{version:await Nhn(JSON.stringify(a)),modules:s},release:()=>(r(),Promise.resolve())}}catch(i){throw r(),i}}}}var lBe=Object.freeze({computer:CUr,computers:RUr,files:phn,mcpServers:W$r,ui:wUr});Gs(),vt(),ir(),kt(),Gs(),kt();var OUr=oe.pipe(rt(pn(1))),Koe=K({attachmentId:pt(OUr)}),dBe={id:gd.make("botanical-home"),commands:{home:{scope:"session",input:K({name:We(oe)}),output:f2},seed:{scope:"agent",input:Koe,output:K({seeded:Cr})}},projection:{schema:pt(Koe)}};xt();var PUr=A.url({protocol:/^computer$/}).transform(e=>new URL(e)).refine(e=>!e.username&&!e.password&&!e.port&&!e.search&&!e.hash,"Computer file locators cannot contain credentials, ports, queries or fragments");function MUr(e,t){function n(o){const a=/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o)?PUr.parse(o):null,u=a===null?"home":decodeURIComponent(a.hostname),c=u==="home"?t:e.get(u);if(c===void 0)throw new Error(`Files connection unavailable: ${u}`);const l=a===null?o:decodeURIComponent(a.pathname.slice(1))||".";return{port:c,path:l,locate:p=>{if(a===null)return p;const m=new URL(a);return m.pathname=p.split("/").map(encodeURIComponent).join("/"),m.href}}}const r={read:async(o,s)=>{const{port:a,path:u}=n(o.path);return{...await a.read({...o,path:u},s),path:o.path}},list:async(o,s)=>{const{port:a,path:u,locate:c}=n(o.path);return pBe(await a.list({...o,path:u},s),o.path,c)},glob:async(o,s)=>{const{port:a,path:u,locate:c}=n(o.path);return pBe(await a.glob({...o,path:u},s),o.path,c)},grep:async(o,s)=>{const{port:a,path:u,locate:c}=n(o.path);return pBe(await a.grep({...o,path:u},s),o.path,c)},replace:async(o,s)=>{const{port:a,path:u}=n(o.path);return{...await a.replace({...o,path:u},s),path:o.path}}},i=t.patch?.bind(t);return i===void 0?r:{...r,patch:i}}function pBe(e,t,n){return{...e,path:t,results:e.results.map(r=>({...r,path:n(r.path)}))}}var DUr={id:dBe.id,capabilities:["state","files","prompt","projection","commands"]},LUr={promptLimit:4e3,guide:"Home supplies read, list, glob and grep over your default Computer. Bare paths and computer://home/ use Home; computer://<name>/ uses that captured attachment. apply_patch, when offered, also works on Home. Only a person changes Home with /home <name>; ask them when no Home is available."},NUr={choice:a0(Koe,{key:()=>"default"})};function $Ur(e){const t=new WeakMap;return s0({id:dBe.id,version:"1.0.0"}).config(LUr).state({version:1,migrations:{},collections:NUr}).define({catalog:sA([{id:"home",title:"Home Computer",category:"Settings",description:"Choose the default Computer",projections:{help:{order:5},palette:{order:5},slash:{aliases:["home"],order:5,arguments:{hint:"<name>",text:{field:"name",arguments:{}}}}}}]),projection:{schema:pt(Koe),read:n=>Ft(Zf(n.state.choice.peek("default")))},files:async(n,r)=>{await e.computers.prepare?.(r);const i=[...e.computers.read(r)],o=n.state.update(l=>{const d=Zf(l.choice.get("default"));if(d!==null)return d;const p=i.length===1?i[0]:void 0;if(p===void 0)return null;const m={attachmentId:p.attachmentId};return l.choice.put(m),m}),s=i.find(l=>l.attachmentId===o?.attachmentId),a=s!==void 0?`Home: ${s.name}.`:o?.attachmentId==null?"No Home selected. Ask a person to choose /home <name>.":"Home's default Computer is detached. Ask a person to choose /home <name>; there is no fallback.",u=i.map(l=>`computer://${encodeURIComponent(l.name)}/`).join(", "),c=`${n.config.guide}
1765
1765
  ${a}
1766
- Captured mounts: ${u||"none"}.`;return t.set(r,c.slice(0,n.config.promptLimit)),s===void 0?null:lBe.files({port:MUr(new Map(i.map(({name:l,port:d})=>[l,d])),s.port)}).tools},prompt:(n,r)=>[{name:"home",text:t.get(r)??"Home file tools were not captured. Ask the person to check Home's Files grant."}],commands:{specs:dBe.commands,handlers:n=>({home:({input:r,sessionId:i})=>qe(function*(){const o=e.computers.read({sessionId:i});if(r.name===void 0){if(o.length===0)return ja({type:"info",message:"No Computers attached. Attach one before choosing Home."});const a=Zf(yield*n.state.choice.get("default")),u=o.find(({attachmentId:l})=>l===a?.attachmentId),c={type:"choice",message:"Choose a Home Computer",summary:"The Agent reads and edits files here by default.",options:o.map(({name:l})=>({value:l,label:l}))};return $f(u===void 0?c:{...c,current:u.name},{},"name")}const s=o.find(({name:a})=>a===r.name);return s===void 0?yield*xe(new nu({reason:"invalid",message:`Computer is not attached: ${r.name}`})):(yield*n.state.choice.put({attachmentId:s.attachmentId}),yield*n.observe(i),ja({type:"success",message:`Home: ${s.name}`}))}),seed:({input:r})=>qe(function*(){return cr(yield*n.state.choice.get("default"))?{seeded:!1}:(yield*n.state.choice.put(r),{seeded:!0})})})}})}async function Fhn(e,t,n){n.throwIfAborted();try{if(await e.checkAuth(t,{signal:n})===void 0)return[]}catch(r){return n.throwIfAborted(),ar("model-default.check-auth",r),[]}if(e.getModels(t).length===0){const r=await e.refresh({providers:[t],signal:n});if(n.throwIfAborted(),r.aborted||r.errors.has(t))return[]}return e.getModels(t)}async function UUr(e,t){const n=e.getProviders(),r=[...n.filter(({id:i})=>i==="fungi"),...n.filter(({id:i})=>i!=="fungi")];for(const i of r){const o=await Fhn(e,i.id,t),s=o.find(a=>"default"in a&&a.default===!0)??o[0];if(s!==void 0)return{providerId:i.id,modelId:s.id}}return null}async function FUr(e,t){const n=[];for(const r of e.getProviders())for(const i of await Fhn(e,r.id,t))n.push({address:`${r.id}/${i.id}`,name:i.name});return n}yk();function mBe(e,t){if(t===void 0)return;const n=hM(e).filter(r=>r!=="off");if(!n.includes(t))throw new Error("Reasoning level "+t+" is not supported by "+e.provider+"/"+e.id+"; supported levels: "+(n.join(", ")||"none"))}function Bhn(e){const t=Pg(e,"medium");return t==="off"?void 0:t}function BUr(e,t,n){return t.reasoning??(n!==void 0&&hM(e).includes(n)?n:Bhn(e))}function jhn(e){return e.session!==null?{preference:e.session,source:"session"}:e.agent!==null?{preference:e.agent,source:"agent"}:null}async function jUr(e){const t=jhn(e);if(t!==null)return t;const n=await UUr(e.models,e.signal);return n===null?null:{preference:n,source:"available"}}xt();var Whn=A.strictObject({agentName:A.literal("Shiitake"),providerId:A.string().min(1).max(160),providerName:A.string().min(1).max(256),modelId:A.string().min(1).max(160),modelName:A.string().min(1).max(256),credential:A.strictObject({kind:A.enum(["oauth","api_key","missing"]),source:A.string().min(1).max(160)}),reasoning:Idn.optional(),label:A.string().min(1).max(640)});import{realpath as qhn}from"node:fs/promises";import{relative as WUr,resolve as zhn,sep as Hhn}from"node:path";import jR from"node:process";Ms(),Vj(),j7e(),Ms(),vt(),Qi(),sl();var qUr=B7e(),zUr=B7e(),Ghn="~effect/process/ChildProcessSpawner/ChildProcessHandle",HUr={[Ghn]:Ghn,...I5,toJSON(){return{_id:"ChildProcessHandle",pid:this.pid}}},Vhn=e=>Object.setPrototypeOf({...e},HUr),GUr=e=>{const t=(r,i)=>e(r).pipe(St(o=>l1t(i?.includeStderr===!0?o.all:o.stdout)),Db),n=(r,i)=>p1t(t(r,i));return Joe.of({spawn:e,exitCode:r=>c1(je(e(r),i=>i.exitCode)),streamString:t,streamLines:n,lines:(r,i)=>h1t(n(r,i)),string:(r,i)=>y1t(t(r,i))})},Joe=class extends Xc()("effect/process/ChildProcessSpawner"){},Khn="~effect/process/ChildProcess",VUr={...Gj({label:"Command",evaluate(e){return Nw(e.context,Joe).spawn(this)}}),[Khn]:Khn},Qoe=(e,t,n)=>Object.assign(Object.create(VUr),{_tag:"StandardCommand",command:e,args:t,options:n}),YU=function(...t){if(Jhn(t[0])){const[o,...s]=t,a=Qhn(o,s);return Qoe(a[0]??"",a.slice(1),{})}if(typeof t[0]=="object"&&!Array.isArray(t[0])&&!Jhn(t[0])){const o=t[0];return function(s,...a){const u=Qhn(s,a);return Qoe(u[0]??"",u.slice(1),o)}}if(typeof t[0]=="string"&&!Array.isArray(t[1])){const[o,s={}]=t;return Qoe(o,[],s)}const[n,r=[],i={}]=t;return Qoe(n,r,i)},Jhn=e=>Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw),hBe=e=>{const t=/^fd(\d+)$/.exec(e);if(t===null)return;const n=parseInt(t[1],10);return n>=3?n:void 0},KUr=e=>`fd${e}`,Qhn=(e,t)=>{let n=[];for(const[r,i]of e.entries())n=JUr(e,t,n,i,r);return n},JUr=(e,t,n,r,i)=>{const o=e.raw[i];if(o===void 0)throw new Error(`Invalid backslash sequence: ${e.raw[i]}`);const{hasLeadingWhitespace:s,hasTrailingWhitespace:a,tokens:u}=XUr(r,o),c=Zhn(n,u,s);if(i===t.length)return c;const l=t[i],d=Array.isArray(l)?l.map(p=>Xhn(p)):[Xhn(l)];return Zhn(c,d,a)},Xhn=e=>typeof e==="string"?e:String(e),Yhn=new Set([" "," ","\r",`
1766
+ Captured mounts: ${u||"none"}.`;return t.set(r,c.slice(0,n.config.promptLimit)),s===void 0?null:lBe.files({port:MUr(new Map(i.map(({name:l,port:d})=>[l,d])),s.port)}).tools},prompt:(n,r)=>[{name:"home",text:t.get(r)??"Home file tools were not captured. Ask the person to check Home's Files grant."}],commands:{specs:dBe.commands,handlers:n=>({home:({input:r,sessionId:i})=>qe(function*(){const o=e.computers.read({sessionId:i});if(r.name===void 0){if(o.length===0)return ja({type:"info",message:"No Computers attached. Attach one before choosing Home."});const a=Zf(yield*n.state.choice.get("default")),u=o.find(({attachmentId:l})=>l===a?.attachmentId),c={type:"choice",message:"Choose a Home Computer",summary:"The Agent reads and edits files here by default.",options:o.map(({name:l})=>({value:l,label:l}))};return $f(u===void 0?c:{...c,current:u.name},{},"name")}const s=o.find(({name:a})=>a===r.name);return s===void 0?yield*xe(new nu({reason:"invalid",message:`Computer is not attached: ${r.name}`})):(yield*n.state.choice.put({attachmentId:s.attachmentId}),yield*n.observe(i),ja({type:"success",message:`Home: ${s.name}`}))}),seed:({input:r})=>qe(function*(){return cr(yield*n.state.choice.get("default"))?{seeded:!1}:(yield*n.state.choice.put(r),{seeded:!0})})})}})}async function Fhn(e,t,n){n.throwIfAborted();let r;try{if(r=await e.checkAuth(t,{signal:n}),r===void 0)return}catch(i){n.throwIfAborted(),ar("model-default.check-auth",i);return}if(e.getModels(t).length===0){const i=await e.refresh({providers:[t],signal:n});if(n.throwIfAborted(),i.aborted||i.errors.has(t))return}return{catalog:e.getModels(t),auth:r}}async function UUr(e,t){const n=e.getProviders(),r=[...n.filter(({id:i})=>i==="fungi"),...n.filter(({id:i})=>i!=="fungi")];for(const i of r){const o=await Fhn(e,i.id,t);if(o===void 0)continue;const{catalog:s,auth:a}=o,u=a.type!=="oauth"?void 0:i.id==="openai"?"gpt-6.1-sol":i.id==="anthropic"?"claude-opus-5-5":void 0,c=s.find(l=>l.id===u)??s.find(l=>"default"in l&&l.default===!0)??s[0];if(c!==void 0)return{providerId:i.id,modelId:c.id}}return null}async function FUr(e,t){const n=[];for(const r of e.getProviders()){const i=await Fhn(e,r.id,t);for(const o of i?.catalog??[])n.push({address:`${r.id}/${o.id}`,name:o.name})}return n}yk();function mBe(e,t){if(t===void 0)return;const n=hM(e).filter(r=>r!=="off");if(!n.includes(t))throw new Error("Reasoning level "+t+" is not supported by "+e.provider+"/"+e.id+"; supported levels: "+(n.join(", ")||"none"))}function Bhn(e){const t=Pg(e,"medium");return t==="off"?void 0:t}function BUr(e,t,n){return t.reasoning??(n!==void 0&&hM(e).includes(n)?n:Bhn(e))}function jhn(e){return e.session!==null?{preference:e.session,source:"session"}:e.agent!==null?{preference:e.agent,source:"agent"}:null}async function jUr(e){const t=jhn(e);if(t!==null)return t;const n=await UUr(e.models,e.signal);return n===null?null:{preference:n,source:"available"}}xt();var Whn=A.strictObject({agentName:A.literal("Shiitake"),providerId:A.string().min(1).max(160),providerName:A.string().min(1).max(256),modelId:A.string().min(1).max(160),modelName:A.string().min(1).max(256),credential:A.strictObject({kind:A.enum(["oauth","api_key","missing"]),source:A.string().min(1).max(160)}),reasoning:Idn.optional(),label:A.string().min(1).max(640)});import{realpath as qhn}from"node:fs/promises";import{relative as WUr,resolve as zhn,sep as Hhn}from"node:path";import jR from"node:process";Ms(),Vj(),j7e(),Ms(),vt(),Qi(),sl();var qUr=B7e(),zUr=B7e(),Ghn="~effect/process/ChildProcessSpawner/ChildProcessHandle",HUr={[Ghn]:Ghn,...I5,toJSON(){return{_id:"ChildProcessHandle",pid:this.pid}}},Vhn=e=>Object.setPrototypeOf({...e},HUr),GUr=e=>{const t=(r,i)=>e(r).pipe(St(o=>l1t(i?.includeStderr===!0?o.all:o.stdout)),Db),n=(r,i)=>p1t(t(r,i));return Joe.of({spawn:e,exitCode:r=>c1(je(e(r),i=>i.exitCode)),streamString:t,streamLines:n,lines:(r,i)=>h1t(n(r,i)),string:(r,i)=>y1t(t(r,i))})},Joe=class extends Xc()("effect/process/ChildProcessSpawner"){},Khn="~effect/process/ChildProcess",VUr={...Gj({label:"Command",evaluate(e){return Nw(e.context,Joe).spawn(this)}}),[Khn]:Khn},Qoe=(e,t,n)=>Object.assign(Object.create(VUr),{_tag:"StandardCommand",command:e,args:t,options:n}),YU=function(...t){if(Jhn(t[0])){const[o,...s]=t,a=Qhn(o,s);return Qoe(a[0]??"",a.slice(1),{})}if(typeof t[0]=="object"&&!Array.isArray(t[0])&&!Jhn(t[0])){const o=t[0];return function(s,...a){const u=Qhn(s,a);return Qoe(u[0]??"",u.slice(1),o)}}if(typeof t[0]=="string"&&!Array.isArray(t[1])){const[o,s={}]=t;return Qoe(o,[],s)}const[n,r=[],i={}]=t;return Qoe(n,r,i)},Jhn=e=>Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw),hBe=e=>{const t=/^fd(\d+)$/.exec(e);if(t===null)return;const n=parseInt(t[1],10);return n>=3?n:void 0},KUr=e=>`fd${e}`,Qhn=(e,t)=>{let n=[];for(const[r,i]of e.entries())n=JUr(e,t,n,i,r);return n},JUr=(e,t,n,r,i)=>{const o=e.raw[i];if(o===void 0)throw new Error(`Invalid backslash sequence: ${e.raw[i]}`);const{hasLeadingWhitespace:s,hasTrailingWhitespace:a,tokens:u}=XUr(r,o),c=Zhn(n,u,s);if(i===t.length)return c;const l=t[i],d=Array.isArray(l)?l.map(p=>Xhn(p)):[Xhn(l)];return Zhn(c,d,a)},Xhn=e=>typeof e==="string"?e:String(e),Yhn=new Set([" "," ","\r",`
1767
1767
  `]),QUr={x:3,u:5},XUr=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};const n=Yhn.has(t[0]),r=[];let i=0;for(let s=0,a=0;s<e.length;s+=1,a+=1){const u=t[a];if(Yhn.has(u))i!==s&&r.push(e.slice(i,s)),i=s+1;else if(u==="\\"){const c=t[a+1];if(c===`
1768
1768
  `)s-=1,a+=1;else if(c==="u"&&t[a+2]==="{"){const l=t.indexOf("}",a+3);parseInt(t.slice(a+3,l),16)>65535&&(s+=1),a=l}else a+=QUr[c]??1}}const o=i===e.length;return o||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:o}},Zhn=(e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t.at(0)}`,...t.slice(1)];e0(),og(),X5(),F0(),vt(),Yi(),H7e(),og(),V7e(),Zn(),WG(),sl();import*as efn from"node:child_process";import{PassThrough as fBe}from"node:stream";var YUr=(e,t,n)=>{const r=e.detached??n!=="win32";return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}};e0();var ts=(e,t)=>(n,[r])=>{let i="Unknown";switch(n.code){case"ENOENT":i="NotFound";break;case"EACCES":i="PermissionDenied";break;case"EEXIST":i="AlreadyExists";break;case"EISDIR":i="BadResource";break;case"ENOTDIR":i="BadResource";break;case"EBUSY":i="Busy";break;case"ELOOP":i="BadResource";break}return jx({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})};uo(),aP(),vt(),Rn(),s1(),WG();var Xoe=e=>Mbe(_vt(ZUr(e),t=>[t])),ZUr=e=>ol(t=>{const n=e.evaluate();return Te(eFr({...e,writable:n,pull:t}))}),eFr=e=>e.pull.pipe(je(t=>{let n=0;return tc(r=>{let i=!1;const o=()=>{for(;n<t.length;){if(i)return;if(!e.writable.write(t[n++],e.encoding)){i||e.writable.once("drain",o);return}}i||r(yt)};return o(),it(()=>{i=!0,e.writable.off("drain",o)})})}),bh({disableYield:!0}),e.endOnDone!==!1?em(t=>"closed"in e.writable&&e.writable.closed?Aa(t):tc(n=>{const r=()=>n(Aa(t));return e.writable.once("finish",r),e.writable.end(),it(()=>{e.writable.off("finish",r)})})):an,u1(tc(t=>{const n=r=>t(xe(e.onError(r)));return e.writable.once("error",n),it(()=>{e.writable.off("error",n)})})));Ec(),uo(),aP(),vt(),Yi(),CT(),svt(),Qp(),sl();var Yoe=e=>Ma(tFr(e)),tFr=e=>ol((t,n)=>nFr({scope:n,readable:e.evaluate(),onError:e.onError??rFr,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),nFr=e=>{const t=e.readable,n=e.closeOnDone??!0,r=e.exit??ovt(void 0),i=e.latch??rP(!1);function o(){i.openUnsafe()}function s(c){r.current=H0(e.onError(c)),i.openUnsafe()}function a(){r.current=H0(Zhe()),i.openUnsafe()}t.on("readable",o),t.once("error",s),t.once("end",a);const u=Wt(function c(){let l=e.readable.read(e.chunkSize);if(l===null)return r.current?r.current:t.readableEnded?xe(Zhe()):(i.closeUnsafe(),je(i.await,c));const d=Fw(l);for(;l=e.readable.read(e.chunkSize),l!==null;)d.push(l);return Te(d)});return Vr(n1(e.scope,it(()=>{t.off("readable",o),t.off("error",s),t.off("end",a),n&&"closed"in e.readable&&!e.readable.closed&&e.readable.destroy()})),u)},rFr=e=>new IZe(e),bA=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Tv=(e,t,n)=>{const{commands:r}=ifn(n),i=r.reduce((o,s)=>{const a=`${s.command} ${s.args.join(" ")}`;return o.length===0?a:`${o} | ${a}`},"");return ts("ChildProcess",e)(t,[i])},tfn=1e3,iFr=10,nfn=(e,t)=>{if(!Mhe(t))return!0;if(globalThis.process.platform==="win32")return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},rfn=(e,t=()=>{})=>efn.execFile("taskkill",["/pid",String(e.pid),"/T","/F"],{windowsHide:!0},t),oFr=qe(function*(){const e=yield*xee,t=yield*Z3,n=jl(function*(w){if(!E5(w.cwd))return yield*e.access(w.cwd),t.resolve(w.cwd)}),r=w=>w.extendEnv?{...globalThis.process.env,...w.env}:w.env,i=w=>fm(w)?"pipe":w,o=w=>uP(w)?"pipe":w,s=w=>{const x={stream:"pipe",encoding:"utf-8",endOnDone:!0};return E5(w.stdin)?x:typeof w.stdin=="string"?{...x,stream:w.stdin}:fm(w.stdin)?{...x,stream:w.stdin}:{stream:w.stdin.stream,encoding:w.stdin.encoding??x.encoding,endOnDone:w.stdin.endOnDone??x.endOnDone}},a=(w,x)=>{const k=w[x];return E5(k)?{stream:"pipe"}:typeof k=="string"?{stream:k}:uP(k)?{stream:k}:{stream:k.stream}},u=w=>{if(E5(w.additionalFds))return[];const x=[];for(const[k,T]of Object.entries(w.additionalFds)){const C=hBe(k);iS(C)&&x.push({fd:C,config:T})}return x.sort((k,T)=>k.fd-T.fd)},c=(w,x,k,T)=>{const C=[i(w.stream),o(x.stream),o(k.stream)];if(T.length===0)return C;const O=T.reduce((P,{fd:$})=>Math.max(P,$),2);for(let P=3;P<=O;P++)C[P]="ignore";for(const{fd:P}of T)C[P]="pipe";return C},l=jl(function*(w,x,k){if(k.length===0)return{getInputFd:()=>cP,getOutputFd:()=>R4};const T=new Map,C=new Map;for(const{config:O,fd:P}of k){const $=x.stdio[P];switch(O.type){case"input":{let B=cP;$&&"write"in $&&(B=Xoe({evaluate:()=>$,onError:q=>Tv(`fromWritable(fd${P})`,bA(q),w)})),O.stream&&(yield*K8(qbe(O.stream,B))),T.set(P,B);break}case"output":{let B=R4;if($&&"read"in $){const q=new fBe;$.on("error",J=>q.destroy(J)),$.pipe(q),B=Yoe({evaluate:()=>q,onError:J=>Tv(`fromReadable(fd${P})`,bA(J),w)})}O.sink&&(B=VG(B,O.sink)),C.set(P,B);break}}}return{getInputFd:O=>T.get(O)??cP,getOutputFd:O=>C.get(O)??R4}}),d=(w,x,k)=>Wt(()=>{let T=cP;return Sj(x.stdin)&&(T=Xoe({evaluate:()=>x.stdin,onError:C=>Tv("fromWritable(stdin)",bA(C),w),endOnDone:k.endOnDone,encoding:k.encoding})),fm(k.stream)?Vr(K8(qbe(k.stream,T)),T):Te(T)}),p=(w,x,k,T)=>{let C=x.stdout?(()=>{const $=new fBe;return x.stdout.on("error",B=>$.destroy(B)),x.stdout.pipe($),Yoe({evaluate:()=>$,onError:B=>Tv("fromReadable(stdout)",bA(B),w)})})():R4,O=x.stderr?(()=>{const $=new fBe;return x.stderr.on("error",B=>$.destroy(B)),x.stderr.pipe($),Yoe({evaluate:()=>$,onError:B=>Tv("fromReadable(stderr)",bA(B),w)})})():R4;uP(k.stream)&&(C=VG(C,k.stream)),uP(T.stream)&&(O=VG(O,T.stream));const P=Wbe(C,O);return{stdout:C,stderr:O,all:P}},m=(w,x)=>tc(k=>{const T=Q5(),C=efn.spawn(w.command,w.args,x);return C.on("error",O=>{k(xe(Tv("spawn",O,w)))}),C.on("exit",(...O)=>{tq(T,Yw(O))}),C.on("spawn",()=>{k(Te([C,T]))}),it(()=>{C.kill("SIGTERM")})}),h=(w,x,k)=>globalThis.process.platform==="win32"?tc(T=>{rfn(x,C=>{T(C?xe(Tv("kill",bA(C),w)):yt)})}):It({try:()=>{globalThis.process.kill(-x.pid,k)},catch:T=>Tv("kill",bA(T),w)}),f=(w,x)=>{if(globalThis.process.platform==="win32"){rfn(w);return}try{globalThis.process.kill(-w.pid,x)}catch{}},g=(w,x,k)=>Wt(()=>{if(!x.kill(k)){const C=new globalThis.Error("Failed to kill child process");return xe(Tv("kill",C,w))}return yt}),y=(w,x,k)=>tc(T=>{const C=Date.now()+k;let O;const P=()=>{clearTimeout(O),w.removeListener("exit",$)},$=()=>{if(clearTimeout(O),Date.now()>=C||!nfn(w,x)){P(),T(yt);return}O=setTimeout($,iFr)};return w.on("exit",$),$(),it(P)}),v=jl(function*(w,x,k,T){const C=O=>h(w,x,O).pipe(nc(()=>g(w,x,O)));yield*C(T?.killSignal??"SIGTERM"),E5(T?.forceKillAfter)?yield*y(x,k,tfn):(yield*y(x,k,Uw(T.forceKillAfter)),nfn(x,k)&&(yield*C("SIGKILL"),yield*y(x,k,tfn))),yield*G0(k)}),_=(w,x)=>{const k=x??"stdout";switch(k){case"stdout":return w.stdout;case"stderr":return w.stderr;case"all":return w.all;default:{const T=hBe(k);return iS(T)?w.getOutputFd(T):w.stdout}}},b=jl(function*(w){switch(w._tag){case"StandardCommand":{const x=s(w.options),k=a(w.options,"stdout"),T=a(w.options,"stderr"),C=u(w.options);let O=!0;const P=yield*n(w.options),$=r(w.options),B=c(x,k,T,C),[q,J]=yield*Fl(m(w,YUr(w.options,{cwd:P,env:$,stdio:B},process.platform)),jl(function*([_e,we]){if(yield*Phe(we)){const[ie]=yield*G0(we);ie!==0&&Sj(ie)?yield*a1(v(w,_e,we,w.options)):O&&process.platform!=="win32"&&w.options.detached!==!1&&(yield*a1(v(w,_e,we,w.options)));return}O&&(yield*a1(v(w,_e,we,w.options)))})),re=zUr(q.pid);q.on("exit",_e=>{_e!==0&&Sj(_e)&&f(q,w.options.killSignal??"SIGTERM")});const ue=it(()=>{O||(q.ref(),O=!0)}),N=it(()=>(O&&(q.unref(),O=!1),ue)),V=yield*d(w,q,x),{all:D,stderr:U,stdout:X}=p(w,q,k,T),{getInputFd:F,getOutputFd:Z}=yield*l(w,q,C),Y=St(Phe(J),_e=>!_e),ye=je(G0(J),([_e,we])=>{if(Sj(_e))return Te(qUr(_e));const Fe=new globalThis.Error(`Process interrupted due to receipt of signal: '${we}'`);return xe(Tv("exitCode",Fe,w))});return Vhn({pid:re,exitCode:ye,isRunning:Y,kill:_e=>v(w,q,J,_e),stdin:V,stdout:X,stderr:U,all:D,getInputFd:F,getOutputFd:Z,unref:N})}case"PipedCommand":{const{commands:x,pipeOptions:k}=ifn(w),[T,...C]=x,O=[yield*b(T)];for(let q=0;q<C.length;q++){const J=C[q],re=k[q]??{},ue=s(J.options),N=Db(Te(_(O[O.length-1],re.from))),V=re.to??"stdin";if(V==="stdin")O.push(yield*b(YU(J.command,J.args,{...J.options,stdin:{...ue,stream:N}})));else{const D=hBe(V);if(iS(D)){const U=KUr(D),X=J.options.additionalFds??{};O.push(yield*b(YU(J.command,J.args,{...J.options,additionalFds:{...X,[U]:{type:"input",stream:N}}})))}else O.push(yield*b(YU(J.command,J.args,{...J.options,stdin:{...ue,stream:N}})))}}const P=O[O.length-1],$=q=>go([...O].reverse(),J=>a1(J.kill(q)),{discard:!0}),B=qe(function*(){const q=[];for(const J of O)q.push(yield*J.unref);return go([...q].reverse(),J=>J,{discard:!0})});return Vhn({pid:P.pid,exitCode:P.exitCode,isRunning:P.isRunning,kill:$,stdin:O[0].stdin,stdout:P.stdout,stderr:P.stderr,all:P.all,getInputFd:P.getInputFd,getOutputFd:P.getOutputFd,unref:B})}}});return GUr(b)}),sFr=C8(Joe,oFr),ifn=e=>{const t=[],n=[],r=a=>{switch(a._tag){case"StandardCommand":{t.push(a);break}case"PipedCommand":{r(a.left),n.push(a.options),r(a.right);break}}};if(r(e),t.length===0)throw new Error("flattenCommand produced empty commands array");const[i,...o]=t;return{commands:[i,...o],pipeOptions:n}};qHt(),vt(),og(),e0();import*as ofn from"node:crypto";var aFr=e=>{switch(e){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512"}},uFr=(e,t)=>It({try:()=>Uint8Array.from(ofn.createHash(aFr(e)).update(t).digest()),catch:n=>jx({module:"Crypto",method:"digest",_tag:"Unknown",description:"Could not compute digest",cause:n})}),cFr=jHt({randomBytes:ofn.randomBytes,digest:uFr}),lFr=Zw(Z7e,cFr),dFr=lFr;xge(),Y8(),uo(),vt(),vt(),H7e(),Rn(),og(),ir(),e0(),f4(),sl();import*as pFr from"node:crypto";import*as fo from"node:fs";import*as mFr from"node:os";import*as WR from"node:path";var Fo=e=>t=>wk({module:"FileSystem",method:e,description:t.message??String(t)}),gBe=(e,t)=>{const n=Number(e);if(!Number.isSafeInteger(n))throw new RangeError(`${t} exceeds the safe integer range: ${e}`);return n},qR=e=>U0(dh(e),bge),sfn=(e,t)=>It({try:()=>gBe(e,"position"),catch:Fo(t)}),hFr=(()=>{const e=_s(fo.access,ts("FileSystem","access"),Fo("access"));return(t,n)=>{let r=fo.constants.F_OK;return n?.readable&&(r|=fo.constants.R_OK),n?.writable&&(r|=fo.constants.W_OK),e(t,r)}})(),fFr=(()=>{const e=_s(fo.cp,ts("FileSystem","copy"),Fo("copy"));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),gFr=(()=>{const e=_s(fo.copyFile,ts("FileSystem","copyFile"),Fo("copyFile"));return(t,n)=>e(t,n)})(),yFr=(()=>{const e=_s(fo.chmod,ts("FileSystem","chmod"),Fo("chmod"));return(t,n)=>e(t,n)})(),vFr=(()=>{const e=_s(fo.chown,ts("FileSystem","chown"),Fo("chown"));return(t,n,r)=>e(t,n,r)})(),_Fr=(()=>{const e=_s(fo.glob,ts("FileSystem","glob"),Fo("glob"));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),wFr=(()=>{const e=_s(fo.link,ts("FileSystem","link"),Fo("link"));return(t,n)=>e(t,n)})(),bFr=(()=>{const e=_s(fo.mkdir,ts("FileSystem","makeDirectory"),Fo("makeDirectory"));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),yBe=e=>{const t=_s(fo.mkdtemp,ts("FileSystem",e),Fo(e));return n=>Wt(()=>{const r=n?.prefix??"",i=typeof n?.directory=="string"?WR.join(n.directory,"."):mFr.tmpdir();return t(r?WR.join(i,r):i+"/")})},xFr=yBe("makeTempDirectory"),vBe=e=>{const t=_s(fo.rm,ts("FileSystem",e),Fo(e));return(n,r)=>t(n,{recursive:r?.recursive??!1,force:r?.force??!1})},SFr=vBe("remove"),EFr=(()=>{const e=yBe("makeTempDirectoryScoped"),t=vBe("makeTempDirectoryScoped");return n=>Fl(e(n),r=>Ul(t(r,{recursive:!0})))})(),kFr=e=>{const t=_s(fo.open,ts("FileSystem",e),Fo(e)),n=_s(fo.close,ts("FileSystem",e),Fo(e));return(r,i)=>j7(Fl(t(r,i?.flag??"r",i?.mode),o=>Ul(n(o))),St(o=>TFr(o,i?.flag?.startsWith("a")??!1)))},AFr=kFr("open"),TFr=(()=>{const e=l=>_s(fo.read,ts("FileSystem",l),Fo(l)),t=e("read"),n=e("readAlloc"),r=_s(fo.fstat,ts("FileSystem","stat"),Fo("stat")),i=_s(fo.ftruncate,ts("FileSystem","truncate"),Fo("truncate")),o=_s(fo.fsync,ts("FileSystem","sync"),Fo("sync")),s=l=>_s(fo.write,ts("FileSystem",l),Fo(l)),a=s("write"),u=s("writeAll");class c{[See];fd;append;position=BigInt(0);constructor(d,p){this[See]=See,this.fd=d,this.append=p}get stat(){return je(r(this.fd,{bigint:!0}),ufn)}get sync(){return o(this.fd)}seek(d,p){return Wt(()=>{const m=p==="start"?d:this.position+d;return m<BigInt(0)?xe(wk({module:"FileSystem",method:"seek",description:"Cannot seek before the start of the file"})):(this.position=m,Te(m))})}read(d){return Wt(()=>{const p=this.position;return St(t(this.fd,{buffer:d,position:p}),m=>(this.position=p+BigInt(m),m))})}readAlloc(d){return Wt(()=>{try{if(!Number.isInteger(d)||d<0)throw new RangeError("size must be a non-negative integer");const p=Buffer.allocUnsafeSlow(d),m=this.position;return St(n(this.fd,{buffer:p,position:m}),h=>{if(h===0)return Ut();if(this.position=m+BigInt(h),h===d)return Ft(p);const f=Buffer.allocUnsafeSlow(h);return p.copy(f,0,0,h),Ft(f)})}catch(p){return xe(Fo("readAlloc")(p))}})}truncate(d){return St(i(this.fd,d||void 0),()=>{if(!this.append){const p=BigInt(d??0);this.position>p&&(this.position=p)}})}write(d){return Wt(()=>{const p=this.position;return je(this.append?Te(void 0):sfn(p,"write"),m=>St(a(this.fd,d,void 0,void 0,m),h=>(this.append||(this.position=p+BigInt(h)),h)))})}writeAllChunk(d){return Wt(()=>{const p=this.position;return je(this.append?Te(void 0):sfn(p,"writeAll"),m=>je(u(this.fd,d,void 0,void 0,m),h=>h===0?xe(jx({module:"FileSystem",method:"writeAll",_tag:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"})):(this.append||(this.position=p+BigInt(h)),h<d.length?this.writeAllChunk(d.subarray(h)):yt)))})}writeAll(d){return d.length===0?yt:this.writeAllChunk(d)}}return(l,d)=>new c(l,d)})(),afn=e=>{const t=yBe(e);return jl(function*(n){const r=yield*t(n),i=pFr.randomBytes(6).toString("hex"),o=WR.join(r,n?.suffix?`${i}${n.suffix}`:i);return yield*cfn(o,new Uint8Array(0)),o})},IFr=afn("makeTempFile"),CFr=(()=>{const e=afn("makeTempFileScoped"),t=vBe("makeTempFileScoped");return n=>Fl(e(n),r=>Ul(t(WR.dirname(r),{recursive:!0})))})(),RFr=(e,t)=>Bi({try:()=>fo.promises.readdir(e,t),catch:n=>ts("FileSystem","readDirectory")(n,[e])}),OFr=e=>tc((t,n)=>{try{fo.readFile(e,{signal:n},(r,i)=>{t(r?xe(ts("FileSystem","readFile")(r,[e])):Te(i))})}catch(r){t(xe(Fo("readFile")(r)))}}),PFr=(()=>{const e=_s(fo.readlink,ts("FileSystem","readLink"),Fo("readLink"));return t=>e(t)})(),MFr=(()=>{const e=_s(fo.realpath,ts("FileSystem","realPath"),Fo("realPath"));return t=>e(t)})(),DFr=(()=>{const e=_s(fo.rename,ts("FileSystem","rename"),Fo("rename"));return(t,n)=>e(t,n)})(),ufn=e=>It({try:()=>({type:e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":e.isBlockDevice()?"BlockDevice":e.isCharacterDevice()?"CharacterDevice":e.isFIFO()?"FIFO":e.isSocket()?"Socket":"Unknown",mtime:dh(e.mtime),atime:dh(e.atime),birthtime:dh(e.birthtime),dev:gBe(e.dev,"dev"),rdev:qR(e.rdev),ino:qR(e.ino),mode:gBe(e.mode,"mode"),nlink:qR(e.nlink),uid:qR(e.uid),gid:qR(e.gid),size:Qq(e.size),blksize:e.blksize!==void 0?Ft(Qq(e.blksize)):Ut(),blocks:qR(e.blocks)}),catch:Fo("stat")}),_Be=(()=>{const e=_s(fo.stat,ts("FileSystem","stat"),Fo("stat"));return t=>je(e(t,{bigint:!0}),ufn)})(),LFr=(()=>{const e=_s(fo.symlink,ts("FileSystem","symlink"),Fo("symlink"));return(t,n)=>e(t,n)})(),NFr=(()=>{const e=_s(fo.truncate,ts("FileSystem","truncate"),Fo("truncate"));return(t,n)=>e(t,n)})(),$Fr=(()=>{const e=_s(fo.utimes,ts("FileSystem","utime"),Fo("utime"));return(t,n,r)=>e(t,n,r)})(),UFr=(e,t,n)=>n1t(r=>Fl(it(()=>{const i=t.type==="Directory"?e:WR.dirname(e),o=fo.watch(e,{recursive:n?.recursive??!1},(s,a)=>{if(a)switch(s){case"rename":{om(G8(_Be(WR.resolve(i,a)),{onSuccess:u=>ay(r,{_tag:"Create",path:a}),onFailure:u=>ay(r,{_tag:"Remove",path:a})}));return}case"change":{wg(r,{_tag:"Update",path:a});return}}});return o.on("error",s=>{a9(r,Khe(jx({module:"FileSystem",_tag:"Unknown",method:"watch",pathOrDescriptor:e,cause:s})))}),o.on("close",()=>{w1(r)}),o}),i=>it(()=>i.close()))),FFr=(e,t,n)=>_Be(t).pipe(St(r=>e.pipe(U0(i=>i.register(t,r,n)),fS(()=>UFr(t,r,n)))),Db),cfn=(e,t,n)=>tc((r,i)=>{try{fo.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},o=>{r(o?xe(ts("FileSystem","writeFile")(o,[e])):yt)})}catch(o){r(xe(Fo("writeFile")(o)))}}),BFr=St(tge(wHt),e=>_Ht({access:hFr,chmod:yFr,chown:vFr,copy:fFr,copyFile:gFr,glob:_Fr,link:wFr,makeDirectory:bFr,makeTempDirectory:xFr,makeTempDirectoryScoped:EFr,makeTempFile:IFr,makeTempFileScoped:CFr,open:AFr,readDirectory:RFr,readFile:OFr,readLink:PFr,realPath:MFr,remove:SFr,rename:DFr,stat:_Be,symlink:LFr,truncate:NFr,utimes:$Fr,watch(t,n){return FFr(e,t,n)},writeFile:cfn})),jFr=C8(xee)(BFr),WFr=jFr;vt(),og(),V7e(),e0();import*as wBe from"node:path";import*as lfn from"node:url";var bBe=e=>({fromFileUrl:t=>It({try:()=>lfn.fileURLToPath(t,{windows:e}),catch:n=>new _k({module:"Path",method:"fromFileUrl",cause:n})}),toFileUrl:t=>It({try:()=>lfn.pathToFileURL(t,{windows:e}),catch:n=>new _k({module:"Path",method:"toFileUrl",cause:n})})}),mJr=Zw(Z3)({[I_]:I_,...wBe.posix,...bBe(!1)}),hJr=Zw(Z3)({[I_]:I_,...wBe.win32,...bBe(!0)}),qFr=Zw(Z3)({[I_]:I_,...wBe,...bBe(void 0)}),zFr=qFr;vt(),og(),e0(),hGt();var HFr=Zw(pGt,mGt({args:it(()=>process.argv.slice(2)),stdinIsTerminal:it(()=>process.stdin.isTTY===!0),stdoutIsTerminal:it(()=>process.stdout.isTTY===!0),stdout:e=>Xoe({evaluate:()=>process.stdout,onError:t=>jx({module:"Stdio",method:"stdout",_tag:"Unknown",cause:t}),endOnDone:e?.endOnDone??!1}),stderr:e=>Xoe({evaluate:()=>process.stderr,onError:t=>jx({module:"Stdio",method:"stderr",_tag:"Unknown",cause:t}),endOnDone:e?.endOnDone??!1}),stdin:Yoe({evaluate:()=>process.stdin,onError:e=>jx({module:"Stdio",method:"stdin",_tag:"Unknown",cause:e}),closeOnDone:!1})})),GFr=HFr;vt(),og(),ir(),e0(),Zn(),f4(),Kvt(),vGt();import*as dfn from"node:readline";var VFr=jl(function*(e=pfn){const t=process.stdin,n=process.stdout,r=yield*yb();let i=t.readableEnded,o=!1;const s=()=>{i=!0,o||w1(r)};t.once("end",s),yield*wh(()=>it(()=>t.off("end",s)));const a=yield*Vvt({acquire:Fl(it(()=>{const m=dfn.createInterface({input:t,escapeCodeTimeout:50}),h=g=>wg(r,g),f=()=>{o=!1,w1(r)};return o=!0,dfn.emitKeypressEvents(t,m),m.on("line",h),m.once("close",f),t.isTTY&&t.setRawMode(!0),{rl:m,onClose:f,onLine:h}}),({rl:m,onClose:h,onLine:f})=>it(()=>{o=!1,m.off("line",f),m.off("close",h),t.isTTY&&t.setRawMode(!1),m.close(),i&&w1(r)})),idleTimeToLive:"10 millis"}),u=it(()=>n.columns??0),c=it(()=>n.rows??0),l=qe(function*(){const m=yield*yb(),h=(y,v)=>{const _={input:gS(y),key:{name:v.name??"",ctrl:!!v.ctrl,meta:!!v.meta,shift:!!v.shift}};wg(m,_),e(_)&&w1(m)},f=setInterval(()=>{},2147483647),g=()=>{clearInterval(f),w1(m)};return yield*wh(()=>it(()=>{clearInterval(f),t.off("keypress",h),t.off("end",g)})),t.on("keypress",h),i?g():(yield*Rbe(a),t.once("end",g)),m}),d=Wt(()=>Jht(r).pipe(je(Ha({onNone:()=>c1(Et(Rbe(a),b1(r))),onSome:Te})),Ti(()=>new gGt({}))));return yGt({columns:u,rows:c,readInput:l,readLine:d,display:m=>d1(tc(h=>{n.write(m,f=>ebn(f)?h(yt):h(xe(wk({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:f}))))}))})}),KFr=C8(y8e,VFr(pfn));function pfn(e){return e.key.ctrl&&(e.key.name==="c"||e.key.name==="d")}var JFr=KFr,QFr=bZe(sFr,Hhe(WFr,dFr,zFr,GFr,JFr));jc(),r1(),vt(),_y(),Yi(),ir(),Qp(),sl(),xt(),Pa(),xt();import{spawn as XFr}from"node:child_process";import{closeSync as xBe,openSync as mfn,readSync as hfn,writeSync as ffn}from"node:fs";import{mkdir as YFr,rm as gfn}from"node:fs/promises";import{join as yfn}from"node:path";import zR from"node:process";import{setTimeout as vfn}from"node:timers/promises";xt();var HR=16*1024,_fn=128*1024,Zoe=A.string().refine(e=>e.isWellFormed(),"Computer exec stdin must be well-formed UTF-16 text (no lone surrogates)").refine(e=>Buffer.byteLength(e,"utf8")<=_fn,`Computer exec stdin exceeds the ${String(_fn)}-byte bound`);function wfn(e,t){return[e,...t].reduce((n,r)=>n+Buffer.byteLength(r,"utf8"),0)}var SBe=A.string().min(1).max(4096).startsWith("/").refine(e=>!e.includes("\0"),"Path cannot contain null bytes");xt();var ZFr=new Set(["PATH","HOME","XDG_RUNTIME_DIR","DBUS_SESSION_BUS_ADDRESS","TMPDIR","SSH_AUTH_SOCK","GIT_DISCOVERY_ACROSS_FILESYSTEM","FUNGI_SANDBOX","FUNGI_SANDBOX_NETWORK_DISABLED","GLIBC_TUNABLES","GCONV_PATH","LOCPATH"]),eBr=A.string().regex(/^[A-Z_][A-Z0-9_]*$/u).refine(e=>!ZFr.has(e)&&!e.startsWith("LD_")&&!e.startsWith("DYLD_"),"Host-owned environment variable"),EBe=A.record(eBr,A.string().max(1024).regex(/^[^\0]*$/u,"Environment values cannot contain NUL")).refine(e=>Object.keys(e).length<=64,{message:"Exec env accepts at most 64 variables"}).describe("Up to 64 extra string variables, each at most 1024 UTF-16 code units, with uppercase ASCII names (letters, digits and underscores; no leading digit). Host-owned names, including HOME, PATH, session/sandbox locators and dynamic-loader controls, are refused.");function bfn(e,t,n={}){const r={...n,PATH:e,HOME:t.HOME};return t.XDG_RUNTIME_DIR&&(r.XDG_RUNTIME_DIR=t.XDG_RUNTIME_DIR),t.DBUS_SESSION_BUS_ADDRESS&&(r.DBUS_SESSION_BUS_ADDRESS=t.DBUS_SESSION_BUS_ADDRESS),r}import{Writable as tBr}from"node:stream";var xfn=8,Sfn=16,Efn=32,R2=8*1024*1024,nBr=64*1024,kfn=16*1024,rBr=6e4,iBr=1e4,oBr=2e3,Afn=dy({family:"local-computer-process",version:1,kinds:{process:{prefix:"local_process"}}}),ese=A.string().max(128).refine(e=>Afn.process.is(e),"Unknown process id"),sBr=A.enum(["running","exited"]),ZU=A.strictObject({id:ese,command:A.string(),cwd:A.string(),state:sBr,exitCode:A.number().int().nullable(),signal:A.string().nullable(),startedAt:A.number().int(),endedAt:A.number().int().nullable(),logPath:A.string(),logBytes:A.number().int().nonnegative(),logStartOffset:A.number().int().nonnegative(),logTruncated:A.boolean()}),aBr=A.strictObject({operation:A.literal("start"),escape:A.strictObject({justification:A.string().min(1).max(2048)}).optional(),command:A.string().min(1).max(HR),stdin:Zoe.optional(),env:EBe.optional(),cwd:SBe.optional()}),uBr=A.strictObject({operation:A.literal("start"),escape:A.strictObject({justification:A.string().min(1).max(2048)}).optional(),executable:A.string().min(1),args:A.array(A.string()).default([]),stdin:Zoe.optional(),env:EBe.optional(),cwd:SBe.optional()}).refine(e=>wfn(e.executable,e.args)<=HR,{message:`Computer exec executable and args exceed ${String(HR)} combined UTF-8 bytes`,path:["args"]}),cBr=A.strictObject({id:ese}),Tfn=A.strictObject({id:ese,offset:A.number().int().nonnegative().default(0),maxBytes:A.number().int().min(1).max(nBr).default(kfn)}),lBr=A.strictObject({id:ese,timeoutMs:A.number().int().min(1).max(rBr).default(iBr)}),dBr=A.strictObject({processes:A.array(ZU).max(Efn)}),Ifn=A.strictObject({process:ZU,offset:A.number().int().nonnegative(),nextOffset:A.number().int().nonnegative(),text:A.string(),complete:A.boolean()}),pBr=A.strictObject({process:ZU,timedOut:A.boolean()}),mBr=A.strictObject({process:ZU,signalled:A.boolean()}),hBr=class extends Error{constructor(e){super(`Computer process not found: ${e}`),this.name="PrivateLocalProcessNotFoundError"}},Cfn=class extends Error{constructor(e,t){super(`This ${t} can run at most ${String(e)} background processes at once; wait for or kill one with exec first`),this.name="PrivateLocalProcessLimitError"}};function kBe(e,t){try{return zR.kill(-e,t),!0}catch(n){if(n instanceof Error&&"code"in n&&(n.code==="ESRCH"||n.code==="EPERM"))return!1;throw n}}function Rfn(e){try{return zR.kill(-e,0),!0}catch(t){if(t instanceof Error&&"code"in t){if(t.code==="ESRCH")return!1;if(t.code==="EPERM")return!0}throw t}}function fBr(e){let t="command"in e?{kind:"shell",command:e.command}:{kind:"direct",executable:e.executable,args:e.args};return e.stdin!==void 0&&(t={...t,stdin:e.stdin}),e.env!==void 0&&(t={...t,env:e.env}),t}function gBr(e){return e.kind==="shell"?e.command:[e.executable,...e.args.map(t=>JSON.stringify(t))].join(" ")}function yBr(e){return"code"in e}function vBr(e,t){for(let n=1;n<=Math.min(4,t);n+=1){const r=e[t-n]??0;if((r&192)===128)continue;if(r<194||r>244)return t;const i=r>=240?4:r>=224?3:2;return n<i?t-n:t}return t}var _Br=class{constructor(e,t,n,r,i,o){this.spec=e,this.cwd=t,this.command=gBr(e),this.logPath=yfn(n,`${this.id}.log`),this.#n=mfn(this.logPath,"wx+",384);const s=Promise.withResolvers();this.closed=s.promise;const a=bfn(r,{HOME:i,XDG_RUNTIME_DIR:zR.env.XDG_RUNTIME_DIR,DBUS_SESSION_BUS_ADDRESS:zR.env.DBUS_SESSION_BUS_ADDRESS},e.env);o!==void 0&&(delete a.XDG_RUNTIME_DIR,delete a.DBUS_SESSION_BUS_ADDRESS,Object.assign(a,o.environment));try{const c=e.kind==="shell"?["sh","-c",e.command]:[e.executable,...e.args],l=[e.stdin===void 0?"ignore":"pipe","pipe","pipe"];if(o?.seccompFilter!==void 0&&l.push("pipe"),this.#e=XFr(o?.executable??c[0],o?.args??c.slice(1),{cwd:t,env:a,detached:!0,stdio:l}),o?.seccompFilter!==void 0){const d=this.#e.stdio[3];if(!(d instanceof tBr))throw this.#e.kill("SIGKILL"),new Error("Local sandbox filter input fd3 is unavailable");d.on("error",p=>{this.#c(Buffer.from(`
1769
1769
  [fungi: sandbox filter failed: ${p.message}]
@@ -1 +1 @@
1
- {"release":"0.24.24","lines":[]}
1
+ {"release":"0.24.28","lines":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/spore",
3
- "version": "0.11.9",
3
+ "version": "0.11.11",
4
4
  "description": "Fungi local agent for terminals and ACP editors",
5
5
  "homepage": "https://docs.fungi.computer/guides/use-fungi-in-your-editor/",
6
6
  "bin": {
@@ -36,10 +36,10 @@
36
36
  "@opencode-ai/pty": "0.3.0"
37
37
  },
38
38
  "optionalDependencies": {
39
- "@fungi.computer/spore-native-linux-x64": "0.11.9",
40
- "@fungi.computer/spore-native-linux-arm64": "0.11.9",
41
- "@fungi.computer/spore-native-darwin-arm64": "0.11.9",
42
- "@fungi.computer/spore-native-darwin-x64": "0.11.9",
39
+ "@fungi.computer/spore-native-linux-x64": "0.11.11",
40
+ "@fungi.computer/spore-native-linux-arm64": "0.11.11",
41
+ "@fungi.computer/spore-native-darwin-arm64": "0.11.11",
42
+ "@fungi.computer/spore-native-darwin-x64": "0.11.11",
43
43
  "@oven/bun-darwin-x64": "1.4.4",
44
44
  "@oven/bun-darwin-aarch64": "1.4.4",
45
45
  "@oven/bun-linux-x64": "1.4.4",