@dhzh/foundry 9.2.0 → 10.0.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,14 +1,14 @@
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{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 oe,symlinkSync as se,unlinkSync as ce,watch as le,writeFileSync as ue}from"node:fs";import de,{homedir as fe,tmpdir as pe}from"node:os";import{createCipheriv as me,createDecipheriv as he,createHash as ge,randomBytes as _e,randomUUID as v,scrypt as ve}from"node:crypto";import{chmod as ye,cp as be,link as xe,lstat as Se,mkdir as Ce,mkdtemp as we,open as Te,readFile as y,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=`9.2.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(de.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=fe()}={}){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}-${v()}.tmp`),o=r.join(n,`.${D}-${v()}.backup`);try{return await Ce(n,{recursive:!0}),await be(t,a,{recursive:!0,errorOnExist:!0}),await At(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 getStatus(){let e=this.configuredSkillRoot??Et();return{version:Ge,targets:await Array.fromAsync(st,async t=>{let n=r.join(this.getTargetParent(t),D);return{target:t,destination:n,status:await Dt(e,n)}})}}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){try{if(!(await Se(t)).isDirectory())return`outdated`}catch(e){return kt(e)?`missing`:`outdated`}try{return await Ot(e,t)?`current`:`outdated`}catch{return`outdated`}}async function Ot(e,t){let[n,i]=await Promise.all([Ee(e,{withFileTypes:!0}),Ee(t,{withFileTypes:!0})]);if(n.length!==i.length)return!1;let a=new Map(i.map(e=>[e.name,e]));for(let i of n){let n=a.get(i.name);if(n?.isDirectory()!==i.isDirectory()||n.isFile()!==i.isFile()||i.isSymbolicLink()||n.isSymbolicLink())return!1;let o=r.join(e,i.name),s=r.join(t,i.name);if(i.isDirectory()){if(!await Ot(o,s))return!1}else if(i.isFile()){let[e,t]=await Promise.all([y(o),y(s)]);if(!e.equals(t))return!1}else return!1}return!0}function kt(e){return typeof e==`object`&&!!e&&Reflect.get(e,`code`)===`ENOENT`}async function At(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 O={instructions:`instructions`,skills:`skills`,agents:`agents`},jt=[O.instructions,O.skills,O.agents];function Mt(e){return jt.includes(e)}const Nt=`manifest.json`,Pt=jt.map(e=>`${e}/`),Ft=new RegExp(String.raw`^${O.instructions}/[a-f0-9-]+\.md$`,`u`),It=new RegExp(String.raw`^${O.agents}/[a-z0-9-]+\.json$`,`u`);function Lt(e){if([Nt,`data/foundry.json`,`settings.json`,...Pt].includes(e)||Ft.test(e)||It.test(e))return!0;let[t,n,...r]=e.replace(/\/$/u,``).split(`/`);return t===O.skills&&!!n&&n===n.trim()&&T(n)&&(r.length===0?e.endsWith(`/`):E(r.join(`/`)))}async function Rt(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 zt(e,t){let n=await Bt(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(!Lt(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 Ce(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await Ce(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await je(await Vt(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(Nt))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Bt(e){return new Promise((t,n)=>{Me.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Vt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Ht=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=x.from(`FOUNDRYX`,`ascii`),Ut=`aes-256-gcm`,Wt=`scrypt`,Gt={N:131072,r:8,p:1};async function Kt(e,t,n){let r=_e(16),i=_e(12),a={version:1,cipher:Ut,kdf:{name:Wt,salt:r.toString(`base64`),...Gt,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=Jt(o.byteLength),c=x.concat([s,o]),l=await Yt(n,r,Gt);try{let n=await Te(t,`w`,384);try{await n.write(c)}finally{await n.close()}await je(u(e),Xt(l,i,c),d(t,{flags:`r+`,mode:384,start:c.byteLength})),await ye(t,384)}catch(e){throw await b(t,{force:!0}),new Ht(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{l.fill(0)}}async function qt(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 Te(e,`r`),o,s,c;try{if(o=await $t(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 $t(a,e,13),c=await $t(a,16,i-16)}finally{await a.close()}let l=Qt(JSON.parse(s.toString(`utf8`)));r=await Yt(n,l.salt,l.header.kdf);let f=x.concat([o,s]);await je(u(e,{start:13+s.byteLength,end:i-16-1}),Zt(r,l.nonce,f,c),d(t,{mode:384})),await ye(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Ht?e:new Ht(tn(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,tn(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 Jt(e){let t=x.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Yt(e,t,n){return new Promise((r,i)=>{ve(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Xt(e,t,n){let r=me(Ut,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 Zt(e,t,n,r){let i=he(Ut,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 Qt(e){if(!en(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Ut||!en(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Wt||typeof t.salt!=`string`||t.N!==Gt.N||t.r!==Gt.r||t.p!==Gt.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:Ut,kdf:{name:Wt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function $t(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 en(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tn(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function nn(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function rn(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`&&Mt(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!Lt(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 jt)n(e);return t})}function an(e){return ge(`sha256`).update(e).digest(`hex`)}var on=class{storage;constructor(e){this.storage=e}async createExport(e){let t=rn(this.storage),n=await we(r.join(pe(),`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:4,appVersion:Ge,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:an(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 Rt([{entryPath:`manifest.json`,filePath:a},...l],o),await Kt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await y(s)}}finally{await nn(n)}}};const sn=/^[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`}},cn=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function ln(e){if(!un(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 un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const dn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function fn(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=wn(t,r.id),a=_n(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function pn(e){return e.transaction(()=>{let t=Cn(e),n;try{n=g(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(Tn(e))return[];throw e}return n.map(e=>yn(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function mn(e,t){return t.transaction(()=>{if(!sn.test(e))return;let n=`${e}.md`;try{return yn(r.join(Cn(t),n),n)}catch(e){if(Tn(e))return;throw e}})}function hn(e,t,n){return n.transaction(()=>{let r=mn(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(wn(n,i.id),_n(i)),i})}function gn(e,t){if(!sn.test(e))return`missing`;let n=Cn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>f(i)?(t.removeTextFile(i),`removed`):`missing`)}function _n(e){return`---\n${Re({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function vn(e,t){let n=dn.exec(e);if(!n)throw j(t);let r=bn(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 ee,existsSync as d,fsyncSync as te,lstatSync as f,mkdirSync as p,openSync as ne,readFileSync as m,readdirSync as h,readlinkSync as re,realpathSync as ie,renameSync as ae,rmSync as g,rmdirSync as oe,statSync as _,symlinkSync as se,unlinkSync as ce,watch as le,writeFileSync as ue}from"node:fs";import de,{homedir as fe,tmpdir as pe}from"node:os";import{createCipheriv as me,createDecipheriv as he,createHash as ge,randomBytes as _e,randomUUID as v,scrypt as ve}from"node:crypto";import{chmod as ye,cp as be,link as xe,lstat as Se,mkdir as Ce,mkdtemp as we,open as Te,readFile as y,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=`10.0.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(de.homedir(),`.foundry`)}function et(){let e=$e();return p(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=fe()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Et();if(!d(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}-${v()}.tmp`),o=r.join(n,`.${D}-${v()}.backup`);try{return await Ce(n,{recursive:!0}),await be(t,a,{recursive:!0,errorOnExist:!0}),await At(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 getStatus(){let e=this.configuredSkillRoot??Et();return{version:Ge,targets:await Array.fromAsync(st,async t=>{let n=r.join(this.getTargetParent(t),D);return{target:t,destination:n,status:await Dt(e,n)}})}}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=>d(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){try{if(!(await Se(t)).isDirectory())return`outdated`}catch(e){return kt(e)?`missing`:`outdated`}try{return await Ot(e,t)?`current`:`outdated`}catch{return`outdated`}}async function Ot(e,t){let[n,i]=await Promise.all([Ee(e,{withFileTypes:!0}),Ee(t,{withFileTypes:!0})]);if(n.length!==i.length)return!1;let a=new Map(i.map(e=>[e.name,e]));for(let i of n){let n=a.get(i.name);if(n?.isDirectory()!==i.isDirectory()||n.isFile()!==i.isFile()||i.isSymbolicLink()||n.isSymbolicLink())return!1;let o=r.join(e,i.name),s=r.join(t,i.name);if(i.isDirectory()){if(!await Ot(o,s))return!1}else if(i.isFile()){let[e,t]=await Promise.all([y(o),y(s)]);if(!e.equals(t))return!1}else return!1}return!0}function kt(e){return typeof e==`object`&&!!e&&Reflect.get(e,`code`)===`ENOENT`}async function At(e,t,n){let r=d(t);r&&await De(t,n);try{await De(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!d(t)&&d(n)&&await De(n,t),e}}const O={instructions:`instructions`,skills:`skills`,agents:`agents`},jt=[O.instructions,O.skills,O.agents];function Mt(e){return jt.includes(e)}const Nt=`manifest.json`,Pt=jt.map(e=>`${e}/`),Ft=new RegExp(String.raw`^${O.instructions}/[a-f0-9-]+\.md$`,`u`),It=new RegExp(String.raw`^${O.agents}/[a-z0-9-]+\.json$`,`u`);function Lt(e){if([Nt,`data/foundry.json`,`settings.json`,...Pt].includes(e)||Ft.test(e)||It.test(e))return!0;let[t,n,...r]=e.replace(/\/$/u,``).split(`/`);return t===O.skills&&!!n&&n===n.trim()&&T(n)&&(r.length===0?e.endsWith(`/`):E(r.join(`/`)))}async function Rt(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,ee(t,{mode:384}))}async function zt(e,t){let n=await Bt(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(!Lt(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 Ce(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await Ce(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await je(await Vt(n,e),ee(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(Nt))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Bt(e){return new Promise((t,n)=>{Me.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Vt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Ht=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=x.from(`FOUNDRYX`,`ascii`),Ut=`aes-256-gcm`,Wt=`scrypt`,Gt={N:131072,r:8,p:1};async function Kt(e,t,n){let r=_e(16),i=_e(12),a={version:1,cipher:Ut,kdf:{name:Wt,salt:r.toString(`base64`),...Gt,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=Jt(o.byteLength),c=x.concat([s,o]),l=await Yt(n,r,Gt);try{let n=await Te(t,`w`,384);try{await n.write(c)}finally{await n.close()}await je(u(e),Xt(l,i,c),ee(t,{flags:`r+`,mode:384,start:c.byteLength})),await ye(t,384)}catch(e){throw await b(t,{force:!0}),new Ht(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{l.fill(0)}}async function qt(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 Te(e,`r`),o,s,c;try{if(o=await $t(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 $t(a,e,13),c=await $t(a,16,i-16)}finally{await a.close()}let l=Qt(JSON.parse(s.toString(`utf8`)));r=await Yt(n,l.salt,l.header.kdf);let d=x.concat([o,s]);await je(u(e,{start:13+s.byteLength,end:i-16-1}),Zt(r,l.nonce,d,c),ee(t,{mode:384})),await ye(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Ht?e:new Ht(tn(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,tn(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 Jt(e){let t=x.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Yt(e,t,n){return new Promise((r,i)=>{ve(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Xt(e,t,n){let r=me(Ut,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 Zt(e,t,n,r){let i=he(Ut,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 Qt(e){if(!en(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Ut||!en(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Wt||typeof t.salt!=`string`||t.N!==Gt.N||t.r!==Gt.r||t.p!==Gt.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:Ut,kdf:{name:Wt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function $t(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 en(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tn(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function nn(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function rn(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=f(a)}catch(e){if(e.code===`ENOENT`&&Mt(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!Lt(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 jt)n(e);return t})}function an(e){return ge(`sha256`).update(e).digest(`hex`)}var on=class{storage;constructor(e){this.storage=e}async createExport(e){let t=rn(this.storage),n=await we(r.join(pe(),`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:4,appVersion:Ge,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:an(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 Rt([{entryPath:`manifest.json`,filePath:a},...l],o),await Kt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await y(s)}}finally{await nn(n)}}};const sn=/^[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`}},cn=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function ln(e){if(!un(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 un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const dn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function fn(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=wn(t,r.id),a=_n(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function pn(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(Tn(e))return[];throw e}return n.map(e=>yn(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function mn(e,t){return t.transaction(()=>{if(!sn.test(e))return;let n=`${e}.md`;try{return yn(r.join(Cn(t),n),n)}catch(e){if(Tn(e))return;throw e}})}function hn(e,t,n){return n.transaction(()=>{let r=mn(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(wn(n,i.id),_n(i)),i})}function gn(e,t){if(!sn.test(e))return`missing`;let n=Cn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>d(i)?(t.removeTextFile(i),`removed`):`missing`)}function _n(e){return`---\n${Re({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function vn(e,t){let n=dn.exec(e);if(!n)throw j(t);let r=bn(n[1]);if(`${r.id}.md`!==t)throw j(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 yn(e,t){return vn(h(e,`utf8`),t)}function bn(e){let t;try{t=Ie(e)}catch{throw j(`frontmatter`)}if(!En(t))throw j(`frontmatter`);let n=xn(t.id),r=xn(t.name);if(!r||r.length>200||!sn.test(n))throw j(`frontmatter`);return{id:n,name:r,createdAt:Sn(t.createdAt),updatedAt:Sn(t.updatedAt)}}function xn(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,O.instructions)}function wn(e,t){if(!sn.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 Tn(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function En(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dn(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 M(e){m(e,{recursive:!0,mode:448}),i.platform!==`win32`&&s(e,448)}function N(e){if(i.platform===`win32`)return;let t=te(e,`r`);try{ee(t)}finally{c(t)}}function On(e,t){kn(e,`${JSON.stringify(t,null,2)}\n`)}function kn(e,t){An(e,t)}function An(e,t){M(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=te(n,`wx`,384);try{ue(i,t),ee(i)}finally{c(i)}ie(n,e),N(r.dirname(e))}finally{_(n,{force:!0})}}const jn=`<!-- foundry:instructions:start -->`,Mn=`<!-- foundry:instructions:end -->`;function Nn(e,t){let n=Pn(e),r=In(t);return`${n}${Fn(n)}${r}\n`}function Pn(e){let t=``,n=0;for(let r of Ln(e)){let e=Rn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function Fn(e){return!e||e.endsWith(`
4
+ `)&&(i=i.slice(1)),{...r,content:i}}function yn(e,t){return vn(m(e,`utf8`),t)}function bn(e){let t;try{t=Ie(e)}catch{throw j(`frontmatter`)}if(!En(t))throw j(`frontmatter`);let n=xn(t.id),r=xn(t.name);if(!r||r.length>200||!sn.test(n))throw j(`frontmatter`);return{id:n,name:r,createdAt:Sn(t.createdAt),updatedAt:Sn(t.updatedAt)}}function xn(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,O.instructions)}function wn(e,t){if(!sn.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 Tn(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function En(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dn(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 M(e){p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&s(e,448)}function N(e){if(i.platform===`win32`)return;let t=ne(e,`r`);try{te(t)}finally{c(t)}}function On(e,t){kn(e,`${JSON.stringify(t,null,2)}\n`)}function kn(e,t){An(e,t)}function An(e,t){M(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=ne(n,`wx`,384);try{ue(i,t),te(i)}finally{c(i)}ae(n,e),N(r.dirname(e))}finally{g(n,{force:!0})}}const jn=`<!-- foundry:instructions:start -->`,Mn=`<!-- foundry:instructions:end -->`;function Nn(e,t){let n=Pn(e),r=In(t);return`${n}${Fn(n)}${r}\n`}function Pn(e){let t=``,n=0;for(let r of Ln(e)){let e=Rn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function Fn(e){return!e||e.endsWith(`
5
5
  `)?``:`
6
6
  `}function In(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
7
7
 
8
- `);return t?`${jn}\n\n${t}\n\n${Mn}`:`${jn}\n${Mn}`}function Ln(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function Rn(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 zn(e,t){let n=r.dirname(e);m(n,{recursive:!0,mode:448});let a=f(e)?oe(e).mode&511:384,o=`${e}.${v()}.tmp`;try{let r=te(o,`wx`,a);try{i.platform!==`win32`&&s(o,a),ue(r,t),ee(r)}finally{c(r)}ie(o,e),N(n)}finally{_(o,{force:!0})}}function P(e,t,n){let r=f(e.filePath);if(n&&!r)return;let i=r?h(e.filePath,`utf8`):``,a=n?Pn(i):Nn(i,t);zn(e.filePath,a)}function Bn(e){f(e.filePath)&&h(e.filePath,`utf8`)}function F(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}function Vn(e){return e.all(`agents`)}function Hn(e,t){return e.get(`agents`,t)}function Un(e,t){return e.put(`agents`,t),t}function Wn(e,t,n){let r=Vn(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(Dn(n).map(e=>[e.id,e])),a=new Map(pn(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),Un(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Gn=class{storage;homeDirectory;constructor(e,t=de.homedir()){this.storage=e,this.homeDirectory=t}list(){return pn(this.storage)}get(e){let t=mn(e,this.storage);if(!t)throw new cn(e);return t}create(e){return fn(e,this.storage)}update(e,t){let n=hn(e,t,this.storage);if(!n)throw new cn(e);return n}delete(e){return this.storage.transaction(()=>{let t=mn(e,this.storage);if(!t||(Wn(this.storage,e,this.homeDirectory),gn(e,this.storage)===`missing`))throw new cn(e);return t})}},Kn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Gn(e),n=de.homedir(),r=Qe){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=Dn(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(Vn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>qn(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=Hn(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=Un(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return qn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Hn(this.storage,e)??F(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);P(n,e.map(({content:e})=>e),!1)}else P(n,[],!0);let a=Date.now();return qn(n,Un(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Hn(this.storage,e)??F(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);P(t,i.map(({content:e})=>e),!1);let a=Date.now();return qn(t,Un(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}applyConfiguration(){this.storage.transaction(()=>{let e=new Map(Vn(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(!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 qn(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 Jn=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},Yn=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},Xn=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,O.skills,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 Jn(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=>I(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()&&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&&Zn(t)&&!I(t,n)&&!I(t,r))throw new Yn(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=ge(`sha256`).update(`${i}\0${a}`).digest(`hex`),n=r.join(t,`.foundry-${e}.tmp`);try{if(Zn(n)&&!I(n,a))throw new Yn(n);if(Zn(n)||se(a,n,`dir`),Zn(i)&&!I(i,a)&&!I(i,o))throw new Yn(i);ie(n,i),N(t)}finally{I(n,a)&&ce(n)}}n!==i&&I(n,o)&&(ce(n),N(t))}}};function Zn(e){try{return p(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function I(e,t){return Zn(e)&&p(e).isSymbolicLink()&&Qn(r.resolve(r.dirname(e),ne(e)))===Qn(t)}function Qn(e){try{return r.join(re(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 $n(e){if(typeof e!=`string`||!E(e))throw new R(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function er(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=$n(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&&(tr(e.content),n+=x.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 tr(e){if(x.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 nr(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}`)}},rr=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function ir(e){return e===e.trim()&&T(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=lt(e.name);if(!ir(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}}function V(e,t){throw new R(e,t,400)}function ar(e){return e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r.isAbsolute(e.path)&&!e.path.includes(`\0`)||V(`SKILL_IMPORT_INVALID_SOURCE`,`path must be an absolute local filesystem path`),{path:e.path}}function or(e){if(!e||typeof e!=`object`||!(`url`in e)||typeof e.url!=`string`)throw new R(`SKILL_IMPORT_INVALID_URL`,`Enter an HTTP or HTTPS file URL`,400);return{url:sr(e.url).href}}function sr(e,t){try{let n=new URL(e.trim(),t);if(![`http:`,`https:`].includes(n.protocol)||n.username||n.password)throw Error(`Invalid URL`);return n}catch{throw new R(`SKILL_IMPORT_INVALID_URL`,`Use an HTTP or HTTPS file URL without embedded credentials`,400)}}function cr(e){e&&typeof e==`object`&&`entries`in e&&Array.isArray(e.entries)&&e.entries.length!==0||V(`SKILL_IMPORT_MISSING_SKILL_MD`,`Select one skill containing SKILL.md`),e.entries.length>5e3&&V(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`);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`)&&V(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path or file`);let i=e.path.normalize(`NFKC`).toLowerCase();if(n.has(i)&&V(`SKILL_IMPORT_DUPLICATE_PATH`,`The skill contains duplicate paths`),n.add(i),e.contents!==null&&((e.contents.length>44739244||x.from(e.contents,`base64`).toString(`base64`)!==e.contents)&&V(`SKILL_IMPORT_INVALID_ENCODING`,`Invalid file encoding`),r+=x.from(e.contents,`base64`).length,r>33554432))throw new R(`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&&V(`SKILL_IMPORT_INVALID_PATH`,`A file occupies a parent directory`)}}let a=i.find(e=>e.path===`SKILL.md`);a?.contents??V(`SKILL_IMPORT_MISSING_SKILL_MD`,`The skill root must contain SKILL.md`);let o=x.from(a.contents,`base64`);if(o.length>2097152)throw new R(`SKILL_IMPORT_SKILL_MD_TOO_LARGE`,`SKILL.md must be at most 2 MiB`,413);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`))&&V(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must contain valid YAML frontmatter`),{skill:{...B(Ie(t[1])),content:e.slice(t[0].length)},entries:i}}catch{V(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must be UTF-8 Markdown with a valid name and description in YAML frontmatter`)}}const lr=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var ur=class{storage;constructor(e){this.storage=e}directory(e){if(!ir(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,O.skills,e)}assertSourceDirectory(e){try{let t=p(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{p(this.directory(e))}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}throw new rr(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 z(e);this.assertSourceDirectory(e);let i=this.directory(e),a=h(r.join(i,`SKILL.md`),`utf8`),o=lr.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 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(p(i).isSymbolicLink())throw new L(`Skill source file must not be a symbolic link`);let a=h(i,`utf8`),o=lr.exec(a)?.[0];if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=t===``||o.endsWith(`
8
+ `);return t?`${jn}\n\n${t}\n\n${Mn}`:`${jn}\n${Mn}`}function Ln(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function Rn(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 zn(e,t){let n=r.dirname(e);p(n,{recursive:!0,mode:448});let a=d(e)?_(e).mode&511:384,o=`${e}.${v()}.tmp`;try{let r=ne(o,`wx`,a);try{i.platform!==`win32`&&s(o,a),ue(r,t),te(r)}finally{c(r)}ae(o,e),N(n)}finally{g(o,{force:!0})}}function P(e,t,n){let r=d(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?Pn(i):Nn(i,t);zn(e.filePath,a)}function Bn(e){d(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 Vn(e){return e.all(`agents`)}function Hn(e,t){return e.get(`agents`,t)}function Un(e,t){return e.put(`agents`,t),t}function Wn(e,t,n){let r=Vn(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(Dn(n).map(e=>[e.id,e])),a=new Map(pn(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),Un(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Gn=class{storage;homeDirectory;constructor(e,t=de.homedir()){this.storage=e,this.homeDirectory=t}list(){return pn(this.storage)}get(e){let t=mn(e,this.storage);if(!t)throw new cn(e);return t}create(e){return fn(e,this.storage)}update(e,t){let n=hn(e,t,this.storage);if(!n)throw new cn(e);return n}delete(e){return this.storage.transaction(()=>{let t=mn(e,this.storage);if(!t||(Wn(this.storage,e,this.homeDirectory),gn(e,this.storage)===`missing`))throw new cn(e);return t})}},Kn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Gn(e),n=de.homedir(),r=Qe){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=Dn(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(Vn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>qn(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=Hn(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=Un(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return qn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Hn(this.storage,e)??F(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);P(n,e.map(({content:e})=>e),!1)}else P(n,[],!0);let a=Date.now();return qn(n,Un(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Hn(this.storage,e)??F(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);P(t,i.map(({content:e})=>e),!1);let a=Date.now();return qn(t,Un(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}applyConfiguration(){this.storage.transaction(()=>{let e=new Map(Vn(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(!d(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 qn(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 Jn=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},Yn=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},Xn=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,O.skills,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 Jn(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=>L(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=h(n)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let t of i)T(t)&&t===t.trim()&&L(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&&Zn(t)===Zn(n)||t&&n&&!e.assignment&&I(t)&&!L(t,n)&&!L(t,r))throw new Yn(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 n=ge(`sha256`).update(`${i}\0${a}`).digest(`hex`),s=r.join(t,`.foundry-${n}.tmp`);try{if(I(s)&&!L(s,a))throw new Yn(s);if(I(s)||se(a,s,`dir`),!e.assignment&&I(i)&&!L(i,a)&&!L(i,o))throw new Yn(i);e.assignment&&I(i)&&f(i).isDirectory()&&g(i,{recursive:!0,force:!0}),ae(s,i),N(t)}finally{L(s,a)&&ce(s)}}let s=e.assignment?I(n)&&f(n).isSymbolicLink():L(n,o);if(n!==i&&s){try{ce(n)}catch(e){if(e.code!==`ENOENT`)throw e}N(t)}}}};function I(e){try{return f(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function L(e,t){return I(e)&&f(e).isSymbolicLink()&&Zn(r.resolve(r.dirname(e),re(e)))===Zn(t)}function Zn(e){try{return r.join(ie(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var R=class extends Error{code=`INVALID_SKILL_INPUT`},z=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function Qn(e){if(typeof e!=`string`||!E(e))throw new z(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function $n(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new R(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new R(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new R(`Invalid file entry`);let o=Qn(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new R(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new R(`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 R(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(er(e.content),n+=x.byteLength(e.content,`utf8`),n>16777216))throw new R(`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 z(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function er(e){if(x.byteLength(e,`utf8`)>2097152)throw new z(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new z(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function tr(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new R(`assigned must be a boolean`);return{assigned:e.assigned}}var B=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},nr=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function rr(e){return e===e.trim()&&T(e)}function V(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new R(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new R(`name is required`);let t=lt(e.name);if(!rr(t))throw new R(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new R(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new R(`description must be 1–1024 characters`);return{name:t,description:n}}function H(e,t){throw new z(e,t,400)}function ir(e){return e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r.isAbsolute(e.path)&&!e.path.includes(`\0`)||H(`SKILL_IMPORT_INVALID_SOURCE`,`path must be an absolute local filesystem path`),{path:e.path}}function ar(e){if(!e||typeof e!=`object`||!(`url`in e)||typeof e.url!=`string`)throw new z(`SKILL_IMPORT_INVALID_URL`,`Enter an HTTP or HTTPS file URL`,400);return{url:or(e.url).href}}function or(e,t){try{let n=new URL(e.trim(),t);if(![`http:`,`https:`].includes(n.protocol)||n.username||n.password)throw Error(`Invalid URL`);return n}catch{throw new z(`SKILL_IMPORT_INVALID_URL`,`Use an HTTP or HTTPS file URL without embedded credentials`,400)}}function sr(e){e&&typeof e==`object`&&`entries`in e&&Array.isArray(e.entries)&&e.entries.length!==0||H(`SKILL_IMPORT_MISSING_SKILL_MD`,`Select one skill containing SKILL.md`),e.entries.length>5e3&&H(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`);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`)&&H(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path or file`);let i=e.path.normalize(`NFKC`).toLowerCase();if(n.has(i)&&H(`SKILL_IMPORT_DUPLICATE_PATH`,`The skill contains duplicate paths`),n.add(i),e.contents!==null&&((e.contents.length>44739244||x.from(e.contents,`base64`).toString(`base64`)!==e.contents)&&H(`SKILL_IMPORT_INVALID_ENCODING`,`Invalid file encoding`),r+=x.from(e.contents,`base64`).length,r>33554432))throw new z(`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&&H(`SKILL_IMPORT_INVALID_PATH`,`A file occupies a parent directory`)}}let a=i.find(e=>e.path===`SKILL.md`);a?.contents??H(`SKILL_IMPORT_MISSING_SKILL_MD`,`The skill root must contain SKILL.md`);let o=x.from(a.contents,`base64`);if(o.length>2097152)throw new z(`SKILL_IMPORT_SKILL_MD_TOO_LARGE`,`SKILL.md must be at most 2 MiB`,413);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`))&&H(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must contain valid YAML frontmatter`),{skill:{...V(Ie(t[1])),content:e.slice(t[0].length)},entries:i}}catch{H(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must be UTF-8 Markdown with a valid name and description in YAML frontmatter`)}}const cr=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var lr=class{storage;constructor(e){this.storage=e}directory(e){if(!rr(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,O.skills,e)}assertSourceDirectory(e){try{let t=f(this.directory(e));if(!t.isDirectory()||t.isSymbolicLink())throw new R(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new B(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 nr(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 B(e);this.assertSourceDirectory(e);let i=this.directory(e),a=m(r.join(i,`SKILL.md`),`utf8`),o=cr.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 B(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 B(e);this.assertSourceDirectory(e);let i=r.join(this.directory(e),`SKILL.md`);if(f(i).isSymbolicLink())throw new R(`Skill source file must not be a symbolic link`);let a=m(i,`utf8`),o=cr.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(ir(e))return this.storage.transaction(()=>{try{let t=h(r.join(this.directory(e),`SKILL.md`),`utf8`),n=lr.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=B(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,O.skills),{withFileTypes:!0}).filter(e=>e.isDirectory()&&ir(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 dr(e){return e.flatMap(e=>e.children?[e,...dr(e.children)]:[e])}var fr=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,O.skills,e);if(!p(t).isDirectory()||p(t).isSymbolicLink()||p(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(p(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)=>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(dr(this.read(e)).map(e=>[e.path,e])),a=new Map(dr(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))}}};async function pr(e){try{let t=await Se(e);if(t.isSymbolicLink()&&V(`SKILL_IMPORT_SYMLINK_SOURCE`,`Select a skill source, not a symbolic link`),t.isFile()&&/\.(?:skill|zip)$/iu.test(e))return hr(t.size),await gr(e);t.isDirectory()||V(`SKILL_IMPORT_INVALID_SOURCE`,`Select a skill folder or a .skill / .zip archive`);let n=await Ee(e,{withFileTypes:!0}),i={bytes:0,entries:0};if(n.some(e=>e.name===`SKILL.md`))return{isBatch:!1,candidates:[await mr(e,i)]};let a=[];for(let t of n)if(t.isDirectory()||t.isSymbolicLink()){i.entries>=5e3&&V(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The source contains too many entries`),i.entries++;try{a.push(await mr(r.join(e,t.name),i))}catch(e){if(e instanceof R&&[`SKILL_IMPORT_TOO_LARGE`,`SKILL_IMPORT_TOO_MANY_ENTRIES`].includes(e.code))throw e;a.push({source:t.name,entries:[],readError:e instanceof R?e:new R(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)})}}return{isBatch:!0,candidates:a}}catch(e){throw e instanceof R?e:new R(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)}}async function mr(e,t){let n=await Se(e);(n.isSymbolicLink()||!n.isDirectory())&&V(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`);let i=await Ee(e);i.includes(`SKILL.md`)||V(`SKILL_IMPORT_MISSING_SKILL_MD`,`The skill folder must contain SKILL.md at its root`);let a=[],o=async(e,n)=>{(!E(n)||n.split(`/`).length>32)&&V(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path`),t.entries>=5e3&&V(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`),t.entries++;let i=await Se(e);if((i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())&&V(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`),i.isDirectory()){a.push({path:n,contents:null});let t=await Ee(e);for(let i of t)await o(r.join(e,i),`${n}/${i}`)}else{hr(t.bytes+i.size);let r=await Te(e,l.O_RDONLY|l.O_NOFOLLOW|l.O_NONBLOCK);try{let e=await r.stat();e.isFile()||V(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Select a regular skill file`),hr(t.bytes+e.size);let i=[],o;do{let e=x.alloc(65536);({bytesRead:o}=await r.read(e)),t.bytes+=o,hr(t.bytes),o>0&&i.push(e.subarray(0,o))}while(o>0);a.push({path:n,contents:x.concat(i).toString(`base64`)})}finally{await r.close()}}};for(let t of i)await o(r.join(e,t),t);return{source:r.basename(e),entries:a}}function hr(e){if(e>33554432)throw new R(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413)}async function gr(e){let{entries:t,unsupported:n}=await _r(e);return t.some(e=>e.path===`SKILL.md`)?(n.length>0&&V(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`),{isBatch:!1,candidates:[{source:typeof e==`string`?r.basename(e):`archive`,entries:t}]}):{isBatch:!0,candidates:[...new Set(t.filter(e=>e.contents===null||e.path.includes(`/`)).map(e=>e.path.split(`/`,1)[0]))].map(e=>({source:e,hasUnsupportedEntries:n.some(t=>t===e||t.startsWith(`${e}/`)),entries:t.filter(t=>t.path.startsWith(`${e}/`)).map(t=>({...t,path:t.path.slice(e.length+1)}))}))}}async function _r(e){let t;try{t=await new Promise((t,n)=>{let r=(e,r)=>{e?n(e):t(r)},i={lazyEntries:!0,autoClose:!1,strictFileNames:!0};typeof e==`string`?Me.open(e,i,r):Me.fromBuffer(e,i,r)})}catch{V(`SKILL_IMPORT_INVALID_ARCHIVE`,`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&&V(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`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 R(`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)&&V(`SKILL_IMPORT_INVALID_ARCHIVE`,`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 R)throw e;V(`SKILL_IMPORT_INVALID_ARCHIVE`,`Unable to read the skill archive`)}finally{t.close()}return{entries:n,unsupported:r}}function vr(e,t){let n=e.headers.get(`content-disposition`)??``,r=/(?:^|;)\s*filename\*=UTF-8''([^;]*)/iu.exec(n)?.[1],i=/(?:^|;)\s*filename=("[^"]*"|[^;]*)/iu.exec(n);try{return r===void 0?i?i[1].trim().replaceAll(/^"|"$/gu,``):decodeURIComponent(t.pathname.split(`/`).at(-1)??``):decodeURIComponent(r.trim())}catch{throw new R(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a .skill, .zip, or SKILL.md file URL`,400)}}async function yr(e){let t=sr(e),n=AbortSignal.timeout(3e4);try{for(let e=0;e<=5;e++){let r=await fetch(t,{signal:n,redirect:`manual`});try{if([301,302,303,307,308].includes(r.status)){let n=r.headers.get(`location`);if(!n||e===5)throw new R(`SKILL_IMPORT_DOWNLOAD_FAILED`,`The download redirected too many times or has no destination`,400);t=sr(n,t);continue}if(!r.ok||!r.body)throw new R(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400);let n=vr(r,t),i=n===`SKILL.md`;if(!i&&!/\.(?:skill|zip)$/iu.test(n)||/text\/html|application\/xhtml\+xml/iu.test(r.headers.get(`content-type`)??``))throw new R(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a direct .skill, .zip, or SKILL.md file URL, not a folder or HTML page`,400);let a=i?2097152:33554432,o=e=>{if(e>a)throw new R(i?`SKILL_IMPORT_SKILL_MD_TOO_LARGE`:`SKILL_IMPORT_TOO_LARGE`,i?`SKILL.md must be at most 2 MiB`:`Skills must be at most 32 MiB`,413)};o(Number(r.headers.get(`content-length`)??0));let s=[],c=0;for await(let e of r.body){let t=x.from(e);c+=t.length,o(c),s.push(t)}let l=x.concat(s);return i?{isBatch:!1,candidates:[{source:`SKILL.md`,entries:[{path:`SKILL.md`,contents:l.toString(`base64`)}]}]}:await gr(l)}finally{if(!r.body?.locked)try{await r.body?.cancel()}catch{}}}}catch(e){throw e instanceof R?e:new R(n.aborted?`SKILL_IMPORT_DOWNLOAD_TIMEOUT`:`SKILL_IMPORT_DOWNLOAD_FAILED`,n.aborted?`The download timed out; try again or import the file locally`:`Unable to download the skill file`,400)}throw new R(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400)}var br=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new ur(e),this.files=new fr(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)}importSource({isBatch:e,candidates:t}){t.length===0&&V(`SKILL_IMPORT_NO_SKILLS`,`The source contains no skill folders at the first level`);let n={imported:[],skipped:[]};for(let r of t)try{if(r.readError)throw r.readError;r.hasUnsupportedEntries&&V(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`);let{skill:e,entries:t}=cr({entries:r.entries});n.imported.push(this.repository.import(e,t))}catch(t){if(!e||!(t instanceof R||t instanceof L||t instanceof rr))throw t;n.skipped.push({source:r.source,code:t.code,message:t.message})}return n}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))}async importLocal(e){let t=ar(e);return this.importSource(await pr(t.path))}async importUrl(e){let t=or(e);return this.importSource(await yr(t.url))}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 Jn(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=er({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})}},H=class extends Error{code;constructor(e,t){super(t),this.code=e}};function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xr(e){if(!U(e)||e.format!==`foundry.data`)throw G(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&U(e.data)&&e.data.path===`data/foundry.json`&&Sr(e.data))return{archiveVersion:2,data:{path:at,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==4||!Array.isArray(e.files)||!Array.isArray(e.directories))throw G(`Unsupported or invalid backup manifest`);return{archiveVersion:4,files:e.files.map(e=>{if(!U(e)||typeof e.path!=`string`||!Sr(e))throw G(`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 G(`Invalid backup directory`);return e})}}function Sr(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 Cr(e){if(!U(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw G(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function wr(e){if(!U(e)||!U(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw G(`Backup data must contain settings, instructions, and agents`);let t=Tr(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:dt(e.settings),instructions:t,agents:Er(e.agents,n)}}function Tr(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!U(e))throw G(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!sn.test(r)||t.has(r))throw G(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw G(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw G(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:W(e.createdAt,n),updatedAt:W(e.updatedAt,n)};return t.add(r),a})}function Er(e,t,n){let r=new Set(w.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!U(e)||!U(e.instructions))throw G(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw G(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw G(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw G(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw G(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw G(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw G(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:W(s.createdAt,a),updatedAt:W(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!U(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 G(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:W(t.createdAt,a),updatedAt:W(t.updatedAt,a)}}return i.add(o),u})}function W(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw G(`Invalid timestamp at index ${t}`);return e}function G(e){return new H(`INVALID_BACKUP`,e)}const Dr=`${O.skills}/`,Or=`${O.instructions}/`,kr=`${O.agents}/`,Ar=RegExp(`^${O.skills}/[^/]+/$`,`u`);function jr(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!Lt(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new H(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||jt.some(t=>e.every(e=>e.path!==`${t}/`)))throw new H(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(Or)&&e.contents!==null).map(e=>vn(Mr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>Ar.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||B(Ie(i[1])).name!==n)throw new H(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(Dr)&&t.path!==Dr&&!a.has(t.path.split(`/`,2)[1]))throw new H(`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 H(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(kr)&&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 H(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(Mr(n));wr({settings:c,instructions:i,agents:s});let l=Er(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 Nr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of pn(e))n.has(t.id)||e.removeTextFile(Pr(t.id));for(let n of t.instructions)e.putTextFile(Pr(n.id),_n(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),Ir(e)})}function Pr(e){return r.join(O.instructions,`${e}.md`)}function Fr(e,t){return e.transaction(()=>{for(let n of jt)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),Lr(t.entries.filter(e=>e.path.startsWith(`${O.agents}/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function Ir(e){return Lr(e.all(`agents`))}function Lr(e){return ge(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function Rr(e){for(let{id:t}of w.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 zr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(Ir(this.storage)!==t)throw new H(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new Kn(this.storage).applyConfiguration(),new br(this.storage).applyAssignments()):Rr(this.storage)})}catch(t){throw t instanceof H?t:new H(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 we(r.join(pe(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await qt(e,i,t);let a=await zt(i,r.join(n,`extracted`)),o=xr(JSON.parse(await y(a[`manifest.json`],`utf8`))),s;if(o.archiveVersion===2){if(Object.keys(a).length!==2||!Object.keys(a).includes(`data/foundry.json`))throw new H(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await y(a[at]);Br(e,o.data);let t=wr(JSON.parse(e.toString(`utf8`)));s=()=>Nr(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 H(`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 y(a[e.path]);Br(t,e),n.push({path:e.path,contents:t})}let r=jr(n);s=()=>Fr(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new H(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof H?e:e instanceof Ht?e.code===`INVALID_PASSPHRASE`?new H(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new H(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new H(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await nn(n)}}};function Br(e,t){if(e.byteLength!==t.bytes||an(e)!==t.sha256)throw new H(`INVALID_BACKUP`,`Backup checksum does not match`)}const Vr=[`agents`,`providers`],Hr=new RegExp(String.raw`^${O.skills}[/\\]([^/\\]+)$`,`u`),Ur=new RegExp(String.raw`^${O.instructions}[/\\][^/\\]+\.md$`,`u`);function Wr(e){let t=Hr.exec(e);return!!(t&&t[1]===t[1].trim()&&T(t[1]))}function Gr(e){return Ur.test(e)||Kr(e)}function Kr(e){let t=e.split(r.sep);return t[0]===O.skills&&t.length>2&&t[1]===t[1].trim()&&T(t[1])&&E(t.slice(2).join(`/`))}function qr(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()-oe(e).mtimeMs>3e4}}var Jr=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=de.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new Xn(e,t),M(e);for(let e of Vr)e!==`providers`&&M(this.collectionPath(e))}collectionPath(e){return r.join(this.path,e===`agents`?O.agents: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(O.agents,`${t}.json`)}return r.relative(this.path,r.join(this.collectionPath(e),`${ge(`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)||!Gr(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{ue(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=oe(e);if(!qr(e))return;let n=r.join(e,`recovering`);try{m(n)}catch(e){if(e.code===`EEXIST`){let e=oe(n);qr(n)&&oe(n).ino===e.ino&&_(n,{recursive:!0,force:!0})}return}if(ue(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),oe(e).ino!==t.ino||!qr(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}))]};On(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}f(t)&&g(t).length===0&&(ae(t),N(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(O.agents,t.name),i=JSON.parse(h(r.join(this.path,n),`utf8`)),a=this.recordPath(`agents`,i.id);if(t.name!==`${ge(`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};On(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(!Kr(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(!Kr(n)||typeof t.bytes!=`string`||Object.keys(t).some(e=>![`file`,`bytes`].includes(e)))throw Error(`Invalid skill file journal`);this.assertLocalSkillPath(e),An(e,x.from(t.bytes,`base64`))}else if(t.createDirectory||t.removeEntry){if(!Kr(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):(_(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)&&!Gr(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(Kr(n)&&this.assertLocalSkillPath(e),t.value===null)_(e,{force:!0}),N(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);kn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else On(e,t.value)}}let t=e.agentInstructions??[];for(let e of t){let t=Dn(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);_(r.join(this.path,`.transaction.json`),{force:!0}),N(this.path)}validateTree(e,t){if(!Mt(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}),M(n);for(let e of t){let t=r.join(n,...e.path.split(`/`));e.contents===null?M(t):An(t,x.from(e.contents,`base64`))}let i=r.join(this.path,e.file);_(i,{recursive:!0,force:!0}),ie(n,i),N(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`);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(!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=Dn(this.agentHomeDirectory).find(({id:e})=>e===t.agentId);if(!e)throw Error(`Unknown agent`);Bn(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};On(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 Yr(e=$e(),t){let n=new Jr(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 Xr(){return et(),Yr()}async function K(e){let t;try{let n=Xr(),r=new Gn(n);t={storage:n,agentsService:new Kn(n,r),settingsService:new St(n),settingsSkillCopyService:new wt,dataExportService:new on(n),dataImportService:new zr(n),instructionsService:r,skillsService:new br(n)},Qr(await e(t))}catch(e){let t=$r(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function Zr(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new q(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Qr(e){console.log(JSON.stringify(e,null,2))}function $r(e){return e instanceof Error?{code:ei(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function ei(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const ti={type:`positional`,description:`Agent ID with Skills support: ${w.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function ni(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:ti,skill:{type:`string`,description:`Existing skill name`,required:!0}},run({args:e}){return K(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const ri=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:{...ti,required:!1}},run({args:e}){return K(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new Jn(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:ni(!0),unassign:ni(!1)}}),ii=w.list().map(({id:e})=>e).join(`, `),J={type:`positional`,description:`Agent ID: ${ii}`,required:!0},ai=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return K(({agentsService:e})=>e.list())}}),oi=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...J,description:`Optional agent ID: ${ii}`,required:!1}},run({args:e}){return K(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new q(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${ii}`);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}))}))})}}),si=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:J,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 K(({agentsService:t})=>{let n=Ke({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),ci=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:J},run({args:e}){return K(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),li=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:J},run({args:e}){return K(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),ui=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:J},run({args:e}){return K(({agentsService:t})=>t.reapply(e.agent))}}),di=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:J},run({args:e}){return K(({agentsService:t})=>t.openInstructionFile(e.agent))}}),fi=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:ai,skills:ri,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:oi,assign:si,enable:ci,disable:li,reapply:ui,open:di}})}}),pi=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 K(({instructionsService:t})=>t.create(ln({name:e.name,content:e.content})))}}),mi=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return K(({instructionsService:e})=>e.list())}}),hi=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 K(({instructionsService:t})=>t.get(e.id))}}),gi=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 K(({instructionsService:t})=>t.update(e.id,ln({name:e.name,content:e.content})))}}),_i=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 K(({instructionsService:t})=>t.delete(e.id))}}),vi=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:pi,list:mi,get:hi,edit:gi,delete:_i}});function yi(e){if(!xi(e)||!Array.isArray(e.targets))throw new bi(`targets must be an array`);if(e.targets.length===0)throw new bi(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!st.includes(e))throw new bi(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var bi=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function xi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Si=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 K(async({dataExportService:t})=>{let n=await t.createExport(Zr(e.passphrase)),r=wi(e.output);return await Ti(n.contents,r,e.force),{filePath:r}})}}),Ci=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 K(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),Zr(e.passphrase));return t.completeImport({apply:e[`apply-agents`],agentRevision:n.agentRevision}),{status:`imported`}})}});function wi(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 Ti(e,t,n){await Ce(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await ke(a,e,{mode:384}),i.platform!==`win32`&&await ye(a,384),n){await De(a,t);return}if(f(t))throw Ei(t);try{await xe(a,t)}catch(e){throw Di(e)?Ei(t):e}}finally{await b(a,{force:!0})}}function Ei(e){return new q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Di(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Y={"color-theme":{field:`theme`,values:tt},language:{field:`language`,values:nt},"time-zone":{field:`timezone`,values:it},"time-format":{field:`timeFormat`,values:rt}},Oi=[...Object.keys(Y),`config-folder`],ki=Object.entries(Y).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
11
- `);function Ai(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const ji=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Oi.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return K(({settingsService:t})=>{let n=Ai(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new q(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Oi.join(`, `)}`);return n[e.key]})}}),Mi=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(Y).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${ki}`,required:!0}},run({args:e}){return K(({settingsService:t})=>{if(e.key===`config-folder`)throw new q(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(Y,e.key))throw new q(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(Y).join(`, `)}`);let n=Y[e.key];if(!n.values.includes(e.value))throw new q(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Ai(t.update(ft({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Ni=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return K(({settingsService:e})=>e.openConfigFolder())}}),Pi=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 K(({settingsSkillCopyService:t})=>{let n=yi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Fi=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:ji,set:Mi,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Ni}}),export:Si,import:Ci,"download-skill":Pi}}),Ii={type:`positional`,description:`Current skill name`,required:!0},Li=e({meta:{name:`manual`,description:`Create skill metadata with an empty Markdown body in ~/.foundry/${O.skills}/<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 K(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),Ri=e({meta:{name:`local`,description:`Import one local skill folder or .skill/.zip archive; discover skills only at the source root or its immediate child folders`},args:{path:{type:`positional`,description:`One folder or .skill/.zip file. Root SKILL.md takes priority; otherwise only immediate child folders are checked. 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 K(({skillsService:t})=>t.importLocal({path:r.resolve(e.path)}))}}),zi=e({meta:{name:`url`,description:`Download and import a .skill/.zip archive or a raw SKILL.md over HTTP(S)`},args:{url:{type:`positional`,description:`Direct HTTP(S) file URL. SKILL.md imports only that file; archives follow local import rules. Metadata name determines the destination; existing names are never overwritten. Prints { imported, skipped } as JSON.`,required:!0}},run({args:e}){return K(({skillsService:t})=>t.importUrl({url:e.url}))}}),Bi=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 K(({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 K(({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 K(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new L(`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 L(`Skill files input must be valid JSON`)}let o=er(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 K(({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 K(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:Li,local:Ri,url:zi}})}});function Vi(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Ke(await Hi(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Ui(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=qe(await Hi(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Ui(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Ui(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Ui(t,e)}}),t}async function Hi(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Ui(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Wi(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 Ki(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(ln(await Gi(t)));return t.json(n,201)}catch(e){return Ki(t,e)}}),t.put(`/:id`,async t=>{try{let n=ln(await Gi(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Ki(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Ki(t,e)}}),t}async function Gi(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function Ki(e,t){if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof cn)return e.json({error:{code:t.code,message:t.message}},404);throw t}const qi=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Ji=[`active`,`disabled`,`deleted`];var X=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function Yi(e){if(!na(e))throw new X(`Provider input must be an object`);let t=Z(e.name,`name`),n=ea(e.protocol),r=ta(e.baseURL),i=e.apiKey===void 0?``:Z(e.apiKey,`apiKey`,{allowEmpty:!0}),a=$i(e.customModels);return{...e.avatar!==void 0&&{avatar:Xi(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Xi(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 X(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Zi(e){if(!na(e))throw new X(`Provider connection must be an object`);return{protocol:ea(e.protocol),baseURL:ta(e.baseURL),apiKey:e.apiKey===void 0?``:Z(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Qi(e){if(typeof e!=`string`||!Ji.includes(e))throw new X(`Invalid provider status`);return e}function $i(e){if(e===void 0)return[];if(!Array.isArray(e))throw new X(`customModels must be an array`);return e.map(e=>{if(!na(e))throw new X(`Each custom model must be an object`);return{id:Z(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:Z(e.displayName,`customModels.displayName`)}})}function ea(e){if(typeof e!=`string`||!qi.includes(e))throw new X(`Invalid provider protocol`);return e}function ta(e){let t=Z(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new X(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function Z(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new X(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new X(`${t} is required`);return r}function na(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ra=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function ia(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(aa(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new ra(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new ra(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new ra(`Provider returned invalid JSON`)}return oa(i)}function aa(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function oa(e){if(!ca(e)||!Array.isArray(e.data))throw new ra(`Provider response does not contain a model list`);return e.data.map(e=>{if(!ca(e)||typeof e.id!=`string`||e.id.length===0)throw new ra(`Provider returned an invalid model entry`);let t=sa(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function sa(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function ca(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var la=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},ua=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=>da(e))}get(e){let t=this.storage.get(`providers`,e);return t?da(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 la;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),da(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new la;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),da(i)})}};function da(e){return{...e,avatar:e.avatar??null,status:e.status}}function fa(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 ma(t,e)}}),n.post(`/models`,async t=>{try{let n=Zi(await pa(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ma(t,e)}}),n.post(`/`,async n=>{try{let r=Yi(await pa(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ma(n,e)}}),n.put(`/:id`,async n=>{try{let r=Yi(await pa(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ma(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await pa(n),i=Qi(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 ma(n,e)}}),n}async function pa(e){try{return await e.req.json()}catch{throw new X(`Request body must be valid JSON`)}}function ma(e,t){if(t instanceof X)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof la)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ra)return e.json({error:{code:t.code,message:t.message}},502);throw t}var ha=class{repository;constructor(e){this.repository=new ua(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 la;return ia(t)}fetchModelsForConnection(e){return ia(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function ga(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 _a(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return va(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=yi(await _a(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return va(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r.get(`/skill-status`,async e=>{try{return e.json(await n.getStatus())}catch(t){return va(e,t)}}),r}async function _a(e){try{return await e.req.json()}catch{throw new ht(`Request body must be valid JSON`)}}function va(e,t){if(t instanceof ht||t instanceof bi)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 ya(e){let t=new S;return t.post(`/import/url`,Ve({maxSize:16384,onError:e=>e.json({error:{code:`SKILL_IMPORT_INVALID_URL`,message:`Import requires a file URL`}},400)}),async t=>{try{let n=await e.importUrl(await ba(t));return t.json(n,n.imported.length>0?201:200)}catch(e){return Q(t,e)}}),t.post(`/import/local`,Ve({maxSize:16384,onError:e=>e.json({error:{code:`SKILL_IMPORT_INVALID_SOURCE`,message:`Import requires a local source path`}},400)}),async t=>{try{let n=await e.importLocal(await ba(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=nr(await ba(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 ba(t);return t.json(e.create(B(n)),201)}catch(e){return Q(t,e)}}),t.put(`/:name`,async t=>{try{let n=await ba(t);if(n&&typeof n==`object`&&`files`in n){let r=er(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 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 ba(e){try{return await e.req.json()}catch{throw new L(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof R)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof Jn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Yn)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 rr)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 xa(e){let t=new S;return t.get(`/`,t=>He(t,async n=>{await Sa(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Ca(n,e)}),c=setInterval(()=>{r||wa(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 Sa(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Ca(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function wa(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Ta=class extends Error{code=`INVALID_EXPORT_INPUT`};function Ea(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Ta(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Da(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Ta(`Request body must be valid JSON`)}let{passphrase:r}=Ea(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 Ta?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 H(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new H(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new H(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await we(r.join(pe(),`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 H?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 nn(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new H(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(Cr(n)),t.json({status:`completed`})}catch(e){if(e instanceof H){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 ka(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 Aa=Ue(a);function ja(e){return`
10
+ `;return this.storage.putTextFile(i,`${o}${s}${t}`),{...n,content:t}})}get(e){if(rr(e))return this.storage.transaction(()=>{try{let t=m(r.join(this.directory(e),`SKILL.md`),`utf8`),n=cr.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=V(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=h(r.join(this.storage.path,O.skills),{withFileTypes:!0}).filter(e=>e.isDirectory()&&rr(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 ur(e){return e.flatMap(e=>e.children?[e,...ur(e.children)]:[e])}var dr=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new B(e);let t=r.join(this.storage.path,O.skills,e);if(!f(t).isDirectory()||f(t).isSymbolicLink()||f(r.dirname(t)).isSymbolicLink())throw new z(`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 z(`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(!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(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(ur(this.read(e)).map(e=>[e.path,e])),a=new Map(ur(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 z(`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 fr(e){try{let t=await Se(e);if(t.isSymbolicLink()&&H(`SKILL_IMPORT_SYMLINK_SOURCE`,`Select a skill source, not a symbolic link`),t.isFile()&&/\.(?:skill|zip)$/iu.test(e))return mr(t.size),await hr(e);t.isDirectory()||H(`SKILL_IMPORT_INVALID_SOURCE`,`Select a skill folder or a .skill / .zip archive`);let n=await Ee(e,{withFileTypes:!0}),i={bytes:0,entries:0};if(n.some(e=>e.name===`SKILL.md`))return{isBatch:!1,candidates:[await pr(e,i)]};let a=[];for(let t of n)if(t.isDirectory()||t.isSymbolicLink()){i.entries>=5e3&&H(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The source contains too many entries`),i.entries++;try{a.push(await pr(r.join(e,t.name),i))}catch(e){if(e instanceof z&&[`SKILL_IMPORT_TOO_LARGE`,`SKILL_IMPORT_TOO_MANY_ENTRIES`].includes(e.code))throw e;a.push({source:t.name,entries:[],readError:e instanceof z?e:new z(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)})}}return{isBatch:!0,candidates:a}}catch(e){throw e instanceof z?e:new z(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)}}async function pr(e,t){let n=await Se(e);(n.isSymbolicLink()||!n.isDirectory())&&H(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`);let i=await Ee(e);i.includes(`SKILL.md`)||H(`SKILL_IMPORT_MISSING_SKILL_MD`,`The skill folder must contain SKILL.md at its root`);let a=[],o=async(e,n)=>{(!E(n)||n.split(`/`).length>32)&&H(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path`),t.entries>=5e3&&H(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`),t.entries++;let i=await Se(e);if((i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())&&H(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`),i.isDirectory()){a.push({path:n,contents:null});let t=await Ee(e);for(let i of t)await o(r.join(e,i),`${n}/${i}`)}else{mr(t.bytes+i.size);let r=await Te(e,l.O_RDONLY|l.O_NOFOLLOW|l.O_NONBLOCK);try{let e=await r.stat();e.isFile()||H(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Select a regular skill file`),mr(t.bytes+e.size);let i=[],o;do{let e=x.alloc(65536);({bytesRead:o}=await r.read(e)),t.bytes+=o,mr(t.bytes),o>0&&i.push(e.subarray(0,o))}while(o>0);a.push({path:n,contents:x.concat(i).toString(`base64`)})}finally{await r.close()}}};for(let t of i)await o(r.join(e,t),t);return{source:r.basename(e),entries:a}}function mr(e){if(e>33554432)throw new z(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413)}async function hr(e){let{entries:t,unsupported:n}=await gr(e);return t.some(e=>e.path===`SKILL.md`)?(n.length>0&&H(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`),{isBatch:!1,candidates:[{source:typeof e==`string`?r.basename(e):`archive`,entries:t}]}):{isBatch:!0,candidates:[...new Set(t.filter(e=>e.contents===null||e.path.includes(`/`)).map(e=>e.path.split(`/`,1)[0]))].map(e=>({source:e,hasUnsupportedEntries:n.some(t=>t===e||t.startsWith(`${e}/`)),entries:t.filter(t=>t.path.startsWith(`${e}/`)).map(t=>({...t,path:t.path.slice(e.length+1)}))}))}}async function gr(e){let t;try{t=await new Promise((t,n)=>{let r=(e,r)=>{e?n(e):t(r)},i={lazyEntries:!0,autoClose:!1,strictFileNames:!0};typeof e==`string`?Me.open(e,i,r):Me.fromBuffer(e,i,r)})}catch{H(`SKILL_IMPORT_INVALID_ARCHIVE`,`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&&H(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`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 z(`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)&&H(`SKILL_IMPORT_INVALID_ARCHIVE`,`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 z)throw e;H(`SKILL_IMPORT_INVALID_ARCHIVE`,`Unable to read the skill archive`)}finally{t.close()}return{entries:n,unsupported:r}}function _r(e,t){let n=e.headers.get(`content-disposition`)??``,r=/(?:^|;)\s*filename\*=UTF-8''([^;]*)/iu.exec(n)?.[1],i=/(?:^|;)\s*filename=("[^"]*"|[^;]*)/iu.exec(n);try{return r===void 0?i?i[1].trim().replaceAll(/^"|"$/gu,``):decodeURIComponent(t.pathname.split(`/`).at(-1)??``):decodeURIComponent(r.trim())}catch{throw new z(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a .skill, .zip, or SKILL.md file URL`,400)}}async function vr(e){let t=or(e),n=AbortSignal.timeout(3e4);try{for(let e=0;e<=5;e++){let r=await fetch(t,{signal:n,redirect:`manual`});try{if([301,302,303,307,308].includes(r.status)){let n=r.headers.get(`location`);if(!n||e===5)throw new z(`SKILL_IMPORT_DOWNLOAD_FAILED`,`The download redirected too many times or has no destination`,400);t=or(n,t);continue}if(!r.ok||!r.body)throw new z(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400);let n=_r(r,t),i=n===`SKILL.md`;if(!i&&!/\.(?:skill|zip)$/iu.test(n)||/text\/html|application\/xhtml\+xml/iu.test(r.headers.get(`content-type`)??``))throw new z(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a direct .skill, .zip, or SKILL.md file URL, not a folder or HTML page`,400);let a=i?2097152:33554432,o=e=>{if(e>a)throw new z(i?`SKILL_IMPORT_SKILL_MD_TOO_LARGE`:`SKILL_IMPORT_TOO_LARGE`,i?`SKILL.md must be at most 2 MiB`:`Skills must be at most 32 MiB`,413)};o(Number(r.headers.get(`content-length`)??0));let s=[],c=0;for await(let e of r.body){let t=x.from(e);c+=t.length,o(c),s.push(t)}let l=x.concat(s);return i?{isBatch:!1,candidates:[{source:`SKILL.md`,entries:[{path:`SKILL.md`,contents:l.toString(`base64`)}]}]}:await hr(l)}finally{if(!r.body?.locked)try{await r.body?.cancel()}catch{}}}}catch(e){throw e instanceof z?e:new z(n.aborted?`SKILL_IMPORT_DOWNLOAD_TIMEOUT`:`SKILL_IMPORT_DOWNLOAD_FAILED`,n.aborted?`The download timed out; try again or import the file locally`:`Unable to download the skill file`,400)}throw new z(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400)}var yr=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new lr(e),this.files=new dr(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)}importSource({isBatch:e,candidates:t}){t.length===0&&H(`SKILL_IMPORT_NO_SKILLS`,`The source contains no skill folders at the first level`);let n={imported:[],skipped:[]};for(let r of t)try{if(r.readError)throw r.readError;r.hasUnsupportedEntries&&H(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`);let{skill:e,entries:t}=sr({entries:r.entries});n.imported.push(this.repository.import(e,t))}catch(t){if(!e||!(t instanceof z||t instanceof R||t instanceof nr))throw t;n.skipped.push({source:r.source,code:t.code,message:t.message})}return n}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 R(`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(V(e))}async importLocal(e){let t=ir(e);return this.importSource(await fr(t.path))}async importUrl(e){let t=ar(e);return this.importSource(await vr(t.url))}get(e){let t=this.repository.get(e);if(!t)throw new B(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(()=>{if(!rr(e))throw new R(`Invalid skill name`);if(this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new Jn(t);n&&this.get(e);let r=this.storage.get(`agents`,t)??F(t),i=Date.now(),a=r.skills??{skillNames:[],createdAt:i,updatedAt:i},o=a.skillNames.filter(t=>t!==e);n&&o.push(e),this.storage.put(`agents`,{...r,skills:{...a,skillNames:o,updatedAt:i}}),this.storage.syncAgentSkillLinks({previousName:e,name:n?e:null,agentIds:[t],assignment:!0})}),{name:e,agentIds:this.assignedIds(e,this.storage.all(`agents`))}}update(e,t){let n=V(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=$n({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})}},U=class extends Error{code;constructor(e,t){super(t),this.code=e}};function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function br(e){if(!W(e)||e.format!==`foundry.data`)throw K(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&W(e.data)&&e.data.path===`data/foundry.json`&&xr(e.data))return{archiveVersion:2,data:{path:at,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==4||!Array.isArray(e.files)||!Array.isArray(e.directories))throw K(`Unsupported or invalid backup manifest`);return{archiveVersion:4,files:e.files.map(e=>{if(!W(e)||typeof e.path!=`string`||!xr(e))throw K(`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 K(`Invalid backup directory`);return e})}}function xr(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 Sr(e){if(!W(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw K(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function Cr(e){if(!W(e)||!W(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw K(`Backup data must contain settings, instructions, and agents`);let t=wr(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:dt(e.settings),instructions:t,agents:Tr(e.agents,n)}}function wr(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!W(e))throw K(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!sn.test(r)||t.has(r))throw K(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw K(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw K(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:G(e.createdAt,n),updatedAt:G(e.updatedAt,n)};return t.add(r),a})}function Tr(e,t,n){let r=new Set(w.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!W(e)||!W(e.instructions))throw K(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw K(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw K(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw K(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw K(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw K(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw K(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:G(s.createdAt,a),updatedAt:G(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!W(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 K(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:G(t.createdAt,a),updatedAt:G(t.updatedAt,a)}}return i.add(o),u})}function G(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw K(`Invalid timestamp at index ${t}`);return e}function K(e){return new U(`INVALID_BACKUP`,e)}const Er=`${O.skills}/`,Dr=`${O.instructions}/`,Or=`${O.agents}/`,kr=RegExp(`^${O.skills}/[^/]+/$`,`u`);function Ar(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!Lt(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new U(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||jt.some(t=>e.every(e=>e.path!==`${t}/`)))throw new U(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(Dr)&&e.contents!==null).map(e=>vn(jr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>kr.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(jr(r));if(!i||V(Ie(i[1])).name!==n)throw new U(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(Er)&&t.path!==Er&&!a.has(t.path.split(`/`,2)[1]))throw new U(`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 U(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(Or)&&e.contents!==null).map(e=>{let t=JSON.parse(jr(e.contents));if(!t||typeof t!=`object`||!(`id`in t)||`${String(t.id)}.json`!==r.posix.basename(e.path))throw new U(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(jr(n));Cr({settings:c,instructions:i,agents:s});let l=Tr(s,new Set(i.map(({id:e})=>e)),a);return{entries:e,settings:dt(c),agents:l}}function jr(e){return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}function Mr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of pn(e))n.has(t.id)||e.removeTextFile(Nr(t.id));for(let n of t.instructions)e.putTextFile(Nr(n.id),_n(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),Fr(e)})}function Nr(e){return r.join(O.instructions,`${e}.md`)}function Pr(e,t){return e.transaction(()=>{for(let n of jt)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),Ir(t.entries.filter(e=>e.path.startsWith(`${O.agents}/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function Fr(e){return Ir(e.all(`agents`))}function Ir(e){return ge(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function Lr(e){for(let{id:t}of w.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 Rr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(Fr(this.storage)!==t)throw new U(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new Kn(this.storage).applyConfiguration(),new yr(this.storage).applyAssignments()):Lr(this.storage)})}catch(t){throw t instanceof U?t:new U(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 we(r.join(pe(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await qt(e,i,t);let a=await zt(i,r.join(n,`extracted`)),o=br(JSON.parse(await y(a[`manifest.json`],`utf8`))),s;if(o.archiveVersion===2){if(Object.keys(a).length!==2||!Object.keys(a).includes(`data/foundry.json`))throw new U(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await y(a[at]);zr(e,o.data);let t=Cr(JSON.parse(e.toString(`utf8`)));s=()=>Mr(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 U(`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 y(a[e.path]);zr(t,e),n.push({path:e.path,contents:t})}let r=Ar(n);s=()=>Pr(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new U(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof U?e:e instanceof Ht?e.code===`INVALID_PASSPHRASE`?new U(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new U(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new U(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await nn(n)}}};function zr(e,t){if(e.byteLength!==t.bytes||an(e)!==t.sha256)throw new U(`INVALID_BACKUP`,`Backup checksum does not match`)}const Br=[`agents`,`providers`],Vr=new RegExp(String.raw`^${O.skills}[/\\]([^/\\]+)$`,`u`),Hr=new RegExp(String.raw`^${O.instructions}[/\\][^/\\]+\.md$`,`u`);function Ur(e){let t=Vr.exec(e);return!!(t&&t[1]===t[1].trim()&&T(t[1]))}function Wr(e){return Hr.test(e)||Gr(e)}function Gr(e){let t=e.split(r.sep);return t[0]===O.skills&&t.length>2&&t[1]===t[1].trim()&&T(t[1])&&E(t.slice(2).join(`/`))}function Kr(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 qr=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=de.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new Xn(e,t),M(e);for(let e of Br)e!==`providers`&&M(this.collectionPath(e))}collectionPath(e){return r.join(this.path,e===`agents`?O.agents: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(O.agents,`${t}.json`)}return r.relative(this.path,r.join(this.collectionPath(e),`${ge(`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)||!Wr(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{ue(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(!Kr(e))return;let n=r.join(e,`recovering`);try{p(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);Kr(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ue(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!Kr(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(!d(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(!d(e)){let e=d(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}))]};On(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}d(t)&&h(t).length===0&&(oe(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(O.agents,t.name),i=JSON.parse(m(r.join(this.path,n),`utf8`)),a=this.recordPath(`agents`,i.id);if(t.name!==`${ge(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(d(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};On(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(!Gr(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.bytes!==void 0){if(!Gr(n)||typeof t.bytes!=`string`||Object.keys(t).some(e=>![`file`,`bytes`].includes(e)))throw Error(`Invalid skill file journal`);this.assertLocalSkillPath(e),An(e,x.from(t.bytes,`base64`))}else if(t.createDirectory||t.removeEntry){if(!Gr(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)&&!Wr(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(Gr(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`);kn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else On(e,t.value)}}let t=e.agentInstructions??[];for(let e of t){let t=Dn(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(!Mt(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}`);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):An(t,x.from(e.contents,`base64`))}let i=r.join(this.path,e.file);g(i,{recursive:!0,force:!0}),ae(n,i),N(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!Ur(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!Ur(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(d(n)){if(!f(n).isDirectory()||f(n).isSymbolicLink()||d(t))throw Error(`Invalid storage directory move`);ae(n,t)}else if(!d(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(!d(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=Dn(this.agentHomeDirectory).find(({id:e})=>e===t.agentId);if(!e)throw Error(`Unknown agent`);Bn(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 dt(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return d(e)?dt(JSON.parse(m(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};On(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 Jr(e=$e(),t){let n=new qr(e,t);try{return n.transaction(()=>{let t=n.readSettings();d(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function Yr(){return et(),Jr()}async function q(e){let t;try{let n=Yr(),r=new Gn(n);t={storage:n,agentsService:new Kn(n,r),settingsService:new St(n),settingsSkillCopyService:new wt,dataExportService:new on(n),dataImportService:new Rr(n),instructionsService:r,skillsService:new yr(n)},Zr(await e(t))}catch(e){let t=Qr(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function Xr(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new J(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var J=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Zr(e){console.log(JSON.stringify(e,null,2))}function Qr(e){return e instanceof Error?{code:$r(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function $r(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const ei={type:`positional`,description:`Agent ID with Skills support: ${w.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function ti(t){return e({meta:{name:t?`assign`:`unassign`,description:t?`Save one assignment and replace its same-name agent entry with a symlink; preserve other assignments`:`Remove one saved assignment and its same-name agent symlink; missing links or sources succeed`},args:{agent:ei,skill:{type:`string`,description:t?`Existing skill name`:`Skill name to remove, even if its source is missing`,required:!0}},run({args:e}){return q(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const ni=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:{...ei,required:!1}},run({args:e}){return q(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new Jn(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:ti(!0),unassign:ti(!1)}}),ri=w.list().map(({id:e})=>e).join(`, `),Y={type:`positional`,description:`Agent ID: ${ri}`,required:!0},ii=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return q(({agentsService:e})=>e.list())}}),ai=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...Y,description:`Optional agent ID: ${ri}`,required:!1}},run({args:e}){return q(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new J(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${ri}`);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}))}))})}}),oi=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:Y,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 q(({agentsService:t})=>{let n=Ke({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),si=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),ci=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),li=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.reapply(e.agent))}}),ui=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.openInstructionFile(e.agent))}}),di=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:ii,skills:ni,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:ai,assign:oi,enable:si,disable:ci,reapply:li,open:ui}})}}),fi=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 q(({instructionsService:t})=>t.create(ln({name:e.name,content:e.content})))}}),pi=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return q(({instructionsService:e})=>e.list())}}),mi=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 q(({instructionsService:t})=>t.get(e.id))}}),hi=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 q(({instructionsService:t})=>t.update(e.id,ln({name:e.name,content:e.content})))}}),gi=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 q(({instructionsService:t})=>t.delete(e.id))}}),_i=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:fi,list:pi,get:mi,edit:hi,delete:gi}});function vi(e){if(!bi(e)||!Array.isArray(e.targets))throw new yi(`targets must be an array`);if(e.targets.length===0)throw new yi(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!st.includes(e))throw new yi(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var yi=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const xi=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 q(async({dataExportService:t})=>{let n=await t.createExport(Xr(e.passphrase)),r=Ci(e.output);return await wi(n.contents,r,e.force),{filePath:r}})}}),Si=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 q(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),Xr(e.passphrase));return t.completeImport({apply:e[`apply-agents`],agentRevision:n.agentRevision}),{status:`imported`}})}});function Ci(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 wi(e,t,n){await Ce(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await ke(a,e,{mode:384}),i.platform!==`win32`&&await ye(a,384),n){await De(a,t);return}if(d(t))throw Ti(t);try{await xe(a,t)}catch(e){throw Ei(e)?Ti(t):e}}finally{await b(a,{force:!0})}}function Ti(e){return new J(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Ei(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Di={"color-theme":{field:`theme`,values:tt},language:{field:`language`,values:nt},"time-zone":{field:`timezone`,values:it},"time-format":{field:`timeFormat`,values:rt}},Oi=[...Object.keys(Di),`config-folder`],ki=Object.entries(Di).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
11
+ `);function Ai(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const ji=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Oi.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return q(({settingsService:t})=>{let n=Ai(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new J(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Oi.join(`, `)}`);return n[e.key]})}}),Mi=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(Di).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${ki}`,required:!0}},run({args:e}){return q(({settingsService:t})=>{if(e.key===`config-folder`)throw new J(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(Di,e.key))throw new J(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(Di).join(`, `)}`);let n=Di[e.key];if(!n.values.includes(e.value))throw new J(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Ai(t.update(ft({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Ni=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return q(({settingsService:e})=>e.openConfigFolder())}}),Pi=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 q(({settingsSkillCopyService:t})=>{let n=vi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Fi=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:ji,set:Mi,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Ni}}),export:xi,import:Si,"download-skill":Pi}}),Ii={type:`positional`,description:`Current skill name`,required:!0},Li=e({meta:{name:`manual`,description:`Create skill metadata with an empty Markdown body in ~/.foundry/${O.skills}/<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 q(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),Ri=e({meta:{name:`local`,description:`Import one local skill folder or .skill/.zip archive; discover skills only at the source root or its immediate child folders`},args:{path:{type:`positional`,description:`One folder or .skill/.zip file. Root SKILL.md takes priority; otherwise only immediate child folders are checked. 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 q(({skillsService:t})=>t.importLocal({path:r.resolve(e.path)}))}}),zi=e({meta:{name:`url`,description:`Download and import a .skill/.zip archive or a raw SKILL.md over HTTP(S)`},args:{url:{type:`positional`,description:`Direct HTTP(S) file URL. SKILL.md imports only that file; archives follow local import rules. Metadata name determines the destination; existing names are never overwritten. Prints { imported, skipped } as JSON.`,required:!0}},run({args:e}){return q(({skillsService:t})=>t.importUrl({url:e.url}))}}),Bi=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 q(({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 q(({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 q(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new R(`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 R(`Skill files input must be valid JSON`)}let o=$n(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 q(({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 q(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:Li,local:Ri,url:zi}})}});function Vi(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Ke(await Hi(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Ui(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=qe(await Hi(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Ui(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Ui(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Ui(t,e)}}),t}async function Hi(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Ui(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Wi(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 Ki(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(ln(await Gi(t)));return t.json(n,201)}catch(e){return Ki(t,e)}}),t.put(`/:id`,async t=>{try{let n=ln(await Gi(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Ki(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Ki(t,e)}}),t}async function Gi(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function Ki(e,t){if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof cn)return e.json({error:{code:t.code,message:t.message}},404);throw t}const qi=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Ji=[`active`,`disabled`,`deleted`];var X=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function Yi(e){if(!na(e))throw new X(`Provider input must be an object`);let t=Z(e.name,`name`),n=ea(e.protocol),r=ta(e.baseURL),i=e.apiKey===void 0?``:Z(e.apiKey,`apiKey`,{allowEmpty:!0}),a=$i(e.customModels);return{...e.avatar!==void 0&&{avatar:Xi(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Xi(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 X(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Zi(e){if(!na(e))throw new X(`Provider connection must be an object`);return{protocol:ea(e.protocol),baseURL:ta(e.baseURL),apiKey:e.apiKey===void 0?``:Z(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Qi(e){if(typeof e!=`string`||!Ji.includes(e))throw new X(`Invalid provider status`);return e}function $i(e){if(e===void 0)return[];if(!Array.isArray(e))throw new X(`customModels must be an array`);return e.map(e=>{if(!na(e))throw new X(`Each custom model must be an object`);return{id:Z(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:Z(e.displayName,`customModels.displayName`)}})}function ea(e){if(typeof e!=`string`||!qi.includes(e))throw new X(`Invalid provider protocol`);return e}function ta(e){let t=Z(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new X(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function Z(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new X(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new X(`${t} is required`);return r}function na(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ra=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function ia(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(aa(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new ra(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new ra(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new ra(`Provider returned invalid JSON`)}return oa(i)}function aa(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function oa(e){if(!ca(e)||!Array.isArray(e.data))throw new ra(`Provider response does not contain a model list`);return e.data.map(e=>{if(!ca(e)||typeof e.id!=`string`||e.id.length===0)throw new ra(`Provider returned an invalid model entry`);let t=sa(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function sa(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function ca(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var la=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},ua=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=>da(e))}get(e){let t=this.storage.get(`providers`,e);return t?da(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 la;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),da(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new la;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),da(i)})}};function da(e){return{...e,avatar:e.avatar??null,status:e.status}}function fa(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 ma(t,e)}}),n.post(`/models`,async t=>{try{let n=Zi(await pa(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ma(t,e)}}),n.post(`/`,async n=>{try{let r=Yi(await pa(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ma(n,e)}}),n.put(`/:id`,async n=>{try{let r=Yi(await pa(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ma(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await pa(n),i=Qi(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 ma(n,e)}}),n}async function pa(e){try{return await e.req.json()}catch{throw new X(`Request body must be valid JSON`)}}function ma(e,t){if(t instanceof X)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof la)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ra)return e.json({error:{code:t.code,message:t.message}},502);throw t}var ha=class{repository;constructor(e){this.repository=new ua(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 la;return ia(t)}fetchModelsForConnection(e){return ia(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function ga(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 _a(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return va(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=vi(await _a(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return va(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r.get(`/skill-status`,async e=>{try{return e.json(await n.getStatus())}catch(t){return va(e,t)}}),r}async function _a(e){try{return await e.req.json()}catch{throw new ht(`Request body must be valid JSON`)}}function va(e,t){if(t instanceof ht||t instanceof yi)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 ya(e){let t=new S;return t.post(`/import/url`,Ve({maxSize:16384,onError:e=>e.json({error:{code:`SKILL_IMPORT_INVALID_URL`,message:`Import requires a file URL`}},400)}),async t=>{try{let n=await e.importUrl(await ba(t));return t.json(n,n.imported.length>0?201:200)}catch(e){return Q(t,e)}}),t.post(`/import/local`,Ve({maxSize:16384,onError:e=>e.json({error:{code:`SKILL_IMPORT_INVALID_SOURCE`,message:`Import requires a local source path`}},400)}),async t=>{try{let n=await e.importLocal(await ba(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=tr(await ba(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 ba(t);return t.json(e.create(V(n)),201)}catch(e){return Q(t,e)}}),t.put(`/:name`,async t=>{try{let n=await ba(t);if(n&&typeof n==`object`&&`files`in n){let r=$n(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),V(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 ba(e){try{return await e.req.json()}catch{throw new R(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof z)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof Jn)return e.json({error:{code:t.code,message:t.message}},404);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}},400);if(t instanceof nr)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof B)return e.json({error:{code:t.code,message:t.message}},404);throw t}function xa(e){let t=new S;return t.get(`/`,t=>He(t,async n=>{await Sa(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Ca(n,e)}),c=setInterval(()=>{r||wa(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 Sa(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Ca(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function wa(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Ta=class extends Error{code=`INVALID_EXPORT_INPUT`};function Ea(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Ta(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Da(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Ta(`Request body must be valid JSON`)}let{passphrase:r}=Ea(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 Ta?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 U(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new U(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new U(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await we(r.join(pe(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await je(Pe.fromWeb(n.req.raw.body),ee(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 U?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 nn(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new U(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(Sr(n)),t.json({status:`completed`})}catch(e){if(e instanceof U){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 ka(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 Aa=Ue(a);function ja(e){return`
12
12
  $ErrorActionPreference = 'Stop'
13
13
  $options = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${x.from(JSON.stringify(e)).toString(`base64`)}')) | ConvertFrom-Json
14
14
  Add-Type -AssemblyName System.Windows.Forms
@@ -66,4 +66,4 @@ function run(argv) {
66
66
  var selected = panel.runModal === $.NSModalResponseOK;
67
67
  return JSON.stringify({ path: selected ? ObjC.unwrap(panel.URL.path) : null });
68
68
  }
69
- `,JSON.stringify(e)]));else if(i.platform===`win32`){let n=x.from(ja(e),`utf16le`).toString(`base64`);({stdout:t}=await Aa(`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:Ma(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 Fa=class{open;isPicking=!1;constructor(e=Pa){this.open=e}async pick(e){if(this.isPicking)throw new $(`FILE_PICKER_BUSY`,`A file picker is already open`,409);let t=ka(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 Ia(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(ka(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 La(e){return e===`/api`||e.startsWith(`/api/`)}function Ra(e,t={}){let n=new S,r=t.providerService??new ha(e),i=t.settingsService??new St(e),a=t.settingsSkillCopyService??new wt,o=t.instructionsService??new Gn(e),s=t.agentsService??new Kn(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`,xa(t.eventHub)),n.route(`/api/file-picker`,Ia(t.filePickerService??new Fa)),n.route(`/api/data-import`,Oa(t.dataImportService??new zr(e),()=>{t.eventHub?.publish(ot,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Da(t.dataExportService??new on(e))),n.route(`/api/agents`,Vi(s)),n.route(`/api/skills`,ya(t.skillsService??new br(e))),n.route(`/api/instructions`,Wi(o)),n.route(`/api/providers`,fa(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,ga(i,e=>{t.eventHub?.publish(ot,e)},a)),n.notFound(e=>La(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),La(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function za(e,t,n){let i=Ra(t,n),a=Be({root:e});i.use(`*`,(e,t)=>La(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`)&&!La(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function Ba(e,t){let n,r=le(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 Va=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 Ha(e){let t=new Va,n=new on(e),r=new zr(e),i=new Gn(e),a=new Kn(e,i),o=new ha(e),s=new St(e),c=new wt,l=new br(e),u=new Fa,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??=Ba(e.path,()=>{t.publish(ot,{fields:[]})})},stop(){f?.(),f=void 0}}}const{dirname:Ua,join:Wa,resolve:Ga}=r,Ka=Ua(Ae(import.meta.url));function qa(){let e=[Ga(Ka,`web`),Ga(i.cwd(),`dist/web`)].find(e=>f(Wa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ja({storage:e,webRoot:t=qa(),onListening:n}){let r=Ha(e),a=za(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 Ya(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 Xa(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 Za=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 Ya(`127.0.0.1`,11111)}catch(e){oo(e);return}let t=Xr(),n=await no();Ja({storage:t,onListening({url:t}){ro(n),console.info(`Foundry is running at ${t}`),e.open&&Xa(t)}})}}),Qa={agents:`ChatGPT (.agents)`,claude:`Claude Code (.claude)`},$a={missing:`not installed`,outdated:`differs from the bundled skill`,current:`up to date`},eo={missing:`✗`,outdated:`!`,current:`✓`},to={missing:`31`,outdated:`33`,current:`32`};async function no(){try{return await new wt().getStatus()}catch{return}}function ro(e){if(!e){console.warn(` ${io(`31`,`✗ Unable to check the Foundry skill`)}`);return}console.info(`Foundry skill (v${e.version})`);for(let t of e.targets){let e=Qa[t.target].padEnd(22);console.info(` ${e}${io(to[t.status],`${eo[t.status]} ${$a[t.status]}`)}`)}let t=e.targets.filter(({status:e})=>e!==`current`);if(t.length===0)return;let n=t.map(({target:e})=>e===`agents`?`.agents`:`.claude`).join(`,`);console.info(` Refresh: foundry settings download-skill --target ${n}`)}function io(e,t){return ao()?`\u{1B}[${e}m${t}\u{1B}[0m`:t}function ao(){return i.env.NO_COLOR===void 0?i.env.FORCE_COLOR===void 0?i.stdout.isTTY:i.env.FORCE_COLOR!==`0`:!1}function oo(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function so(){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:Za,settings:Fi,instructions:vi,agents:fi,skills:Bi}}),t}t(so());export{};
69
+ `,JSON.stringify(e)]));else if(i.platform===`win32`){let n=x.from(ja(e),`utf16le`).toString(`base64`);({stdout:t}=await Aa(`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:Ma(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 Fa=class{open;isPicking=!1;constructor(e=Pa){this.open=e}async pick(e){if(this.isPicking)throw new $(`FILE_PICKER_BUSY`,`A file picker is already open`,409);let t=ka(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 Ia(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(ka(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 La(e){return e===`/api`||e.startsWith(`/api/`)}function Ra(e,t={}){let n=new S,r=t.providerService??new ha(e),i=t.settingsService??new St(e),a=t.settingsSkillCopyService??new wt,o=t.instructionsService??new Gn(e),s=t.agentsService??new Kn(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`,xa(t.eventHub)),n.route(`/api/file-picker`,Ia(t.filePickerService??new Fa)),n.route(`/api/data-import`,Oa(t.dataImportService??new Rr(e),()=>{t.eventHub?.publish(ot,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Da(t.dataExportService??new on(e))),n.route(`/api/agents`,Vi(s)),n.route(`/api/skills`,ya(t.skillsService??new yr(e))),n.route(`/api/instructions`,Wi(o)),n.route(`/api/providers`,fa(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,ga(i,e=>{t.eventHub?.publish(ot,e)},a)),n.notFound(e=>La(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),La(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function za(e,t,n){let i=Ra(t,n),a=Be({root:e});i.use(`*`,(e,t)=>La(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`)&&!La(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function Ba(e,t){let n,r=le(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 Va=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 Ha(e){let t=new Va,n=new on(e),r=new Rr(e),i=new Gn(e),a=new Kn(e,i),o=new ha(e),s=new St(e),c=new wt,l=new yr(e),u=new Fa,ee={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u},d;return{services:ee,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u,eventHub:t},start(){d??=Ba(e.path,()=>{t.publish(ot,{fields:[]})})},stop(){d?.(),d=void 0}}}const{dirname:Ua,join:Wa,resolve:Ga}=r,Ka=Ua(Ae(import.meta.url));function qa(){let e=[Ga(Ka,`web`),Ga(i.cwd(),`dist/web`)].find(e=>d(Wa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ja({storage:e,webRoot:t=qa(),onListening:n}){let r=Ha(e),a=za(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 Ya(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 Xa(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 Za=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 Ya(`127.0.0.1`,11111)}catch(e){oo(e);return}let t=Yr(),n=await no();Ja({storage:t,onListening({url:t}){ro(n),console.info(`Foundry is running at ${t}`),e.open&&Xa(t)}})}}),Qa={agents:`ChatGPT (.agents)`,claude:`Claude Code (.claude)`},$a={missing:`not installed`,outdated:`differs from the bundled skill`,current:`up to date`},eo={missing:`✗`,outdated:`!`,current:`✓`},to={missing:`31`,outdated:`33`,current:`32`};async function no(){try{return await new wt().getStatus()}catch{return}}function ro(e){if(!e){console.warn(` ${io(`31`,`✗ Unable to check the Foundry skill`)}`);return}console.info(`Foundry skill (v${e.version})`);for(let t of e.targets){let e=Qa[t.target].padEnd(22);console.info(` ${e}${io(to[t.status],`${eo[t.status]} ${$a[t.status]}`)}`)}let t=e.targets.filter(({status:e})=>e!==`current`);if(t.length===0)return;let n=t.map(({target:e})=>e===`agents`?`.agents`:`.claude`).join(`,`);console.info(` Refresh: foundry settings download-skill --target ${n}`)}function io(e,t){return ao()?`\u{1B}[${e}m${t}\u{1B}[0m`:t}function ao(){return i.env.NO_COLOR===void 0?i.env.FORCE_COLOR===void 0?i.stdout.isTTY:i.env.FORCE_COLOR!==`0`:!1}function oo(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function so(){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:Za,settings:Fi,instructions:_i,agents:di,skills:Bi}}),t}t(so());export{};
@@ -210,22 +210,26 @@ foundry agents skills unassign chatgpt --skill hello
210
210
  `list` returns an array of registered Skill agents with `id`, `name`, `icon`,
211
211
  `directory`, and saved `skillNames`; the optional agent ID filters the array.
212
212
  It shows persisted assignments even if a link was removed externally.
213
- `assign` and `unassign` operate on one existing Skill and preserve other
214
- assignments. Both print `{ "name": "hello", "agentIds": [...] }` describing
215
- that Skill's remaining assigned agents. Repeated assignment repairs a missing
216
- link without duplication; repeated unassignment is safe. Targets and help
217
- come from the agent registry. Skill assignment is independent of instruction
218
- application and takes effect immediately, without a separate enable command.
219
-
220
- Assignment creates
221
- a directory symlink in that registered agent's Skill directory; deselection
222
- unlinks only entries pointing to the current source. The UI reads saved
223
- `skills.skillNames` from each agent profile at
224
- `~/.foundry/agents/<agent-id>.json`. Existing links are imported once for a
225
- profile without Skill state. External link removal leaves the saved assignment
226
- intact; assigning again or editing the Skill repairs a missing link. Available targets
227
- come from the registry's Skills capability; the Instructions apply switch does
228
- not control Skill availability.
213
+ `assign` requires an existing library Skill. It adds its name once to the
214
+ selected agent record and creates a directory symlink at
215
+ `<agent-skill-directory>/<skill-name>`. An existing entry at that exact name
216
+ is replaced, including files, directories, stale links, and dangling links.
217
+ Other names and agents stay unchanged. Link replacement never deletes a
218
+ symlink's target directory.
219
+
220
+ `unassign` removes the name from the selected saved record and unlinks any
221
+ same-name symbolic link, regardless of its target. Missing links, saved names,
222
+ and library sources succeed; ordinary files and directories remain intact.
223
+ Repeated assign/unassign is safe. Both print `{ "name": "hello", "agentIds": [...] }`
224
+ describing that Skill's remaining saved assignments. These writes operate on
225
+ saved JSON directly rather than importing other external links.
226
+
227
+ The UI reads saved `skills.skillNames` from each agent profile at
228
+ `~/.foundry/agents/<agent-id>.json`. Reading assignments imports existing matching
229
+ links once for a profile without Skill state. External link removal leaves a
230
+ saved assignment intact; assigning again repairs or replaces its named entry.
231
+ Targets come from the registry's Skills capability. Skill assignment takes
232
+ effect immediately and is independent of the Instructions apply switch.
229
233
 
230
234
  Each edit creates or refreshes directory symlinks only for saved assigned
231
235
  agents. This includes edits to description only and missing links for those
@@ -257,8 +261,9 @@ for filesystem behavior and official agent references.
257
261
  - `SKILL_NAME_CONFLICT`: the destination already exists. Create/edit flows require
258
262
  another name; import leaves the existing directory, including an incomplete
259
263
  skill directory, untouched.
260
- - `SKILL_LINK_CONFLICT`: an unrelated entry occupies a registered agent
261
- destination. Preserve that entry and resolve the conflict before retrying.
264
+ - `SKILL_LINK_CONFLICT`: a destination blocks metadata synchronization or rename,
265
+ or an agent directory aliases the library source itself. Resolve that conflict
266
+ before retrying. Explicit assign replaces normal same-name agent entries.
262
267
  - `SKILL_AGENT_NOT_FOUND`: the agent is not registered with Skills support.
263
268
  - Missing required flags produce CLI argument errors.
264
269
  - `skills save` rejects malformed JSON and invalid file trees with the same
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dhzh/foundry",
3
3
  "type": "module",
4
- "version": "9.2.0",
4
+ "version": "10.0.0",
5
5
  "devEngines": {
6
6
  "packageManager": {
7
7
  "name": "pnpm",