@dhzh/foundry 11.3.1 → 11.5.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/README.md +2 -0
- package/dist/index.mjs +5 -5
- package/dist/skills/foundry/SKILL.md +1 -1
- package/dist/skills/foundry/references/skills.md +26 -2
- package/dist/web/assets/{code-editor-CtQzOEql.js → code-editor-YF9gNfN1.js} +3 -3
- package/dist/web/assets/{freemarker2-DBsyOEyw.js → freemarker2-BK-OiiAx.js} +1 -1
- package/dist/web/assets/{handlebars-W9WYCAy1.js → handlebars-BUwXV45a.js} +1 -1
- package/dist/web/assets/{html-6nrZu9iW.js → html-CXsFLKGB.js} +1 -1
- package/dist/web/assets/{index-B-NQl0ZA.js → index-RlfP9eIp.js} +91 -82
- package/dist/web/assets/{javascript-D4CrBxx5.js → javascript-Y_X3V72k.js} +1 -1
- package/dist/web/assets/{jsonMode-DpDBFbN6.js → jsonMode-CaATTrPS.js} +1 -1
- package/dist/web/assets/{liquid-D-MNcHk5.js → liquid-BsbVwgwO.js} +1 -1
- package/dist/web/assets/{mdx-BLpIkdYm.js → mdx-CXoIMvVj.js} +1 -1
- package/dist/web/assets/{python-D8gXK07F.js → python-5rrcKFZw.js} +1 -1
- package/dist/web/assets/{razor-C7ZLx6ca.js → razor-BisWohB-.js} +1 -1
- package/dist/web/assets/{typescript-Dz5wGpka.js → typescript-RLonLSrX.js} +1 -1
- package/dist/web/assets/{xml-Dz6MGmV6.js → xml-CvWpnmZP.js} +1 -1
- package/dist/web/assets/{yaml-4c38m5TE.js → yaml-BwPqT32L.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,6 +35,8 @@ metadata. The full `get` output can be edited and submitted directly.
|
|
|
35
35
|
Use `foundry agents skills list [agent]` to inspect saved assignments,
|
|
36
36
|
`foundry agents skills installed [agent]` to inspect Skills physically present
|
|
37
37
|
in each agent's Skills directory,
|
|
38
|
+
`foundry agents skills bring-in <agent> --skill <name>` to copy an installed
|
|
39
|
+
Skill into Foundry and replace the agent entry with a Foundry symlink,
|
|
38
40
|
`foundry agents skills assign <agent> --skill <name>` to create or repair a
|
|
39
41
|
link, and `foundry agents skills unassign <agent> --skill <name>` to remove it.
|
|
40
42
|
These commands share the Web UI's services, validation, and storage transactions.
|
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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{chmodSync as a,closeSync as o,constants as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,lstatSync as f,mkdirSync as p,openSync as ee,readFileSync as m,readdirSync as h,readlinkSync as te,realpathSync as ne,renameSync as re,rmSync as g,rmdirSync as ie,statSync as _,symlinkSync as ae,unlinkSync as oe,watch as se,writeFileSync as ce}from"node:fs";import le,{homedir as ue,tmpdir as de}from"node:os";import{createCipheriv as fe,createDecipheriv as pe,createHash as me,randomBytes as he,randomUUID as v,scrypt as ge}from"node:crypto";import{chmod as _e,cp as ve,link as ye,lstat as be,mkdir as xe,mkdtemp as Se,open as Ce,readFile as y,readdir as we,rename as Te,rm as b,stat as Ee,writeFile as De}from"node:fs/promises";import{fileURLToPath as Oe}from"node:url";import{pipeline as ke}from"node:stream/promises";import Ae from"yauzl";import je from"yazl";import{Buffer as x}from"node:buffer";import{Readable as Me,Transform as Ne}from"node:stream";import{parse as Pe,parseDocument as Fe,stringify as Ie}from"yaml";import{execFile as Le,spawn as Re}from"node:child_process";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=`11.3.1`,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(){return r.join(le.homedir(),`.foundry`)}function $e(){let e=Qe();return p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&a(e,448),e}const et=[`system`,`light`,`dark`],tt=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],nt=[`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`],rt=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],it=`data/foundry.json`,at=`settings.changed`,ot=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function st(e,t){return ot.compare(e,t)}const ct=[`agents`,`claude`],lt=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function ut(e){return e.trim().normalize(`NFKC`)}function T(e){let t=ut(e);return[...t].length<=64&&t===t.toLowerCase()&<.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 dt={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}}};function ft(e){let t=yt(e)?e:{},n=yt(t.workspace)?t.workspace:{},r=yt(n.appearance)?n.appearance:{},i=yt(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":_t(r[`color-theme`],et,dt.workspace.appearance[`color-theme`])},"language-region":{language:_t(i.language,tt,dt.workspace[`language-region`].language),"time-format":_t(i[`time-format`],nt,dt.workspace[`language-region`][`time-format`]),"time-zone":_t(i[`time-zone`],rt,dt.workspace[`language-region`][`time-zone`])}}}}function pt(e){if(!yt(e))throw new gt(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=vt(e.theme,et,`theme`)),`language`in e&&(t.language=vt(e.language,tt,`language`)),`timeFormat`in e&&(t.timeFormat=vt(e.timeFormat,nt,`timeFormat`)),`timezone`in e&&(t.timezone=vt(e.timezone,rt,`timezone`)),t}function mt(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 ht(e){return{workspace:e.workspace}}var gt=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function _t(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function vt(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new gt(`Invalid ${n}`);return e}function yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bt(e){return e.readSettings()}function xt(e){return ht(bt(e))}function St(e,t){return t.transaction(()=>{let n=mt(bt(t),e);return t.setSettings(n),ht(n)})}var Ct=class{storage;configFolder;constructor(e,t=Qe()){this.storage=e,this.configFolder=t}read(){return{...xt(this.storage),configFolder:this.configFolder}}update(e){return{...St(e,this.storage),configFolder:this.configFolder}}};const wt=r.dirname(Oe(import.meta.url)),D=`foundry`;var Tt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ue()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Dt();if(!u(r.join(t,`SKILL.md`)))throw new Et(`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 xe(n,{recursive:!0}),await ve(t,a,{recursive:!0,errorOnExist:!0}),await jt(a,i,o),{target:e,destination:i}}catch(e){throw await b(a,{recursive:!0,force:!0}),e instanceof Et?e:new Et(`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??Dt();return{version:Ge,targets:await Array.fromAsync(ct,async t=>{let n=r.join(this.getTargetParent(t),D);return{target:t,destination:n,status:await Ot(e,n)}})}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},Et=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function Dt(){let e=[r.resolve(wt,`skills`,D),r.resolve(wt,`..`,`..`,`..`,`skills`,D),r.resolve(i.cwd(),`skills`,D)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new Et(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function Ot(e,t){try{if(!(await be(t)).isDirectory())return`outdated`}catch(e){return At(e)?`missing`:`outdated`}try{return await kt(e,t)?`current`:`outdated`}catch{return`outdated`}}async function kt(e,t){let[n,i]=await Promise.all([we(e,{withFileTypes:!0}),we(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 kt(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 At(e){return typeof e==`object`&&!!e&&Reflect.get(e,`code`)===`ENOENT`}async function jt(e,t,n){let r=u(t);r&&await Te(t,n);try{await Te(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await Te(n,t),e}}const O={instructions:`instructions`,skills:`skills`,agents:`agents`},Mt=[O.instructions,O.skills,O.agents];function Nt(e){return Mt.includes(e)}const Pt=`manifest.json`,Ft=Mt.map(e=>`${e}/`),It=new RegExp(String.raw`^${O.instructions}/[a-f0-9-]+\.md$`,`u`),Lt=new RegExp(String.raw`^${O.agents}/[a-z0-9-]+\.json$`,`u`);function Rt(e){if([Pt,`data/foundry.json`,`settings.json`,...Ft].includes(e)||It.test(e)||Lt.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 zt(e,t){let n=new je.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 ke(n.outputStream,l(t,{mode:384}))}async function Bt(e,t){let n=await Vt(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(!Rt(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 xe(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await xe(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await ke(await Ht(n,e),l(o,{mode:384})),i.set(e.fileName,o),n.readEntry())};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await b(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(Pt))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Vt(e){return new Promise((t,n)=>{Ae.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Ht(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Ut=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=x.from(`FOUNDRYX`,`ascii`),Wt=`aes-256-gcm`,Gt=`scrypt`,Kt={N:131072,r:8,p:1};async function qt(e,t,n){let r=he(16),i=he(12),a={version:1,cipher:Wt,kdf:{name:Gt,salt:r.toString(`base64`),...Kt,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=Yt(o.byteLength),u=x.concat([s,o]),d=await Xt(n,r,Kt);try{let n=await Ce(t,`w`,384);try{await n.write(u)}finally{await n.close()}await ke(c(e),Zt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await _e(t,384)}catch(e){throw await b(t,{force:!0}),new Ut(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function Jt(e,t,n){let r;try{let i=(await Ee(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await Ce(e,`r`),o,s,u;try{if(o=await en(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 en(a,e,13),u=await en(a,16,i-16)}finally{await a.close()}let d=$t(JSON.parse(s.toString(`utf8`)));r=await Xt(n,d.salt,d.header.kdf);let f=x.concat([o,s]);await ke(c(e,{start:13+s.byteLength,end:i-16-1}),Qt(r,d.nonce,f,u),l(t,{mode:384})),await _e(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Ut?e:new Ut(nn(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,nn(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 Yt(e){let t=x.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Xt(e,t,n){return new Promise((r,i)=>{ge(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Zt(e,t,n){let r=fe(Wt,e,t,{authTagLength:16});return r.setAAD(n),new Ne({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 Qt(e,t,n,r){let i=pe(Wt,e,t,{authTagLength:16});return i.setAAD(n),new Ne({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 $t(e){if(!tn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Wt||!tn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Gt||typeof t.salt!=`string`||t.N!==Kt.N||t.r!==Kt.r||t.p!==Kt.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:Wt,kdf:{name:Gt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function en(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 tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function rn(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function an(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`&&Nt(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!Rt(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 Mt)n(e);return t})}function on(e){return me(`sha256`).update(e).digest(`hex`)}var sn=class{storage;constructor(e){this.storage=e}async createExport(e){let t=an(this.storage),n=await Se(r.join(de(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=r.join(n,`manifest.json`),o=r.join(n,`foundry.zip`),s=r.join(n,`foundry.foundry-backup`),c={format:`foundry.data`,archiveVersion:4,appVersion:Ge,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:on(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 De(t,i.contents,{mode:384}),l.push({entryPath:i.path,filePath:t})}return await De(a,JSON.stringify(c,null,2),{mode:384}),await zt([{entryPath:`manifest.json`,filePath:a},...l],o),await qt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await y(s)}}finally{await rn(n)}}};const cn=/^[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`}},ln=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function un(e){if(!dn(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 dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const fn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function pn(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=Tn(t,r.id),a=vn(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function mn(e){return e.transaction(()=>{let t=wn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(En(e))return[];throw e}return n.map(e=>bn(r.join(t,e),e)).toSorted((e,t)=>st(e.name,t.name))})}function hn(e,t){return t.transaction(()=>{if(!cn.test(e))return;let n=`${e}.md`;try{return bn(r.join(wn(t),n),n)}catch(e){if(En(e))return;throw e}})}function gn(e,t,n){return n.transaction(()=>{let r=hn(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(Tn(n,i.id),vn(i)),i})}function _n(e,t){if(!cn.test(e))return`missing`;let n=wn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>u(i)?(t.removeTextFile(i),`removed`):`missing`)}function vn(e){return`---\n${Ie({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function yn(e,t){let n=fn.exec(e);if(!n)throw j(t);let r=xn(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{chmodSync as a,closeSync as o,constants as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,lstatSync as f,mkdirSync as p,openSync as ee,readFileSync as m,readdirSync as h,readlinkSync as te,realpathSync as ne,renameSync as re,rmSync as g,rmdirSync as ie,statSync as _,symlinkSync as ae,unlinkSync as oe,watch as se,writeFileSync as ce}from"node:fs";import le,{homedir as ue,tmpdir as de}from"node:os";import{createCipheriv as fe,createDecipheriv as pe,createHash as me,randomBytes as he,randomUUID as v,scrypt as ge}from"node:crypto";import{chmod as _e,cp as ve,link as ye,lstat as be,mkdir as xe,mkdtemp as Se,open as Ce,readFile as y,readdir as we,rename as Te,rm as b,stat as Ee,writeFile as De}from"node:fs/promises";import{fileURLToPath as Oe}from"node:url";import{pipeline as ke}from"node:stream/promises";import Ae from"yauzl";import je from"yazl";import{Buffer as x}from"node:buffer";import{Readable as Me,Transform as Ne}from"node:stream";import{parse as Pe,parseDocument as Fe,stringify as Ie}from"yaml";import{execFile as Le,spawn as Re}from"node:child_process";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=`11.5.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(){return r.join(le.homedir(),`.foundry`)}function $e(){let e=Qe();return p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&a(e,448),e}const et=[`system`,`light`,`dark`],tt=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],nt=[`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`],rt=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],it=`data/foundry.json`,at=`settings.changed`,ot=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function st(e,t){return ot.compare(e,t)}const ct=[`agents`,`claude`],lt=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function ut(e){return e.trim().normalize(`NFKC`)}function T(e){let t=ut(e);return[...t].length<=64&&t===t.toLowerCase()&<.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 dt={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}}};function ft(e){let t=yt(e)?e:{},n=yt(t.workspace)?t.workspace:{},r=yt(n.appearance)?n.appearance:{},i=yt(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":_t(r[`color-theme`],et,dt.workspace.appearance[`color-theme`])},"language-region":{language:_t(i.language,tt,dt.workspace[`language-region`].language),"time-format":_t(i[`time-format`],nt,dt.workspace[`language-region`][`time-format`]),"time-zone":_t(i[`time-zone`],rt,dt.workspace[`language-region`][`time-zone`])}}}}function pt(e){if(!yt(e))throw new gt(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=vt(e.theme,et,`theme`)),`language`in e&&(t.language=vt(e.language,tt,`language`)),`timeFormat`in e&&(t.timeFormat=vt(e.timeFormat,nt,`timeFormat`)),`timezone`in e&&(t.timezone=vt(e.timezone,rt,`timezone`)),t}function mt(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 ht(e){return{workspace:e.workspace}}var gt=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function _t(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function vt(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new gt(`Invalid ${n}`);return e}function yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bt(e){return e.readSettings()}function xt(e){return ht(bt(e))}function St(e,t){return t.transaction(()=>{let n=mt(bt(t),e);return t.setSettings(n),ht(n)})}var Ct=class{storage;configFolder;constructor(e,t=Qe()){this.storage=e,this.configFolder=t}read(){return{...xt(this.storage),configFolder:this.configFolder}}update(e){return{...St(e,this.storage),configFolder:this.configFolder}}};const wt=r.dirname(Oe(import.meta.url)),D=`foundry`;var Tt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ue()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Dt();if(!u(r.join(t,`SKILL.md`)))throw new Et(`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 xe(n,{recursive:!0}),await ve(t,a,{recursive:!0,errorOnExist:!0}),await jt(a,i,o),{target:e,destination:i}}catch(e){throw await b(a,{recursive:!0,force:!0}),e instanceof Et?e:new Et(`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??Dt();return{version:Ge,targets:await Array.fromAsync(ct,async t=>{let n=r.join(this.getTargetParent(t),D);return{target:t,destination:n,status:await Ot(e,n)}})}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},Et=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function Dt(){let e=[r.resolve(wt,`skills`,D),r.resolve(wt,`..`,`..`,`..`,`skills`,D),r.resolve(i.cwd(),`skills`,D)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new Et(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function Ot(e,t){try{if(!(await be(t)).isDirectory())return`outdated`}catch(e){return At(e)?`missing`:`outdated`}try{return await kt(e,t)?`current`:`outdated`}catch{return`outdated`}}async function kt(e,t){let[n,i]=await Promise.all([we(e,{withFileTypes:!0}),we(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 kt(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 At(e){return typeof e==`object`&&!!e&&Reflect.get(e,`code`)===`ENOENT`}async function jt(e,t,n){let r=u(t);r&&await Te(t,n);try{await Te(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await Te(n,t),e}}const O={instructions:`instructions`,skills:`skills`,agents:`agents`},Mt=[O.instructions,O.skills,O.agents];function Nt(e){return Mt.includes(e)}const Pt=`manifest.json`,Ft=Mt.map(e=>`${e}/`),It=new RegExp(String.raw`^${O.instructions}/[a-f0-9-]+\.md$`,`u`),Lt=new RegExp(String.raw`^${O.agents}/[a-z0-9-]+\.json$`,`u`);function Rt(e){if([Pt,`data/foundry.json`,`settings.json`,...Ft].includes(e)||It.test(e)||Lt.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 zt(e,t){let n=new je.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 ke(n.outputStream,l(t,{mode:384}))}async function Bt(e,t){let n=await Vt(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(!Rt(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 xe(r.dirname(o),{recursive:!0,mode:448}),e.fileName.endsWith(`/`)?(await xe(o,{recursive:!0,mode:448}),i.set(e.fileName,o),n.readEntry()):(await ke(await Ht(n,e),l(o,{mode:384})),i.set(e.fileName,o),n.readEntry())};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await b(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(Pt))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Vt(e){return new Promise((t,n)=>{Ae.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Ht(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Ut=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=x.from(`FOUNDRYX`,`ascii`),Wt=`aes-256-gcm`,Gt=`scrypt`,Kt={N:131072,r:8,p:1};async function qt(e,t,n){let r=he(16),i=he(12),a={version:1,cipher:Wt,kdf:{name:Gt,salt:r.toString(`base64`),...Kt,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=Yt(o.byteLength),u=x.concat([s,o]),d=await Xt(n,r,Kt);try{let n=await Ce(t,`w`,384);try{await n.write(u)}finally{await n.close()}await ke(c(e),Zt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await _e(t,384)}catch(e){throw await b(t,{force:!0}),new Ut(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function Jt(e,t,n){let r;try{let i=(await Ee(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await Ce(e,`r`),o,s,u;try{if(o=await en(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 en(a,e,13),u=await en(a,16,i-16)}finally{await a.close()}let d=$t(JSON.parse(s.toString(`utf8`)));r=await Xt(n,d.salt,d.header.kdf);let f=x.concat([o,s]);await ke(c(e,{start:13+s.byteLength,end:i-16-1}),Qt(r,d.nonce,f,u),l(t,{mode:384})),await _e(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Ut?e:new Ut(nn(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,nn(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 Yt(e){let t=x.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Xt(e,t,n){return new Promise((r,i)=>{ge(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Zt(e,t,n){let r=fe(Wt,e,t,{authTagLength:16});return r.setAAD(n),new Ne({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 Qt(e,t,n,r){let i=pe(Wt,e,t,{authTagLength:16});return i.setAAD(n),new Ne({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 $t(e){if(!tn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Wt||!tn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Gt||typeof t.salt!=`string`||t.N!==Kt.N||t.r!==Kt.r||t.p!==Kt.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:Wt,kdf:{name:Gt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function en(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 tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function rn(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function an(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`&&Nt(i)){t.push({path:`${i}/`,contents:null});return}throw e}let s=`${i}${o.isDirectory()?`/`:``}`;if(!o.isDirectory()&&!o.isFile()||o.isSymbolicLink()||!Rt(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 Mt)n(e);return t})}function on(e){return me(`sha256`).update(e).digest(`hex`)}var sn=class{storage;constructor(e){this.storage=e}async createExport(e){let t=an(this.storage),n=await Se(r.join(de(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=r.join(n,`manifest.json`),o=r.join(n,`foundry.zip`),s=r.join(n,`foundry.foundry-backup`),c={format:`foundry.data`,archiveVersion:4,appVersion:Ge,createdAt:i,files:t.filter(e=>e.contents!==null).map(e=>({path:e.path,bytes:e.contents.byteLength,sha256:on(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 De(t,i.contents,{mode:384}),l.push({entryPath:i.path,filePath:t})}return await De(a,JSON.stringify(c,null,2),{mode:384}),await zt([{entryPath:`manifest.json`,filePath:a},...l],o),await qt(o,s,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await y(s)}}finally{await rn(n)}}};const cn=/^[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`}},ln=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function un(e){if(!dn(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 dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const fn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function pn(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=Tn(t,r.id),a=vn(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function mn(e){return e.transaction(()=>{let t=wn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(En(e))return[];throw e}return n.map(e=>bn(r.join(t,e),e)).toSorted((e,t)=>st(e.name,t.name))})}function hn(e,t){return t.transaction(()=>{if(!cn.test(e))return;let n=`${e}.md`;try{return bn(r.join(wn(t),n),n)}catch(e){if(En(e))return;throw e}})}function gn(e,t,n){return n.transaction(()=>{let r=hn(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(Tn(n,i.id),vn(i)),i})}function _n(e,t){if(!cn.test(e))return`missing`;let n=wn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>u(i)?(t.removeTextFile(i),`removed`):`missing`)}function vn(e){return`---\n${Ie({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function yn(e,t){let n=fn.exec(e);if(!n)throw j(t);let r=xn(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
4
|
`)&&(i=i.slice(1)),{...r,content:i}}function bn(e,t){return yn(m(e,`utf8`),t)}function xn(e){let t;try{t=Pe(e)}catch{throw j(`frontmatter`)}if(!Dn(t))throw j(`frontmatter`);let n=Sn(t.id),r=Sn(t.name);if(!r||r.length>200||!cn.test(n))throw j(`frontmatter`);return{id:n,name:r,createdAt:Cn(t.createdAt),updatedAt:Cn(t.updatedAt)}}function Sn(e){return typeof e==`string`?e:``}function Cn(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw j(`frontmatter`);return e}function wn(e){return r.join(e.path,O.instructions)}function Tn(e,t){if(!cn.test(t))throw Error(`Invalid instruction ID`);return r.join(wn(e),`${t}.md`)}function j(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function En(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function Dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function M(e,t=w){return t.list().map(t=>{let n=t.capabilities.skills?.directory;return{id:t.id,name:t.name,icon:t.icon.name,instructionFile:Ye(t.capabilities.instructions.file),filePath:Xe(e,t.capabilities.instructions.file),...n&&{skillsDirectoryPath:Xe(e,n)},capabilities:Ze(t)}})}function N(e){p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&a(e,448)}function P(e){if(i.platform===`win32`)return;let t=ee(e,`r`);try{d(t)}finally{o(t)}}function On(e,t){kn(e,`${JSON.stringify(t,null,2)}\n`)}function kn(e,t){An(e,t)}function An(e,t){N(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=ee(n,`wx`,384);try{ce(i,t),d(i)}finally{o(i)}re(n,e),P(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);p(n,{recursive:!0,mode:448});let s=u(e)?_(e).mode&511:384,c=`${e}.${v()}.tmp`;try{let r=ee(c,`wx`,s);try{i.platform!==`win32`&&a(c,s),ce(r,t),d(r)}finally{o(r)}re(c,e),P(n)}finally{g(c,{force:!0})}}function F(e,t,n){let r=u(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){u(e.filePath)&&m(e.filePath,`utf8`)}function I(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(M(n).map(e=>[e.id,e])),a=new Map(mn(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&&F(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}})}}function Gn(e,t,n){let r=Vn(e).filter(({instructions:e})=>e.enabled&&e.instructionIds.includes(t.id));if(r.length===0)return;let i=new Map(M(n).map(e=>[e.id,e])),a=new Map(mn(e).map(e=>[e.id,e.content]));a.set(t.id,t.content);for(let e of r){let t=i.get(e.id);t&&F(t,e.instructions.instructionIds.map(e=>a.get(e)).filter(e=>e!==void 0),!1)}}var Kn=class{storage;homeDirectory;constructor(e,t=le.homedir()){this.storage=e,this.homeDirectory=t}list(){return mn(this.storage)}get(e){let t=hn(e,this.storage);if(!t)throw new ln(e);return t}create(e){return pn(e,this.storage)}update(e,t){return this.storage.transaction(()=>{let n=gn(e,t,this.storage);if(!n)throw new ln(e);return Gn(this.storage,n,this.homeDirectory),n})}delete(e){return this.storage.transaction(()=>{let t=hn(e,this.storage);if(!t||(Wn(this.storage,e,this.homeDirectory),_n(e,this.storage)===`missing`))throw new ln(e);return t})}};const qn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Jn(e){let t;try{t=h(e,{withFileTypes:!0,encoding:`utf8`})}catch(e){if(Zn(e))return[];throw e}let n=[];for(let i of t){let t=r.join(e,i.name),a=i.isSymbolicLink(),o;try{o=_(t)}catch{continue}if(!o.isDirectory())continue;let s=r.join(t,`SKILL.md`),c;try{let e=_(s);if(!e.isFile()||e.size>2097152)continue;c=Xn(m(s,`utf8`))}catch{continue}if(!c)continue;let l=a?$n(t):null;n.push({directoryName:i.name,...c,...l!==null&&{originPath:l}})}return n.toSorted((e,t)=>e.name.localeCompare(t.name))}function Yn(e){let t;try{t=h(e,{withFileTypes:!0,encoding:`utf8`})}catch(e){if(Zn(e))return[];throw e}return t.filter(e=>e.isSymbolicLink()).map(t=>{let n=$n(r.join(e,t.name));return n!==null&&er(n)?n:null}).filter(e=>e!==null)}function Xn(e){let t=qn.exec(e);if(!t)return null;let n;try{n=Pe(t[1])}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=typeof r.name==`string`?r.name.trim():``,a=typeof r.description==`string`?r.description.trim():``;return i&&a?{name:i,description:a}:null}function Zn(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function Qn(e){return r.resolve(r.dirname(e),te(e))}function $n(e){try{return Qn(e)}catch{return null}}function er(e){try{return _(e).isDirectory()}catch{return!1}}var tr=class{storage;instructionsService;definitions;constructor(e,t=new Kn(e),n=le.homedir()){this.storage=e,this.instructionsService=t,this.definitions=M(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=>nr(t,(e.get(t.id)??I(t.id)).instructions))}listInstalledSkills(e){let t=this.requireDefinition(e);if(!t.skillsDirectoryPath)throw new C(`AGENT_SKILLS_NOT_SUPPORTED`,`Agent does not support skills: ${e}`,404);return Jn(t.skillsDirectoryPath)}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=Hn(this.storage,e)??I(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&F(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 nr(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Hn(this.storage,e)??I(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);F(n,e.map(({content:e})=>e),!1)}else F(n,[],!0);let a=Date.now();return nr(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)??I(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);F(t,i.map(({content:e})=>e),!1);let a=Date.now();return nr(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)??I(t.id)).instructions;return{agentId:t.id,enabled:n.enabled,contents:n.enabled?this.readAssignedInstructions(n.instructionIds).map(({content:e})=>e):[]}}))})}instructionFileTarget(e){let t=this.requireDefinition(e);return{instructionFile:t.instructionFile,filePath:t.filePath}}};function nr(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 rr=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},ir=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},ar=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 rr(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=>R(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()&&R(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&&or(t)===or(n)||t&&n&&!e.assignment&&L(t)&&!R(t,n)&&!R(t,r))throw new ir(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=me(`sha256`).update(`${i}\0${a}`).digest(`hex`),s=r.join(t,`.foundry-${n}.tmp`);try{if(L(s)&&!R(s,a))throw new ir(s);if(L(s)||ae(a,s,`dir`),!e.assignment&&L(i)&&!R(i,a)&&!R(i,o))throw new ir(i);e.assignment&&L(i)&&f(i).isDirectory()&&g(i,{recursive:!0,force:!0}),re(s,i),P(t)}finally{R(s,a)&&oe(s)}}let s=e.assignment?L(n)&&f(n).isSymbolicLink():R(n,o);if(n!==i&&s){try{oe(n)}catch(e){if(e.code!==`ENOENT`)throw e}P(t)}}}};function L(e){try{return f(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function R(e,t){return L(e)&&f(e).isSymbolicLink()&&or(r.resolve(r.dirname(e),te(e)))===or(t)}function or(e){try{return r.join(ne(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var z=class extends Error{code=`INVALID_SKILL_INPUT`},B=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function sr(e){if(typeof e!=`string`||!E(e))throw new B(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function cr(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new z(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new z(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new z(`Invalid file entry`);let o=sr(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new z(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new z(`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 z(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(lr(e.content),n+=x.byteLength(e.content,`utf8`),n>16777216))throw new z(`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 B(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function lr(e){if(x.byteLength(e,`utf8`)>2097152)throw new B(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new B(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function ur(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new z(`assigned must be a boolean`);return{assigned:e.assigned}}var V=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},dr=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function fr(e){return e===e.trim()&&T(e)}function H(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new z(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new z(`name is required`);let t=ut(e.name);if(!fr(t))throw new z(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new z(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new z(`description must be 1–1024 characters`);return{name:t,description:n}}function U(e,t){throw new B(e,t,400)}function pr(e){return e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r.isAbsolute(e.path)&&!e.path.includes(`\0`)||U(`SKILL_IMPORT_INVALID_SOURCE`,`path must be an absolute local filesystem path`),{path:e.path}}function mr(e){if(!e||typeof e!=`object`||!(`url`in e)||typeof e.url!=`string`)throw new B(`SKILL_IMPORT_INVALID_URL`,`Enter an HTTP or HTTPS file URL`,400);return{url:hr(e.url).href}}function hr(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 B(`SKILL_IMPORT_INVALID_URL`,`Use an HTTP or HTTPS file URL without embedded credentials`,400)}}function gr(e){e&&typeof e==`object`&&`entries`in e&&Array.isArray(e.entries)&&e.entries.length!==0||U(`SKILL_IMPORT_MISSING_SKILL_MD`,`Select one skill containing SKILL.md`),e.entries.length>5e3&&U(`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`)&&U(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path or file`);let i=e.path.normalize(`NFKC`).toLowerCase();if(n.has(i)&&U(`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)&&U(`SKILL_IMPORT_INVALID_ENCODING`,`Invalid file encoding`),r+=x.from(e.contents,`base64`).length,r>33554432))throw new B(`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&&U(`SKILL_IMPORT_INVALID_PATH`,`A file occupies a parent directory`)}}let a=i.find(e=>e.path===`SKILL.md`);a?.contents??U(`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 B(`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`))&&U(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must contain valid YAML frontmatter`),{skill:{...H(Pe(t[1])),content:e.slice(t[0].length)},entries:i}}catch{U(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must be UTF-8 Markdown with a valid name and description in YAML frontmatter`)}}const _r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function vr(e,t){let n=_r.exec(t);if(!n)throw new z(`SKILL.md must contain YAML frontmatter`);let r;try{r=Pe(n[1])}catch{throw new z(`SKILL.md must contain valid YAML frontmatter`)}let i=H(r);if(i.name!==ut(e))throw new z(`Skill name must match its directory; use the rename action to change it`);return{...i,content:t.slice(n[0].length)}}var yr=class{storage;constructor(e){this.storage=e}directory(e){if(!fr(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 z(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new V(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 dr(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${Ie(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 V(e);this.assertSourceDirectory(e);let i=this.directory(e),a=m(r.join(i,`SKILL.md`),`utf8`),o=_r.exec(a);if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=Fe(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 V(e);return this.assertSourceDirectory(e),this.storage.removeSkillDirectory(this.directory(e)),t})}get(e){if(fr(e))return this.storage.transaction(()=>{try{return vr(e,m(r.join(this.directory(e),`SKILL.md`),`utf8`))}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()&&fr(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 br(e){return e.flatMap(e=>e.children?[e,...br(e.children)]:[e])}var xr=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new V(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 B(`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 B(`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=(e,t)=>h(e,{withFileTypes:!0}).toSorted((e,t)=>e.name.localeCompare(t.name)).flatMap(i=>{let a=t?`${t}/${i.name}`:i.name;if(!E(a)||i.isSymbolicLink())return[];let o=r.join(e,i.name);if(i.isDirectory())return[{path:a,children:n(o,a)}];if(!i.isFile())return[];let s=null;if(f(o).size<=2097152)try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(m(o));s=e.includes(`\0`)?null:e}catch{}return[{path:a,content:s}]});return n(t,``)}replace(e,t){let n=this.root(e),i=new Map(br(this.read(e)).map(e=>[e.path,e])),a=new Map(br(t).map(e=>[e.path,e]));for(let t of a.values()){if(this.assertLocal(n,t.path),t.content===null&&i.get(t.path)?.content!==null)throw new B(`SKILL_FILE_NOT_TEXT`,`Uneditable files must refer to existing unchanged files`,415);t.path===`SKILL.md`&&typeof t.content==`string`&&vr(e,t.content)}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 e of a.values()){let t=i.get(e.path),a=r.join(n,e.path);e.children?t?.children||this.storage.createSkillFolder(a):e.content!==null&&e.content!==t?.content&&this.storage.putTextFile(a,e.content)}}};async function Sr(e){try{let t=await be(e);if(t.isSymbolicLink()&&U(`SKILL_IMPORT_SYMLINK_SOURCE`,`Select a skill source, not a symbolic link`),t.isFile()&&/\.(?:skill|zip)$/iu.test(e))return wr(t.size),await Tr(e);t.isDirectory()||U(`SKILL_IMPORT_INVALID_SOURCE`,`Select a skill folder or a .skill / .zip archive`);let n=await we(e,{withFileTypes:!0}),i={bytes:0,entries:0};if(n.some(e=>e.name===`SKILL.md`))return{isBatch:!1,candidates:[await Cr(e,i)]};let a=[];for(let t of n)if(t.isDirectory()||t.isSymbolicLink()){i.entries>=5e3&&U(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The source contains too many entries`),i.entries++;try{a.push(await Cr(r.join(e,t.name),i))}catch(e){if(e instanceof B&&[`SKILL_IMPORT_TOO_LARGE`,`SKILL_IMPORT_TOO_MANY_ENTRIES`].includes(e.code))throw e;a.push({source:t.name,entries:[],readError:e instanceof B?e:new B(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)})}}return{isBatch:!0,candidates:a}}catch(e){throw e instanceof B?e:new B(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)}}async function Cr(e,t){let n=await be(e);(n.isSymbolicLink()||!n.isDirectory())&&U(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`);let i=await we(e);i.includes(`SKILL.md`)||U(`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)&&U(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path`),t.entries>=5e3&&U(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`),t.entries++;let i=await be(e);if((i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())&&U(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`),i.isDirectory()){a.push({path:n,contents:null});let t=await we(e);for(let i of t)await o(r.join(e,i),`${n}/${i}`)}else{wr(t.bytes+i.size);let r=await Ce(e,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);try{let e=await r.stat();e.isFile()||U(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Select a regular skill file`),wr(t.bytes+e.size);let i=[],o;do{let e=x.alloc(65536);({bytesRead:o}=await r.read(e)),t.bytes+=o,wr(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 wr(e){if(e>33554432)throw new B(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413)}async function Tr(e){let{entries:t,unsupported:n}=await Er(e);return t.some(e=>e.path===`SKILL.md`)?(n.length>0&&U(`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 Er(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`?Ae.open(e,i,r):Ae.fromBuffer(e,i,r)})}catch{U(`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&&U(`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 B(`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)&&U(`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 B)throw e;U(`SKILL_IMPORT_INVALID_ARCHIVE`,`Unable to read the skill archive`)}finally{t.close()}return{entries:n,unsupported:r}}function Dr(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 B(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a .skill, .zip, or SKILL.md file URL`,400)}}async function Or(e){let t=hr(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 B(`SKILL_IMPORT_DOWNLOAD_FAILED`,`The download redirected too many times or has no destination`,400);t=hr(n,t);continue}if(!r.ok||!r.body)throw new B(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400);let n=Dr(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 B(`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 B(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 Tr(l)}finally{if(!r.body?.locked)try{await r.body?.cancel()}catch{}}}}catch(e){throw e instanceof B?e:new B(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 B(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400)}var kr=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new yr(e),this.files=new xr(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)??I(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&&U(`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&&U(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`);let{skill:e,entries:t}=gr({entries:r.entries});n.imported.push(this.repository.import(e,t))}catch(t){if(!e||!(t instanceof B||t instanceof z||t instanceof dr))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 z(`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)??I(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(H(e))}async importLocal(e){let t=pr(e);return this.importSource(await Sr(t.path))}async importUrl(e){let t=mr(e);return this.importSource(await Or(t.url))}get(e){let t=this.repository.get(e);if(!t)throw new V(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(!fr(e))throw new z(`Invalid skill name`);if(this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new rr(t);n&&this.get(e);let r=this.storage.get(`agents`,t)??I(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=H(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=cr({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})}},W=class extends Error{code;constructor(e,t){super(t),this.code=e}};function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ar(e){if(!G(e)||e.format!==`foundry.data`)throw q(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&G(e.data)&&e.data.path===`data/foundry.json`&&jr(e.data))return{archiveVersion:2,data:{path:it,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==4||!Array.isArray(e.files)||!Array.isArray(e.directories))throw q(`Unsupported or invalid backup manifest`);return{archiveVersion:4,files:e.files.map(e=>{if(!G(e)||typeof e.path!=`string`||!jr(e))throw q(`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 q(`Invalid backup directory`);return e})}}function jr(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 Mr(e){if(!G(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw q(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function Nr(e){if(!G(e)||!G(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw q(`Backup data must contain settings, instructions, and agents`);let t=Pr(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:ft(e.settings),instructions:t,agents:Fr(e.agents,n)}}function Pr(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!G(e))throw q(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!cn.test(r)||t.has(r))throw q(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw q(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw q(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:K(e.createdAt,n),updatedAt:K(e.updatedAt,n)};return t.add(r),a})}function Fr(e,t,n){let r=new Set(w.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!G(e)||!G(e.instructions))throw q(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw q(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw q(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw q(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw q(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw q(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw q(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:K(s.createdAt,a),updatedAt:K(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!G(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 q(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:K(t.createdAt,a),updatedAt:K(t.updatedAt,a)}}return i.add(o),u})}function K(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw q(`Invalid timestamp at index ${t}`);return e}function q(e){return new W(`INVALID_BACKUP`,e)}const Ir=`${O.skills}/`,Lr=`${O.instructions}/`,Rr=`${O.agents}/`,zr=RegExp(`^${O.skills}/[^/]+/$`,`u`);function Br(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!Rt(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new W(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||Mt.some(t=>e.every(e=>e.path!==`${t}/`)))throw new W(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(Lr)&&e.contents!==null).map(e=>yn(Vr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>zr.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(Vr(r));if(!i||H(Pe(i[1])).name!==n)throw new W(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(Ir)&&t.path!==Ir&&!a.has(t.path.split(`/`,2)[1]))throw new W(`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 W(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(Rr)&&e.contents!==null).map(e=>{let t=JSON.parse(Vr(e.contents));if(!t||typeof t!=`object`||!(`id`in t)||`${String(t.id)}.json`!==r.posix.basename(e.path))throw new W(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(Vr(n));Nr({settings:c,instructions:i,agents:s});let l=Fr(s,new Set(i.map(({id:e})=>e)),a);return{entries:e,settings:ft(c),agents:l}}function Vr(e){return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}function Hr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of mn(e))n.has(t.id)||e.removeTextFile(Ur(t.id));for(let n of t.instructions)e.putTextFile(Ur(n.id),vn(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`,{...I(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),Gr(e)})}function Ur(e){return r.join(O.instructions,`${e}.md`)}function Wr(e,t){return e.transaction(()=>{for(let n of Mt)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),Kr(t.entries.filter(e=>e.path.startsWith(`${O.agents}/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function Gr(e){return Kr(e.all(`agents`))}function Kr(e){return me(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function qr(e){for(let{id:t}of w.list()){let n=e.get(`agents`,t)??I(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 Jr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(Gr(this.storage)!==t)throw new W(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new tr(this.storage).applyConfiguration(),new kr(this.storage).applyAssignments()):qr(this.storage)})}catch(t){throw t instanceof W?t:new W(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 Se(r.join(de(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await Jt(e,i,t);let a=await Bt(i,r.join(n,`extracted`)),o=Ar(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 W(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await y(a[it]);Yr(e,o.data);let t=Nr(JSON.parse(e.toString(`utf8`)));s=()=>Hr(this.storage,t)}else{let e=new Set(Object.keys(a)),t=[`manifest.json`,...o.files.map(e=>e.path),...o.directories];if(new Set(t).size!==t.length||t.length!==Object.keys(a).length||t.some(t=>!e.has(t)))throw new W(`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]);Yr(t,e),n.push({path:e.path,contents:t})}let r=Br(n);s=()=>Wr(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new W(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof W?e:e instanceof Ut?e.code===`INVALID_PASSPHRASE`?new W(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new W(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new W(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await rn(n)}}};function Yr(e,t){if(e.byteLength!==t.bytes||on(e)!==t.sha256)throw new W(`INVALID_BACKUP`,`Backup checksum does not match`)}function Xr(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=Re(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}var J=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`OpenPathError`}};function Zr(e){if(!Qr(e)||typeof e.path!=`string`||e.path.length===0||e.path.includes(`\0`))throw new J(`INVALID_OPEN_PATH`,`path must be a non-empty filesystem path`,400);return{path:e.path}}function Qr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $r=class{homeDirectory;configFolder;opener;definitions;constructor(e=le.homedir(),t=Qe(),n=Xr,r=M(e)){this.homeDirectory=e,this.configFolder=t,this.opener=n,this.definitions=r}resolvePath(e){let t=e===`~`?this.homeDirectory:e.startsWith(`~/`)||e.startsWith(`~\\`)?r.join(this.homeDirectory,e.slice(2)):e;if(!r.isAbsolute(t))throw new J(`INVALID_OPEN_PATH`,`path must be absolute or start with ~/`,400);return r.resolve(t)}allowedPaths(){let e=/* @__PURE__ */ new Set([r.resolve(this.configFolder)]);for(let t of this.definitions)if(e.add(r.resolve(t.filePath)),t.skillsDirectoryPath)for(let n of Yn(t.skillsDirectoryPath))e.add(r.resolve(n));return e}open(e){let t=this.resolvePath(e);if(!this.allowedPaths().has(t))throw new J(`OPEN_PATH_NOT_ALLOWED`,`Path is not an openable Foundry target`,403);try{_(t)}catch(e){throw ei(e)?new J(`OPEN_PATH_NOT_FOUND`,`The target path does not exist`,404):e}return this.opener(t),{path:t}}};function ei(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}const ti=[`agents`,`providers`],ni=new RegExp(String.raw`^${O.skills}[/\\]([^/\\]+)$`,`u`),ri=new RegExp(String.raw`^${O.instructions}[/\\][^/\\]+\.md$`,`u`);function ii(e){let t=ni.exec(e);return!!(t&&t[1]===t[1].trim()&&T(t[1]))}function ai(e){return ri.test(e)||oi(e)}function oi(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 si(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 ci=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=le.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new ar(e,t),N(e);for(let e of ti)e!==`providers`&&N(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),`${me(`sha256`).update(t).digest(`hex`)}.json`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!ai(t))throw Error(`Invalid storage text filename`);return t}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=r.join(this.path,`.lock`),n=Date.now();for(;;)try{p(t,{mode:448});try{ce(r.join(t,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384})}catch(e){throw g(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,this.initializeProviders(),this.initializeAgents(),e()}finally{this.lockDepth=0,g(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=_(e);if(!si(e))return;let n=r.join(e,`recovering`);try{p(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);si(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ce(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!si(e)){g(n,{recursive:!0,force:!0});return}g(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!u(e))return;let t=JSON.parse(m(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!u(e)){let e=u(t)?h(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};On(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(ie(t),P(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!==`${me(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(u(r.join(this.path,a))){let e=JSON.parse(m(r.join(this.path,a),`utf8`));if(JSON.stringify(e)!==JSON.stringify(i))throw Error(`Conflicting legacy agent record: ${i.id}`)}else e.push({file:a,value:i});e.push({file:n,value:null})}if(e.length===0)return;let i={changes:e};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(!oi(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(!oi(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(!oi(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?N(e):(g(e,{recursive:!0,force:!0}),P(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)&&!ai(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(oi(n)&&this.assertLocalSkillPath(e),t.value===null)g(e,{force:!0}),P(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=M(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`);F(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}),P(this.path)}validateTree(e,t){if(!Nt(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}),N(n);for(let e of t){let t=r.join(n,...e.path.split(`/`));e.contents===null?N(t):An(t,x.from(e.contents,`base64`))}let i=r.join(this.path,e.file);g(i,{recursive:!0,force:!0}),re(n,i),P(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!ii(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!ii(t)||e.value!==void 0||e.text!==void 0||e.moveTo!==void 0&&e.removeDirectory!==void 0)throw Error(`Invalid storage directory journal`);let n=r.join(this.path,t);if(e.moveTo!==void 0){let t=r.join(this.path,this.skillDirectory(e.moveTo));if(u(n)){if(!f(n).isDirectory()||f(n).isSymbolicLink()||u(t))throw Error(`Invalid storage directory move`);re(n,t)}else if(!u(t)||!f(t).isDirectory()||f(t).isSymbolicLink())throw Error(`Missing storage directory move`)}else if(e.removeDirectory===!0)g(n,{recursive:!0,force:!0});else throw Error(`Invalid storage directory journal`);P(r.dirname(n))}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=r.join(this.path,t);if(!u(e))return;n=JSON.parse(m(e,`utf8`))}let i=n;if(this.recordPath(e,i.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(i)}replaceTree(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.validateTree(e,t),this.directoryChanges.push({file:e,tree:structuredClone(t)})}syncAgentInstructions(e){if(!this.changes)throw Error(`Storage writes require a transaction`);for(let t of e){let e=M(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 ft(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?ft(JSON.parse(m(e,`utf8`))):structuredClone(dt)})}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`,ft(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 li(e=Qe(),t){let n=new ci(e,t);try{return n.transaction(()=>{let t=n.readSettings();u(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function ui(){return $e(),li()}async function Y(e){let t;try{let n=ui(),r=new Kn(n);t={storage:n,agentsService:new tr(n,r),settingsService:new Ct(n),settingsSkillCopyService:new Tt,dataExportService:new sn(n),dataImportService:new Jr(n),instructionsService:r,skillsService:new kr(n),openPathService:new $r},fi(await e(t))}catch(e){let t=pi(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function di(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new X(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var X=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function fi(e){console.log(JSON.stringify(e,null,2))}function pi(e){return e instanceof Error?{code:mi(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function mi(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const hi={type:`positional`,description:`Agent ID with Skills support: ${w.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function gi(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:hi,skill:{type:`string`,description:t?`Existing skill name`:`Skill name to remove, even if its source is missing`,required:!0}},run({args:e}){return Y(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const _i=e({meta:{name:`skills`,description:`Inspect installed skills, saved assignments, or change assignments`},subCommands:{list:e({meta:{name:`list`,description:`List agents, skill directories, and saved skill names as JSON`},args:{agent:{...hi,required:!1}},run({args:e}){return Y(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new rr(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)}))})}}),installed:e({meta:{name:`installed`,description:`List skills physically installed in agent skill directories as JSON`},args:{agent:{...hi,required:!1}},run({args:e}){return Y(({agentsService:t})=>{let n=t.list().map(e=>{let t=e.capabilities.skills?.directory;return t?{agent:e,directory:t}:null}).filter(e=>e!==null);if(e.agent!==void 0&&n.every(({agent:t})=>t.id!==e.agent))throw new rr(e.agent);return n.filter(({agent:t})=>e.agent===void 0||t.id===e.agent).map(({agent:e,directory:n})=>({id:e.id,name:e.name,icon:e.icon,directory:n,skills:t.listInstalledSkills(e.id)}))})}}),assign:gi(!0),unassign:gi(!1)}}),vi=w.list().map(({id:e})=>e).join(`, `),yi={type:`positional`,description:`Agent ID: ${vi}`,required:!0},bi=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return Y(({agentsService:e})=>e.list())}}),xi=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...yi,description:`Optional agent ID: ${vi}`,required:!1}},run({args:e}){return Y(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new X(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${vi}`);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:yi,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 Y(({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:yi},run({args:e}){return Y(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),wi=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:yi},run({args:e}){return Y(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),Ti=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:yi},run({args:e}){return Y(({agentsService:t})=>t.reapply(e.agent))}}),Ei=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:yi},run({args:e}){return Y(({agentsService:t,openPathService:n})=>{let r=t.instructionFileTarget(e.agent);return n.open(r.filePath),{path:r.instructionFile}})}}),Di=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:bi,skills:_i,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:xi,assign:Si,enable:Ci,disable:wi,reapply:Ti,open:Ei}})}}),Oi=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 Y(({instructionsService:t})=>t.create(un({name:e.name,content:e.content})))}}),ki=e({meta:{name:`list`,description:`List instructions by name as JSON`},run(){return Y(({instructionsService:e})=>e.list())}}),Ai=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 Y(({instructionsService:t})=>t.get(e.id))}}),ji=e({meta:{name:`edit`,description:`Replace an instruction and synchronize enabled agents`},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 Y(({instructionsService:t})=>t.update(e.id,un({name:e.name,content:e.content})))}}),Mi=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 Y(({instructionsService:t})=>t.delete(e.id))}}),Ni=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:Oi,list:ki,get:Ai,edit:ji,delete:Mi}});function Pi(e){if(!Ii(e)||!Array.isArray(e.targets))throw new Fi(`targets must be an array`);if(e.targets.length===0)throw new Fi(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!ct.includes(e))throw new Fi(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Fi=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Ii(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Li=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 Y(async({dataExportService:t})=>{let n=await t.createExport(di(e.passphrase)),r=zi(e.output);return await Bi(n.contents,r,e.force),{filePath:r}})}}),Ri=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},"apply-agents":{type:`boolean`,description:`Apply imported agent instructions and skill links to this machine; otherwise clear imported agent configuration`,default:!1},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return Y(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),di(e.passphrase));return t.completeImport({apply:e[`apply-agents`],agentRevision:n.agentRevision}),{status:`imported`}})}});function zi(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 Bi(e,t,n){await xe(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await De(a,e,{mode:384}),i.platform!==`win32`&&await _e(a,384),n){await Te(a,t);return}if(u(t))throw Vi(t);try{await ye(a,t)}catch(e){throw Hi(e)?Vi(t):e}}finally{await b(a,{force:!0})}}function Vi(e){return new X(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Hi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Ui={"color-theme":{field:`theme`,values:et},language:{field:`language`,values:tt},"time-zone":{field:`timezone`,values:rt},"time-format":{field:`timeFormat`,values:nt}},Wi=[...Object.keys(Ui),`config-folder`],Gi=Object.entries(Ui).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
9
|
-
`);function Ki(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const qi=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Wi.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return Y(({settingsService:t})=>{let n=Ki(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new X(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Wi.join(`, `)}`);return n[e.key]})}}),Ji=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(Ui).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${Gi}`,required:!0}},run({args:e}){return Y(({settingsService:t})=>{if(e.key===`config-folder`)throw new X(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(Ui,e.key))throw new X(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(Ui).join(`, `)}`);let n=Ui[e.key];if(!n.values.includes(e.value))throw new X(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Ki(t.update(pt({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Yi=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Y(({settingsService:e,openPathService:t})=>{let{configFolder:n}=e.read();return t.open(n),{configFolder:n}})}}),Xi=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 Y(({settingsSkillCopyService:t})=>{let n=Pi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Zi=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:qi,set:Ji,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Yi}}),export:Li,import:Ri,"download-skill":Xi}}),Qi={type:`positional`,description:`Current skill name`,required:!0},$i=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 Y(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),ea=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 Y(({skillsService:t})=>t.importLocal({path:r.resolve(e.path)}))}}),ta=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 Y(({skillsService:t})=>t.importUrl({url:e.url}))}}),na=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 Y(({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:Qi},run({args:e}){return Y(({skillsService:t})=>t.detail(e.skill))}}),save:e({meta:{name:`save`,description:`Replace the complete skill files tree; omitted entries are deleted and file contents are saved verbatim`},args:{skill:Qi,file:{type:`string`,description:`JSON file containing { files }, or - for stdin. Accepts get output; only files is applied. SKILL.md is required; its content includes valid YAML frontmatter. Null content preserves existing opaque files.`,valueHint:`path|-`,required:!0}},run({args:e}){return Y(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new z(`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 z(`Skill files input must be valid JSON`)}let o=cr(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 Y(({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 Y(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:$i,local:ea,url:ta}})}});function ra(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.get(`/:id/skills`,t=>{try{return t.json(e.listInstalledSkills(t.req.param(`id`)))}catch(e){return aa(t,e)}}),t.put(`/:id/instructions`,async t=>{try{let n=Ke(await ia(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return aa(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=qe(await ia(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return aa(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return aa(t,e)}}),t}async function ia(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function aa(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function oa(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 ca(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(un(await sa(t)));return t.json(n,201)}catch(e){return ca(t,e)}}),t.put(`/:id`,async t=>{try{let n=un(await sa(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return ca(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return ca(t,e)}}),t}async function sa(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function ca(e,t){if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof ln)return e.json({error:{code:t.code,message:t.message}},404);throw t}const la=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],ua=[`active`,`disabled`,`deleted`];var Z=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function da(e){if(!ya(e))throw new Z(`Provider input must be an object`);let t=va(e.name,`name`),n=ga(e.protocol),r=_a(e.baseURL),i=e.apiKey===void 0?``:va(e.apiKey,`apiKey`,{allowEmpty:!0}),a=ha(e.customModels);return{...e.avatar!==void 0&&{avatar:fa(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function fa(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 Z(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function pa(e){if(!ya(e))throw new Z(`Provider connection must be an object`);return{protocol:ga(e.protocol),baseURL:_a(e.baseURL),apiKey:e.apiKey===void 0?``:va(e.apiKey,`apiKey`,{allowEmpty:!0})}}function ma(e){if(typeof e!=`string`||!ua.includes(e))throw new Z(`Invalid provider status`);return e}function ha(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Z(`customModels must be an array`);return e.map(e=>{if(!ya(e))throw new Z(`Each custom model must be an object`);return{id:va(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:va(e.displayName,`customModels.displayName`)}})}function ga(e){if(typeof e!=`string`||!la.includes(e))throw new Z(`Invalid provider protocol`);return e}function _a(e){let t=va(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new Z(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function va(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new Z(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new Z(`${t} is required`);return r}function ya(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ba=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function xa(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(Sa(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new ba(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new ba(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new ba(`Provider returned invalid JSON`)}return Ca(i)}function Sa(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function Ca(e){if(!Ta(e)||!Array.isArray(e.data))throw new ba(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Ta(e)||typeof e.id!=`string`||e.id.length===0)throw new ba(`Provider returned an invalid model entry`);let t=wa(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function wa(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Ta(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ea=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Da=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=>Oa(e))}get(e){let t=this.storage.get(`providers`,e);return t?Oa(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 Ea;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),Oa(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new Ea;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),Oa(i)})}};function Oa(e){return{...e,avatar:e.avatar??null,status:e.status}}function ka(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 ja(t,e)}}),n.post(`/models`,async t=>{try{let n=pa(await Aa(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ja(t,e)}}),n.post(`/`,async n=>{try{let r=da(await Aa(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ja(n,e)}}),n.put(`/:id`,async n=>{try{let r=da(await Aa(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ja(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Aa(n),i=ma(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 ja(n,e)}}),n}async function Aa(e){try{return await e.req.json()}catch{throw new Z(`Request body must be valid JSON`)}}function ja(e,t){if(t instanceof Z)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Ea)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ba)return e.json({error:{code:t.code,message:t.message}},502);throw t}var Ma=class{repository;constructor(e){this.repository=new Da(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 Ea;return xa(t)}fetchModelsForConnection(e){return xa(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function Na(e,t=()=>{},n=new Tt){let r=new S;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=pt(await Pa(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Fa(n,e)}}),r.post(`/skill-copy`,async e=>{try{let t=Pi(await Pa(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Fa(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 Fa(e,t)}}),r}async function Pa(e){try{return await e.req.json()}catch{throw new gt(`Request body must be valid JSON`)}}function Fa(e,t){if(t instanceof gt||t instanceof Fi)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Et)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Ia(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 La(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 La(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=ur(await La(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 La(t);return t.json(e.create(H(n)),201)}catch(e){return Q(t,e)}}),t.put(`/:name`,async t=>{try{let n=await La(t);if(n&&typeof n==`object`&&`files`in n){let r=cr(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),H(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 La(e){try{return await e.req.json()}catch{throw new z(`Request body must be valid JSON`)}}function Q(e,t){if(t instanceof B)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof rr)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ir)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}},400);if(t instanceof dr)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof V)return e.json({error:{code:t.code,message:t.message}},404);throw t}function Ra(e){let t=new S;return t.get(`/`,t=>He(t,async n=>{await za(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Ba(n,e)}),c=setInterval(()=>{r||Va(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 za(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Ba(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Va(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Ha=class extends Error{code=`INVALID_EXPORT_INPUT`};function Ua(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Ha(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Wa(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Ha(`Request body must be valid JSON`)}let{passphrase:r}=Ua(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 Ha?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 Ga(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 W(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new W(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new W(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await Se(r.join(de(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await ke(Me.fromWeb(n.req.raw.body),l(o,{mode:384}));let s=await e.importData(o,a);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json(s)}catch(e){return e instanceof W?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 rn(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new W(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(Mr(n)),t.json({status:`completed`})}catch(e){if(e instanceof W){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 qa=Ue(Le);function Ja(e){return`
|
|
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 s=u(e)?_(e).mode&511:384,c=`${e}.${v()}.tmp`;try{let r=ee(c,`wx`,s);try{i.platform!==`win32`&&a(c,s),ce(r,t),d(r)}finally{o(r)}re(c,e),P(n)}finally{g(c,{force:!0})}}function F(e,t,n){let r=u(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){u(e.filePath)&&m(e.filePath,`utf8`)}function I(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(M(n).map(e=>[e.id,e])),a=new Map(mn(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&&F(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}})}}function Gn(e,t,n){let r=Vn(e).filter(({instructions:e})=>e.enabled&&e.instructionIds.includes(t.id));if(r.length===0)return;let i=new Map(M(n).map(e=>[e.id,e])),a=new Map(mn(e).map(e=>[e.id,e.content]));a.set(t.id,t.content);for(let e of r){let t=i.get(e.id);t&&F(t,e.instructions.instructionIds.map(e=>a.get(e)).filter(e=>e!==void 0),!1)}}var Kn=class{storage;homeDirectory;constructor(e,t=le.homedir()){this.storage=e,this.homeDirectory=t}list(){return mn(this.storage)}get(e){let t=hn(e,this.storage);if(!t)throw new ln(e);return t}create(e){return pn(e,this.storage)}update(e,t){return this.storage.transaction(()=>{let n=gn(e,t,this.storage);if(!n)throw new ln(e);return Gn(this.storage,n,this.homeDirectory),n})}delete(e){return this.storage.transaction(()=>{let t=hn(e,this.storage);if(!t||(Wn(this.storage,e,this.homeDirectory),_n(e,this.storage)===`missing`))throw new ln(e);return t})}};const qn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Jn(e,t){let n;try{n=h(e,{withFileTypes:!0,encoding:`utf8`})}catch(e){if(Zn(e))return[];throw e}let i=[];for(let a of n){let n=r.join(e,a.name),o=a.isSymbolicLink(),s;try{s=_(n)}catch{continue}if(!s.isDirectory())continue;let c=r.join(n,`SKILL.md`),l;try{let e=_(c);if(!e.isFile()||e.size>2097152)continue;l=Xn(m(c,`utf8`))}catch{continue}if(!l)continue;let u=o?$n(n):null,d=o&&t!==void 0&&tr(n,r.join(t,a.name));i.push({directoryName:a.name,...l,isManaged:d,...u!==null&&{originPath:u}})}return i.toSorted((e,t)=>e.name.localeCompare(t.name))}function Yn(e){let t;try{t=h(e,{withFileTypes:!0,encoding:`utf8`})}catch(e){if(Zn(e))return[];throw e}return t.filter(e=>e.isSymbolicLink()).map(t=>{let n=$n(r.join(e,t.name));return n!==null&&er(n)?n:null}).filter(e=>e!==null)}function Xn(e){let t=qn.exec(e);if(!t)return null;let n;try{n=Pe(t[1])}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=typeof r.name==`string`?r.name.trim():``,a=typeof r.description==`string`?r.description.trim():``;return i&&a?{name:i,description:a}:null}function Zn(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function Qn(e){return r.resolve(r.dirname(e),te(e))}function $n(e){try{return Qn(e)}catch{return null}}function er(e){try{return _(e).isDirectory()}catch{return!1}}function tr(e,t){try{return ne(e)===ne(t)}catch{return!1}}var nr=class{storage;instructionsService;definitions;constructor(e,t=new Kn(e),n=le.homedir()){this.storage=e,this.instructionsService=t,this.definitions=M(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=>rr(t,(e.get(t.id)??I(t.id)).instructions))}listInstalledSkills(e){let t=this.requireDefinition(e);if(!t.skillsDirectoryPath)throw new C(`AGENT_SKILLS_NOT_SUPPORTED`,`Agent does not support skills: ${e}`,404);return Jn(t.skillsDirectoryPath,r.join(this.storage.path,O.skills))}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=Hn(this.storage,e)??I(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&F(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 rr(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Hn(this.storage,e)??I(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);F(n,e.map(({content:e})=>e),!1)}else F(n,[],!0);let a=Date.now();return rr(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)??I(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);F(t,i.map(({content:e})=>e),!1);let a=Date.now();return rr(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)??I(t.id)).instructions;return{agentId:t.id,enabled:n.enabled,contents:n.enabled?this.readAssignedInstructions(n.instructionIds).map(({content:e})=>e):[]}}))})}instructionFileTarget(e){let t=this.requireDefinition(e);return{instructionFile:t.instructionFile,filePath:t.filePath}}};function rr(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 L=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},ir=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},ar=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 L(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=>z(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()&&z(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&&or(t)===or(n)||t&&n&&!e.assignment&&R(t)&&!z(t,n)&&!z(t,r))throw new ir(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=me(`sha256`).update(`${i}\0${a}`).digest(`hex`),s=r.join(t,`.foundry-${n}.tmp`);try{if(R(s)&&!z(s,a))throw new ir(s);if(R(s)||ae(a,s,`dir`),!e.assignment&&R(i)&&!z(i,a)&&!z(i,o))throw new ir(i);e.assignment&&R(i)&&f(i).isDirectory()&&g(i,{recursive:!0,force:!0}),re(s,i),P(t)}finally{z(s,a)&&oe(s)}}let s=e.assignment?R(n)&&f(n).isSymbolicLink():z(n,o);if(n!==i&&s){try{oe(n)}catch(e){if(e.code!==`ENOENT`)throw e}P(t)}}}};function R(e){try{return f(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function z(e,t){return R(e)&&f(e).isSymbolicLink()&&or(r.resolve(r.dirname(e),te(e)))===or(t)}function or(e){try{return r.join(ne(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var B=class extends Error{code=`INVALID_SKILL_INPUT`},V=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function sr(e){if(typeof e!=`string`||!E(e))throw new V(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function cr(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new B(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new B(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new B(`Invalid file entry`);let o=sr(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new B(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new B(`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 B(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(lr(e.content),n+=x.byteLength(e.content,`utf8`),n>16777216))throw new B(`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 V(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function lr(e){if(x.byteLength(e,`utf8`)>2097152)throw new V(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new V(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function ur(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new B(`assigned must be a boolean`);return{assigned:e.assigned}}var H=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},dr=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function fr(e){return e===e.trim()&&T(e)}function U(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new B(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new B(`name is required`);let t=ut(e.name);if(!fr(t))throw new B(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new B(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new B(`description must be 1–1024 characters`);return{name:t,description:n}}function W(e,t){throw new V(e,t,400)}function pr(e){return e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&r.isAbsolute(e.path)&&!e.path.includes(`\0`)||W(`SKILL_IMPORT_INVALID_SOURCE`,`path must be an absolute local filesystem path`),{path:e.path}}function mr(e){if(!e||typeof e!=`object`||!(`url`in e)||typeof e.url!=`string`)throw new V(`SKILL_IMPORT_INVALID_URL`,`Enter an HTTP or HTTPS file URL`,400);return{url:hr(e.url).href}}function hr(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 V(`SKILL_IMPORT_INVALID_URL`,`Use an HTTP or HTTPS file URL without embedded credentials`,400)}}function gr(e){e&&typeof e==`object`&&`entries`in e&&Array.isArray(e.entries)&&e.entries.length!==0||W(`SKILL_IMPORT_MISSING_SKILL_MD`,`Select one skill containing SKILL.md`),e.entries.length>5e3&&W(`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`)&&W(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path or file`);let i=e.path.normalize(`NFKC`).toLowerCase();if(n.has(i)&&W(`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)&&W(`SKILL_IMPORT_INVALID_ENCODING`,`Invalid file encoding`),r+=x.from(e.contents,`base64`).length,r>33554432))throw new V(`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&&W(`SKILL_IMPORT_INVALID_PATH`,`A file occupies a parent directory`)}}let a=i.find(e=>e.path===`SKILL.md`);a?.contents??W(`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 V(`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`))&&W(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must contain valid YAML frontmatter`),{skill:{...U(Pe(t[1])),content:e.slice(t[0].length)},entries:i}}catch{W(`SKILL_IMPORT_INVALID_METADATA`,`SKILL.md must be UTF-8 Markdown with a valid name and description in YAML frontmatter`)}}const _r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function vr(e,t){let n=_r.exec(t);if(!n)throw new B(`SKILL.md must contain YAML frontmatter`);let r;try{r=Pe(n[1])}catch{throw new B(`SKILL.md must contain valid YAML frontmatter`)}let i=U(r);if(i.name!==ut(e))throw new B(`Skill name must match its directory; use the rename action to change it`);return{...i,content:t.slice(n[0].length)}}var yr=class{storage;constructor(e){this.storage=e}directory(e){if(!fr(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 B(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new H(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 dr(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${Ie(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 H(e);this.assertSourceDirectory(e);let i=this.directory(e),a=m(r.join(i,`SKILL.md`),`utf8`),o=_r.exec(a);if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=Fe(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 H(e);return this.assertSourceDirectory(e),this.storage.removeSkillDirectory(this.directory(e)),t})}get(e){if(fr(e))return this.storage.transaction(()=>{try{return vr(e,m(r.join(this.directory(e),`SKILL.md`),`utf8`))}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()&&fr(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 br(e){return e.flatMap(e=>e.children?[e,...br(e.children)]:[e])}var xr=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new H(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 V(`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 V(`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=(e,t)=>h(e,{withFileTypes:!0}).toSorted((e,t)=>e.name.localeCompare(t.name)).flatMap(i=>{let a=t?`${t}/${i.name}`:i.name;if(!E(a)||i.isSymbolicLink())return[];let o=r.join(e,i.name);if(i.isDirectory())return[{path:a,children:n(o,a)}];if(!i.isFile())return[];let s=null;if(f(o).size<=2097152)try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(m(o));s=e.includes(`\0`)?null:e}catch{}return[{path:a,content:s}]});return n(t,``)}replace(e,t){let n=this.root(e),i=new Map(br(this.read(e)).map(e=>[e.path,e])),a=new Map(br(t).map(e=>[e.path,e]));for(let t of a.values()){if(this.assertLocal(n,t.path),t.content===null&&i.get(t.path)?.content!==null)throw new V(`SKILL_FILE_NOT_TEXT`,`Uneditable files must refer to existing unchanged files`,415);t.path===`SKILL.md`&&typeof t.content==`string`&&vr(e,t.content)}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 e of a.values()){let t=i.get(e.path),a=r.join(n,e.path);e.children?t?.children||this.storage.createSkillFolder(a):e.content!==null&&e.content!==t?.content&&this.storage.putTextFile(a,e.content)}}};async function Sr(e){try{let t=await be(e);if(t.isSymbolicLink()&&W(`SKILL_IMPORT_SYMLINK_SOURCE`,`Select a skill source, not a symbolic link`),t.isFile()&&/\.(?:skill|zip)$/iu.test(e))return Tr(t.size),await Er(e);t.isDirectory()||W(`SKILL_IMPORT_INVALID_SOURCE`,`Select a skill folder or a .skill / .zip archive`);let n=await we(e,{withFileTypes:!0}),i={bytes:0,entries:0};if(n.some(e=>e.name===`SKILL.md`))return{isBatch:!1,candidates:[await wr(e,i)]};let a=[];for(let t of n)if(t.isDirectory()||t.isSymbolicLink()){i.entries>=5e3&&W(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The source contains too many entries`),i.entries++;try{a.push(await wr(r.join(e,t.name),i))}catch(e){if(e instanceof V&&[`SKILL_IMPORT_TOO_LARGE`,`SKILL_IMPORT_TOO_MANY_ENTRIES`].includes(e.code))throw e;a.push({source:t.name,entries:[],readError:e instanceof V?e:new V(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)})}}return{isBatch:!0,candidates:a}}catch(e){throw e instanceof V?e:new V(`SKILL_IMPORT_READ_FAILED`,`Unable to read the selected skill source`,400)}}async function Cr(e){return wr(e,{bytes:0,entries:0})}async function wr(e,t){let n=await be(e);(n.isSymbolicLink()||!n.isDirectory())&&W(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`);let i=await we(e);i.includes(`SKILL.md`)||W(`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)&&W(`SKILL_IMPORT_INVALID_PATH`,`The skill contains an invalid path`),t.entries>=5e3&&W(`SKILL_IMPORT_TOO_MANY_ENTRIES`,`The skill contains too many entries`),t.entries++;let i=await be(e);if((i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())&&W(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Skills must contain only regular files and directories`),i.isDirectory()){a.push({path:n,contents:null});let t=await we(e);for(let i of t)await o(r.join(e,i),`${n}/${i}`)}else{Tr(t.bytes+i.size);let r=await Ce(e,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);try{let e=await r.stat();e.isFile()||W(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`Select a regular skill file`),Tr(t.bytes+e.size);let i=[],o;do{let e=x.alloc(65536);({bytesRead:o}=await r.read(e)),t.bytes+=o,Tr(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 Tr(e){if(e>33554432)throw new V(`SKILL_IMPORT_TOO_LARGE`,`Skills must be at most 32 MiB`,413)}async function Er(e){let{entries:t,unsupported:n}=await Dr(e);return t.some(e=>e.path===`SKILL.md`)?(n.length>0&&W(`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 Dr(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`?Ae.open(e,i,r):Ae.fromBuffer(e,i,r)})}catch{W(`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&&W(`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 V(`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)&&W(`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 V)throw e;W(`SKILL_IMPORT_INVALID_ARCHIVE`,`Unable to read the skill archive`)}finally{t.close()}return{entries:n,unsupported:r}}function Or(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 V(`SKILL_IMPORT_UNSUPPORTED_URL_FILE`,`Use a .skill, .zip, or SKILL.md file URL`,400)}}async function kr(e){let t=hr(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 V(`SKILL_IMPORT_DOWNLOAD_FAILED`,`The download redirected too many times or has no destination`,400);t=hr(n,t);continue}if(!r.ok||!r.body)throw new V(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400);let n=Or(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 V(`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 V(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 Er(l)}finally{if(!r.body?.locked)try{await r.body?.cancel()}catch{}}}}catch(e){throw e instanceof V?e:new V(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 V(`SKILL_IMPORT_DOWNLOAD_FAILED`,`Unable to download the skill file`,400)}var Ar=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new yr(e),this.files=new xr(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)??I(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&&W(`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&&W(`SKILL_IMPORT_UNSUPPORTED_ENTRIES`,`The skill contains symbolic links or unsupported entries`);let{skill:e,entries:t}=gr({entries:r.entries});n.imported.push(this.repository.import(e,t))}catch(t){if(!e||!(t instanceof V||t instanceof B||t instanceof dr))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 B(`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)??I(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(U(e))}async importLocal(e){let t=pr(e);return this.importSource(await Sr(t.path))}async importUrl(e){let t=mr(e);return this.importSource(await kr(t.url))}get(e){let t=this.repository.get(e);if(!t)throw new H(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(!fr(e))throw new B(`Invalid skill name`);if(this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new L(t);n&&this.get(e);let r=this.storage.get(`agents`,t)??I(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`))}}async bringIn(e,t){if(!fr(t))throw new B(`Invalid skill name`);let n=M(this.storage.agentHomeDirectory).find(({id:t})=>t===e);if(!n?.skillsDirectoryPath)throw new L(e);let i=r.join(this.storage.path,O.skills),a=Jn(n.skillsDirectoryPath,i).find(({directoryName:e})=>e===t);if(!a)throw new H(t);if(a.isManaged)throw new V(`SKILL_ALREADY_MANAGED`,`Skill is already managed by Foundry`,409);if(a.name!==t)throw new B(`Skill name must match its directory; use the rename action to change it`);let o;try{o=ne(r.join(n.skillsDirectoryPath,t))}catch{throw new V(`SKILL_IMPORT_READ_FAILED`,`Unable to resolve the installed skill`,400)}let s;if(!this.repository.get(t)&&(s=gr({entries:(await Cr(o)).entries}),s.skill.name!==t))throw new B(`Skill name must match its directory; use the rename action to change it`);return this.storage.transaction(()=>{s&&!this.repository.get(s.skill.name)&&this.repository.import(s.skill,s.entries);let n=this.storage.get(`agents`,e)??I(e),r=Date.now(),i=n.skills??{skillNames:[],createdAt:r,updatedAt:r},a=i.skillNames.filter(e=>e!==t);a.push(t),this.storage.put(`agents`,{...n,skills:{...i,skillNames:a,updatedAt:r}}),this.storage.syncAgentSkillLinks({previousName:t,name:t,agentIds:[e],assignment:!0})}),this.get(t)}deleteInstalled(e,t){let n=M(this.storage.agentHomeDirectory).find(({id:t})=>t===e);if(!n?.skillsDirectoryPath)throw new L(e);if(!t||t===`.`||t===`..`||t!==r.basename(t)||t.includes(`\\`))throw new B(`Invalid installed skill directory name`);let i=n.skillsDirectoryPath;return this.storage.transaction(()=>{let n=r.join(i,t),a;try{let e=f(n);a=e.isSymbolicLink()?`link`:e.isDirectory()?`directory`:`file`}catch(e){throw e.code===`ENOENT`?new H(t):e}let o=a===`link`&&jr(n,r.join(this.storage.path,O.skills,t));a===`link`?oe(n):g(n,{recursive:!0,force:!0});let s=this.storage.get(`agents`,e);return o&&s?.skills?.skillNames.includes(t)&&this.storage.put(`agents`,{...s,skills:{...s.skills,skillNames:s.skills.skillNames.filter(e=>e!==t),updatedAt:Date.now()}}),{agentId:e,directoryName:t,kind:a}})}update(e,t){let n=U(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=cr({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})}};function jr(e,t){try{return f(e).isSymbolicLink()?Mr(r.resolve(r.dirname(e),te(e)))===Mr(t):!1}catch{return!1}}function Mr(e){try{return r.join(ne(r.dirname(e)),r.basename(e))}catch{return r.resolve(e)}}var G=class extends Error{code;constructor(e,t){super(t),this.code=e}};function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nr(e){if(!K(e)||e.format!==`foundry.data`)throw q(`Unsupported or invalid backup manifest`);if(e.archiveVersion===2&&K(e.data)&&e.data.path===`data/foundry.json`&&Pr(e.data))return{archiveVersion:2,data:{path:it,bytes:e.data.bytes,sha256:e.data.sha256}};if(e.archiveVersion!==4||!Array.isArray(e.files)||!Array.isArray(e.directories))throw q(`Unsupported or invalid backup manifest`);return{archiveVersion:4,files:e.files.map(e=>{if(!K(e)||typeof e.path!=`string`||!Pr(e))throw q(`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 q(`Invalid backup directory`);return e})}}function Pr(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 Fr(e){if(!K(e)||typeof e.apply!=`boolean`||typeof e.agentRevision!=`string`||!/^[a-f0-9]{64}$/u.test(e.agentRevision))throw q(`An apply choice and agent revision are required`);return{apply:e.apply,agentRevision:e.agentRevision}}function Ir(e){if(!K(e)||!K(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw q(`Backup data must contain settings, instructions, and agents`);let t=Lr(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:ft(e.settings),instructions:t,agents:Rr(e.agents,n)}}function Lr(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!K(e))throw q(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!cn.test(r)||t.has(r))throw q(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw q(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw q(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:zr(e.createdAt,n),updatedAt:zr(e.updatedAt,n)};return t.add(r),a})}function Rr(e,t,n){let r=new Set(w.list().map(({id:e})=>e)),i=/* @__PURE__ */ new Set;return e.map((e,a)=>{if(!K(e)||!K(e.instructions))throw q(`Invalid agent at index ${a}`);let o=e.id;if(typeof o!=`string`||!r.has(o)||i.has(o))throw q(`Invalid agent at index ${a}`);let s=e.instructions,c=s.instructionIds;if(!Array.isArray(c))throw q(`Invalid instruction assignment for agent ${o}`);let l=c.map(e=>{if(typeof e!=`string`)throw q(`Invalid instruction assignment for agent ${o}`);return e});if(new Set(l).size!==l.length||l.some(e=>!t.has(e)))throw q(`Invalid instruction assignment for agent ${o}`);if(typeof s.enabled!=`boolean`)throw q(`Invalid enabled state for agent ${o}`);if(s.enabled&&l.length===0)throw q(`Enabled agent ${o} has no instructions`);let u={id:o,instructions:{instructionIds:l,enabled:s.enabled,createdAt:zr(s.createdAt,a),updatedAt:zr(s.updatedAt,a)}};if(n&&e.skills!==void 0){let t=e.skills;if(!K(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 q(`Invalid skill assignment for agent ${o}`);u.skills={skillNames:t.skillNames,createdAt:zr(t.createdAt,a),updatedAt:zr(t.updatedAt,a)}}return i.add(o),u})}function zr(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw q(`Invalid timestamp at index ${t}`);return e}function q(e){return new G(`INVALID_BACKUP`,e)}const Br=`${O.skills}/`,Vr=`${O.instructions}/`,Hr=`${O.agents}/`,Ur=RegExp(`^${O.skills}/[^/]+/$`,`u`);function Wr(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=n.path.replace(/\/$/u,``);if(!Rt(n.path)||n.path===`manifest.json`||n.path===`data/foundry.json`||t.has(e)||n.path.endsWith(`/`)!==(n.contents===null))throw new G(`INVALID_BACKUP`,`Invalid or duplicate backup file`);t.add(e)}let n=e.find(e=>e.path===`settings.json`)?.contents;if(!n||Mt.some(t=>e.every(e=>e.path!==`${t}/`)))throw new G(`INVALID_BACKUP`,`Backup is missing required files or directories`);let i=e.filter(e=>e.path.startsWith(Vr)&&e.contents!==null).map(e=>yn(Gr(e.contents),r.posix.basename(e.path))),a=/* @__PURE__ */ new Set,o=e.filter(e=>Ur.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(Gr(r));if(!i||U(Pe(i[1])).name!==n)throw new G(`INVALID_BACKUP`,`Skill name must match its directory`);a.add(n)}for(let t of e){if(t.path.startsWith(Br)&&t.path!==Br&&!a.has(t.path.split(`/`,2)[1]))throw new G(`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 G(`INVALID_BACKUP`,`Backup directory is missing`)}}let s=e.filter(e=>e.path.startsWith(Hr)&&e.contents!==null).map(e=>{let t=JSON.parse(Gr(e.contents));if(!t||typeof t!=`object`||!(`id`in t)||`${String(t.id)}.json`!==r.posix.basename(e.path))throw new G(`INVALID_BACKUP`,`Agent ID must match its filename`);return t}),c=JSON.parse(Gr(n));Ir({settings:c,instructions:i,agents:s});let l=Rr(s,new Set(i.map(({id:e})=>e)),a);return{entries:e,settings:ft(c),agents:l}}function Gr(e){return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}function Kr(e,t){return e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of mn(e))n.has(t.id)||e.removeTextFile(qr(t.id));for(let n of t.instructions)e.putTextFile(qr(n.id),vn(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`,{...I(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),Yr(e)})}function qr(e){return r.join(O.instructions,`${e}.md`)}function Jr(e,t){return e.transaction(()=>{for(let n of Mt)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),Xr(t.entries.filter(e=>e.path.startsWith(`${O.agents}/`)&&e.contents!==null).map(e=>JSON.parse(e.contents.toString(`utf8`))))})}function Yr(e){return Xr(e.all(`agents`))}function Xr(e){return me(`sha256`).update(JSON.stringify(e.toSorted((e,t)=>e.id.localeCompare(t.id)))).digest(`hex`)}function Zr(e){for(let{id:t}of w.list()){let n=e.get(`agents`,t)??I(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 Qr=class{storage;constructor(e){this.storage=e}completeImport({apply:e,agentRevision:t}){try{this.storage.transaction(()=>{if(Yr(this.storage)!==t)throw new G(`IMPORT_CHANGED`,`Agent configuration has changed since this import`);e?(new nr(this.storage).applyConfiguration(),new Ar(this.storage).applyAssignments()):Zr(this.storage)})}catch(t){throw t instanceof G?t:new G(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 Se(r.join(de(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await Jt(e,i,t);let a=await Bt(i,r.join(n,`extracted`)),o=Nr(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 G(`INVALID_BACKUP`,`Invalid legacy backup entries`);let e=await y(a[it]);$r(e,o.data);let t=Ir(JSON.parse(e.toString(`utf8`)));s=()=>Kr(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 G(`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]);$r(t,e),n.push({path:e.path,contents:t})}let r=Wr(n);s=()=>Jr(this.storage,r)}try{return{status:`imported`,agentRevision:s()}}catch{throw new G(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof G?e:e instanceof Ut?e.code===`INVALID_PASSPHRASE`?new G(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new G(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new G(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await rn(n)}}};function $r(e,t){if(e.byteLength!==t.bytes||on(e)!==t.sha256)throw new G(`INVALID_BACKUP`,`Backup checksum does not match`)}function ei(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=Re(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}var ti=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`OpenPathError`}};function ni(e){if(!ri(e)||typeof e.path!=`string`||e.path.length===0||e.path.includes(`\0`))throw new ti(`INVALID_OPEN_PATH`,`path must be a non-empty filesystem path`,400);return{path:e.path}}function ri(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ii=class{homeDirectory;configFolder;opener;definitions;constructor(e=le.homedir(),t=Qe(),n=ei,r=M(e)){this.homeDirectory=e,this.configFolder=t,this.opener=n,this.definitions=r}resolvePath(e){let t=e===`~`?this.homeDirectory:e.startsWith(`~/`)||e.startsWith(`~\\`)?r.join(this.homeDirectory,e.slice(2)):e;if(!r.isAbsolute(t))throw new ti(`INVALID_OPEN_PATH`,`path must be absolute or start with ~/`,400);return r.resolve(t)}allowedPaths(){let e=/* @__PURE__ */ new Set([r.resolve(this.configFolder)]);for(let t of this.definitions)if(e.add(r.resolve(t.filePath)),t.skillsDirectoryPath)for(let n of Yn(t.skillsDirectoryPath))e.add(r.resolve(n));return e}open(e){let t=this.resolvePath(e);if(!this.allowedPaths().has(t))throw new ti(`OPEN_PATH_NOT_ALLOWED`,`Path is not an openable Foundry target`,403);try{_(t)}catch(e){throw ai(e)?new ti(`OPEN_PATH_NOT_FOUND`,`The target path does not exist`,404):e}return this.opener(t),{path:t}}};function ai(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}const oi=[`agents`,`providers`],si=new RegExp(String.raw`^${O.skills}[/\\]([^/\\]+)$`,`u`),ci=new RegExp(String.raw`^${O.instructions}[/\\][^/\\]+\.md$`,`u`);function li(e){let t=si.exec(e);return!!(t&&t[1]===t[1].trim()&&T(t[1]))}function ui(e){return ci.test(e)||di(e)}function di(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 fi(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 pi=class{path;agentHomeDirectory;changes=null;textChanges=null;directoryChanges=null;skillLinkChanges=[];agentInstructionChanges=[];skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=le.homedir()){this.path=e,this.agentHomeDirectory=t,this.skillLinks=new ar(e,t),N(e);for(let e of oi)e!==`providers`&&N(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),`${me(`sha256`).update(t).digest(`hex`)}.json`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!ui(t))throw Error(`Invalid storage text filename`);return t}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=r.join(this.path,`.lock`),n=Date.now();for(;;)try{p(t,{mode:448});try{ce(r.join(t,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384})}catch(e){throw g(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,this.initializeProviders(),this.initializeAgents(),e()}finally{this.lockDepth=0,g(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=_(e);if(!fi(e))return;let n=r.join(e,`recovering`);try{p(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);fi(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ce(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!fi(e)){g(n,{recursive:!0,force:!0});return}g(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!u(e))return;let t=JSON.parse(m(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!u(e)){let e=u(t)?h(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};On(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(ie(t),P(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!==`${me(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(u(r.join(this.path,a))){let e=JSON.parse(m(r.join(this.path,a),`utf8`));if(JSON.stringify(e)!==JSON.stringify(i))throw Error(`Conflicting legacy agent record: ${i.id}`)}else e.push({file:a,value:i});e.push({file:n,value:null})}if(e.length===0)return;let i={changes:e};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(!di(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(!di(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(!di(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?N(e):(g(e,{recursive:!0,force:!0}),P(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)&&!ui(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(di(n)&&this.assertLocalSkillPath(e),t.value===null)g(e,{force:!0}),P(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=M(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`);F(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}),P(this.path)}validateTree(e,t){if(!Nt(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}),N(n);for(let e of t){let t=r.join(n,...e.path.split(`/`));e.contents===null?N(t):An(t,x.from(e.contents,`base64`))}let i=r.join(this.path,e.file);g(i,{recursive:!0,force:!0}),re(n,i),P(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!li(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!li(t)||e.value!==void 0||e.text!==void 0||e.moveTo!==void 0&&e.removeDirectory!==void 0)throw Error(`Invalid storage directory journal`);let n=r.join(this.path,t);if(e.moveTo!==void 0){let t=r.join(this.path,this.skillDirectory(e.moveTo));if(u(n)){if(!f(n).isDirectory()||f(n).isSymbolicLink()||u(t))throw Error(`Invalid storage directory move`);re(n,t)}else if(!u(t)||!f(t).isDirectory()||f(t).isSymbolicLink())throw Error(`Missing storage directory move`)}else if(e.removeDirectory===!0)g(n,{recursive:!0,force:!0});else throw Error(`Invalid storage directory journal`);P(r.dirname(n))}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=r.join(this.path,t);if(!u(e))return;n=JSON.parse(m(e,`utf8`))}let i=n;if(this.recordPath(e,i.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(i)}replaceTree(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.validateTree(e,t),this.directoryChanges.push({file:e,tree:structuredClone(t)})}syncAgentInstructions(e){if(!this.changes)throw Error(`Storage writes require a transaction`);for(let t of e){let e=M(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 ft(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?ft(JSON.parse(m(e,`utf8`))):structuredClone(dt)})}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`,ft(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 mi(e=Qe(),t){let n=new pi(e,t);try{return n.transaction(()=>{let t=n.readSettings();u(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function hi(){return $e(),mi()}async function J(e){let t;try{let n=hi(),r=new Kn(n);t={storage:n,agentsService:new nr(n,r),settingsService:new Ct(n),settingsSkillCopyService:new Tt,dataExportService:new sn(n),dataImportService:new Qr(n),instructionsService:r,skillsService:new Ar(n),openPathService:new ii},_i(await e(t))}catch(e){let t=vi(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function gi(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new Y(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Y=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function _i(e){console.log(JSON.stringify(e,null,2))}function vi(e){return e instanceof Error?{code:yi(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function yi(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const bi={type:`positional`,description:`Agent ID with Skills support: ${w.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function xi(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:bi,skill:{type:`string`,description:t?`Existing skill name`:`Skill name to remove, even if its source is missing`,required:!0}},run({args:e}){return J(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const Si=e({meta:{name:`skills`,description:`Inspect installed skills, saved assignments, or change assignments`},subCommands:{list:e({meta:{name:`list`,description:`List agents, skill directories, and saved skill names as JSON`},args:{agent:{...bi,required:!1}},run({args:e}){return J(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new L(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)}))})}}),installed:e({meta:{name:`installed`,description:`List skills physically installed in agent skill directories as JSON`},args:{agent:{...bi,required:!1}},run({args:e}){return J(({agentsService:t})=>{let n=t.list().map(e=>{let t=e.capabilities.skills?.directory;return t?{agent:e,directory:t}:null}).filter(e=>e!==null);if(e.agent!==void 0&&n.every(({agent:t})=>t.id!==e.agent))throw new L(e.agent);return n.filter(({agent:t})=>e.agent===void 0||t.id===e.agent).map(({agent:e,directory:n})=>({id:e.id,name:e.name,icon:e.icon,directory:n,skills:t.listInstalledSkills(e.id)}))})}}),"bring-in":e({meta:{name:`bring-in`,description:`Copy an installed skill into Foundry if needed, then replace the agent entry with a Foundry symlink`},args:{agent:bi,skill:{type:`string`,description:`Installed skill directory name`,required:!0}},run({args:e}){return J(({skillsService:t})=>t.bringIn(e.agent,e.skill))}}),delete:e({meta:{name:`delete`,description:`Delete an installed skill entry: unlink a symbolic link or delete an ordinary file or folder; a Foundry-managed link also clears its saved assignment`},args:{agent:bi,skill:{type:`string`,description:`Installed skill directory name`,required:!0}},run({args:e}){return J(({skillsService:t})=>t.deleteInstalled(e.agent,e.skill))}}),assign:xi(!0),unassign:xi(!1)}}),Ci=w.list().map(({id:e})=>e).join(`, `),wi={type:`positional`,description:`Agent ID: ${Ci}`,required:!0},Ti=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return J(({agentsService:e})=>e.list())}}),Ei=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...wi,description:`Optional agent ID: ${Ci}`,required:!1}},run({args:e}){return J(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new Y(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${Ci}`);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}))}))})}}),Di=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:wi,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 J(({agentsService:t})=>{let n=Ke({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Oi=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:wi},run({args:e}){return J(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),ki=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:wi},run({args:e}){return J(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),Ai=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:wi},run({args:e}){return J(({agentsService:t})=>t.reapply(e.agent))}}),ji=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:wi},run({args:e}){return J(({agentsService:t,openPathService:n})=>{let r=t.instructionFileTarget(e.agent);return n.open(r.filePath),{path:r.instructionFile}})}}),Mi=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:Ti,skills:Si,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:Ei,assign:Di,enable:Oi,disable:ki,reapply:Ai,open:ji}})}}),Ni=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 J(({instructionsService:t})=>t.create(un({name:e.name,content:e.content})))}}),Pi=e({meta:{name:`list`,description:`List instructions by name as JSON`},run(){return J(({instructionsService:e})=>e.list())}}),Fi=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 J(({instructionsService:t})=>t.get(e.id))}}),Ii=e({meta:{name:`edit`,description:`Replace an instruction and synchronize enabled agents`},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 J(({instructionsService:t})=>t.update(e.id,un({name:e.name,content:e.content})))}}),Li=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 J(({instructionsService:t})=>t.delete(e.id))}}),Ri=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:Ni,list:Pi,get:Fi,edit:Ii,delete:Li}});function zi(e){if(!Vi(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`||!ct.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 Vi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Hi=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 J(async({dataExportService:t})=>{let n=await t.createExport(gi(e.passphrase)),r=Wi(e.output);return await Gi(n.contents,r,e.force),{filePath:r}})}}),Ui=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 J(async({dataImportService:t})=>{let n=await t.importData(r.resolve(e.file),gi(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 Gi(e,t,n){await xe(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await De(a,e,{mode:384}),i.platform!==`win32`&&await _e(a,384),n){await Te(a,t);return}if(u(t))throw Ki(t);try{await ye(a,t)}catch(e){throw qi(e)?Ki(t):e}}finally{await b(a,{force:!0})}}function Ki(e){return new Y(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function qi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Ji={"color-theme":{field:`theme`,values:et},language:{field:`language`,values:tt},"time-zone":{field:`timezone`,values:rt},"time-format":{field:`timeFormat`,values:nt}},Yi=[...Object.keys(Ji),`config-folder`],Xi=Object.entries(Ji).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
9
|
+
`);function Zi(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const Qi=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Yi.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return J(({settingsService:t})=>{let n=Zi(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new Y(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Yi.join(`, `)}`);return n[e.key]})}}),$i=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(Ji).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${Xi}`,required:!0}},run({args:e}){return J(({settingsService:t})=>{if(e.key===`config-folder`)throw new Y(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(Ji,e.key))throw new Y(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(Ji).join(`, `)}`);let n=Ji[e.key];if(!n.values.includes(e.value))throw new Y(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Zi(t.update(pt({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),ea=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return J(({settingsService:e,openPathService:t})=>{let{configFolder:n}=e.read();return t.open(n),{configFolder:n}})}}),ta=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 J(({settingsSkillCopyService:t})=>{let n=zi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),na=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:Qi,set:$i,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:ea}}),export:Hi,import:Ui,"download-skill":ta}}),ra={type:`positional`,description:`Current skill name`,required:!0},ia=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 J(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),aa=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 J(({skillsService:t})=>t.importLocal({path:r.resolve(e.path)}))}}),oa=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 J(({skillsService:t})=>t.importUrl({url:e.url}))}}),sa=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 J(({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:ra},run({args:e}){return J(({skillsService:t})=>t.detail(e.skill))}}),save:e({meta:{name:`save`,description:`Replace the complete skill files tree; omitted entries are deleted and file contents are saved verbatim`},args:{skill:ra,file:{type:`string`,description:`JSON file containing { files }, or - for stdin. Accepts get output; only files is applied. SKILL.md is required; its content includes valid YAML frontmatter. Null content preserves existing opaque files.`,valueHint:`path|-`,required:!0}},run({args:e}){return J(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new B(`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 B(`Skill files input must be valid JSON`)}let o=cr(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 J(({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 J(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:ia,local:aa,url:oa}})}});function ca(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 la(t));return t.json(n,n.imported.length>0?201:200)}catch(e){return X(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 la(t));return t.json(n,n.imported.length>0?201:200)}catch(e){return X(t,e)}}),t.get(`/agents/assignments`,t=>t.json(e.assignments())),t.put(`/:name/agents/:id`,async t=>{try{let n=ur(await la(t));return t.json(e.setAssignment(t.req.param(`name`),t.req.param(`id`),n.assigned))}catch(e){return X(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 X(t,e)}}),t.post(`/`,async t=>{try{let n=await la(t);return t.json(e.create(U(n)),201)}catch(e){return X(t,e)}}),t.put(`/:name`,async t=>{try{let n=await la(t);if(n&&typeof n==`object`&&`files`in n){let r=cr(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),U(n)))}catch(e){return X(t,e)}}),t.delete(`/:name`,t=>{try{return e.delete(t.req.param(`name`)),t.body(null,204)}catch(e){return X(t,e)}}),t}async function la(e){try{return await e.req.json()}catch{throw new B(`Request body must be valid JSON`)}}function X(e,t){if(t instanceof V)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof L)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ir)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}},400);if(t instanceof dr)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof H)return e.json({error:{code:t.code,message:t.message}},404);throw t}function ua(e,t){let n=new S;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id/skills`,t=>{try{return t.json(e.listInstalledSkills(t.req.param(`id`)))}catch(e){return fa(t,e)}}),n.post(`/:id/skills/:directoryName/bring-in`,async e=>{try{return e.json(await t.bringIn(e.req.param(`id`),e.req.param(`directoryName`)))}catch(t){return X(e,t)}}),n.delete(`/:id/skills/:directoryName`,e=>{try{return e.json(t.deleteInstalled(e.req.param(`id`),e.req.param(`directoryName`)))}catch(t){return X(e,t)}}),n.put(`/:id/instructions`,async t=>{try{let n=Ke(await da(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return fa(t,e)}}),n.put(`/:id/enabled`,async t=>{try{let n=qe(await da(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return fa(t,e)}}),n.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return fa(t,e)}}),n}async function da(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function fa(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function pa(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 ha(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(un(await ma(t)));return t.json(n,201)}catch(e){return ha(t,e)}}),t.put(`/:id`,async t=>{try{let n=un(await ma(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return ha(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return ha(t,e)}}),t}async function ma(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function ha(e,t){if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof ln)return e.json({error:{code:t.code,message:t.message}},404);throw t}const ga=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],_a=[`active`,`disabled`,`deleted`];var Z=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function va(e){if(!Ea(e))throw new Z(`Provider input must be an object`);let t=Ta(e.name,`name`),n=Ca(e.protocol),r=wa(e.baseURL),i=e.apiKey===void 0?``:Ta(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Sa(e.customModels);return{...e.avatar!==void 0&&{avatar:ya(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function ya(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 Z(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function ba(e){if(!Ea(e))throw new Z(`Provider connection must be an object`);return{protocol:Ca(e.protocol),baseURL:wa(e.baseURL),apiKey:e.apiKey===void 0?``:Ta(e.apiKey,`apiKey`,{allowEmpty:!0})}}function xa(e){if(typeof e!=`string`||!_a.includes(e))throw new Z(`Invalid provider status`);return e}function Sa(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Z(`customModels must be an array`);return e.map(e=>{if(!Ea(e))throw new Z(`Each custom model must be an object`);return{id:Ta(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:Ta(e.displayName,`customModels.displayName`)}})}function Ca(e){if(typeof e!=`string`||!ga.includes(e))throw new Z(`Invalid provider protocol`);return e}function wa(e){let t=Ta(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new Z(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function Ta(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new Z(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new Z(`${t} is required`);return r}function Ea(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Q=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Da(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(Oa(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new Q(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new Q(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new Q(`Provider returned invalid JSON`)}return ka(i)}function Oa(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function ka(e){if(!ja(e)||!Array.isArray(e.data))throw new Q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!ja(e)||typeof e.id!=`string`||e.id.length===0)throw new Q(`Provider returned an invalid model entry`);let t=Aa(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Aa(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function ja(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ma=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Na=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=>Pa(e))}get(e){let t=this.storage.get(`providers`,e);return t?Pa(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 Ma;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),Pa(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new Ma;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),Pa(i)})}};function Pa(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 La(t,e)}}),n.post(`/models`,async t=>{try{let n=ba(await Ia(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return La(t,e)}}),n.post(`/`,async n=>{try{let r=va(await Ia(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return La(n,e)}}),n.put(`/:id`,async n=>{try{let r=va(await Ia(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return La(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Ia(n),i=xa(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 La(n,e)}}),n}async function Ia(e){try{return await e.req.json()}catch{throw new Z(`Request body must be valid JSON`)}}function La(e,t){if(t instanceof Z)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Ma)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Q)return e.json({error:{code:t.code,message:t.message}},502);throw t}var Ra=class{repository;constructor(e){this.repository=new Na(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 Ma;return Da(t)}fetchModelsForConnection(e){return Da(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function za(e,t=()=>{},n=new Tt){let r=new S;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=pt(await Ba(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Va(n,e)}}),r.post(`/skill-copy`,async e=>{try{let t=zi(await Ba(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 Ba(e){try{return await e.req.json()}catch{throw new gt(`Request body must be valid JSON`)}}function Va(e,t){if(t instanceof gt||t instanceof Bi)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Et)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Ha(e){let t=new S;return t.get(`/`,t=>He(t,async n=>{await Ua(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Wa(n,e)}),c=setInterval(()=>{r||Ga(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 Ua(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Wa(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Ga(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Ka=class extends Error{code=`INVALID_EXPORT_INPUT`};function qa(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Ka(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Ja(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Ka(`Request body must be valid JSON`)}let{passphrase:r}=qa(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 Ka?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 Ya(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 G(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new G(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new G(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await Se(r.join(de(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await ke(Me.fromWeb(n.req.raw.body),l(o,{mode:384}));let s=await e.importData(o,a);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json(s)}catch(e){return e instanceof G?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 rn(i)}}),n.post(`/agents`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new G(`INVALID_BACKUP`,`A JSON apply choice is required`)}return e.completeImport(Fr(n)),t.json({status:`completed`})}catch(e){if(e instanceof G){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 Xa(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 Za=Ue(Le);function Qa(e){return`
|
|
10
10
|
$ErrorActionPreference = 'Stop'
|
|
11
11
|
$options = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${x.from(JSON.stringify(e)).toString(`base64`)}')) | ConvertFrom-Json
|
|
12
12
|
Add-Type -AssemblyName System.Windows.Forms
|
|
@@ -39,7 +39,7 @@ try {
|
|
|
39
39
|
if ($null -ne $dialog) { $dialog.Dispose() }
|
|
40
40
|
$owner.Dispose()
|
|
41
41
|
}
|
|
42
|
-
`}function
|
|
42
|
+
`}function $a(e){return e instanceof Error?Reflect.get(e,`code`):void 0}async function eo(e){let t=[`--file-selection`];e.title&&t.push(`--title=${e.title}`),e.kind===`directory`?t.push(`--directory`):e.extensions?.length&&t.push(`--file-filter=${e.extensions.map(e=>`*.${e}`).join(` `)}`);try{let{stdout:e}=await Za(`zenity`,t);return{path:e.replace(/\r?\n$/u,``)||null}}catch(e){if($a(e)===1)return{path:null};if($a(e)!==`ENOENT`)throw e}let n=[e.kind===`directory`?`--getexistingdirectory`:`--getopenfilename`,`.`];e.kind===`file`&&e.extensions?.length&&n.push(e.extensions.map(e=>`*.${e}`).join(` `)),e.title&&n.push(`--title`,e.title);try{let{stdout:e}=await Za(`kdialog`,n);return{path:e.replace(/\r?\n$/u,``)||null}}catch(e){if($a(e)===1)return{path:null};throw e}}async function to(e){try{if(e.kind===`file-or-directory`&&i.platform!==`darwin`)throw new $(`FILE_PICKER_UNAVAILABLE`,`Combined file and directory selection is currently supported on macOS`,503);if(i.platform===`linux`)return await eo(e);let t;if(i.platform===`darwin`)({stdout:t}=await Za(`osascript`,[`-l`,`JavaScript`,`-e`,`
|
|
43
43
|
ObjC.import('AppKit');
|
|
44
44
|
function createPanel(options) {
|
|
45
45
|
var panel = $.NSOpenPanel.openPanel;
|
|
@@ -64,4 +64,4 @@ function run(argv) {
|
|
|
64
64
|
var selected = panel.runModal === $.NSModalResponseOK;
|
|
65
65
|
return JSON.stringify({ path: selected ? ObjC.unwrap(panel.URL.path) : null });
|
|
66
66
|
}
|
|
67
|
-
`,JSON.stringify(e)]));else if(i.platform===`win32`){let n=x.from(
|
|
67
|
+
`,JSON.stringify(e)]));else if(i.platform===`win32`){let n=x.from(Qa(e),`utf16le`).toString(`base64`);({stdout:t}=await Za(`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:$a(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 no=class{open;isPicking=!1;constructor(e=to){this.open=e}async pick(e){if(this.isPicking)throw new $(`FILE_PICKER_BUSY`,`A file picker is already open`,409);let t=Xa(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 ro(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(Xa(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 io(e){let t=new S;return t.post(`/`,async t=>{try{let n=ni(await ao(t));return t.json(e.open(n.path))}catch(e){if(e instanceof ti)return t.json({error:{code:e.code,message:e.message}},e.status);throw e}}),t}async function ao(e){try{return await e.req.json()}catch{throw new ti(`INVALID_OPEN_PATH`,`Request body must be valid JSON`,400)}}function oo(e){return e===`/api`||e.startsWith(`/api/`)}function so(e,t={}){let n=new S,r=t.providerService??new Ra(e),i=t.settingsService??new Ct(e),a=t.settingsSkillCopyService??new Tt,o=t.instructionsService??new Kn(e),s=t.agentsService??new nr(e,o),c=t.skillsService??new Ar(e),l=t.openPathService??new ii(void 0,i.read().configFolder);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Ge,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,Ha(t.eventHub)),n.route(`/api/file-picker`,ro(t.filePickerService??new no)),n.route(`/api/open-path`,io(l)),n.route(`/api/data-import`,Ya(t.dataImportService??new Qr(e),()=>{t.eventHub?.publish(at,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Ja(t.dataExportService??new sn(e))),n.route(`/api/agents`,ua(s,c)),n.route(`/api/skills`,ca(c)),n.route(`/api/instructions`,pa(o)),n.route(`/api/providers`,Fa(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,za(i,e=>{t.eventHub?.publish(at,e)},a)),n.notFound(e=>oo(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),oo(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function co(e,t,n){let i=so(t,n),a=Be({root:e});i.use(`*`,(e,t)=>oo(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`)&&!oo(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function lo(e,t){let n,r=se(e,{persistent:!1},(e,r)=>{(r===null||r===`settings.json`)&&(clearTimeout(n),n=setTimeout(t,30),n.unref())});return r.on(`error`,()=>{console.error(`Unable to watch Foundry settings`)}),()=>{clearTimeout(n),r.close()}}var uo=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 fo(e){let t=new uo,n=new sn(e),r=new Qr(e),i=new Kn(e),a=new nr(e,i),o=new Ra(e),s=new Ct(e),c=new Tt,l=new Ar(e),u=new no,d=new ii,f={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u,openPathService:d},p;return{services:f,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,filePickerService:u,openPathService:d,eventHub:t},start(){p??=lo(e.path,()=>{t.publish(at,{fields:[]})})},stop(){p?.(),p=void 0}}}const{dirname:po,join:mo,resolve:ho}=r,go=po(Oe(import.meta.url));function _o(){let e=[ho(go,`web`),ho(i.cwd(),`dist/web`)].find(e=>u(mo(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function vo({storage:e,webRoot:t=_o(),onListening:n}){let r=fo(e),a=co(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 yo(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 bo(e){let t=`xdg-open`,n=[e];i.platform===`darwin`?t=`open`:i.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=Re(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const xo=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 yo(`127.0.0.1`,11111)}catch(e){Ao(e);return}let t=hi(),n=await Eo();vo({storage:t,onListening({url:t}){Do(n),console.info(`Foundry is running at ${t}`),e.open&&bo(t)}})}}),So={agents:`ChatGPT (.agents)`,claude:`Claude Code (.claude)`},Co={missing:`not installed`,outdated:`differs from the bundled skill`,current:`up to date`},wo={missing:`✗`,outdated:`!`,current:`✓`},To={missing:`31`,outdated:`33`,current:`32`};async function Eo(){try{return await new Tt().getStatus()}catch{return}}function Do(e){if(!e){console.warn(` ${Oo(`31`,`✗ Unable to check the Foundry skill`)}`);return}console.info(`Foundry skill (v${e.version})`);for(let t of e.targets){let e=So[t.target].padEnd(22);console.info(` ${e}${Oo(To[t.status],`${wo[t.status]} ${Co[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 Oo(e,t){return ko()?`\u{1B}[${e}m${t}\u{1B}[0m`:t}function ko(){return i.env.NO_COLOR===void 0?i.env.FORCE_COLOR===void 0?i.stdout.isTTY:i.env.FORCE_COLOR!==`0`:!1}function Ao(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function jo(){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:xo,settings:na,instructions:Ri,agents:Mi,skills:sa}}),t}t(jo());export{};
|
|
@@ -33,7 +33,7 @@ the command details, output shapes, failure modes, and end-to-end examples.
|
|
|
33
33
|
| --- | --- | --- |
|
|
34
34
|
| Create, read, edit, delete, or list reusable Markdown instructions | `foundry instructions` | [Instructions](references/instructions.md) |
|
|
35
35
|
| List, read, create, edit metadata or files, or delete a Skill | `foundry skills` | [Skills](references/skills.md) |
|
|
36
|
-
| Inspect installed Skills, saved assignments, assign, or unassign | `foundry agents skills` | [Skill assignments](references/skills.md#external-symbolic-links) |
|
|
36
|
+
| Inspect installed Skills, saved assignments, bring in, delete, assign, or unassign | `foundry agents skills` | [Skill assignments](references/skills.md#external-symbolic-links) |
|
|
37
37
|
| Inspect, assign, enable, disable, or reapply instructions for an agent | `foundry agents instructions` | [Agents](references/agents.md) |
|
|
38
38
|
| Inspect supported agents and raw assignment state | `foundry agents list` | [Agents](references/agents.md) |
|
|
39
39
|
| Read or change application preferences | `foundry settings get/set` | [Settings](references/settings.md) |
|