@dhzh/foundry 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,69 @@
1
1
  #!/usr/bin/env node
2
- import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:path";import i from"node:process";import{spawn as a}from"node:child_process";import{chmodSync as o,closeSync as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,lstatSync as f,mkdirSync as p,openSync as ee,readFileSync as m,readdirSync as h,readlinkSync as te,realpathSync as ne,renameSync as re,rmSync as g,rmdirSync as ie,statSync as _,symlinkSync as ae,unlinkSync as oe,watch as se,writeFileSync as ce}from"node:fs";import le,{homedir as ue,tmpdir as de}from"node:os";import{createCipheriv as fe,createDecipheriv as pe,createHash as me,randomBytes as he,randomUUID as v,scrypt as ge}from"node:crypto";import{chmod as _e,cp as ve,link as ye,mkdir as be,mkdtemp as xe,open as Se,readFile as Ce,rename as we,rm as y,stat as Te,writeFile as Ee}from"node:fs/promises";import{fileURLToPath as De}from"node:url";import{pipeline as Oe}from"node:stream/promises";import ke from"yauzl";import Ae from"yazl";import{Buffer as b}from"node:buffer";import{Readable as je,Transform as Me}from"node:stream";import{parse as Ne,parseDocument as Pe,stringify as Fe}from"yaml";import{serve as Ie}from"@hono/node-server";import{serveStatic as Le}from"@hono/node-server/serve-static";import{Hono as x}from"hono";import{streamSSE as Re}from"hono/streaming";import{createServer as ze}from"node:net";var Be=`8.0.0`,S=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function Ve(e){if(!Ue(e)||!Array.isArray(e.instructionIds))throw new S(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new S(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new S(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function He(e){if(!Ue(e)||typeof e.enabled!=`boolean`)throw new S(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const C=new class{adapters;constructor(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(n.id)||t.has(n.id))throw Error(`Invalid or duplicate agent ID: ${n.id}`);t.add(n.id);let{instructions:e,skills:r}=n.capabilities;if(!Object.hasOwn(n.capabilities,`instructions`))throw Error(`Missing instruction configuration for agent: ${n.id}`);for(let t of[e.file,r?.directory])if(t&&(t.length===0||t.some(e=>!e||e===`.`||e===`..`||/[/\\:\0]/u.test(e))))throw Error(`Invalid home-relative path for agent: ${n.id}`)}this.adapters=structuredClone(e)}list(){return this.adapters}get(e){return this.adapters.find(t=>t.id===e)}supporting(e){return this.adapters.filter(t=>t.capabilities[e]!==void 0)}}([{id:`chatgpt`,name:`ChatGPT`,icon:{name:`openai`,invertInDark:!0},capabilities:{instructions:{file:[`.codex`,`AGENTS.md`]},skills:{directory:[`.agents`,`skills`]}}},{id:`claude-code`,name:`Claude Code`,icon:{name:`claudecode`,asset:`claudecode-color`},capabilities:{instructions:{file:[`.claude`,`CLAUDE.md`]},skills:{directory:[`.claude`,`skills`]}}}]);function We(e){return`~/${e.join(`/`)}`}function Ge(e,t){return r.join(e,...t)}function Ke(e){let{instructions:t,skills:n}=e.capabilities;return{instructions:{file:We(t.file)},...n&&{skills:{directory:We(n.directory)}}}}function qe(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=a(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Je(){return r.join(le.homedir(),`.foundry`)}function Ye(){let e=Je();return p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const Xe=[`system`,`light`,`dark`],Ze=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Qe=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],$e=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],et=`data/foundry.json`,tt=`settings.changed`,nt=[`agents`,`claude`],rt=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function it(e){return e.trim().normalize(`NFKC`)}function w(e){let t=it(e);return[...t].length<=64&&t===t.toLowerCase()&&rt.test(t)}function T(e){return e.length>0&&e.length<=1024&&e.split(`/`).every(e=>e.length>0&&e.length<=255&&e!==`.`&&e!==`..`&&!/[\\<>:"|?*]/u.test(e)&&!/\p{Cc}/u.test(e)&&!/[. ]$/u.test(e)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(e))}const E={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}}};function D(e){let t=dt(e)?e:{},n=dt(t.workspace)?t.workspace:{},r=dt(n.appearance)?n.appearance:{},i=dt(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":lt(r[`color-theme`],Xe,E.workspace.appearance[`color-theme`])},"language-region":{language:lt(i.language,Ze,E.workspace[`language-region`].language),"time-format":lt(i[`time-format`],Qe,E.workspace[`language-region`][`time-format`]),"time-zone":lt(i[`time-zone`],$e,E.workspace[`language-region`][`time-zone`])}}}}function at(e){if(!dt(e))throw new ct(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=ut(e.theme,Xe,`theme`)),`language`in e&&(t.language=ut(e.language,Ze,`language`)),`timeFormat`in e&&(t.timeFormat=ut(e.timeFormat,Qe,`timeFormat`)),`timezone`in e&&(t.timezone=ut(e.timezone,$e,`timezone`)),t}function ot(e,t){return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}}}}function st(e){return{workspace:e.workspace}}var ct=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function lt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function ut(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new ct(`Invalid ${n}`);return e}function dt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ft(e){return e.readSettings()}function pt(e){return st(ft(e))}function mt(e,t){return t.transaction(()=>{let n=ot(ft(t),e);return t.setSettings(n),st(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=Je(),n=qe){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...pt(this.storage),configFolder:this.configFolder}}update(e){return{...mt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const gt=r.dirname(De(import.meta.url)),O=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ue()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??yt();if(!u(r.join(t,`SKILL.md`)))throw new vt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,O),a=r.join(n,`.${O}-${v()}.tmp`),o=r.join(n,`.${O}-${v()}.backup`);try{return await be(n,{recursive:!0}),await ve(t,a,{recursive:!0,errorOnExist:!0}),await bt(a,i,o),{target:e,destination:i}}catch(e){throw await y(a,{recursive:!0,force:!0}),e instanceof vt?e:new vt(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return r.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:r.join(this.getTargetParent(e),O)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},vt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function yt(){let e=[r.resolve(gt,`skills`,O),r.resolve(gt,`..`,`..`,`..`,`skills`,O),r.resolve(i.cwd(),`skills`,O)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new vt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function bt(e,t,n){let r=u(t);r&&await we(t,n);try{await we(e,t),r&&await y(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await we(n,t),e}}const xt=`manifest.json`;function St(e){if([xt,`data/foundry.json`,`settings.json`,`instructions/`,`skill/`,`agents/`].includes(e)||/^instructions\/[a-f0-9-]+\.md$/u.test(e)||/^agents\/[a-z0-9-]+\.json$/u.test(e))return!0;let[t,n,...r]=e.replace(/\/$/u,``).split(`/`);return t===`skill`&&!!n&&n===n.trim()&&w(n)&&(r.length===0?e.endsWith(`/`):T(r.join(`/`)))}async function Ct(e,t){let n=new Ae.ZipFile;for(let t of e)t.filePath?n.addFile(t.filePath,t.entryPath,{compress:!0}):n.addEmptyDirectory(t.entryPath,{mode:448});n.end(),await Oe(n.outputStream,l(t,{mode:384}))}async function wt(e,t){let n=await Tt(e),i=/* @__PURE__ */ new Map;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!St(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);let a=e.externalFileAttributes>>>16&61440;if(![0,32768,16384].includes(a)||a===16384&&!e.fileName.endsWith(`/`)||i.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let o=r.join(t,e.fileName);await be(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await be(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await Oe(await Et(n,e),l(o,{mode:384})),i.set(e.fileName,o),n.readEntry())};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await y(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(xt))throw await y(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Tt(e){return new Promise((t,n)=>{ke.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Et(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Dt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=b.from(`FOUNDRYX`,`ascii`),Ot=`aes-256-gcm`,kt=`scrypt`,At={N:131072,r:8,p:1};async function jt(e,t,n){let r=he(16),i=he(12),a={version:1,cipher:Ot,kdf:{name:kt,salt:r.toString(`base64`),...At,keyLength:32},nonce:i.toString(`base64`)},o=b.from(JSON.stringify(a),`utf8`),s=Nt(o.byteLength),u=b.concat([s,o]),d=await Pt(n,r,At);try{let n=await Se(t,`w`,384);try{await n.write(u)}finally{await n.close()}await Oe(c(e),Ft(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await _e(t,384)}catch(e){throw await y(t,{force:!0}),new Dt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function Mt(e,t,n){let r;try{let i=(await Te(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await Se(e,`r`),o,s,u;try{if(o=await Rt(a,13,0),!o.subarray(0,k.byteLength).equals(k))throw Error(`The export file signature is invalid`);if(o.readUInt8(k.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(k.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await Rt(a,e,13),u=await Rt(a,16,i-16)}finally{await a.close()}let d=Lt(JSON.parse(s.toString(`utf8`)));r=await Pt(n,d.salt,d.header.kdf);let f=b.concat([o,s]);await Oe(c(e,{start:13+s.byteLength,end:i-16-1}),It(r,d.nonce,f,u),l(t,{mode:384})),await _e(t,384)}catch(e){throw await y(t,{force:!0}),e instanceof Dt?e:new Dt(Bt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Bt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function Nt(e){let t=b.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Pt(e,t,n){return new Promise((r,i)=>{ge(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Ft(e,t,n){let r=fe(Ot,e,t,{authTagLength:16});return r.setAAD(n),new Me({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,b.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function It(e,t,n,r){let i=pe(Ot,e,t,{authTagLength:16});return i.setAAD(n),new Me({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Lt(e){if(!zt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Ot||!zt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==kt||typeof t.salt!=`string`||t.N!==At.N||t.r!==At.r||t.p!==At.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=b.from(t.salt,`base64`),r=b.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:Ot,kdf:{name:kt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Rt(e,t,n){let r=b.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function zt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Vt(e){try{await y(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function Ht(e){return e.transaction(()=>{let t=[{path:`settings.json`,contents:b.from(`${JSON.stringify(e.readSettings(),null,2)}\n`)}],n=i=>{let a=r.join(e.path,i),o;try{o=f(a)}catch(e){if(e.code===`ENOENT`&&[`instructions`,`skill`,`agents`].includes(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!St(s))throw Error(`Backup sources must contain supported local files and directories`);if(t.push({path:s,contents:o.isDirectory()?null:m(a)}),!o.isDirectory())return;let c=h(a).toSorted((e,t)=>e.localeCompare(t));for(let e of c)n(`${i}/${e}`)};for(let e of[`instructions`,`skill`,`agents`])n(e);return t})}function Ut(e){return me(`sha256`).update(e).digest(`hex`)}var Wt=class{storage;constructor(e){this.storage=e}async createExport(e){let t=Ht(this.storage),n=await xe(r.join(de(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=r.join(n,`manifest.json`),o=r.join(n,`foundry.zip`),s=r.join(n,`foundry.foundry-backup`),c={format:`foundry.data`,archiveVersion:3,appVersion:Be,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:Ut(e.contents)})),directories:t.filter(e=>e.contents===null).map(e=>e.path)},l=[];for(let[e,i]of t.entries())if(i.contents===null)l.push({entryPath:i.path});else{let t=r.join(n,`file-${e}`);await Ee(t,i.contents,{mode:384}),l.push({entryPath:i.path,filePath:t})}return await Ee(a,JSON.stringify(c,null,2),{mode:384}),await Ct([{entryPath:`manifest.json`,filePath:a},...l],o),await jt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await Ce(s)}}finally{await Vt(n)}}};const Gt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var A=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Kt=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function qt(e){if(!Jt(e))throw new A(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new A(`name is required`);let t=e.name.trim();if(!t)throw new A(`name is required`);if(t.length>200)throw new A(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new A(`content is required`);if(e.content.length>1e6)throw new A(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Yt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Xt(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=ln(t,r.id),a=tn(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function Zt(e){return e.transaction(()=>{let t=cn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(un(e))return[];throw e}return n.map(e=>rn(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function Qt(e,t){return t.transaction(()=>{if(!Gt.test(e))return;let n=`${e}.md`;try{return rn(r.join(cn(t),n),n)}catch(e){if(un(e))return;throw e}})}function $t(e,t,n){return n.transaction(()=>{let r=Qt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(ln(n,i.id),tn(i)),i})}function en(e,t){if(!Gt.test(e))return`missing`;let n=cn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>u(i)?(t.removeTextFile(i),`removed`):`missing`)}function tn(e){return`---\n${Fe({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function nn(e,t){let n=Yt.exec(e);if(!n)throw j(t);let r=an(n[1]);if(`${r.id}.md`!==t)throw j(t);let i=e.slice(n[0].length);return i.startsWith(`\r
2
+ import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:path";import i from"node:process";import{execFile as a,spawn as o}from"node:child_process";import{chmodSync as s,closeSync as c,constants as l,createReadStream as u,createWriteStream as d,existsSync as f,fsyncSync as ee,lstatSync as p,mkdirSync as m,openSync as te,readFileSync as h,readdirSync as g,readlinkSync as ne,realpathSync as re,renameSync as ie,rmSync as _,rmdirSync as ae,statSync as v,symlinkSync as oe,unlinkSync as se,watch as ce,writeFileSync as le}from"node:fs";import ue,{homedir as de,tmpdir as fe}from"node:os";import{createCipheriv as pe,createDecipheriv as me,createHash as he,randomBytes as ge,randomUUID as y,scrypt as _e}from"node:crypto";import{chmod as ve,cp as ye,link as be,lstat as xe,mkdir as Se,mkdtemp as Ce,open as we,readFile as Te,readdir as Ee,rename as De,rm as b,stat as Oe,writeFile as ke}from"node:fs/promises";import{fileURLToPath as Ae}from"node:url";import{pipeline as je}from"node:stream/promises";import Me from"yauzl";import Ne from"yazl";import{Buffer as x}from"node:buffer";import{Readable as Pe,Transform as Fe}from"node:stream";import{parse as Ie,parseDocument as Le,stringify as Re}from"yaml";import{serve as ze}from"@hono/node-server";import{serveStatic as Be}from"@hono/node-server/serve-static";import{Hono as S}from"hono";import{bodyLimit as Ve}from"hono/body-limit";import{streamSSE as He}from"hono/streaming";import{promisify as Ue}from"node:util";import{createServer as We}from"node:net";var Ge=`8.1.0`,C=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function Ke(e){if(!Je(e)||!Array.isArray(e.instructionIds))throw new C(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new C(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new C(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function qe(e){if(!Je(e)||typeof e.enabled!=`boolean`)throw new C(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Je(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const w=new class{adapters;constructor(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(n.id)||t.has(n.id))throw Error(`Invalid or duplicate agent ID: ${n.id}`);t.add(n.id);let{instructions:e,skills:r}=n.capabilities;if(!Object.hasOwn(n.capabilities,`instructions`))throw Error(`Missing instruction configuration for agent: ${n.id}`);for(let t of[e.file,r?.directory])if(t&&(t.length===0||t.some(e=>!e||e===`.`||e===`..`||/[/\\:\0]/u.test(e))))throw Error(`Invalid home-relative path for agent: ${n.id}`)}this.adapters=structuredClone(e)}list(){return this.adapters}get(e){return this.adapters.find(t=>t.id===e)}supporting(e){return this.adapters.filter(t=>t.capabilities[e]!==void 0)}}([{id:`chatgpt`,name:`ChatGPT`,icon:{name:`openai`,invertInDark:!0},capabilities:{instructions:{file:[`.codex`,`AGENTS.md`]},skills:{directory:[`.agents`,`skills`]}}},{id:`claude-code`,name:`Claude Code`,icon:{name:`claudecode`,asset:`claudecode-color`},capabilities:{instructions:{file:[`.claude`,`CLAUDE.md`]},skills:{directory:[`.claude`,`skills`]}}}]);function Ye(e){return`~/${e.join(`/`)}`}function Xe(e,t){return r.join(e,...t)}function Ze(e){let{instructions:t,skills:n}=e.capabilities;return{instructions:{file:Ye(t.file)},...n&&{skills:{directory:Ye(n.directory)}}}}function Qe(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=o(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function $e(){return r.join(ue.homedir(),`.foundry`)}function et(){let e=$e();return m(e,{recursive:!0,mode:448}),i.platform!==`win32`&&s(e,448),e}const tt=[`system`,`light`,`dark`],nt=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],rt=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],it=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],at=`data/foundry.json`,ot=`settings.changed`,st=[`agents`,`claude`],ct=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function lt(e){return e.trim().normalize(`NFKC`)}function T(e){let t=lt(e);return[...t].length<=64&&t===t.toLowerCase()&&ct.test(t)}function E(e){return e.length>0&&e.length<=1024&&e.split(`/`).every(e=>e.length>0&&e.length<=255&&e!==`.`&&e!==`..`&&!/[\\<>:"|?*]/u.test(e)&&!/\p{Cc}/u.test(e)&&!/[. ]$/u.test(e)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(e))}const ut={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}}};function dt(e){let t=vt(e)?e:{},n=vt(t.workspace)?t.workspace:{},r=vt(n.appearance)?n.appearance:{},i=vt(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":gt(r[`color-theme`],tt,ut.workspace.appearance[`color-theme`])},"language-region":{language:gt(i.language,nt,ut.workspace[`language-region`].language),"time-format":gt(i[`time-format`],rt,ut.workspace[`language-region`][`time-format`]),"time-zone":gt(i[`time-zone`],it,ut.workspace[`language-region`][`time-zone`])}}}}function ft(e){if(!vt(e))throw new ht(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=_t(e.theme,tt,`theme`)),`language`in e&&(t.language=_t(e.language,nt,`language`)),`timeFormat`in e&&(t.timeFormat=_t(e.timeFormat,rt,`timeFormat`)),`timezone`in e&&(t.timezone=_t(e.timezone,it,`timezone`)),t}function pt(e,t){return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}}}}function mt(e){return{workspace:e.workspace}}var ht=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function gt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function _t(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new ht(`Invalid ${n}`);return e}function vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yt(e){return e.readSettings()}function bt(e){return mt(yt(e))}function xt(e,t){return t.transaction(()=>{let n=pt(yt(t),e);return t.setSettings(n),mt(n)})}var St=class{storage;configFolder;openFolder;constructor(e,t=$e(),n=Qe){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...bt(this.storage),configFolder:this.configFolder}}update(e){return{...xt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const Ct=r.dirname(Ae(import.meta.url)),D=`foundry`;var wt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=de()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Et();if(!f(r.join(t,`SKILL.md`)))throw new Tt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,D),a=r.join(n,`.${D}-${y()}.tmp`),o=r.join(n,`.${D}-${y()}.backup`);try{return await Se(n,{recursive:!0}),await ye(t,a,{recursive:!0,errorOnExist:!0}),await Dt(a,i,o),{target:e,destination:i}}catch(e){throw await b(a,{recursive:!0,force:!0}),e instanceof Tt?e:new Tt(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return r.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:r.join(this.getTargetParent(e),D)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},Tt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function Et(){let e=[r.resolve(Ct,`skills`,D),r.resolve(Ct,`..`,`..`,`..`,`skills`,D),r.resolve(i.cwd(),`skills`,D)].find(e=>f(r.join(e,`SKILL.md`)));if(!e)throw new Tt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function Dt(e,t,n){let r=f(t);r&&await De(t,n);try{await De(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!f(t)&&f(n)&&await De(n,t),e}}const Ot=`manifest.json`;function kt(e){if([Ot,`data/foundry.json`,`settings.json`,`instructions/`,`skill/`,`agents/`].includes(e)||/^instructions\/[a-f0-9-]+\.md$/u.test(e)||/^agents\/[a-z0-9-]+\.json$/u.test(e))return!0;let[t,n,...r]=e.replace(/\/$/u,``).split(`/`);return t===`skill`&&!!n&&n===n.trim()&&T(n)&&(r.length===0?e.endsWith(`/`):E(r.join(`/`)))}async function At(e,t){let n=new Ne.ZipFile;for(let t of e)t.filePath?n.addFile(t.filePath,t.entryPath,{compress:!0}):n.addEmptyDirectory(t.entryPath,{mode:448});n.end(),await je(n.outputStream,d(t,{mode:384}))}async function jt(e,t){let n=await Mt(e),i=/* @__PURE__ */ new Map;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!kt(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);let a=e.externalFileAttributes>>>16&61440;if(![0,32768,16384].includes(a)||a===16384&&!e.fileName.endsWith(`/`)||i.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let o=r.join(t,e.fileName);await Se(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await Se(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await je(await Nt(n,e),d(o,{mode:384})),i.set(e.fileName,o),n.readEntry())};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await b(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(Ot))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Mt(e){return new Promise((t,n)=>{Me.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Nt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Pt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const O=x.from(`FOUNDRYX`,`ascii`),Ft=`aes-256-gcm`,It=`scrypt`,Lt={N:131072,r:8,p:1};async function Rt(e,t,n){let r=ge(16),i=ge(12),a={version:1,cipher:Ft,kdf:{name:It,salt:r.toString(`base64`),...Lt,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=Bt(o.byteLength),c=x.concat([s,o]),l=await Vt(n,r,Lt);try{let n=await we(t,`w`,384);try{await n.write(c)}finally{await n.close()}await je(u(e),Ht(l,i,c),d(t,{flags:`r+`,mode:384,start:c.byteLength})),await ve(t,384)}catch(e){throw await b(t,{force:!0}),new Pt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{l.fill(0)}}async function zt(e,t,n){let r;try{let i=(await Oe(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await we(e,`r`),o,s,c;try{if(o=await Gt(a,13,0),!o.subarray(0,O.byteLength).equals(O))throw Error(`The export file signature is invalid`);if(o.readUInt8(O.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(O.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await Gt(a,e,13),c=await Gt(a,16,i-16)}finally{await a.close()}let l=Wt(JSON.parse(s.toString(`utf8`)));r=await Vt(n,l.salt,l.header.kdf);let f=x.concat([o,s]);await je(u(e,{start:13+s.byteLength,end:i-16-1}),Ut(r,l.nonce,f,c),d(t,{mode:384})),await ve(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Pt?e:new Pt(qt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,qt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function Bt(e){let t=x.alloc(13);return O.copy(t,0),t.writeUInt8(1,O.byteLength),t.writeUInt32BE(e,O.byteLength+1),t}function Vt(e,t,n){return new Promise((r,i)=>{_e(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Ht(e,t,n){let r=pe(Ft,e,t,{authTagLength:16});return r.setAAD(n),new Fe({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,x.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Ut(e,t,n,r){let i=me(Ft,e,t,{authTagLength:16});return i.setAAD(n),new Fe({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Wt(e){if(!Kt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Ft||!Kt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==It||typeof t.salt!=`string`||t.N!==Lt.N||t.r!==Lt.r||t.p!==Lt.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=x.from(t.salt,`base64`),r=x.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:Ft,kdf:{name:It,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Gt(e,t,n){let r=x.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Kt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Jt(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function Yt(e){return e.transaction(()=>{let t=[{path:`settings.json`,contents:x.from(`${JSON.stringify(e.readSettings(),null,2)}\n`)}],n=i=>{let a=r.join(e.path,i),o;try{o=p(a)}catch(e){if(e.code===`ENOENT`&&[`instructions`,`skill`,`agents`].includes(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!kt(s))throw Error(`Backup sources must contain supported local files and directories`);if(t.push({path:s,contents:o.isDirectory()?null:h(a)}),!o.isDirectory())return;let c=g(a).toSorted((e,t)=>e.localeCompare(t));for(let e of c)n(`${i}/${e}`)};for(let e of[`instructions`,`skill`,`agents`])n(e);return t})}function Xt(e){return he(`sha256`).update(e).digest(`hex`)}var Zt=class{storage;constructor(e){this.storage=e}async createExport(e){let t=Yt(this.storage),n=await Ce(r.join(fe(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=r.join(n,`manifest.json`),o=r.join(n,`foundry.zip`),s=r.join(n,`foundry.foundry-backup`),c={format:`foundry.data`,archiveVersion:3,appVersion:Ge,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:Xt(e.contents)})),directories:t.filter(e=>e.contents===null).map(e=>e.path)},l=[];for(let[e,i]of t.entries())if(i.contents===null)l.push({entryPath:i.path});else{let t=r.join(n,`file-${e}`);await ke(t,i.contents,{mode:384}),l.push({entryPath:i.path,filePath:t})}return await ke(a,JSON.stringify(c,null,2),{mode:384}),await At([{entryPath:`manifest.json`,filePath:a},...l],o),await Rt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await Te(s)}}finally{await Jt(n)}}};const Qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var k=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},$t=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function en(e){if(!tn(e))throw new k(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new k(`name is required`);let t=e.name.trim();if(!t)throw new k(`name is required`);if(t.length>200)throw new k(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new k(`content is required`);if(e.content.length>1e6)throw new k(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const nn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function rn(e,t){let n=Date.now(),r={id:y(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=gn(t,r.id),a=ln(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function an(e){return e.transaction(()=>{let t=hn(e),n;try{n=g(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(_n(e))return[];throw e}return n.map(e=>dn(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function on(e,t){return t.transaction(()=>{if(!Qt.test(e))return;let n=`${e}.md`;try{return dn(r.join(hn(t),n),n)}catch(e){if(_n(e))return;throw e}})}function sn(e,t,n){return n.transaction(()=>{let r=on(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(gn(n,i.id),ln(i)),i})}function cn(e,t){if(!Qt.test(e))return`missing`;let n=hn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>f(i)?(t.removeTextFile(i),`removed`):`missing`)}function ln(e){return`---\n${Re({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function un(e,t){let n=nn.exec(e);if(!n)throw A(t);let r=fn(n[1]);if(`${r.id}.md`!==t)throw A(t);let i=e.slice(n[0].length);return i.startsWith(`\r
3
3
  `)?i=i.slice(2):i.startsWith(`
4
- `)&&(i=i.slice(1)),{...r,content:i}}function rn(e,t){return nn(m(e,`utf8`),t)}function an(e){let t;try{t=Ne(e)}catch{throw j(`frontmatter`)}if(!dn(t))throw j(`frontmatter`);let n=on(t.id),r=on(t.name);if(!r||r.length>200||!Gt.test(n))throw j(`frontmatter`);return{id:n,name:r,createdAt:sn(t.createdAt),updatedAt:sn(t.updatedAt)}}function on(e){return typeof e==`string`?e:``}function sn(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw j(`frontmatter`);return e}function cn(e){return r.join(e.path,`instructions`)}function ln(e,t){if(!Gt.test(t))throw Error(`Invalid instruction ID`);return r.join(cn(e),`${t}.md`)}function j(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function un(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fn(e,t=C){return t.list().map(t=>({id:t.id,name:t.name,icon:t.icon.name,instructionFile:We(t.capabilities.instructions.file),filePath:Ge(e,t.capabilities.instructions.file),capabilities:Ke(t)}))}function M(e){p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function N(e){if(i.platform===`win32`)return;let t=ee(e,`r`);try{d(t)}finally{s(t)}}function pn(e,t){mn(e,`${JSON.stringify(t,null,2)}\n`)}function mn(e,t){hn(e,t)}function hn(e,t){M(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=ee(n,`wx`,384);try{ce(i,t),d(i)}finally{s(i)}re(n,e),N(r.dirname(e))}finally{g(n,{force:!0})}}const gn=`<!-- foundry:instructions:start -->`,_n=`<!-- foundry:instructions:end -->`;function vn(e,t){let n=yn(e),r=xn(t);return`${n}${bn(n)}${r}\n`}function yn(e){let t=``,n=0;for(let r of Sn(e)){let e=Cn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function bn(e){return!e||e.endsWith(`
4
+ `)&&(i=i.slice(1)),{...r,content:i}}function dn(e,t){return un(h(e,`utf8`),t)}function fn(e){let t;try{t=Ie(e)}catch{throw A(`frontmatter`)}if(!vn(t))throw A(`frontmatter`);let n=pn(t.id),r=pn(t.name);if(!r||r.length>200||!Qt.test(n))throw A(`frontmatter`);return{id:n,name:r,createdAt:mn(t.createdAt),updatedAt:mn(t.updatedAt)}}function pn(e){return typeof e==`string`?e:``}function mn(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw A(`frontmatter`);return e}function hn(e){return r.join(e.path,`instructions`)}function gn(e,t){if(!Qt.test(t))throw Error(`Invalid instruction ID`);return r.join(hn(e),`${t}.md`)}function A(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function _n(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yn(e,t=w){return t.list().map(t=>({id:t.id,name:t.name,icon:t.icon.name,instructionFile:Ye(t.capabilities.instructions.file),filePath:Xe(e,t.capabilities.instructions.file),capabilities:Ze(t)}))}function j(e){m(e,{recursive:!0,mode:448}),i.platform!==`win32`&&s(e,448)}function M(e){if(i.platform===`win32`)return;let t=te(e,`r`);try{ee(t)}finally{c(t)}}function bn(e,t){xn(e,`${JSON.stringify(t,null,2)}\n`)}function xn(e,t){Sn(e,t)}function Sn(e,t){j(r.dirname(e));let n=`${e}.${y()}.tmp`;try{let i=te(n,`wx`,384);try{le(i,t),ee(i)}finally{c(i)}ie(n,e),M(r.dirname(e))}finally{_(n,{force:!0})}}const Cn=`<!-- foundry:instructions:start -->`,wn=`<!-- foundry:instructions:end -->`;function Tn(e,t){let n=En(e),r=On(t);return`${n}${Dn(n)}${r}\n`}function En(e){let t=``,n=0;for(let r of kn(e)){let e=An(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function Dn(e){return!e||e.endsWith(`
5
5
  `)?``:`
6
- `}function xn(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
6
+ `}function On(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
7
7
 
8
- `);return t?`${gn}\n\n${t}\n\n${_n}`:`${gn}\n${_n}`}function Sn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function Cn(e){let t=e.replace(/\r?\n$/u,``).trim();return/^<!--\s*foundry\b/iu.test(t)?/\bstart\b/iu.test(t)?`start`:/\bend\b/iu.test(t)?`end`:`other`:null}function wn(e,t){let n=r.dirname(e);p(n,{recursive:!0,mode:448});let a=u(e)?_(e).mode&511:384,c=`${e}.${v()}.tmp`;try{let r=ee(c,`wx`,a);try{i.platform!==`win32`&&o(c,a),ce(r,t),d(r)}finally{s(r)}re(c,e),N(n)}finally{g(c,{force:!0})}}function P(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?yn(i):vn(i,t);wn(e.filePath,a)}function Tn(e){u(e.filePath)&&m(e.filePath,`utf8`)}function F(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}function En(e){return e.all(`agents`)}function Dn(e,t){return e.get(`agents`,t)}function On(e,t){return e.put(`agents`,t),t}function kn(e,t,n){let r=En(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(fn(n).map(e=>[e.id,e])),a=new Map(Zt(e).map(e=>[e.id,e])),o=Date.now();for(let n of r){let r=n.instructions,s=r.instructionIds.filter(e=>e!==t),c=i.get(n.id);c&&r.enabled&&P(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),On(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var An=class{storage;homeDirectory;constructor(e,t=le.homedir()){this.storage=e,this.homeDirectory=t}list(){return Zt(this.storage)}get(e){let t=Qt(e,this.storage);if(!t)throw new Kt(e);return t}create(e){return Xt(e,this.storage)}update(e,t){let n=$t(e,t,this.storage);if(!n)throw new Kt(e);return n}delete(e){return this.storage.transaction(()=>{let t=Qt(e,this.storage);if(!t||(kn(this.storage,e,this.homeDirectory),en(e,this.storage)===`missing`))throw new Kt(e);return t})}},jn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new An(e),n=le.homedir(),r=qe){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=fn(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new S(`AGENT_NOT_FOUND`,`Unknown agent: ${e}`,404);return t}readAssignedInstructions(e){let t=new Map(this.instructionsService.list().map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e);if(!n)throw new S(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}list(){let e=new Map(En(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>Mn(t,(e.get(t.id)??F(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=Dn(this.storage,e)??F(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&P(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=On(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return Mn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Dn(this.storage,e)??F(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new S(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);P(n,e.map(({content:e})=>e),!1)}else P(n,[],!0);let a=Date.now();return Mn(n,On(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Dn(this.storage,e)??F(e),r=n.instructions;if(!r.enabled)throw new S(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);P(t,i.map(({content:e})=>e),!1);let a=Date.now();return Mn(t,On(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}applyConfiguration(){this.storage.transaction(()=>{let e=new Map(En(this.storage).map(e=>[e.id,e]));this.storage.syncAgentInstructions(this.definitions.map(t=>{let n=(e.get(t.id)??F(t.id)).instructions;return{agentId:t.id,enabled:n.enabled,contents:n.enabled?this.readAssignedInstructions(n.instructionIds).map(({content:e})=>e):[]}}))})}openInstructionFile(e){let t=this.requireDefinition(e);if(!u(t.filePath))throw new S(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function Mn(e,t){return{id:e.id,name:e.name,icon:e.icon,capabilities:e.capabilities,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}var Nn=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},Pn=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},Fn=class{libraryRoot;homeDirectory;registry;constructor(e,t,n=C){this.libraryRoot=e,this.homeDirectory=t,this.registry=n}source(e){if(e!==e.trim()||!w(e))throw Error(`Invalid agent skill link name`);return r.resolve(this.libraryRoot,`skill`,e)}destinations(e){let t=this.source(e.previousName),n=e.name===null?null:this.source(e.name),i=this.registry.supporting(`skills`),a=e.agentIds??[];for(let e of a)if(i.every(t=>t.id!==e))throw new Nn(e);return[...new Set(i.filter(t=>!e.agentIds||e.agentIds.includes(t.id)).map(e=>Ge(this.homeDirectory,e.capabilities.skills.directory)))].map(i=>({directory:i,previous:r.join(i,e.previousName),destination:e.name===null?null:r.join(i,e.name),previousSource:t,source:n}))}targets(){return this.registry.supporting(`skills`).map(e=>({id:e.id,name:e.name,icon:e.icon.name,directory:We(e.capabilities.skills.directory)}))}assignedAgentIds(e){let t=this.source(e);return this.registry.supporting(`skills`).filter(n=>I(r.join(Ge(this.homeDirectory,n.capabilities.skills.directory),e),t)).map(e=>e.id)}linkedNames(){let e=/* @__PURE__ */ new Set;for(let{directory:t}of this.targets()){let n=r.join(this.homeDirectory,t.slice(2)),i;try{i=h(n)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let t of i)w(t)&&t===t.trim()&&I(r.join(n,t),this.source(t))&&e.add(t)}return[...e]}validate(e){for(let{destination:t,source:n,previousSource:r}of this.destinations(e))if(t&&n&&In(t)&&!I(t,n)&&!I(t,r))throw new Pn(t)}apply(e){this.validate(e);for(let{directory:t,previous:n,destination:i,source:a,previousSource:o}of this.destinations(e)){if(i&&a){p(t,{recursive:!0,mode:448});let e=me(`sha256`).update(`${i}\0${a}`).digest(`hex`),n=r.join(t,`.foundry-${e}.tmp`);try{if(In(n)&&!I(n,a))throw new Pn(n);if(In(n)||ae(a,n,`dir`),In(i)&&!I(i,a)&&!I(i,o))throw new Pn(i);re(n,i),N(t)}finally{I(n,a)&&oe(n)}}n!==i&&I(n,o)&&(oe(n),N(t))}}};function In(e){try{return f(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function I(e,t){return In(e)&&f(e).isSymbolicLink()&&Ln(r.resolve(r.dirname(e),te(e)))===Ln(t)}function Ln(e){try{return r.join(ne(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var L=class extends Error{code=`INVALID_SKILL_INPUT`},R=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function Rn(e){if(typeof e!=`string`||!T(e))throw new R(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function zn(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new L(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new L(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new L(`Invalid file entry`);let o=Rn(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new L(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new L(`Invalid directory entry`);return{path:o,children:r(e.children,o,a+1)}}if(!(`content`in e)||typeof e.content!=`string`&&e.content!==null)throw new L(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(Bn(e.content),n+=b.byteLength(e.content,`utf8`),n>16777216))throw new L(`Skill text exceeds 16 MiB`);return{path:o,content:e.content}})},i=r(e.files,``,0);if(i.every(e=>e.path!==`SKILL.md`||typeof e.content!=`string`))throw new R(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function Bn(e){if(b.byteLength(e,`utf8`)>2097152)throw new R(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new R(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function Vn(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new L(`assigned must be a boolean`);return{assigned:e.assigned}}var z=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},Hn=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function Un(e){return e===e.trim()&&w(e)}function B(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new L(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new L(`name is required`);let t=it(e.name);if(!Un(t))throw new L(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new L(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new L(`description must be 1–1024 characters`);return{name:t,description:n}}const Wn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var Gn=class{storage;constructor(e){this.storage=e}directory(e){if(!Un(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,`skill`,e)}assertSourceDirectory(e){try{let t=f(this.directory(e));if(!t.isDirectory()||t.isSymbolicLink())throw new L(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new z(e):t}}assertAvailable(e){try{f(this.directory(e))}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}throw new Hn(e)}create(e){return this.storage.transaction(()=>{let t=this.directory(e.name);return this.assertAvailable(e.name),this.storage.putTextFile(r.join(t,`SKILL.md`),`---\n${Fe(e).trimEnd()}\n---\n`),{...e,content:``}})}update(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new z(e);this.assertSourceDirectory(e);let i=this.directory(e),a=m(r.join(i,`SKILL.md`),`utf8`),o=Wn.exec(a);if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=Pe(o[1]);s.set(`name`,t.name),s.set(`description`,t.description);let c=this.directory(t.name);return e!==t.name&&(this.assertAvailable(t.name),this.storage.moveSkillDirectory(i,c)),this.storage.putTextFile(r.join(c,`SKILL.md`),`---\n${s.toString().trimEnd()}\n---\n${n.content}`),{...t,content:n.content}})}delete(e){return this.storage.transaction(()=>{let t=this.get(e);if(!t)throw new z(e);return this.assertSourceDirectory(e),this.storage.removeSkillDirectory(this.directory(e)),t})}updateContent(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new z(e);this.assertSourceDirectory(e);let i=r.join(this.directory(e),`SKILL.md`);if(f(i).isSymbolicLink())throw new L(`Skill source file must not be a symbolic link`);let a=m(i,`utf8`),o=Wn.exec(a)?.[0];if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=t===``||o.endsWith(`
8
+ `);return t?`${Cn}\n\n${t}\n\n${wn}`:`${Cn}\n${wn}`}function kn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function An(e){let t=e.replace(/\r?\n$/u,``).trim();return/^<!--\s*foundry\b/iu.test(t)?/\bstart\b/iu.test(t)?`start`:/\bend\b/iu.test(t)?`end`:`other`:null}function jn(e,t){let n=r.dirname(e);m(n,{recursive:!0,mode:448});let a=f(e)?v(e).mode&511:384,o=`${e}.${y()}.tmp`;try{let r=te(o,`wx`,a);try{i.platform!==`win32`&&s(o,a),le(r,t),ee(r)}finally{c(r)}ie(o,e),M(n)}finally{_(o,{force:!0})}}function N(e,t,n){let r=f(e.filePath);if(n&&!r)return;let i=r?h(e.filePath,`utf8`):``,a=n?En(i):Tn(i,t);jn(e.filePath,a)}function Mn(e){f(e.filePath)&&h(e.filePath,`utf8`)}function P(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}function Nn(e){return e.all(`agents`)}function Pn(e,t){return e.get(`agents`,t)}function Fn(e,t){return e.put(`agents`,t),t}function In(e,t,n){let r=Nn(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(yn(n).map(e=>[e.id,e])),a=new Map(an(e).map(e=>[e.id,e])),o=Date.now();for(let n of r){let r=n.instructions,s=r.instructionIds.filter(e=>e!==t),c=i.get(n.id);c&&r.enabled&&N(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),Fn(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Ln=class{storage;homeDirectory;constructor(e,t=ue.homedir()){this.storage=e,this.homeDirectory=t}list(){return an(this.storage)}get(e){let t=on(e,this.storage);if(!t)throw new $t(e);return t}create(e){return rn(e,this.storage)}update(e,t){let n=sn(e,t,this.storage);if(!n)throw new $t(e);return n}delete(e){return this.storage.transaction(()=>{let t=on(e,this.storage);if(!t||(In(this.storage,e,this.homeDirectory),cn(e,this.storage)===`missing`))throw new $t(e);return t})}},Rn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Ln(e),n=ue.homedir(),r=Qe){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=yn(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new C(`AGENT_NOT_FOUND`,`Unknown agent: ${e}`,404);return t}readAssignedInstructions(e){let t=new Map(this.instructionsService.list().map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e);if(!n)throw new C(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}list(){let e=new Map(Nn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>zn(t,(e.get(t.id)??P(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=Pn(this.storage,e)??P(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&N(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=Fn(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return zn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Pn(this.storage,e)??P(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new C(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);N(n,e.map(({content:e})=>e),!1)}else N(n,[],!0);let a=Date.now();return zn(n,Fn(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Pn(this.storage,e)??P(e),r=n.instructions;if(!r.enabled)throw new C(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);N(t,i.map(({content:e})=>e),!1);let a=Date.now();return zn(t,Fn(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}applyConfiguration(){this.storage.transaction(()=>{let e=new Map(Nn(this.storage).map(e=>[e.id,e]));this.storage.syncAgentInstructions(this.definitions.map(t=>{let n=(e.get(t.id)??P(t.id)).instructions;return{agentId:t.id,enabled:n.enabled,contents:n.enabled?this.readAssignedInstructions(n.instructionIds).map(({content:e})=>e):[]}}))})}openInstructionFile(e){let t=this.requireDefinition(e);if(!f(t.filePath))throw new C(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function zn(e,t){return{id:e.id,name:e.name,icon:e.icon,capabilities:e.capabilities,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}var Bn=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},Vn=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},Hn=class{libraryRoot;homeDirectory;registry;constructor(e,t,n=w){this.libraryRoot=e,this.homeDirectory=t,this.registry=n}source(e){if(e!==e.trim()||!T(e))throw Error(`Invalid agent skill link name`);return r.resolve(this.libraryRoot,`skill`,e)}destinations(e){let t=this.source(e.previousName),n=e.name===null?null:this.source(e.name),i=this.registry.supporting(`skills`),a=e.agentIds??[];for(let e of a)if(i.every(t=>t.id!==e))throw new Bn(e);return[...new Set(i.filter(t=>!e.agentIds||e.agentIds.includes(t.id)).map(e=>Xe(this.homeDirectory,e.capabilities.skills.directory)))].map(i=>({directory:i,previous:r.join(i,e.previousName),destination:e.name===null?null:r.join(i,e.name),previousSource:t,source:n}))}targets(){return this.registry.supporting(`skills`).map(e=>({id:e.id,name:e.name,icon:e.icon.name,directory:Ye(e.capabilities.skills.directory)}))}assignedAgentIds(e){let t=this.source(e);return this.registry.supporting(`skills`).filter(n=>F(r.join(Xe(this.homeDirectory,n.capabilities.skills.directory),e),t)).map(e=>e.id)}linkedNames(){let e=/* @__PURE__ */ new Set;for(let{directory:t}of this.targets()){let n=r.join(this.homeDirectory,t.slice(2)),i;try{i=g(n)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let t of i)T(t)&&t===t.trim()&&F(r.join(n,t),this.source(t))&&e.add(t)}return[...e]}validate(e){for(let{destination:t,source:n,previousSource:r}of this.destinations(e))if(t&&n&&Un(t)&&!F(t,n)&&!F(t,r))throw new Vn(t)}apply(e){this.validate(e);for(let{directory:t,previous:n,destination:i,source:a,previousSource:o}of this.destinations(e)){if(i&&a){m(t,{recursive:!0,mode:448});let e=he(`sha256`).update(`${i}\0${a}`).digest(`hex`),n=r.join(t,`.foundry-${e}.tmp`);try{if(Un(n)&&!F(n,a))throw new Vn(n);if(Un(n)||oe(a,n,`dir`),Un(i)&&!F(i,a)&&!F(i,o))throw new Vn(i);ie(n,i),M(t)}finally{F(n,a)&&se(n)}}n!==i&&F(n,o)&&(se(n),M(t))}}};function Un(e){try{return p(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function F(e,t){return Un(e)&&p(e).isSymbolicLink()&&Wn(r.resolve(r.dirname(e),ne(e)))===Wn(t)}function Wn(e){try{return r.join(re(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var I=class extends Error{code=`INVALID_SKILL_INPUT`},L=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function Gn(e){if(typeof e!=`string`||!E(e))throw new L(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function Kn(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new I(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new I(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new I(`Invalid file entry`);let o=Gn(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new I(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new I(`Invalid directory entry`);return{path:o,children:r(e.children,o,a+1)}}if(!(`content`in e)||typeof e.content!=`string`&&e.content!==null)throw new I(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(qn(e.content),n+=x.byteLength(e.content,`utf8`),n>16777216))throw new I(`Skill text exceeds 16 MiB`);return{path:o,content:e.content}})},i=r(e.files,``,0);if(i.every(e=>e.path!==`SKILL.md`||typeof e.content!=`string`))throw new L(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function qn(e){if(x.byteLength(e,`utf8`)>2097152)throw new L(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new L(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function Jn(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new I(`assigned must be a boolean`);return{assigned:e.assigned}}var R=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},Yn=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function Xn(e){return e===e.trim()&&T(e)}function z(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new I(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new I(`name is required`);let t=lt(e.name);if(!Xn(t))throw new I(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new I(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new I(`description must be 1–1024 characters`);return{name:t,description:n}}function B(e){throw new L(`INVALID_SKILL_IMPORT`,e,400)}function Zn(e){return e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r.isAbsolute(e.path)&&!e.path.includes(`\0`)||B(`path must be an absolute local filesystem path`),{path:e.path}}function Qn(e){(!e||typeof e!=`object`||!(`entries`in e)||!Array.isArray(e.entries)||e.entries.length===0||e.entries.length>5e3)&&B(`Select one skill containing SKILL.md`);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=0,i=e.entries.map(e=>{(!e||typeof e!=`object`||!(`path`in e)||typeof e.path!=`string`||!E(e.path)||e.path.split(`/`).length>32||!(`contents`in e)||e.contents!==null&&typeof e.contents!=`string`)&&B(`The skill contains an invalid path or file`);let i=e.path.normalize(`NFKC`).toLowerCase();if(n.has(i)&&B(`The skill contains duplicate paths`),n.add(i),e.contents!==null&&((e.contents.length>44739244||x.from(e.contents,`base64`).toString(`base64`)!==e.contents)&&B(`Invalid file encoding`),r+=x.from(e.contents,`base64`).length,r>33554432))throw new L(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413);return t.set(i,e.contents),{path:e.path,contents:e.contents}});for(let e of t.keys()){let n=e.split(`/`);for(let e=1;e<n.length;e++){let r=n.slice(0,e).join(`/`);t.has(r)&&t.get(r)!==null&&B(`A file occupies a parent directory`)}}let a=i.find(e=>e.path===`SKILL.md`);a?.contents??B(`The skill root must contain SKILL.md`);let o=x.from(a.contents,`base64`);o.length>2097152&&B(`SKILL.md must be at most 2 MiB`);try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(o),t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(e);return(!t||e.includes(`\0`))&&B(`SKILL.md must contain valid YAML frontmatter`),{skill:{...z(Ie(t[1])),content:e.slice(t[0].length)},entries:i}}catch{B(`SKILL.md must be UTF-8 Markdown with a valid name and description in YAML frontmatter`)}}const $n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var er=class{storage;constructor(e){this.storage=e}directory(e){if(!Xn(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,`skill`,e)}assertSourceDirectory(e){try{let t=p(this.directory(e));if(!t.isDirectory()||t.isSymbolicLink())throw new I(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new R(e):t}}assertAvailable(e){try{p(this.directory(e))}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}throw new Yn(e)}create(e){return this.storage.transaction(()=>{let t=this.directory(e.name);return this.assertAvailable(e.name),this.storage.putTextFile(r.join(t,`SKILL.md`),`---\n${Re(e).trimEnd()}\n---\n`),{...e,content:``}})}import(e,t){return this.storage.transaction(()=>{this.assertAvailable(e.name);for(let n of t){let t=r.join(this.directory(e.name),...n.path.split(`/`));n.contents===null?this.storage.createSkillFolder(t):this.storage.putSkillFile(t,n.contents)}return e})}update(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new R(e);this.assertSourceDirectory(e);let i=this.directory(e),a=h(r.join(i,`SKILL.md`),`utf8`),o=$n.exec(a);if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=Le(o[1]);s.set(`name`,t.name),s.set(`description`,t.description);let c=this.directory(t.name);return e!==t.name&&(this.assertAvailable(t.name),this.storage.moveSkillDirectory(i,c)),this.storage.putTextFile(r.join(c,`SKILL.md`),`---\n${s.toString().trimEnd()}\n---\n${n.content}`),{...t,content:n.content}})}delete(e){return this.storage.transaction(()=>{let t=this.get(e);if(!t)throw new R(e);return this.assertSourceDirectory(e),this.storage.removeSkillDirectory(this.directory(e)),t})}updateContent(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new R(e);this.assertSourceDirectory(e);let i=r.join(this.directory(e),`SKILL.md`);if(p(i).isSymbolicLink())throw new I(`Skill source file must not be a symbolic link`);let a=h(i,`utf8`),o=$n.exec(a)?.[0];if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=t===``||o.endsWith(`
9
9
  `)?``:`
10
- `;return this.storage.putTextFile(i,`${o}${s}${t}`),{...n,content:t}})}get(e){if(Un(e))return this.storage.transaction(()=>{try{let t=m(r.join(this.directory(e),`SKILL.md`),`utf8`),n=Wn.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=B(Ne(n[1]));if(i.name!==it(e))throw Error(`Skill name does not match directory: ${e}`);return{...i,content:t.slice(n[0].length)}}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}})}list(){return this.storage.transaction(()=>{let e;try{e=h(r.join(this.storage.path,`skill`),{withFileTypes:!0}).filter(e=>e.isDirectory()&&Un(e.name)).map(e=>e.name)}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return[];throw e}return e.toSorted((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=this.get(e);return t?[t]:[]})})}};function Kn(e){return e.flatMap(e=>e.children?[e,...Kn(e.children)]:[e])}var qn=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new z(e);let t=r.join(this.storage.path,`skill`,e);if(!f(t).isDirectory()||f(t).isSymbolicLink()||f(r.dirname(t)).isSymbolicLink())throw new R(`INVALID_SKILL_FILE_PATH`,`Skill source must be a local directory`,400);return t}assertLocal(e,t){let n=e;for(let e of t.split(`/`)){n=r.join(n,e);try{if(f(n).isSymbolicLink())throw new R(`INVALID_SKILL_FILE_PATH`,`Symbolic links cannot be changed through the editor`,400)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;return}}}read(e){let t=this.root(e),n=(t,i)=>h(t,{withFileTypes:!0}).toSorted((e,t)=>e.name.localeCompare(t.name)).flatMap(a=>{let o=i?`${i}/${a.name}`:a.name;if(!T(o)||a.isSymbolicLink())return[];let s=r.join(t,a.name);if(a.isDirectory())return[{path:o,children:n(s,o)}];if(!a.isFile())return[];if(o===`SKILL.md`)return[{path:o,content:this.skills.get(e).content}];let c=null;if(f(s).size<=2097152)try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(m(s));c=e.includes(`\0`)?null:e}catch{}return[{path:o,content:c}]});return n(t,``)}replace(e,t){let n=this.root(e),i=new Map(Kn(this.read(e)).map(e=>[e.path,e])),a=new Map(Kn(t).map(e=>[e.path,e]));for(let e of a.values())if(this.assertLocal(n,e.path),e.content===null&&i.get(e.path)?.content!==null)throw new R(`SKILL_FILE_NOT_TEXT`,`Uneditable files must refer to existing unchanged files`,415);let o=[];for(let e of i.values()){let t=a.get(e.path);t&&!!e.children==!!t.children||o.some(t=>e.path.startsWith(`${t}/`))||(this.storage.removeSkillEntry(r.join(n,e.path)),o.push(e.path))}for(let t of a.values()){let a=i.get(t.path),o=r.join(n,t.path);t.children?a?.children||this.storage.createSkillFolder(o):t.content!==null&&t.content!==a?.content&&(t.path===`SKILL.md`?this.skills.updateContent(e,t.content):this.storage.putTextFile(o,t.content))}}},Jn=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new Gn(e),this.files=new qn(e,this.repository)}assignmentRecords(){let e=new Map(this.storage.all(`agents`).map(e=>[e.id,e])),t=this.storage.listSkillAgents().filter(({id:t})=>!e.get(t)?.skills);if(t.length>0){let n=this.list().map(({name:e})=>({name:e,agentIds:this.storage.discoverLinkedSkillAgents(e)})),r=Date.now();for(let{id:i}of t){let t=e.get(i)??F(i);t.skills={skillNames:n.filter(({agentIds:e})=>e.includes(i)).map(({name:e})=>e),createdAt:r,updatedAt:r},this.storage.put(`agents`,t),e.set(i,t)}}return e.values().toArray()}assignedIds(e,t){return this.storage.listSkillAgents().filter(({id:n})=>t.some(t=>t.id===n&&t.skills?.skillNames.includes(e))).map(({id:e})=>e)}applyAssignments(){this.storage.transaction(()=>{let e=this.storage.all(`agents`),t=new Set(this.list().map(({name:e})=>e));for(let n of e)if(n.skills?.skillNames.some(e=>!t.has(e)))throw new L(`Assigned skill does not exist`);let n=this.storage.listSkillAgents().map(({id:e})=>e);for(let t of n){let n=e.find(e=>e.id===t)??F(t);if(n.skills)continue;let r=Date.now();this.storage.put(`agents`,{...n,skills:{skillNames:[],createdAt:r,updatedAt:r}})}let r=/* @__PURE__ */ new Set([...t,...this.storage.linkedSkillNames()]);for(let t of r){let r=this.assignedIds(t,e),i=n.filter(e=>!r.includes(e));r.length>0&&this.storage.syncAgentSkillLinks({previousName:t,name:t,agentIds:r}),i.length>0&&this.storage.syncAgentSkillLinks({previousName:t,name:null,agentIds:i})}})}create(e){return this.repository.create(B(e))}get(e){let t=this.repository.get(e);if(!t)throw new z(e);return t}list(){return this.repository.list()}assignments(){return this.storage.transaction(()=>{let e=this.assignmentRecords();return{agents:this.storage.listSkillAgents(),skills:this.list().map(({name:t})=>({name:t,agentIds:this.assignedIds(t,e)}))}})}setAssignment(e,t,n){return this.storage.transaction(()=>{this.get(e);let r=this.assignmentRecords().find(({id:e})=>e===t);if(!r?.skills||this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new Nn(t);let i=r.skills.skillNames.filter(t=>t!==e);n&&i.push(e),this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:i,updatedAt:Date.now()}}),this.storage.syncAgentSkillLinks({previousName:e,name:n?e:null,agentIds:[t]})}),{name:e,agentIds:this.assignedIds(e,this.storage.all(`agents`))}}update(e,t){let n=B(t);return this.storage.transaction(()=>{let t=this.assignmentRecords(),r=this.assignedIds(e,t),i=this.repository.update(e,n);if(e!==n.name)for(let r of t)r.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:r.skills.skillNames.map(t=>t===e?n.name:t),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:n.name,agentIds:r}),i})}detail(e){return this.storage.transaction(()=>({...this.get(e),files:this.files.read(e)}))}saveFiles(e,t){let n=zn({files:t});return this.storage.transaction(()=>this.files.replace(e,n.files)),this.detail(e)}delete(e){return this.storage.transaction(()=>{let t=this.assignmentRecords(),n=this.repository.delete(e);for(let n of t)n.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...n,skills:{...n.skills,skillNames:n.skills.skillNames.filter(t=>t!==e),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:null}),n})}},V=class extends Error{code;constructor(e,t){super(t),this.code=e}};function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yn(e){if(!H(e)||e.format!==`foundry.data`)throw W(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&H(e.data)&&e.data.path===`data/foundry.json`&&Xn(e.data))return{archiveVersion:2,data:{path:et,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==3||!Array.isArray(e.files)||!Array.isArray(e.directories))throw W(`Unsupported or invalid backup manifest`);return{archiveVersion:3,files:e.files.map(e=>{if(!H(e)||typeof e.path!=`string`||!Xn(e))throw W(`Invalid backup file checksum`);return{path:e.path,bytes:e.bytes,sha256:e.sha256}}),directories:e.directories.map(e=>{if(typeof e!=`string`||!e.endsWith(`/`))throw W(`Invalid backup directory`);return e})}}function Xn(e){return typeof e.bytes==`number`&&Number.isSafeInteger(e.bytes)&&e.bytes>=0&&typeof e.sha256==`string`&&/^[a-f0-9]{64}$/u.test(e.sha256)}function Zn(e){if(!H(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw W(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function Qn(e){if(!H(e)||!H(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw W(`Backup data must contain settings, instructions, and agents`);let t=$n(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:D(e.settings),instructions:t,agents:er(e.agents,n)}}function $n(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!H(e))throw W(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!Gt.test(r)||t.has(r))throw W(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw W(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw W(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:U(e.createdAt,n),updatedAt:U(e.updatedAt,n)};return t.add(r),a})}function er(e,t,n){let r=new Set(C.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!H(e)||!H(e.instructions))throw W(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw W(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw W(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw W(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw W(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw W(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw W(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:U(s.createdAt,a),updatedAt:U(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!H(t)||!Array.isArray(t.skillNames)||t.skillNames.some(e=>typeof e!=`string`||!n.has(e))||new Set(t.skillNames).size!==t.skillNames.length||!C.get(o)?.capabilities.skills)throw W(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:U(t.createdAt,a),updatedAt:U(t.updatedAt,a)}}return i.add(o),u})}function U(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw W(`Invalid timestamp at index ${t}`);return e}function W(e){return new V(`INVALID_BACKUP`,e)}function tr(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!St(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new V(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||[`instructions/`,`skill/`,`agents/`].some(t=>e.every(e=>e.path!==t)))throw new V(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(`instructions/`)&&e.contents!==null).map(e=>nn(nr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>/^skill\/[^/]+\/$/u.test(e.path));for(let t of o){let n=t.path.split(`/`,2)[1],r=e.find(e=>e.path===`${t.path}SKILL.md`)?.contents,i=r&&/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(nr(r));if(!i||B(Ne(i[1])).name!==n)throw new V(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(`skill/`)&&t.path!==`skill/`&&!a.has(t.path.split(`/`,2)[1]))throw new V(`INVALID_BACKUP`,`Skill source is missing SKILL.md`);let n=t.path.replace(/\/$/u,``).split(`/`);for(let t=1;t<n.length;t++){let r=`${n.slice(0,t).join(`/`)}/`;if(e.every(e=>e.path!==r||e.contents!==null))throw new V(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(`agents/`)&&e.contents!==null).map(e=>{let t=JSON.parse(nr(e.contents));if(!t||typeof t!=`object`||!(`id`in t)||`${String(t.id)}.json`!==r.posix.basename(e.path))throw new V(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(nr(n));Qn({settings:c,instructions:i,agents:s});let l=er(s,new Set(i.map(({id:e})=>e)),a);return{entries:e,settings:D(c),agents:l}}function nr(e){return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}function rr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of Zt(e))n.has(t.id)||e.removeTextFile(ir(t.id));for(let n of t.instructions)e.putTextFile(ir(n.id),tn(n));let r=new Set(t.agents.map(({id:e})=>e)),i=new Map(e.all(`agents`).map(e=>[e.id,e]));for(let t of i.values())r.has(t.id)||(t.skills?e.put(`agents`,{...F(t.id),skills:t.skills}):e.remove(`agents`,t.id));for(let n of t.agents){let t=i.get(n.id)?.skills;e.put(`agents`,{...n,...t&&{skills:t}})}return e.setSettings(t.settings),or(e)})}function ir(e){return r.join(`instructions`,`${e}.md`)}function ar(e,t){return e.transaction(()=>{for(let n of[`instructions`,`skill`,`agents`])e.replaceTree(n,t.entries.filter(e=>e.path.startsWith(`${n}/`)&&e.path!==`${n}/`).map(e=>({path:e.path.slice(n.length+1).replace(/\/$/u,``),contents:e.contents?.toString(`base64`)??null})));return e.setSettings(t.settings),sr(t.entries.filter(e=>e.path.startsWith(`agents/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function or(e){return sr(e.all(`agents`))}function sr(e){return me(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function cr(e){for(let{id:t}of C.list()){let n=e.get(`agents`,t)??F(t),r=Date.now();e.put(`agents`,{...n,instructions:{...n.instructions,instructionIds:[],enabled:!1,updatedAt:r},skills:{skillNames:[],createdAt:n.skills?.createdAt??r,updatedAt:r}})}}var lr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(or(this.storage)!==t)throw new V(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new jn(this.storage).applyConfiguration(),new Jn(this.storage).applyAssignments()):cr(this.storage)})}catch(t){throw t instanceof V?t:new V(e?`AGENT_APPLY_FAILED`:`IMPORT_FAILED`,e?`Data was imported, but agent configuration could not be applied. Check agent file access and skill destination conflicts, then retry.`:`Unable to clear imported agent configuration`)}}async importData(e,t){let n=await xe(r.join(de(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await Mt(e,i,t);let a=await wt(i,r.join(n,`extracted`)),o=Yn(JSON.parse(await Ce(a[`manifest.json`],`utf8`))),s;if(o.archiveVersion===2){if(Object.keys(a).length!==2||!Object.keys(a).includes(`data/foundry.json`))throw new V(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await Ce(a[et]);ur(e,o.data);let t=Qn(JSON.parse(e.toString(`utf8`)));s=()=>rr(this.storage,t)}else{let e=new Set(Object.keys(a)),t=[`manifest.json`,...o.files.map(e=>e.path),...o.directories];if(new Set(t).size!==t.length||t.length!==Object.keys(a).length||t.some(t=>!e.has(t)))throw new V(`INVALID_BACKUP`,`Backup entries do not match the manifest`);let n=o.directories.map(e=>({path:e,contents:null}));for(let e of o.files){let t=await Ce(a[e.path]);ur(t,e),n.push({path:e.path,contents:t})}let r=tr(n);s=()=>ar(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new V(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof V?e:e instanceof Dt?e.code===`INVALID_PASSPHRASE`?new V(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new V(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new V(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await Vt(n)}}};function ur(e,t){if(e.byteLength!==t.bytes||Ut(e)!==t.sha256)throw new V(`INVALID_BACKUP`,`Backup checksum does not match`)}const dr=[`agents`,`providers`];function fr(e){let t=/^skill[/\\]([^/\\]+)$/u.exec(e);return!!(t&&t[1]===t[1].trim()&&w(t[1]))}function pr(e){return/^instructions[/\\][^/\\]+\.md$/u.test(e)||mr(e)}function mr(e){let t=e.split(r.sep);return t[0]===`skill`&&t.length>2&&t[1]===t[1].trim()&&w(t[1])&&T(t.slice(2).join(`/`))}function hr(e){try{let t=JSON.parse(m(r.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return i.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-_(e).mtimeMs>3e4}}var gr=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=le.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new Fn(e,t),M(e);for(let e of dr)e!==`providers`&&M(this.collectionPath(e))}collectionPath(e){return r.join(this.path,e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);if(e===`agents`){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t))throw Error(`Invalid agent record ID`);return r.join(`agents`,`${t}.json`)}return r.relative(this.path,r.join(this.collectionPath(e),`${me(`sha256`).update(t).digest(`hex`)}.json`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!pr(t))throw Error(`Invalid storage text filename`);return t}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=r.join(this.path,`.lock`),n=Date.now();for(;;)try{p(t,{mode:448});try{ce(r.join(t,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384})}catch(e){throw g(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,this.initializeProviders(),this.initializeAgents(),e()}finally{this.lockDepth=0,g(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=_(e);if(!hr(e))return;let n=r.join(e,`recovering`);try{p(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);hr(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ce(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!hr(e)){g(n,{recursive:!0,force:!0});return}g(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!u(e))return;let t=JSON.parse(m(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!u(e)){let e=u(t)?h(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};pn(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(ie(t),N(this.path))}initializeAgents(){let e=[],t=this.collectionPath(`agents`),n=h(t,{withFileTypes:!0});for(let t of n){if(!t.isFile()||!/^[a-f0-9]{64}\.json$/u.test(t.name))continue;let n=r.join(`agents`,t.name),i=JSON.parse(m(r.join(this.path,n),`utf8`)),a=this.recordPath(`agents`,i.id);if(t.name!==`${me(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(u(r.join(this.path,a))){let e=JSON.parse(m(r.join(this.path,a),`utf8`));if(JSON.stringify(e)!==JSON.stringify(i))throw Error(`Conflicting legacy agent record: ${i.id}`)}else e.push({file:a,value:i});e.push({file:n,value:null})}if(e.length===0)return;let i={changes:e};pn(r.join(this.path,`.transaction.json`),i),this.applyJournal(i)}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(m(r.join(this.path,`providers.json`),`utf8`));if(!Array.isArray(e))throw TypeError(`Invalid Foundry providers collection`);let t=/* @__PURE__ */ new Set;for(let n of e){if(!n||typeof n.id!=`string`||t.has(n.id))throw Error(`Invalid or duplicate provider ID`);this.recordPath(`providers`,n.id),t.add(n.id)}return structuredClone(e)}assertLocalSkillPath(e){let t=r.relative(this.path,e);if(!mr(t))throw Error(`Invalid skill entry path`);let n=this.path;for(let e of t.split(r.sep)){n=r.join(n,e);try{if(f(n).isSymbolicLink())throw Error(`Cannot write through symbolic links in skill storage`)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;break}}}applyJournal(e){for(let t of e.changes){if(t.tree!==void 0){this.applyTreeChange(t);continue}let e=r.resolve(this.path,t.file),n=r.relative(this.path,e);if(t.createDirectory||t.removeEntry){if(!mr(n)||t.value!==void 0||t.text!==void 0||t.moveTo!==void 0||t.removeDirectory||t.createDirectory&&t.removeEntry)throw Error(`Invalid skill entry journal`);this.assertLocalSkillPath(e),t.createDirectory?M(e):(g(e,{recursive:!0,force:!0}),N(r.dirname(e)))}else if(t.moveTo!==void 0||t.removeDirectory!==void 0)this.applyDirectoryChange(t,n);else{if(n.startsWith(`..`)||r.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|[a-z][a-z-]*[/\\][a-f0-9]{64}\.json|agents[/\\][a-z0-9]+(?:-[a-z0-9]+)*\.json)$/u.test(n)&&!pr(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(mr(n)&&this.assertLocalSkillPath(e),t.value===null)g(e,{force:!0}),N(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);mn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else pn(e,t.value)}}let t=e.agentInstructions??[];for(let e of t){let t=fn(this.agentHomeDirectory).find(({id:t})=>t===e.agentId);if(!t||typeof e.enabled!=`boolean`||!Array.isArray(e.contents)||e.contents.some(e=>typeof e!=`string`))throw Error(`Invalid agent instruction journal`);P(t,e.contents,!e.enabled)}let n=e.skillLinks?Array.isArray(e.skillLinks)?e.skillLinks:[e.skillLinks]:[];for(let e of n)this.skillLinks.apply(e);g(r.join(this.path,`.transaction.json`),{force:!0}),N(this.path)}validateTree(e,t){if(![`instructions`,`skill`,`agents`].includes(e)||!Array.isArray(t))throw Error(`Invalid storage replacement tree`);let n=/* @__PURE__ */ new Map;for(let e of t){if(!T(e.path)||n.has(e.path)||e.contents!==null&&typeof e.contents!=`string`)throw Error(`Invalid storage tree entry`);n.set(e.path,e.contents)}for(let e of n.keys()){let t=e.split(`/`);for(let e=1;e<t.length;e++){let r=t.slice(0,e).join(`/`);if(n.has(r)&&n.get(r)!==null)throw Error(`File occupies a storage tree directory`)}}}applyTreeChange(e){let t=e.tree;if(this.validateTree(e.file,t),Object.keys(e).some(e=>![`file`,`tree`].includes(e)))throw Error(`Invalid storage tree journal`);let n=r.join(this.path,`.replace-${e.file}`);g(n,{recursive:!0,force:!0}),M(n);for(let e of t){let t=r.join(n,...e.path.split(`/`));e.contents===null?M(t):hn(t,b.from(e.contents,`base64`))}let i=r.join(this.path,e.file);g(i,{recursive:!0,force:!0}),re(n,i),N(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!fr(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!fr(t)||e.value!==void 0||e.text!==void 0||e.moveTo!==void 0&&e.removeDirectory!==void 0)throw Error(`Invalid storage directory journal`);let n=r.join(this.path,t);if(e.moveTo!==void 0){let t=r.join(this.path,this.skillDirectory(e.moveTo));if(u(n)){if(!f(n).isDirectory()||f(n).isSymbolicLink()||u(t))throw Error(`Invalid storage directory move`);re(n,t)}else if(!u(t)||!f(t).isDirectory()||f(t).isSymbolicLink())throw Error(`Missing storage directory move`)}else if(e.removeDirectory===!0)g(n,{recursive:!0,force:!0});else throw Error(`Invalid storage directory journal`);N(r.dirname(n))}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=r.join(this.path,t);if(!u(e))return;n=JSON.parse(m(e,`utf8`))}let i=n;if(this.recordPath(e,i.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(i)}replaceTree(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.validateTree(e,t),this.directoryChanges.push({file:e,tree:structuredClone(t)})}syncAgentInstructions(e){if(!this.changes)throw Error(`Storage writes require a transaction`);for(let t of e){let e=fn(this.agentHomeDirectory).find(({id:e})=>e===t.agentId);if(!e)throw Error(`Unknown agent`);Tn(e)}this.agentInstructionChanges.push(...structuredClone(e))}linkedSkillNames(){return this.locked(()=>this.skillLinks.linkedNames())}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>r.relative(this.path,r.join(t,e.name))));if(this.changes){let e=r.relative(this.path,t);for(let t of this.changes.keys())r.dirname(t)===e&&n.add(t)}let i=[];for(let t of n){let n=this.readRecord(e,t);n&&i.push(n)}return i})}get(e,t){return this.locked(()=>{let n=this.recordPath(e,t);return e===`providers`?this.all(e).find(e=>e.id===t):this.readRecord(e,n)})}readSettings(){return this.locked(()=>{if(this.changes?.has(`settings.json`))return D(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?D(JSON.parse(m(e,`utf8`))):structuredClone(E)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);let n=this.recordPath(e,t.id);if(e===`providers`){let n=this.all(e),r=n.findIndex(e=>e.id===t.id);r===-1?n.push(t):n[r]=t,this.changes.set(`providers.json`,structuredClone(n))}else this.changes.set(n,structuredClone(t))}remove(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(this.recordPath(e,t),null)}putTextFile(e,t){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),t)}createSkillFolder(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),createDirectory:!0})}removeSkillEntry(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),removeEntry:!0})}removeTextFile(e){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),null)}moveSkillDirectory(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),moveTo:this.skillDirectory(t)})}removeSkillDirectory(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),removeDirectory:!0})}syncAgentSkillLinks(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.skillLinks.validate(e),this.skillLinkChanges.push(structuredClone(e))}listSkillAgents(){return this.skillLinks.targets()}discoverLinkedSkillAgents(e){return this.locked(()=>this.skillLinks.assignedAgentIds(e))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,D(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map,this.textChanges=/* @__PURE__ */ new Map,this.directoryChanges=[];let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);let i=[...this.directoryChanges,...[...this.changes].map(([e,t])=>({file:e,value:t})),...[...this.textChanges].map(([e,t])=>t===null?{file:e,value:t}:{file:e,text:t})];if(i.length>0||this.skillLinkChanges.length>0||this.agentInstructionChanges.length>0){let e={changes:i,skillLinks:this.skillLinkChanges,agentInstructions:this.agentInstructionChanges};pn(r.join(this.path,`.transaction.json`),e),t={value:n},this.applyJournal(e)}return n}catch(e){if(t)return this.recover(),t.value;throw e}finally{this.changes=null,this.textChanges=null,this.directoryChanges=null,this.skillLinkChanges=[],this.agentInstructionChanges=[]}})}close(){this.closed=!0}};function _r(e=Je(),t){let n=new gr(e,t);try{return n.transaction(()=>{let t=n.readSettings();u(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function vr(){return Ye(),_r()}async function G(e){let t;try{let n=vr(),r=new An(n);t={storage:n,agentsService:new jn(n,r),settingsService:new ht(n),settingsSkillCopyService:new _t,dataExportService:new Wt(n),dataImportService:new lr(n),instructionsService:r,skillsService:new Jn(n)},br(await e(t))}catch(e){let t=xr(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function yr(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new K(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var K=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function br(e){console.log(JSON.stringify(e,null,2))}function xr(e){return e instanceof Error?{code:Sr(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Sr(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Cr={type:`positional`,description:`Agent ID with Skills support: ${C.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function wr(t){return e({meta:{name:t?`assign`:`unassign`,description:t?`Assign one skill and create or repair its agent symlink; preserve other assignments`:`Unassign one skill and unlink its matching agent entry; preserve other assignments`},args:{agent:Cr,skill:{type:`string`,description:`Existing skill name`,required:!0}},run({args:e}){return G(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const Tr=e({meta:{name:`skills`,description:`Inspect, assign, or unassign skills through registered agent symlinks`},subCommands:{list:e({meta:{name:`list`,description:`List agents, skill directories, and saved skill names as JSON`},args:{agent:{...Cr,required:!1}},run({args:e}){return G(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new Nn(e.agent);return n.agents.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({...e,skillNames:n.skills.filter(({agentIds:t})=>t.includes(e.id)).map(({name:e})=>e)}))})}}),assign:wr(!0),unassign:wr(!1)}}),Er=C.list().map(({id:e})=>e).join(`, `),q={type:`positional`,description:`Agent ID: ${Er}`,required:!0},Dr=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return G(({agentsService:e})=>e.list())}}),Or=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...q,description:`Optional agent ID: ${Er}`,required:!1}},run({args:e}){return G(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new K(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${Er}`);let i=new Map(n.list().map(e=>[e.id,e.name]));return r.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({id:e.id,name:e.name,instructionFile:e.instructionFile,enabled:e.enabled,instructions:e.instructionIds.map(e=>({id:e,name:i.get(e)??null}))}))})}}),kr=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:q,instructions:{type:`string`,description:`Comma-separated instruction IDs in block order; pass an empty string to clear`,valueHint:`id1,id2`,required:!0}},run({args:e}){return G(({agentsService:t})=>{let n=Ve({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Ar=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),jr=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),Mr=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.reapply(e.agent))}}),Nr=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.openInstructionFile(e.agent))}}),Pr=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:Dr,skills:Tr,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:Or,assign:kr,enable:Ar,disable:jr,reapply:Mr,open:Nr}})}}),Fr=e({meta:{name:`new`,description:`Create an instruction from a name and Markdown content`},args:{name:{type:`string`,description:`Instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.create(qt({name:e.name,content:e.content})))}}),Ir=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return G(({instructionsService:e})=>e.list())}}),Lr=e({meta:{name:`get`,description:`Read one instruction by ID as JSON`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.get(e.id))}}),Rr=e({meta:{name:`edit`,description:`Replace an instruction name and Markdown content`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0},name:{type:`string`,description:`New instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`New Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.update(e.id,qt({name:e.name,content:e.content})))}}),zr=e({meta:{name:`delete`,description:`Delete an instruction and remove it from every agent`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.delete(e.id))}}),Br=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:Fr,list:Ir,get:Lr,edit:Rr,delete:zr}});function Vr(e){if(!Ur(e)||!Array.isArray(e.targets))throw new Hr(`targets must be an array`);if(e.targets.length===0)throw new Hr(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!nt.includes(e))throw new Hr(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Hr=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Ur(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Wr=e({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return G(async({dataExportService:t})=>{let n=await t.createExport(yr(e.passphrase)),r=Kr(e.output);return await qr(n.contents,r,e.force),{filePath:r}})}}),Gr=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},"apply-agents":{type:`boolean`,description:`Apply imported agent instructions and skill links to this machine; otherwise clear imported agent configuration`,default:!1},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return G(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),yr(e.passphrase));return t.completeImport({apply:e[`apply-agents`],agentRevision:n.agentRevision}),{status:`imported`}})}});function Kr(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,i=r.resolve(n);return i.toLowerCase().endsWith(`.foundry-backup`)?i:`${i}.foundry-backup`}async function qr(e,t,n){await be(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await Ee(a,e,{mode:384}),i.platform!==`win32`&&await _e(a,384),n){await we(a,t);return}if(u(t))throw Jr(t);try{await ye(a,t)}catch(e){throw Yr(e)?Jr(t):e}}finally{await y(a,{force:!0})}}function Jr(e){return new K(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Yr(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const J={"color-theme":{field:`theme`,values:Xe},language:{field:`language`,values:Ze},"time-zone":{field:`timezone`,values:$e},"time-format":{field:`timeFormat`,values:Qe}},Xr=[...Object.keys(J),`config-folder`],Zr=Object.entries(J).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
11
- `);function Qr(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const $r=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Xr.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return G(({settingsService:t})=>{let n=Qr(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new K(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Xr.join(`, `)}`);return n[e.key]})}}),ei=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(J).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${Zr}`,required:!0}},run({args:e}){return G(({settingsService:t})=>{if(e.key===`config-folder`)throw new K(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(J,e.key))throw new K(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(J).join(`, `)}`);let n=J[e.key];if(!n.values.includes(e.value))throw new K(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Qr(t.update(at({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),ti=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return G(({settingsService:e})=>e.openConfigFolder())}}),ni=e({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return G(({settingsSkillCopyService:t})=>{let n=Vr({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),ri=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:$r,set:ei,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:ti}}),export:Wr,import:Gr,"download-skill":ni}}),ii={type:`positional`,description:`Current skill name`,required:!0},ai=e({meta:{name:`manual`,description:`Create skill metadata with an empty Markdown body in ~/.foundry/skill/<name>/SKILL.md`},args:{name:{type:`string`,description:`Unique name: 1–64 Unicode letters or digits, lowercase where applicable, with single hyphens between words`,valueHint:`hello`,required:!0},description:{type:`string`,description:`When an agent should use this skill (1–1024 characters)`,valueHint:`text`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),oi=e({meta:{name:`skills`,description:`Manage skills in the Foundry library`},subCommands:{list:e({meta:{name:`list`,description:`List all skill names and descriptions as JSON`},run(){return G(({skillsService:e})=>e.list().map(({name:e,description:t})=>({name:e,description:t})))}}),get:e({meta:{name:`get`,description:`Read skill metadata and the complete nested files tree as JSON`},args:{skill:ii},run({args:e}){return G(({skillsService:t})=>t.detail(e.skill))}}),save:e({meta:{name:`save`,description:`Replace the complete skill files tree; omitted entries are deleted and metadata is preserved`},args:{skill:ii,file:{type:`string`,description:`JSON file containing { files }, or - for stdin. Accepts get output; only files is applied. SKILL.md is required; its content excludes frontmatter. Null content preserves existing opaque files.`,valueHint:`path|-`,required:!0}},run({args:e}){return G(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new L(`Pipe JSON to stdin or provide a JSON file with --file`);let n=m(e.file===`-`?0:r.resolve(e.file),`utf8`),a;try{a=JSON.parse(n)}catch{throw new L(`Skill files input must be valid JSON`)}let o=zn(a);return t.saveFiles(e.skill,o.files)})}}),edit:e({meta:{name:`edit`,description:`Update skill metadata and refresh links in assigned agent skill directories`},args:{skill:{type:`positional`,description:`Current skill name`,required:!0},name:{type:`string`,description:`New unique skill name`,required:!0},description:{type:`string`,description:`New description (1–1024 characters)`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.update(e.skill,{name:e.name,description:e.description}))}}),delete:e({meta:{name:`delete`,description:`Delete a skill and its files, and unlink matching registered agent entries`},args:{skill:{type:`positional`,description:`Skill name to permanently delete`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:ai}})}});function si(e){let t=new x;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Ve(await ci(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return li(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=He(await ci(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return li(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return li(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return li(t,e)}}),t}async function ci(e){try{return await e.req.json()}catch{throw new S(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function li(e,t){if(t instanceof S)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function ui(e){let t=new x;return t.get(`/`,t=>t.json(e.list())),t.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return fi(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(qt(await di(t)));return t.json(n,201)}catch(e){return fi(t,e)}}),t.put(`/:id`,async t=>{try{let n=qt(await di(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return fi(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return fi(t,e)}}),t}async function di(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function fi(e,t){if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Kt)return e.json({error:{code:t.code,message:t.message}},404);throw t}const pi=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],mi=[`active`,`disabled`,`deleted`];var Y=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function hi(e){if(!Si(e))throw new Y(`Provider input must be an object`);let t=X(e.name,`name`),n=bi(e.protocol),r=xi(e.baseURL),i=e.apiKey===void 0?``:X(e.apiKey,`apiKey`,{allowEmpty:!0}),a=yi(e.customModels);return{...e.avatar!==void 0&&{avatar:gi(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function gi(e){if(e===null)return null;if(typeof e==`string`&&e.length<=2796236){let t=/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,/u.exec(e);if(t){let n=e.slice(t[0].length),r=n.endsWith(`==`)?2:+!!n.endsWith(`=`);if(n.length>0&&n.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(n)&&n.length/4*3-r<=2097152)return e}}throw new Y(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function _i(e){if(!Si(e))throw new Y(`Provider connection must be an object`);return{protocol:bi(e.protocol),baseURL:xi(e.baseURL),apiKey:e.apiKey===void 0?``:X(e.apiKey,`apiKey`,{allowEmpty:!0})}}function vi(e){if(typeof e!=`string`||!mi.includes(e))throw new Y(`Invalid provider status`);return e}function yi(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Y(`customModels must be an array`);return e.map(e=>{if(!Si(e))throw new Y(`Each custom model must be an object`);return{id:X(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:X(e.displayName,`customModels.displayName`)}})}function bi(e){if(typeof e!=`string`||!pi.includes(e))throw new Y(`Invalid provider protocol`);return e}function xi(e){let t=X(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new Y(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function X(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new Y(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new Y(`${t} is required`);return r}function Si(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Z=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Ci(e,t=fetch){let n={accept:`application/json`};e.protocol===`anthropic-messages`?(n[`anthropic-version`]=`2023-06-01`,e.apiKey&&(n[`x-api-key`]=e.apiKey)):n.authorization=`Bearer ${e.apiKey||`local-provider`}`;let r;try{r=await t(wi(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new Z(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new Z(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new Z(`Provider returned invalid JSON`)}return Ti(i)}function wi(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function Ti(e){if(!Di(e)||!Array.isArray(e.data))throw new Z(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Di(e)||typeof e.id!=`string`||e.id.length===0)throw new Z(`Provider returned an invalid model entry`);let t=Ei(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Ei(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Oi=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},ki=class{storage;constructor(e){this.storage=e}list(){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt-e.updatedAt).map(e=>Ai(e))}get(e){let t=this.storage.get(`providers`,e);return t?Ai(t):null}getConnection(e){let t=this.storage.get(`providers`,e);return t&&t.status!==`deleted`?{protocol:t.protocol,baseURL:t.baseURL,apiKey:t.apiKey}:null}save(e,t){return this.storage.transaction(()=>{let n=t?this.storage.get(`providers`,t):void 0;if(t&&!n)throw new Oi;let r=Date.now(),i={id:t??v(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Ai(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new Oi;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),Ai(i)})}};function Ai(e){return{...e,avatar:e.avatar??null,status:e.status}}function ji(e,t=()=>{}){let n=new x;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return Q(t,e)}}),n.post(`/models`,async t=>{try{let n=_i(await Mi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return Q(t,e)}}),n.post(`/`,async n=>{try{let r=hi(await Mi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return Q(n,e)}}),n.put(`/:id`,async n=>{try{let r=hi(await Mi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return Q(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Mi(n),i=vi(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return Q(n,e)}}),n}async function Mi(e){try{return await e.req.json()}catch{throw new Y(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof Y)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Oi)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Z)return e.json({error:{code:t.code,message:t.message}},502);throw t}var Ni=class{repository;constructor(e){this.repository=new ki(e)}list(){return this.repository.list()}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Oi;return Ci(t)}fetchModelsForConnection(e){return Ci(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function Pi(e,t=()=>{},n=new _t){let r=new x;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=at(await Fi(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Ii(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=Vr(await Fi(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Ii(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Fi(e){try{return await e.req.json()}catch{throw new ct(`Request body must be valid JSON`)}}function Ii(e,t){if(t instanceof ct||t instanceof Hr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof vt)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Li(e){let t=new x;return t.get(`/agents/assignments`,t=>t.json(e.assignments())),t.put(`/:name/agents/:id`,async t=>{try{let n=Vn(await Ri(t));return t.json(e.setAssignment(t.req.param(`name`),t.req.param(`id`),n.assigned))}catch(e){return $(t,e)}}),t.get(`/`,t=>t.json(e.list())),t.get(`/:name`,t=>{try{return t.json(e.detail(t.req.param(`name`)))}catch(e){return $(t,e)}}),t.post(`/`,async t=>{try{let n=await Ri(t);return t.json(e.create(B(n)),201)}catch(e){return $(t,e)}}),t.put(`/:name`,async t=>{try{let n=await Ri(t);if(n&&typeof n==`object`&&`files`in n){let r=zn(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),B(n)))}catch(e){return $(t,e)}}),t.delete(`/:name`,t=>{try{return e.delete(t.req.param(`name`)),t.body(null,204)}catch(e){return $(t,e)}}),t}async function Ri(e){try{return await e.req.json()}catch{throw new L(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof R)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof Nn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Pn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof L)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Hn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof z)return e.json({error:{code:t.code,message:t.message}},404);throw t}function zi(e){let t=new x;return t.get(`/`,t=>Re(t,async n=>{await Bi(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Vi(n,e)}),c=setInterval(()=>{r||Hi(n)},15e3),l=()=>{o()};t.req.raw.signal.addEventListener(`abort`,l,{once:!0}),n.onAbort(o),t.req.raw.signal.aborted&&o(),await i,clearInterval(c),s(),t.req.raw.signal.removeEventListener(`abort`,l)})),t}function Bi(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Vi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Hi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Ui=class extends Error{code=`INVALID_EXPORT_INPUT`};function Wi(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Ui(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Gi(e){let t=new x;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Ui(`Request body must be valid JSON`)}let{passphrase:r}=Wi(n),i=await e.createExport(r);return t.body(i.contents,200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${i.fileName}"`,"cache-control":`no-store`})}catch(e){return e instanceof Ui?t.json({error:{code:e.code,message:e.message}},400):t.json({error:{code:`DATA_EXPORT_FAILED`,message:`Unable to export data`}},500)}}),t}function Ki(e,t){let n=new x;return n.post(`/`,async n=>{let i;try{if(n.req.header(`content-type`)?.split(`;`,1)[0].trim()!==`application/octet-stream`||!n.req.raw.body)throw new V(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new V(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new V(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await xe(r.join(de(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await Oe(je.fromWeb(n.req.raw.body),l(o,{mode:384}));let s=await e.importData(o,a);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json(s)}catch(e){return e instanceof V?n.json({error:{code:e.code,message:e.message}},e.code===`IMPORT_FAILED`?500:400):n.json({error:{code:`IMPORT_FAILED`,message:`Unable to import data`}},500)}finally{i&&await Vt(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new V(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(Zn(n)),t.json({status:`completed`})}catch(e){if(e instanceof V){let n=e.code===`IMPORT_CHANGED`?409:e.code===`AGENT_APPLY_FAILED`||e.code===`IMPORT_FAILED`?500:400;return t.json({error:{code:e.code,message:e.message}},n)}return t.json({error:{code:`IMPORT_FAILED`,message:`Unable to complete import`}},500)}}),n}function qi(e){return e===`/api`||e.startsWith(`/api/`)}function Ji(e,t={}){let n=new x,r=t.providerService??new Ni(e),i=t.settingsService??new ht(e),a=t.settingsSkillCopyService??new _t,o=t.instructionsService??new An(e),s=t.agentsService??new jn(e,o);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Be,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,zi(t.eventHub)),n.route(`/api/data-import`,Ki(t.dataImportService??new lr(e),()=>{t.eventHub?.publish(tt,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Gi(t.dataExportService??new Wt(e))),n.route(`/api/agents`,si(s)),n.route(`/api/skills`,Li(t.skillsService??new Jn(e))),n.route(`/api/instructions`,ui(o)),n.route(`/api/providers`,ji(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Pi(i,e=>{t.eventHub?.publish(tt,e)},a)),n.notFound(e=>qi(e.req.path)?e.json({error:{code:`NOT_FOUND`,message:`API route not found`}},404):e.text(`Not Found`,404)),n.onError((e,t)=>(console.error(e),qi(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Yi(e,t,n){let i=Ji(t,n),a=Le({root:e});i.use(`*`,(e,t)=>qi(e.req.path)?t():a(e,t));let o=Le({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!qi(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function Xi(e,t){let n,r=se(e,{persistent:!1},(e,r)=>{(r===null||r===`settings.json`)&&(clearTimeout(n),n=setTimeout(t,30),n.unref())});return r.on(`error`,()=>{console.error(`Unable to watch Foundry settings`)}),()=>{clearTimeout(n),r.close()}}var Zi=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:v(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function Qi(e){let t=new Zi,n=new Wt(e),r=new lr(e),i=new An(e),a=new jn(e,i),o=new Ni(e),s=new ht(e),c=new _t,l=new Jn(e),u={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l},d;return{services:u,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,eventHub:t},start(){d??=Xi(e.path,()=>{t.publish(tt,{fields:[]})})},stop(){d?.(),d=void 0}}}const{dirname:$i,join:ea,resolve:ta}=r,na=$i(De(import.meta.url));function ra(){let e=[ta(na,`web`),ta(i.cwd(),`dist/web`)].find(e=>u(ea(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function ia({storage:e,webRoot:t=ra(),onListening:n}){let r=Qi(e),a=Yi(t,e,r.apiOptions);r.start();let o=Ie({fetch:a.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return o.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),i.exitCode=1}),o.on(`close`,r.stop),o}function aa(e,t){return new Promise((n,r)=>{let i=ze();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function oa(e){let t=`xdg-open`,n=[e];i.platform===`darwin`?t=`open`:i.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=a(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const sa=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await aa(`127.0.0.1`,11111)}catch(e){ca(e);return}ia({storage:vr(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&oa(t)}})}});function ca(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function la(){let t,r=e({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await n(t)}});return t=e({meta:{name:`foundry`,version:Be,description:`Manage Foundry settings, instructions, and skills or start the Web UI`},default:`help`,subCommands:{help:r,web:sa,settings:ri,instructions:Br,agents:Pr,skills:oi}}),t}t(la());export{};
10
+ `;return this.storage.putTextFile(i,`${o}${s}${t}`),{...n,content:t}})}get(e){if(Xn(e))return this.storage.transaction(()=>{try{let t=h(r.join(this.directory(e),`SKILL.md`),`utf8`),n=$n.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=z(Ie(n[1]));if(i.name!==lt(e))throw Error(`Skill name does not match directory: ${e}`);return{...i,content:t.slice(n[0].length)}}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}})}list(){return this.storage.transaction(()=>{let e;try{e=g(r.join(this.storage.path,`skill`),{withFileTypes:!0}).filter(e=>e.isDirectory()&&Xn(e.name)).map(e=>e.name)}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return[];throw e}return e.toSorted((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=this.get(e);return t?[t]:[]})})}};function tr(e){return e.flatMap(e=>e.children?[e,...tr(e.children)]:[e])}var nr=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new R(e);let t=r.join(this.storage.path,`skill`,e);if(!p(t).isDirectory()||p(t).isSymbolicLink()||p(r.dirname(t)).isSymbolicLink())throw new L(`INVALID_SKILL_FILE_PATH`,`Skill source must be a local directory`,400);return t}assertLocal(e,t){let n=e;for(let e of t.split(`/`)){n=r.join(n,e);try{if(p(n).isSymbolicLink())throw new L(`INVALID_SKILL_FILE_PATH`,`Symbolic links cannot be changed through the editor`,400)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;return}}}read(e){let t=this.root(e),n=(t,i)=>g(t,{withFileTypes:!0}).toSorted((e,t)=>e.name.localeCompare(t.name)).flatMap(a=>{let o=i?`${i}/${a.name}`:a.name;if(!E(o)||a.isSymbolicLink())return[];let s=r.join(t,a.name);if(a.isDirectory())return[{path:o,children:n(s,o)}];if(!a.isFile())return[];if(o===`SKILL.md`)return[{path:o,content:this.skills.get(e).content}];let c=null;if(p(s).size<=2097152)try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(h(s));c=e.includes(`\0`)?null:e}catch{}return[{path:o,content:c}]});return n(t,``)}replace(e,t){let n=this.root(e),i=new Map(tr(this.read(e)).map(e=>[e.path,e])),a=new Map(tr(t).map(e=>[e.path,e]));for(let e of a.values())if(this.assertLocal(n,e.path),e.content===null&&i.get(e.path)?.content!==null)throw new L(`SKILL_FILE_NOT_TEXT`,`Uneditable files must refer to existing unchanged files`,415);let o=[];for(let e of i.values()){let t=a.get(e.path);t&&!!e.children==!!t.children||o.some(t=>e.path.startsWith(`${t}/`))||(this.storage.removeSkillEntry(r.join(n,e.path)),o.push(e.path))}for(let t of a.values()){let a=i.get(t.path),o=r.join(n,t.path);t.children?a?.children||this.storage.createSkillFolder(o):t.content!==null&&t.content!==a?.content&&(t.path===`SKILL.md`?this.skills.updateContent(e,t.content):this.storage.putTextFile(o,t.content))}}};async function rr(e){try{let t=await xe(e);if(t.isSymbolicLink()&&B(`Select a skill source, not a symbolic link`),t.isFile()&&/\.(?:skill|zip)$/iu.test(e)){ir(t.size);let{entries:n,unsupported:i}=await ar(e);return n.some(e=>e.path===`SKILL.md`)?(i.length>0&&B(`The skill contains symbolic links or unsupported entries`),{isBatch:!1,candidates:[{source:r.basename(e),entries:n}]}):{isBatch:!0,candidates:[...new Set(n.filter(e=>e.contents===null||e.path.includes(`/`)).map(e=>e.path.split(`/`,1)[0]))].map(e=>({source:e,hasUnsupportedEntries:i.some(t=>t===e||t.startsWith(`${e}/`)),entries:n.filter(t=>t.path.startsWith(`${e}/`)).map(t=>({...t,path:t.path.slice(e.length+1)}))}))}}t.isDirectory()||B(`Select a skill folder or a .skill / .zip archive`);let n=[],i=0,a=async(e,t)=>{(!E(t)||t.split(`/`).length>32||n.length>=5e3)&&B(`The skill contains invalid paths or too many entries`);let o=await xe(e);if((o.isSymbolicLink()||!o.isFile()&&!o.isDirectory())&&B(`Skills must contain only regular files and directories`),o.isDirectory()){n.push({path:t,contents:null});let i=await Ee(e);for(let n of i)await a(r.join(e,n),`${t}/${n}`)}else{ir(i+o.size);let r=await we(e,l.O_RDONLY|l.O_NOFOLLOW|l.O_NONBLOCK);try{let e=await r.stat();e.isFile()||B(`Select a regular skill file`),ir(i+e.size);let a=[],o;do{let e=x.alloc(65536);({bytesRead:o}=await r.read(e)),i+=o,ir(i),o>0&&a.push(e.subarray(0,o))}while(o>0);n.push({path:t,contents:x.concat(a).toString(`base64`)})}finally{await r.close()}}},o=await Ee(e);o.includes(`SKILL.md`)||B(`The selected folder must contain SKILL.md at its root`);for(let t of o)await a(r.join(e,t),t);return{isBatch:!1,candidates:[{source:r.basename(e),entries:n}]}}catch(e){throw e instanceof L?e:new L(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)}}function ir(e){if(e>33554432)throw new L(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413)}async function ar(e){let t;try{t=await new Promise((t,n)=>{Me.open(e,{lazyEntries:!0,autoClose:!1,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}catch{B(`Select a valid .skill or .zip archive`)}let n=[],r=[],i=0;try{await new Promise((e,a)=>{t.on(`error`,a),t.on(`end`,e),t.on(`entry`,e=>{(async()=>{let a=e.fileName.endsWith(`/`),o=a?e.fileName.slice(0,-1):e.fileName,s=e.externalFileAttributes>>>16&61440;if(n.length>=5e3&&B(`The archive contains too many files`),!E(o)||![0,32768,16384].includes(s)||s===16384&&!a||s===32768&&a){r.push(o),n.push({path:o,contents:null}),t.readEntry();return}if(i+=e.uncompressedSize,i>33554432)throw new L(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413);let c=null;if(!a){let n=await new Promise((n,r)=>{t.openReadStream(e,(e,t)=>e?r(e):n(t))}),r=[],i=0;for await(let t of n){let n=x.from(t);i+=n.length,(i>e.uncompressedSize||i>33554432)&&B(`Invalid archive size`),r.push(n)}c=x.concat(r).toString(`base64`)}n.push({path:o,contents:c}),t.readEntry()})().catch(a)}),t.readEntry()})}catch(e){if(e instanceof L)throw e;B(`Unable to read the skill archive`)}finally{t.close()}return{entries:n,unsupported:r}}var or=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new er(e),this.files=new nr(e,this.repository)}assignmentRecords(){let e=new Map(this.storage.all(`agents`).map(e=>[e.id,e])),t=this.storage.listSkillAgents().filter(({id:t})=>!e.get(t)?.skills);if(t.length>0){let n=this.list().map(({name:e})=>({name:e,agentIds:this.storage.discoverLinkedSkillAgents(e)})),r=Date.now();for(let{id:i}of t){let t=e.get(i)??P(i);t.skills={skillNames:n.filter(({agentIds:e})=>e.includes(i)).map(({name:e})=>e),createdAt:r,updatedAt:r},this.storage.put(`agents`,t),e.set(i,t)}}return e.values().toArray()}assignedIds(e,t){return this.storage.listSkillAgents().filter(({id:n})=>t.some(t=>t.id===n&&t.skills?.skillNames.includes(e))).map(({id:e})=>e)}applyAssignments(){this.storage.transaction(()=>{let e=this.storage.all(`agents`),t=new Set(this.list().map(({name:e})=>e));for(let n of e)if(n.skills?.skillNames.some(e=>!t.has(e)))throw new I(`Assigned skill does not exist`);let n=this.storage.listSkillAgents().map(({id:e})=>e);for(let t of n){let n=e.find(e=>e.id===t)??P(t);if(n.skills)continue;let r=Date.now();this.storage.put(`agents`,{...n,skills:{skillNames:[],createdAt:r,updatedAt:r}})}let r=/* @__PURE__ */ new Set([...t,...this.storage.linkedSkillNames()]);for(let t of r){let r=this.assignedIds(t,e),i=n.filter(e=>!r.includes(e));r.length>0&&this.storage.syncAgentSkillLinks({previousName:t,name:t,agentIds:r}),i.length>0&&this.storage.syncAgentSkillLinks({previousName:t,name:null,agentIds:i})}})}create(e){return this.repository.create(z(e))}async importLocal(e){let{isBatch:t,candidates:n}=await rr(Zn(e).path);n.length===0&&B(`The archive contains no skill folders at the first level`);let r={imported:[],skipped:[]};for(let e of n)try{e.hasUnsupportedEntries&&B(`The skill contains symbolic links or unsupported entries`);let{skill:t,entries:n}=Qn({entries:e.entries});r.imported.push(this.repository.import(t,n))}catch(n){if(!t||!(n instanceof L||n instanceof I||n instanceof Yn))throw n;r.skipped.push({source:e.source,code:n.code,message:n.message})}return r}get(e){let t=this.repository.get(e);if(!t)throw new R(e);return t}list(){return this.repository.list()}assignments(){return this.storage.transaction(()=>{let e=this.assignmentRecords();return{agents:this.storage.listSkillAgents(),skills:this.list().map(({name:t})=>({name:t,agentIds:this.assignedIds(t,e)}))}})}setAssignment(e,t,n){return this.storage.transaction(()=>{this.get(e);let r=this.assignmentRecords().find(({id:e})=>e===t);if(!r?.skills||this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new Bn(t);let i=r.skills.skillNames.filter(t=>t!==e);n&&i.push(e),this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:i,updatedAt:Date.now()}}),this.storage.syncAgentSkillLinks({previousName:e,name:n?e:null,agentIds:[t]})}),{name:e,agentIds:this.assignedIds(e,this.storage.all(`agents`))}}update(e,t){let n=z(t);return this.storage.transaction(()=>{let t=this.assignmentRecords(),r=this.assignedIds(e,t),i=this.repository.update(e,n);if(e!==n.name)for(let r of t)r.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:r.skills.skillNames.map(t=>t===e?n.name:t),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:n.name,agentIds:r}),i})}detail(e){return this.storage.transaction(()=>({...this.get(e),files:this.files.read(e)}))}saveFiles(e,t){let n=Kn({files:t});return this.storage.transaction(()=>this.files.replace(e,n.files)),this.detail(e)}delete(e){return this.storage.transaction(()=>{let t=this.assignmentRecords(),n=this.repository.delete(e);for(let n of t)n.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...n,skills:{...n.skills,skillNames:n.skills.skillNames.filter(t=>t!==e),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:null}),n})}},V=class extends Error{code;constructor(e,t){super(t),this.code=e}};function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sr(e){if(!H(e)||e.format!==`foundry.data`)throw W(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&H(e.data)&&e.data.path===`data/foundry.json`&&cr(e.data))return{archiveVersion:2,data:{path:at,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==3||!Array.isArray(e.files)||!Array.isArray(e.directories))throw W(`Unsupported or invalid backup manifest`);return{archiveVersion:3,files:e.files.map(e=>{if(!H(e)||typeof e.path!=`string`||!cr(e))throw W(`Invalid backup file checksum`);return{path:e.path,bytes:e.bytes,sha256:e.sha256}}),directories:e.directories.map(e=>{if(typeof e!=`string`||!e.endsWith(`/`))throw W(`Invalid backup directory`);return e})}}function cr(e){return typeof e.bytes==`number`&&Number.isSafeInteger(e.bytes)&&e.bytes>=0&&typeof e.sha256==`string`&&/^[a-f0-9]{64}$/u.test(e.sha256)}function lr(e){if(!H(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw W(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function ur(e){if(!H(e)||!H(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw W(`Backup data must contain settings, instructions, and agents`);let t=dr(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:dt(e.settings),instructions:t,agents:fr(e.agents,n)}}function dr(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!H(e))throw W(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!Qt.test(r)||t.has(r))throw W(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw W(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw W(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:U(e.createdAt,n),updatedAt:U(e.updatedAt,n)};return t.add(r),a})}function fr(e,t,n){let r=new Set(w.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!H(e)||!H(e.instructions))throw W(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw W(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw W(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw W(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw W(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw W(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw W(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:U(s.createdAt,a),updatedAt:U(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!H(t)||!Array.isArray(t.skillNames)||t.skillNames.some(e=>typeof e!=`string`||!n.has(e))||new Set(t.skillNames).size!==t.skillNames.length||!w.get(o)?.capabilities.skills)throw W(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:U(t.createdAt,a),updatedAt:U(t.updatedAt,a)}}return i.add(o),u})}function U(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw W(`Invalid timestamp at index ${t}`);return e}function W(e){return new V(`INVALID_BACKUP`,e)}function pr(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!kt(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new V(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||[`instructions/`,`skill/`,`agents/`].some(t=>e.every(e=>e.path!==t)))throw new V(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(`instructions/`)&&e.contents!==null).map(e=>un(mr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>/^skill\/[^/]+\/$/u.test(e.path));for(let t of o){let n=t.path.split(`/`,2)[1],r=e.find(e=>e.path===`${t.path}SKILL.md`)?.contents,i=r&&/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(mr(r));if(!i||z(Ie(i[1])).name!==n)throw new V(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(`skill/`)&&t.path!==`skill/`&&!a.has(t.path.split(`/`,2)[1]))throw new V(`INVALID_BACKUP`,`Skill source is missing SKILL.md`);let n=t.path.replace(/\/$/u,``).split(`/`);for(let t=1;t<n.length;t++){let r=`${n.slice(0,t).join(`/`)}/`;if(e.every(e=>e.path!==r||e.contents!==null))throw new V(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(`agents/`)&&e.contents!==null).map(e=>{let t=JSON.parse(mr(e.contents));if(!t||typeof t!=`object`||!(`id`in t)||`${String(t.id)}.json`!==r.posix.basename(e.path))throw new V(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(mr(n));ur({settings:c,instructions:i,agents:s});let l=fr(s,new Set(i.map(({id:e})=>e)),a);return{entries:e,settings:dt(c),agents:l}}function mr(e){return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}function hr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of an(e))n.has(t.id)||e.removeTextFile(gr(t.id));for(let n of t.instructions)e.putTextFile(gr(n.id),ln(n));let r=new Set(t.agents.map(({id:e})=>e)),i=new Map(e.all(`agents`).map(e=>[e.id,e]));for(let t of i.values())r.has(t.id)||(t.skills?e.put(`agents`,{...P(t.id),skills:t.skills}):e.remove(`agents`,t.id));for(let n of t.agents){let t=i.get(n.id)?.skills;e.put(`agents`,{...n,...t&&{skills:t}})}return e.setSettings(t.settings),vr(e)})}function gr(e){return r.join(`instructions`,`${e}.md`)}function _r(e,t){return e.transaction(()=>{for(let n of[`instructions`,`skill`,`agents`])e.replaceTree(n,t.entries.filter(e=>e.path.startsWith(`${n}/`)&&e.path!==`${n}/`).map(e=>({path:e.path.slice(n.length+1).replace(/\/$/u,``),contents:e.contents?.toString(`base64`)??null})));return e.setSettings(t.settings),yr(t.entries.filter(e=>e.path.startsWith(`agents/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function vr(e){return yr(e.all(`agents`))}function yr(e){return he(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function br(e){for(let{id:t}of w.list()){let n=e.get(`agents`,t)??P(t),r=Date.now();e.put(`agents`,{...n,instructions:{...n.instructions,instructionIds:[],enabled:!1,updatedAt:r},skills:{skillNames:[],createdAt:n.skills?.createdAt??r,updatedAt:r}})}}var xr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(vr(this.storage)!==t)throw new V(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new Rn(this.storage).applyConfiguration(),new or(this.storage).applyAssignments()):br(this.storage)})}catch(t){throw t instanceof V?t:new V(e?`AGENT_APPLY_FAILED`:`IMPORT_FAILED`,e?`Data was imported, but agent configuration could not be applied. Check agent file access and skill destination conflicts, then retry.`:`Unable to clear imported agent configuration`)}}async importData(e,t){let n=await Ce(r.join(fe(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await zt(e,i,t);let a=await jt(i,r.join(n,`extracted`)),o=sr(JSON.parse(await Te(a[`manifest.json`],`utf8`))),s;if(o.archiveVersion===2){if(Object.keys(a).length!==2||!Object.keys(a).includes(`data/foundry.json`))throw new V(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await Te(a[at]);Sr(e,o.data);let t=ur(JSON.parse(e.toString(`utf8`)));s=()=>hr(this.storage,t)}else{let e=new Set(Object.keys(a)),t=[`manifest.json`,...o.files.map(e=>e.path),...o.directories];if(new Set(t).size!==t.length||t.length!==Object.keys(a).length||t.some(t=>!e.has(t)))throw new V(`INVALID_BACKUP`,`Backup entries do not match the manifest`);let n=o.directories.map(e=>({path:e,contents:null}));for(let e of o.files){let t=await Te(a[e.path]);Sr(t,e),n.push({path:e.path,contents:t})}let r=pr(n);s=()=>_r(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new V(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof V?e:e instanceof Pt?e.code===`INVALID_PASSPHRASE`?new V(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new V(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new V(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await Jt(n)}}};function Sr(e,t){if(e.byteLength!==t.bytes||Xt(e)!==t.sha256)throw new V(`INVALID_BACKUP`,`Backup checksum does not match`)}const Cr=[`agents`,`providers`];function wr(e){let t=/^skill[/\\]([^/\\]+)$/u.exec(e);return!!(t&&t[1]===t[1].trim()&&T(t[1]))}function Tr(e){return/^instructions[/\\][^/\\]+\.md$/u.test(e)||Er(e)}function Er(e){let t=e.split(r.sep);return t[0]===`skill`&&t.length>2&&t[1]===t[1].trim()&&T(t[1])&&E(t.slice(2).join(`/`))}function Dr(e){try{let t=JSON.parse(h(r.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return i.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-v(e).mtimeMs>3e4}}var Or=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=ue.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new Hn(e,t),j(e);for(let e of Cr)e!==`providers`&&j(this.collectionPath(e))}collectionPath(e){return r.join(this.path,e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);if(e===`agents`){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t))throw Error(`Invalid agent record ID`);return r.join(`agents`,`${t}.json`)}return r.relative(this.path,r.join(this.collectionPath(e),`${he(`sha256`).update(t).digest(`hex`)}.json`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!Tr(t))throw Error(`Invalid storage text filename`);return t}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=r.join(this.path,`.lock`),n=Date.now();for(;;)try{m(t,{mode:448});try{le(r.join(t,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384})}catch(e){throw _(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,this.initializeProviders(),this.initializeAgents(),e()}finally{this.lockDepth=0,_(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=v(e);if(!Dr(e))return;let n=r.join(e,`recovering`);try{m(n)}catch(e){if(e.code===`EEXIST`){let e=v(n);Dr(n)&&v(n).ino===e.ino&&_(n,{recursive:!0,force:!0})}return}if(le(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),v(e).ino!==t.ino||!Dr(e)){_(n,{recursive:!0,force:!0});return}_(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!f(e))return;let t=JSON.parse(h(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!f(e)){let e=f(t)?g(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};bn(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}f(t)&&g(t).length===0&&(ae(t),M(this.path))}initializeAgents(){let e=[],t=this.collectionPath(`agents`),n=g(t,{withFileTypes:!0});for(let t of n){if(!t.isFile()||!/^[a-f0-9]{64}\.json$/u.test(t.name))continue;let n=r.join(`agents`,t.name),i=JSON.parse(h(r.join(this.path,n),`utf8`)),a=this.recordPath(`agents`,i.id);if(t.name!==`${he(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(f(r.join(this.path,a))){let e=JSON.parse(h(r.join(this.path,a),`utf8`));if(JSON.stringify(e)!==JSON.stringify(i))throw Error(`Conflicting legacy agent record: ${i.id}`)}else e.push({file:a,value:i});e.push({file:n,value:null})}if(e.length===0)return;let i={changes:e};bn(r.join(this.path,`.transaction.json`),i),this.applyJournal(i)}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(h(r.join(this.path,`providers.json`),`utf8`));if(!Array.isArray(e))throw TypeError(`Invalid Foundry providers collection`);let t=/* @__PURE__ */ new Set;for(let n of e){if(!n||typeof n.id!=`string`||t.has(n.id))throw Error(`Invalid or duplicate provider ID`);this.recordPath(`providers`,n.id),t.add(n.id)}return structuredClone(e)}assertLocalSkillPath(e){let t=r.relative(this.path,e);if(!Er(t))throw Error(`Invalid skill entry path`);let n=this.path;for(let e of t.split(r.sep)){n=r.join(n,e);try{if(p(n).isSymbolicLink())throw Error(`Cannot write through symbolic links in skill storage`)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;break}}}applyJournal(e){for(let t of e.changes){if(t.tree!==void 0){this.applyTreeChange(t);continue}let e=r.resolve(this.path,t.file),n=r.relative(this.path,e);if(t.bytes!==void 0){if(!Er(n)||typeof t.bytes!=`string`||Object.keys(t).some(e=>![`file`,`bytes`].includes(e)))throw Error(`Invalid skill file journal`);this.assertLocalSkillPath(e),Sn(e,x.from(t.bytes,`base64`))}else if(t.createDirectory||t.removeEntry){if(!Er(n)||t.value!==void 0||t.text!==void 0||t.moveTo!==void 0||t.removeDirectory||t.createDirectory&&t.removeEntry)throw Error(`Invalid skill entry journal`);this.assertLocalSkillPath(e),t.createDirectory?j(e):(_(e,{recursive:!0,force:!0}),M(r.dirname(e)))}else if(t.moveTo!==void 0||t.removeDirectory!==void 0)this.applyDirectoryChange(t,n);else{if(n.startsWith(`..`)||r.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|[a-z][a-z-]*[/\\][a-f0-9]{64}\.json|agents[/\\][a-z0-9]+(?:-[a-z0-9]+)*\.json)$/u.test(n)&&!Tr(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(Er(n)&&this.assertLocalSkillPath(e),t.value===null)_(e,{force:!0}),M(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);xn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else bn(e,t.value)}}let t=e.agentInstructions??[];for(let e of t){let t=yn(this.agentHomeDirectory).find(({id:t})=>t===e.agentId);if(!t||typeof e.enabled!=`boolean`||!Array.isArray(e.contents)||e.contents.some(e=>typeof e!=`string`))throw Error(`Invalid agent instruction journal`);N(t,e.contents,!e.enabled)}let n=e.skillLinks?Array.isArray(e.skillLinks)?e.skillLinks:[e.skillLinks]:[];for(let e of n)this.skillLinks.apply(e);_(r.join(this.path,`.transaction.json`),{force:!0}),M(this.path)}validateTree(e,t){if(![`instructions`,`skill`,`agents`].includes(e)||!Array.isArray(t))throw Error(`Invalid storage replacement tree`);let n=/* @__PURE__ */ new Map;for(let e of t){if(!E(e.path)||n.has(e.path)||e.contents!==null&&typeof e.contents!=`string`)throw Error(`Invalid storage tree entry`);n.set(e.path,e.contents)}for(let e of n.keys()){let t=e.split(`/`);for(let e=1;e<t.length;e++){let r=t.slice(0,e).join(`/`);if(n.has(r)&&n.get(r)!==null)throw Error(`File occupies a storage tree directory`)}}}applyTreeChange(e){let t=e.tree;if(this.validateTree(e.file,t),Object.keys(e).some(e=>![`file`,`tree`].includes(e)))throw Error(`Invalid storage tree journal`);let n=r.join(this.path,`.replace-${e.file}`);_(n,{recursive:!0,force:!0}),j(n);for(let e of t){let t=r.join(n,...e.path.split(`/`));e.contents===null?j(t):Sn(t,x.from(e.contents,`base64`))}let i=r.join(this.path,e.file);_(i,{recursive:!0,force:!0}),ie(n,i),M(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!wr(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!wr(t)||e.value!==void 0||e.text!==void 0||e.moveTo!==void 0&&e.removeDirectory!==void 0)throw Error(`Invalid storage directory journal`);let n=r.join(this.path,t);if(e.moveTo!==void 0){let t=r.join(this.path,this.skillDirectory(e.moveTo));if(f(n)){if(!p(n).isDirectory()||p(n).isSymbolicLink()||f(t))throw Error(`Invalid storage directory move`);ie(n,t)}else if(!f(t)||!p(t).isDirectory()||p(t).isSymbolicLink())throw Error(`Missing storage directory move`)}else if(e.removeDirectory===!0)_(n,{recursive:!0,force:!0});else throw Error(`Invalid storage directory journal`);M(r.dirname(n))}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=r.join(this.path,t);if(!f(e))return;n=JSON.parse(h(e,`utf8`))}let i=n;if(this.recordPath(e,i.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(i)}replaceTree(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.validateTree(e,t),this.directoryChanges.push({file:e,tree:structuredClone(t)})}syncAgentInstructions(e){if(!this.changes)throw Error(`Storage writes require a transaction`);for(let t of e){let e=yn(this.agentHomeDirectory).find(({id:e})=>e===t.agentId);if(!e)throw Error(`Unknown agent`);Mn(e)}this.agentInstructionChanges.push(...structuredClone(e))}linkedSkillNames(){return this.locked(()=>this.skillLinks.linkedNames())}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(g(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>r.relative(this.path,r.join(t,e.name))));if(this.changes){let e=r.relative(this.path,t);for(let t of this.changes.keys())r.dirname(t)===e&&n.add(t)}let i=[];for(let t of n){let n=this.readRecord(e,t);n&&i.push(n)}return i})}get(e,t){return this.locked(()=>{let n=this.recordPath(e,t);return e===`providers`?this.all(e).find(e=>e.id===t):this.readRecord(e,n)})}readSettings(){return this.locked(()=>{if(this.changes?.has(`settings.json`))return dt(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return f(e)?dt(JSON.parse(h(e,`utf8`))):structuredClone(ut)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);let n=this.recordPath(e,t.id);if(e===`providers`){let n=this.all(e),r=n.findIndex(e=>e.id===t.id);r===-1?n.push(t):n[r]=t,this.changes.set(`providers.json`,structuredClone(n))}else this.changes.set(n,structuredClone(t))}remove(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(this.recordPath(e,t),null)}putTextFile(e,t){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),t)}createSkillFolder(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),createDirectory:!0})}putSkillFile(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),bytes:t})}removeSkillEntry(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),removeEntry:!0})}removeTextFile(e){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),null)}moveSkillDirectory(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),moveTo:this.skillDirectory(t)})}removeSkillDirectory(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),removeDirectory:!0})}syncAgentSkillLinks(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.skillLinks.validate(e),this.skillLinkChanges.push(structuredClone(e))}listSkillAgents(){return this.skillLinks.targets()}discoverLinkedSkillAgents(e){return this.locked(()=>this.skillLinks.assignedAgentIds(e))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,dt(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map,this.textChanges=/* @__PURE__ */ new Map,this.directoryChanges=[];let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);let i=[...this.directoryChanges,...[...this.changes].map(([e,t])=>({file:e,value:t})),...[...this.textChanges].map(([e,t])=>t===null?{file:e,value:t}:{file:e,text:t})];if(i.length>0||this.skillLinkChanges.length>0||this.agentInstructionChanges.length>0){let e={changes:i,skillLinks:this.skillLinkChanges,agentInstructions:this.agentInstructionChanges};bn(r.join(this.path,`.transaction.json`),e),t={value:n},this.applyJournal(e)}return n}catch(e){if(t)return this.recover(),t.value;throw e}finally{this.changes=null,this.textChanges=null,this.directoryChanges=null,this.skillLinkChanges=[],this.agentInstructionChanges=[]}})}close(){this.closed=!0}};function kr(e=$e(),t){let n=new Or(e,t);try{return n.transaction(()=>{let t=n.readSettings();f(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function Ar(){return et(),kr()}async function G(e){let t;try{let n=Ar(),r=new Ln(n);t={storage:n,agentsService:new Rn(n,r),settingsService:new St(n),settingsSkillCopyService:new wt,dataExportService:new Zt(n),dataImportService:new xr(n),instructionsService:r,skillsService:new or(n)},Mr(await e(t))}catch(e){let t=Nr(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function jr(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new K(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var K=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Mr(e){console.log(JSON.stringify(e,null,2))}function Nr(e){return e instanceof Error?{code:Pr(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Pr(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Fr={type:`positional`,description:`Agent ID with Skills support: ${w.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function Ir(t){return e({meta:{name:t?`assign`:`unassign`,description:t?`Assign one skill and create or repair its agent symlink; preserve other assignments`:`Unassign one skill and unlink its matching agent entry; preserve other assignments`},args:{agent:Fr,skill:{type:`string`,description:`Existing skill name`,required:!0}},run({args:e}){return G(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const Lr=e({meta:{name:`skills`,description:`Inspect, assign, or unassign skills through registered agent symlinks`},subCommands:{list:e({meta:{name:`list`,description:`List agents, skill directories, and saved skill names as JSON`},args:{agent:{...Fr,required:!1}},run({args:e}){return G(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new Bn(e.agent);return n.agents.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({...e,skillNames:n.skills.filter(({agentIds:t})=>t.includes(e.id)).map(({name:e})=>e)}))})}}),assign:Ir(!0),unassign:Ir(!1)}}),Rr=w.list().map(({id:e})=>e).join(`, `),q={type:`positional`,description:`Agent ID: ${Rr}`,required:!0},zr=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return G(({agentsService:e})=>e.list())}}),Br=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...q,description:`Optional agent ID: ${Rr}`,required:!1}},run({args:e}){return G(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new K(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${Rr}`);let i=new Map(n.list().map(e=>[e.id,e.name]));return r.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({id:e.id,name:e.name,instructionFile:e.instructionFile,enabled:e.enabled,instructions:e.instructionIds.map(e=>({id:e,name:i.get(e)??null}))}))})}}),Vr=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:q,instructions:{type:`string`,description:`Comma-separated instruction IDs in block order; pass an empty string to clear`,valueHint:`id1,id2`,required:!0}},run({args:e}){return G(({agentsService:t})=>{let n=Ke({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Hr=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),Ur=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),Wr=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.reapply(e.agent))}}),Gr=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:q},run({args:e}){return G(({agentsService:t})=>t.openInstructionFile(e.agent))}}),Kr=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:zr,skills:Lr,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:Br,assign:Vr,enable:Hr,disable:Ur,reapply:Wr,open:Gr}})}}),qr=e({meta:{name:`new`,description:`Create an instruction from a name and Markdown content`},args:{name:{type:`string`,description:`Instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.create(en({name:e.name,content:e.content})))}}),Jr=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return G(({instructionsService:e})=>e.list())}}),Yr=e({meta:{name:`get`,description:`Read one instruction by ID as JSON`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.get(e.id))}}),Xr=e({meta:{name:`edit`,description:`Replace an instruction name and Markdown content`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0},name:{type:`string`,description:`New instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`New Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.update(e.id,en({name:e.name,content:e.content})))}}),Zr=e({meta:{name:`delete`,description:`Delete an instruction and remove it from every agent`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return G(({instructionsService:t})=>t.delete(e.id))}}),Qr=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:qr,list:Jr,get:Yr,edit:Xr,delete:Zr}});function $r(e){if(!ti(e)||!Array.isArray(e.targets))throw new ei(`targets must be an array`);if(e.targets.length===0)throw new ei(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!st.includes(e))throw new ei(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var ei=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ni=e({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return G(async({dataExportService:t})=>{let n=await t.createExport(jr(e.passphrase)),r=ii(e.output);return await ai(n.contents,r,e.force),{filePath:r}})}}),ri=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},"apply-agents":{type:`boolean`,description:`Apply imported agent instructions and skill links to this machine; otherwise clear imported agent configuration`,default:!1},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return G(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),jr(e.passphrase));return t.completeImport({apply:e[`apply-agents`],agentRevision:n.agentRevision}),{status:`imported`}})}});function ii(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,i=r.resolve(n);return i.toLowerCase().endsWith(`.foundry-backup`)?i:`${i}.foundry-backup`}async function ai(e,t,n){await Se(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${y()}.tmp`);try{if(await ke(a,e,{mode:384}),i.platform!==`win32`&&await ve(a,384),n){await De(a,t);return}if(f(t))throw oi(t);try{await be(a,t)}catch(e){throw si(e)?oi(t):e}}finally{await b(a,{force:!0})}}function oi(e){return new K(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function si(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const J={"color-theme":{field:`theme`,values:tt},language:{field:`language`,values:nt},"time-zone":{field:`timezone`,values:it},"time-format":{field:`timeFormat`,values:rt}},ci=[...Object.keys(J),`config-folder`],li=Object.entries(J).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
11
+ `);function ui(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const di=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${ci.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return G(({settingsService:t})=>{let n=ui(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new K(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${ci.join(`, `)}`);return n[e.key]})}}),fi=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(J).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${li}`,required:!0}},run({args:e}){return G(({settingsService:t})=>{if(e.key===`config-folder`)throw new K(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(J,e.key))throw new K(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(J).join(`, `)}`);let n=J[e.key];if(!n.values.includes(e.value))throw new K(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=ui(t.update(ft({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),pi=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return G(({settingsService:e})=>e.openConfigFolder())}}),mi=e({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return G(({settingsSkillCopyService:t})=>{let n=$r({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),hi=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:di,set:fi,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:pi}}),export:ni,import:ri,"download-skill":mi}}),gi={type:`positional`,description:`Current skill name`,required:!0},_i=e({meta:{name:`manual`,description:`Create skill metadata with an empty Markdown body in ~/.foundry/skill/<name>/SKILL.md`},args:{name:{type:`string`,description:`Unique name: 1–64 Unicode letters or digits, lowercase where applicable, with single hyphens between words`,valueHint:`hello`,required:!0},description:{type:`string`,description:`When an agent should use this skill (1–1024 characters)`,valueHint:`text`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),vi=e({meta:{name:`local`,description:`Import one local skill folder or .skill/.zip archive; discover skills only at the archive root or its immediate child folders`},args:{path:{type:`positional`,description:`One folder containing root SKILL.md, or one .skill/.zip file. Relative paths resolve from the current directory. Metadata name determines the destination; existing names are never overwritten. Prints { imported, skipped } as JSON.`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.importLocal({path:r.resolve(e.path)}))}}),yi=e({meta:{name:`skills`,description:`Manage skills in the Foundry library`},subCommands:{list:e({meta:{name:`list`,description:`List all skill names and descriptions as JSON`},run(){return G(({skillsService:e})=>e.list().map(({name:e,description:t})=>({name:e,description:t})))}}),get:e({meta:{name:`get`,description:`Read skill metadata and the complete nested files tree as JSON`},args:{skill:gi},run({args:e}){return G(({skillsService:t})=>t.detail(e.skill))}}),save:e({meta:{name:`save`,description:`Replace the complete skill files tree; omitted entries are deleted and metadata is preserved`},args:{skill:gi,file:{type:`string`,description:`JSON file containing { files }, or - for stdin. Accepts get output; only files is applied. SKILL.md is required; its content excludes frontmatter. Null content preserves existing opaque files.`,valueHint:`path|-`,required:!0}},run({args:e}){return G(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new I(`Pipe JSON to stdin or provide a JSON file with --file`);let n=h(e.file===`-`?0:r.resolve(e.file),`utf8`),a;try{a=JSON.parse(n)}catch{throw new I(`Skill files input must be valid JSON`)}let o=Kn(a);return t.saveFiles(e.skill,o.files)})}}),edit:e({meta:{name:`edit`,description:`Update skill metadata and refresh links in assigned agent skill directories`},args:{skill:{type:`positional`,description:`Current skill name`,required:!0},name:{type:`string`,description:`New unique skill name`,required:!0},description:{type:`string`,description:`New description (1–1024 characters)`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.update(e.skill,{name:e.name,description:e.description}))}}),delete:e({meta:{name:`delete`,description:`Delete a skill and its files, and unlink matching registered agent entries`},args:{skill:{type:`positional`,description:`Skill name to permanently delete`,required:!0}},run({args:e}){return G(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:_i,local:vi}})}});function bi(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Ke(await xi(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Si(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=qe(await xi(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Si(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Si(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Si(t,e)}}),t}async function xi(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Si(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Ci(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return Ti(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(en(await wi(t)));return t.json(n,201)}catch(e){return Ti(t,e)}}),t.put(`/:id`,async t=>{try{let n=en(await wi(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Ti(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Ti(t,e)}}),t}async function wi(e){try{return await e.req.json()}catch{throw new k(`Request body must be valid JSON`)}}function Ti(e,t){if(t instanceof k)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof $t)return e.json({error:{code:t.code,message:t.message}},404);throw t}const Ei=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Di=[`active`,`disabled`,`deleted`];var Y=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function Oi(e){if(!Fi(e))throw new Y(`Provider input must be an object`);let t=X(e.name,`name`),n=Ni(e.protocol),r=Pi(e.baseURL),i=e.apiKey===void 0?``:X(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Mi(e.customModels);return{...e.avatar!==void 0&&{avatar:ki(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function ki(e){if(e===null)return null;if(typeof e==`string`&&e.length<=2796236){let t=/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,/u.exec(e);if(t){let n=e.slice(t[0].length),r=n.endsWith(`==`)?2:+!!n.endsWith(`=`);if(n.length>0&&n.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(n)&&n.length/4*3-r<=2097152)return e}}throw new Y(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Ai(e){if(!Fi(e))throw new Y(`Provider connection must be an object`);return{protocol:Ni(e.protocol),baseURL:Pi(e.baseURL),apiKey:e.apiKey===void 0?``:X(e.apiKey,`apiKey`,{allowEmpty:!0})}}function ji(e){if(typeof e!=`string`||!Di.includes(e))throw new Y(`Invalid provider status`);return e}function Mi(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Y(`customModels must be an array`);return e.map(e=>{if(!Fi(e))throw new Y(`Each custom model must be an object`);return{id:X(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:X(e.displayName,`customModels.displayName`)}})}function Ni(e){if(typeof e!=`string`||!Ei.includes(e))throw new Y(`Invalid provider protocol`);return e}function Pi(e){let t=X(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new Y(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function X(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new Y(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new Y(`${t} is required`);return r}function Fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Z=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Ii(e,t=fetch){let n={accept:`application/json`};e.protocol===`anthropic-messages`?(n[`anthropic-version`]=`2023-06-01`,e.apiKey&&(n[`x-api-key`]=e.apiKey)):n.authorization=`Bearer ${e.apiKey||`local-provider`}`;let r;try{r=await t(Li(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new Z(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new Z(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new Z(`Provider returned invalid JSON`)}return Ri(i)}function Li(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function Ri(e){if(!Bi(e)||!Array.isArray(e.data))throw new Z(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Bi(e)||typeof e.id!=`string`||e.id.length===0)throw new Z(`Provider returned an invalid model entry`);let t=zi(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function zi(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Vi=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Hi=class{storage;constructor(e){this.storage=e}list(){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt-e.updatedAt).map(e=>Ui(e))}get(e){let t=this.storage.get(`providers`,e);return t?Ui(t):null}getConnection(e){let t=this.storage.get(`providers`,e);return t&&t.status!==`deleted`?{protocol:t.protocol,baseURL:t.baseURL,apiKey:t.apiKey}:null}save(e,t){return this.storage.transaction(()=>{let n=t?this.storage.get(`providers`,t):void 0;if(t&&!n)throw new Vi;let r=Date.now(),i={id:t??y(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Ui(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new Vi;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),Ui(i)})}};function Ui(e){return{...e,avatar:e.avatar??null,status:e.status}}function Wi(e,t=()=>{}){let n=new S;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return Ki(t,e)}}),n.post(`/models`,async t=>{try{let n=Ai(await Gi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return Ki(t,e)}}),n.post(`/`,async n=>{try{let r=Oi(await Gi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return Ki(n,e)}}),n.put(`/:id`,async n=>{try{let r=Oi(await Gi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return Ki(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Gi(n),i=ji(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return Ki(n,e)}}),n}async function Gi(e){try{return await e.req.json()}catch{throw new Y(`Request body must be valid JSON`)}}function Ki(e,t){if(t instanceof Y)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Vi)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Z)return e.json({error:{code:t.code,message:t.message}},502);throw t}var qi=class{repository;constructor(e){this.repository=new Hi(e)}list(){return this.repository.list()}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Vi;return Ii(t)}fetchModelsForConnection(e){return Ii(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function Ji(e,t=()=>{},n=new wt){let r=new S;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=ft(await Yi(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Xi(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=$r(await Yi(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Xi(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Yi(e){try{return await e.req.json()}catch{throw new ht(`Request body must be valid JSON`)}}function Xi(e,t){if(t instanceof ht||t instanceof ei)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Tt)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Zi(e){let t=new S;return t.post(`/import/local`,Ve({maxSize:16384,onError:e=>e.json({error:{code:`INVALID_SKILL_IMPORT`,message:`Import requires a local source path`}},400)}),async t=>{try{let n=await e.importLocal(await Qi(t));return t.json(n,n.imported.length>0?201:200)}catch(e){return Q(t,e)}}),t.get(`/agents/assignments`,t=>t.json(e.assignments())),t.put(`/:name/agents/:id`,async t=>{try{let n=Jn(await Qi(t));return t.json(e.setAssignment(t.req.param(`name`),t.req.param(`id`),n.assigned))}catch(e){return Q(t,e)}}),t.get(`/`,t=>t.json(e.list())),t.get(`/:name`,t=>{try{return t.json(e.detail(t.req.param(`name`)))}catch(e){return Q(t,e)}}),t.post(`/`,async t=>{try{let n=await Qi(t);return t.json(e.create(z(n)),201)}catch(e){return Q(t,e)}}),t.put(`/:name`,async t=>{try{let n=await Qi(t);if(n&&typeof n==`object`&&`files`in n){let r=Kn(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),z(n)))}catch(e){return Q(t,e)}}),t.delete(`/:name`,t=>{try{return e.delete(t.req.param(`name`)),t.body(null,204)}catch(e){return Q(t,e)}}),t}async function Qi(e){try{return await e.req.json()}catch{throw new I(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof L)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof Bn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Vn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof I)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Yn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof R)return e.json({error:{code:t.code,message:t.message}},404);throw t}function $i(e){let t=new S;return t.get(`/`,t=>He(t,async n=>{await ea(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||ta(n,e)}),c=setInterval(()=>{r||na(n)},15e3),l=()=>{o()};t.req.raw.signal.addEventListener(`abort`,l,{once:!0}),n.onAbort(o),t.req.raw.signal.aborted&&o(),await i,clearInterval(c),s(),t.req.raw.signal.removeEventListener(`abort`,l)})),t}function ea(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function ta(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function na(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var ra=class extends Error{code=`INVALID_EXPORT_INPUT`};function ia(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new ra(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function aa(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new ra(`Request body must be valid JSON`)}let{passphrase:r}=ia(n),i=await e.createExport(r);return t.body(i.contents,200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${i.fileName}"`,"cache-control":`no-store`})}catch(e){return e instanceof ra?t.json({error:{code:e.code,message:e.message}},400):t.json({error:{code:`DATA_EXPORT_FAILED`,message:`Unable to export data`}},500)}}),t}function oa(e,t){let n=new S;return n.post(`/`,async n=>{let i;try{if(n.req.header(`content-type`)?.split(`;`,1)[0].trim()!==`application/octet-stream`||!n.req.raw.body)throw new V(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new V(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new V(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await Ce(r.join(fe(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await je(Pe.fromWeb(n.req.raw.body),d(o,{mode:384}));let s=await e.importData(o,a);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json(s)}catch(e){return e instanceof V?n.json({error:{code:e.code,message:e.message}},e.code===`IMPORT_FAILED`?500:400):n.json({error:{code:`IMPORT_FAILED`,message:`Unable to import data`}},500)}finally{i&&await Jt(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new V(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(lr(n)),t.json({status:`completed`})}catch(e){if(e instanceof V){let n=e.code===`IMPORT_CHANGED`?409:e.code===`AGENT_APPLY_FAILED`||e.code===`IMPORT_FAILED`?500:400;return t.json({error:{code:e.code,message:e.message}},n)}return t.json({error:{code:`IMPORT_FAILED`,message:`Unable to complete import`}},500)}}),n}var $=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function sa(e){if(!e||typeof e!=`object`||!(`kind`in e)||e.kind!==`file`&&e.kind!==`directory`&&e.kind!==`file-or-directory`)throw new $(`INVALID_FILE_PICKER_INPUT`,`kind must be file, directory, or file-or-directory`,400);let t={kind:e.kind};if(`title`in e){if(typeof e.title!=`string`||e.title.length>200||/\p{Cc}/u.test(e.title))throw new $(`INVALID_FILE_PICKER_INPUT`,`title must be at most 200 characters without control characters`,400);t.title=e.title}if(`extensions`in e){if(!Array.isArray(e.extensions)||e.extensions.length>20||e.extensions.some(e=>typeof e!=`string`||!/^[a-z0-9]{1,16}$/iu.test(e)))throw new $(`INVALID_FILE_PICKER_INPUT`,`extensions must contain file extensions without leading dots`,400);t.extensions=[...new Set(e.extensions)]}return t}const ca=Ue(a);function la(e){return`
12
+ $ErrorActionPreference = 'Stop'
13
+ $options = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${x.from(JSON.stringify(e)).toString(`base64`)}')) | ConvertFrom-Json
14
+ Add-Type -AssemblyName System.Windows.Forms
15
+ $dialog = $null
16
+ $owner = New-Object System.Windows.Forms.Form
17
+ $owner.TopMost = $true
18
+ try {
19
+ if ($options.kind -eq 'directory') {
20
+ $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
21
+ $dialog.Description = $options.title
22
+ $dialog.ShowNewFolderButton = $false
23
+ } else {
24
+ $dialog = New-Object System.Windows.Forms.OpenFileDialog
25
+ $dialog.Title = $options.title
26
+ $dialog.Multiselect = $false
27
+ $dialog.CheckFileExists = $true
28
+ if ($options.extensions.Count -gt 0) {
29
+ $patterns = ($options.extensions | ForEach-Object { '*.' + $_ }) -join ';'
30
+ $dialog.Filter = 'Files (' + $patterns + ')|' + $patterns
31
+ }
32
+ }
33
+ $selected = $null
34
+ if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) {
35
+ if ($options.kind -eq 'directory') { $selected = $dialog.SelectedPath }
36
+ else { $selected = $dialog.FileName }
37
+ }
38
+ [Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
39
+ [Console]::Out.Write((@{ path = $selected } | ConvertTo-Json -Compress))
40
+ } finally {
41
+ if ($null -ne $dialog) { $dialog.Dispose() }
42
+ $owner.Dispose()
43
+ }
44
+ `}function ua(e){return e instanceof Error?Reflect.get(e,`code`):void 0}async function da(e){let t=[`--file-selection`];e.title&&t.push(`--title=${e.title}`),e.kind===`directory`?t.push(`--directory`):e.extensions?.length&&t.push(`--file-filter=${e.extensions.map(e=>`*.${e}`).join(` `)}`);try{let{stdout:e}=await ca(`zenity`,t);return{path:e.replace(/\r?\n$/u,``)||null}}catch(e){if(ua(e)===1)return{path:null};if(ua(e)!==`ENOENT`)throw e}let n=[e.kind===`directory`?`--getexistingdirectory`:`--getopenfilename`,`.`];e.kind===`file`&&e.extensions?.length&&n.push(e.extensions.map(e=>`*.${e}`).join(` `)),e.title&&n.push(`--title`,e.title);try{let{stdout:e}=await ca(`kdialog`,n);return{path:e.replace(/\r?\n$/u,``)||null}}catch(e){if(ua(e)===1)return{path:null};throw e}}async function fa(e){try{if(e.kind===`file-or-directory`&&i.platform!==`darwin`)throw new $(`FILE_PICKER_UNAVAILABLE`,`Combined file and directory selection is currently supported on macOS`,503);if(i.platform===`linux`)return await da(e);let t;if(i.platform===`darwin`)({stdout:t}=await ca(`osascript`,[`-l`,`JavaScript`,`-e`,`
45
+ ObjC.import('AppKit');
46
+ function createPanel(options) {
47
+ var panel = $.NSOpenPanel.openPanel;
48
+ panel.canChooseFiles = options.kind !== 'directory';
49
+ panel.canChooseDirectories = options.kind !== 'file';
50
+ panel.allowsMultipleSelection = false;
51
+ panel.resolvesAliases = true;
52
+ if (options.title) panel.title = options.title;
53
+ if (options.kind !== 'directory' && options.extensions && options.extensions.length) {
54
+ // AppKit applies this filter to selectable directories too.
55
+ panel.allowedFileTypes = options.kind === 'file-or-directory'
56
+ ? options.extensions.concat(['public.folder'])
57
+ : options.extensions;
58
+ }
59
+ return panel;
60
+ }
61
+ function run(argv) {
62
+ var app = $.NSApplication.sharedApplication;
63
+ app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);
64
+ var panel = createPanel(JSON.parse(argv[0]));
65
+ app.activateIgnoringOtherApps(true);
66
+ var selected = panel.runModal === $.NSModalResponseOK;
67
+ return JSON.stringify({ path: selected ? ObjC.unwrap(panel.URL.path) : null });
68
+ }
69
+ `,JSON.stringify(e)]));else if(i.platform===`win32`){let n=x.from(la(e),`utf16le`).toString(`base64`);({stdout:t}=await ca(`powershell.exe`,[`-NoProfile`,`-STA`,`-EncodedCommand`,n],{windowsHide:!0,encoding:`utf8`}))}else throw new $(`FILE_PICKER_UNAVAILABLE`,`Native file selection is unavailable on this platform`,503);return JSON.parse(t)}catch(e){throw e instanceof $?e:ua(e)===`ENOENT`?new $(`FILE_PICKER_UNAVAILABLE`,`No native file picker is available`,503):new $(`FILE_PICKER_FAILED`,`Unable to open the native file picker`,500)}}var pa=class{open;isPicking=!1;constructor(e=fa){this.open=e}async pick(e){if(this.isPicking)throw new $(`FILE_PICKER_BUSY`,`A file picker is already open`,409);let t=sa(e);this.isPicking=!0;try{let e=await this.open(t);if(e.path!==null&&(typeof e.path!=`string`||!r.isAbsolute(e.path)||e.path.includes(`\0`)))throw new $(`FILE_PICKER_FAILED`,`The native file picker returned an invalid path`,500);return{path:e.path}}finally{this.isPicking=!1}}};function ma(e){let t=new S;return t.post(`/`,Ve({maxSize:4096,onError:e=>e.json({error:{code:`INVALID_FILE_PICKER_INPUT`,message:`File picker options are too large`}},400)}),async t=>{try{let n;try{n=await t.req.json()}catch{throw new $(`INVALID_FILE_PICKER_INPUT`,`Request body must be valid JSON`,400)}return t.json(await e.pick(sa(n)))}catch(e){return e instanceof $?t.json({error:{code:e.code,message:e.message}},e.status):t.json({error:{code:`FILE_PICKER_FAILED`,message:`Unable to open the native file picker`}},500)}}),t}function ha(e){return e===`/api`||e.startsWith(`/api/`)}function ga(e,t={}){let n=new S,r=t.providerService??new qi(e),i=t.settingsService??new St(e),a=t.settingsSkillCopyService??new wt,o=t.instructionsService??new Ln(e),s=t.agentsService??new Rn(e,o);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Ge,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,$i(t.eventHub)),n.route(`/api/file-picker`,ma(t.filePickerService??new pa)),n.route(`/api/data-import`,oa(t.dataImportService??new xr(e),()=>{t.eventHub?.publish(ot,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,aa(t.dataExportService??new Zt(e))),n.route(`/api/agents`,bi(s)),n.route(`/api/skills`,Zi(t.skillsService??new or(e))),n.route(`/api/instructions`,Ci(o)),n.route(`/api/providers`,Wi(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Ji(i,e=>{t.eventHub?.publish(ot,e)},a)),n.notFound(e=>ha(e.req.path)?e.json({error:{code:`NOT_FOUND`,message:`API route not found`}},404):e.text(`Not Found`,404)),n.onError((e,t)=>(console.error(e),ha(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function _a(e,t,n){let i=ga(t,n),a=Be({root:e});i.use(`*`,(e,t)=>ha(e.req.path)?t():a(e,t));let o=Be({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!ha(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function va(e,t){let n,r=ce(e,{persistent:!1},(e,r)=>{(r===null||r===`settings.json`)&&(clearTimeout(n),n=setTimeout(t,30),n.unref())});return r.on(`error`,()=>{console.error(`Unable to watch Foundry settings`)}),()=>{clearTimeout(n),r.close()}}var ya=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:y(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function ba(e){let t=new ya,n=new Zt(e),r=new xr(e),i=new Ln(e),a=new Rn(e,i),o=new qi(e),s=new St(e),c=new wt,l=new or(e),u=new pa,d={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u},f;return{services:d,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u,eventHub:t},start(){f??=va(e.path,()=>{t.publish(ot,{fields:[]})})},stop(){f?.(),f=void 0}}}const{dirname:xa,join:Sa,resolve:Ca}=r,wa=xa(Ae(import.meta.url));function Ta(){let e=[Ca(wa,`web`),Ca(i.cwd(),`dist/web`)].find(e=>f(Sa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ea({storage:e,webRoot:t=Ta(),onListening:n}){let r=ba(e),a=_a(t,e,r.apiOptions);r.start();let o=ze({fetch:a.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return o.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),i.exitCode=1}),o.on(`close`,r.stop),o}function Da(e,t){return new Promise((n,r)=>{let i=We();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function Oa(e){let t=`xdg-open`,n=[e];i.platform===`darwin`?t=`open`:i.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=o(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ka=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await Da(`127.0.0.1`,11111)}catch(e){Aa(e);return}Ea({storage:Ar(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Oa(t)}})}});function Aa(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function ja(){let t,r=e({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await n(t)}});return t=e({meta:{name:`foundry`,version:Ge,description:`Manage Foundry settings, instructions, and skills or start the Web UI`},default:`help`,subCommands:{help:r,web:ka,settings:hi,instructions:Qr,agents:Kr,skills:yi}}),t}t(ja());export{};