@dhzh/foundry 7.0.0 → 7.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:process";import{spawn as i}from"node:child_process";import{chmodSync as a,closeSync as o,createReadStream as s,createWriteStream as c,existsSync as l,fsyncSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,renameSync as ee,rmSync as h,rmdirSync as te,statSync as g,watch as ne,writeFileSync as _}from"node:fs";import re,{homedir as ie,tmpdir as ae}from"node:os";import v from"node:path";import{createCipheriv as oe,createDecipheriv as se,createHash as ce,randomBytes as le,randomUUID as y,scrypt as ue}from"node:crypto";import{chmod as de,cp as fe,link as pe,mkdir as me,mkdtemp as he,open as ge,readFile as _e,readdir as ve,rename as b,rm as x,stat as ye,writeFile as be}from"node:fs/promises";import{fileURLToPath as xe}from"node:url";import{Buffer as S}from"node:buffer";import{pipeline as C}from"node:stream/promises";import Se from"yauzl";import Ce from"yazl";import{Readable as we,Transform as Te}from"node:stream";import{serve as Ee}from"@hono/node-server";import{serveStatic as De}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{StringDecoder as Oe}from"node:string_decoder";import{createZstdDecompress as ke}from"node:zlib";import{streamSSE as Ae}from"hono/streaming";import{FirecrawlClient as je}from"firecrawl";import{parse as Me}from"tldts";import{createServer as Ne}from"node:net";var Pe=`7.0.0`;const Fe=[`system`,`light`,`dark`],Ie=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Le=[`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`],Re=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],ze=[`firecrawl`],T=`data/foundry.json`,Be=`settings.changed`,Ve=[`agents`,`claude`],E={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function He(e){let t=A(e)?e:{},n=A(t.workspace)?t.workspace:{},r=A(n.appearance)?n.appearance:{},i=A(n[`language-region`])?n[`language-region`]:{},a=A(t.features)?t.features:{},o=A(a.library)?a.library:{},s=A(o.captures)?o.captures:{},c=A(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":O(r[`color-theme`],Fe,E.workspace.appearance[`color-theme`])},"language-region":{language:O(i.language,Ie,E.workspace[`language-region`].language),"time-format":O(i[`time-format`],Le,E.workspace[`language-region`][`time-format`]),"time-zone":O(i[`time-zone`],Re,E.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:qe(s.fetcher),maxAttempts:Ye(s.maxAttempts,10,1),fetchConcurrency:Ye(s.fetchConcurrency,5,2),firecrawl:{apiKey:Qe(c.apiKey)}}}}}}function Ue(e){if(!A(e))throw new D(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=k(e.theme,Fe,`theme`)),`language`in e&&(t.language=k(e.language,Ie,`language`)),`timeFormat`in e&&(t.timeFormat=k(e.timeFormat,Le,`timeFormat`)),`timezone`in e&&(t.timezone=k(e.timezone,Re,`timezone`)),`captures`in e&&(t.captures=Ke(e.captures)),t}function We(e,t){let n=e.features.library.captures,r=t.captures;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`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function Ge(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var D=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function Ke(e){if(!A(e))throw new D(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:k(e.fetcher,ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Xe(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=Xe(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=Ze(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function qe(e){return Je(e,ze)}function Je(e,t){return typeof e==`string`&&t.includes(e)?e:null}function O(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function k(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new D(`Invalid ${n}`);return e}function Ye(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Xe(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new D(`${n} must be an integer from 1 to ${t}`);return e}function Ze(e,t){if(typeof e!=`string`)throw new D(`${t} must be a string`);return e.trim()}function Qe(e){return typeof e==`string`?e:``}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $e(e){if(!tt(e)||!Array.isArray(e.targets))throw new et(`targets must be an array`);if(e.targets.length===0)throw new et(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Ve.includes(e))throw new et(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var et=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function tt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nt(e){let t=r.platform===`darwin`?`open`:r.platform===`win32`?`explorer`:`xdg-open`,n=i(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function rt(){return v.join(re.homedir(),`.foundry`)}function it(){let e=rt();return d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448),e}function j(e){return e.readSettings()}function at(e){return Ge(j(e))}function ot(e,t){return t.transaction(()=>{let n=We(j(t),e);return t.setSettings(n),Ge(n)})}var st=class{storage;configFolder;openFolder;constructor(e,t=rt(),n=nt){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...at(this.storage),configFolder:this.configFolder}}update(e){return{...ot(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const ct=v.dirname(xe(import.meta.url)),M=`foundry`;var lt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ie()}={}){this.configuredSkillRoot=e,this.homeDirectory=v.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??ut();if(!l(v.join(t,`SKILL.md`)))throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=v.join(n,M),i=v.join(n,`.${M}-${y()}.tmp`),a=v.join(n,`.${M}-${y()}.backup`);try{return await me(n,{recursive:!0}),await fe(t,i,{recursive:!0,errorOnExist:!0}),await dt(i,r,a),{target:e,destination:r}}catch(e){throw await x(i,{recursive:!0,force:!0}),e instanceof N?e:new N(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return v.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:v.join(this.getTargetParent(e),M)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},N=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function ut(){let e=[v.resolve(ct,`skills`,M),v.resolve(ct,`..`,`..`,`..`,`skills`,M),v.resolve(r.cwd(),`skills`,M)].find(e=>l(v.join(e,`SKILL.md`)));if(!e)throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function dt(e,t,n){let r=l(t);r&&await b(t,n);try{await b(e,t),r&&await x(n,{recursive:!0,force:!0})}catch(e){throw r&&!l(t)&&l(n)&&await b(n,t),e}}const ft=`manifest.json`,pt=/* @__PURE__ */ new Set([ft,T]);async function mt(e,t){let n=new Ce.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await C(n.outputStream,c(t,{mode:384}))}async function ht(e,t){let n=await gt(e),r=/* @__PURE__ */ new Map;try{await new Promise((e,i)=>{let a=e=>{i(e instanceof Error?e:Error(String(e)))},o=async e=>{if(!pt.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||r.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let i=v.join(t,e.fileName);await me(v.dirname(i),{recursive:!0,mode:448}),await C(await _t(n,e),c(i,{mode:384})),r.set(e.fileName,i),n.readEntry()};n.on(`error`,a),n.on(`end`,e),n.on(`entry`,e=>{o(e).catch(a)}),n.readEntry()})}catch(e){throw await x(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(ft)||!r.has(`data/foundry.json`))throw await x(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function gt(e){return new Promise((t,n)=>{Se.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function _t(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var vt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const P=S.from(`FOUNDRYX`,`ascii`),F=`aes-256-gcm`,yt=`scrypt`,I={N:131072,r:8,p:1};async function bt(e,t,n){let r=le(16),i=le(12),a={version:1,cipher:F,kdf:{name:yt,salt:r.toString(`base64`),...I,keyLength:32},nonce:i.toString(`base64`)},o=S.from(JSON.stringify(a),`utf8`),l=St(o.byteLength),u=S.concat([l,o]),d=await Ct(n,r,I);try{let n=await ge(t,`w`,384);try{await n.write(u)}finally{await n.close()}await C(s(e),wt(d,i,u),c(t,{flags:`r+`,mode:384,start:u.byteLength})),await de(t,384)}catch(e){throw await x(t,{force:!0}),new vt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function xt(e,t,n){let r;try{let i=(await ye(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await ge(e,`r`),o,l,u;try{if(o=await Dt(a,13,0),!o.subarray(0,P.byteLength).equals(P))throw Error(`The export file signature is invalid`);if(o.readUInt8(P.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(P.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`);l=await Dt(a,e,13),u=await Dt(a,16,i-16)}finally{await a.close()}let d=Et(JSON.parse(l.toString(`utf8`)));r=await Ct(n,d.salt,d.header.kdf);let f=S.concat([o,l]);await C(s(e,{start:13+l.byteLength,end:i-16-1}),Tt(r,d.nonce,f,u),c(t,{mode:384})),await de(t,384)}catch(e){throw await x(t,{force:!0}),e instanceof vt?e:new vt(kt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,kt(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 St(e){let t=S.alloc(13);return P.copy(t,0),t.writeUInt8(1,P.byteLength),t.writeUInt32BE(e,P.byteLength+1),t}function Ct(e,t,n){return new Promise((r,i)=>{ue(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function wt(e,t,n){let r=oe(F,e,t,{authTagLength:16});return r.setAAD(n),new Te({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,S.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Tt(e,t,n,r){let i=se(F,e,t,{authTagLength:16});return i.setAAD(n),new Te({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 Et(e){if(!Ot(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==F||!Ot(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==yt||typeof t.salt!=`string`||t.N!==I.N||t.r!==I.r||t.p!==I.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=S.from(t.salt,`base64`),r=S.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:F,kdf:{name:yt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Dt(e,t,n){let r=S.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Ot(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function At(e){try{await x(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function jt(e){return{settings:e.readSettings()}}var Mt=class{storage;constructor(e){this.storage=e}async createExport(e){let t=jt(this.storage),n=await he(v.join(ae(),`foundry-export-`));try{let r=(/* @__PURE__ */ new Date()).toISOString(),i=JSON.stringify(t,null,2),a=v.join(n,`foundry.json`),o=v.join(n,`manifest.json`),s=v.join(n,`foundry.zip`),c=v.join(n,`foundry.foundry-backup`),l={format:`foundry.data`,archiveVersion:1,appVersion:Pe,createdAt:r,data:{path:T,bytes:S.byteLength(i,`utf8`),sha256:ce(`sha256`).update(i).digest(`hex`)}};return await be(a,i,{mode:384}),await be(o,JSON.stringify(l,null,2),{mode:384}),await mt([{entryPath:`manifest.json`,filePath:o},{entryPath:T,filePath:a}],s),await bt(s,c,e),{fileName:`foundry-${r.replaceAll(`:`,`-`)}.foundry-backup`,contents:await _e(c)}}finally{await At(n)}}},L=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pt(e){if(!Nt(e)||e.format!==`foundry.data`||e.archiveVersion!==1||!Nt(e.data)||e.data.path!==`data/foundry.json`||typeof e.data.bytes!=`number`||!Number.isSafeInteger(e.data.bytes)||e.data.bytes<=0||typeof e.data.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.data.sha256))throw new L(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:T,bytes:e.data.bytes,sha256:e.data.sha256}}}function Ft(e){if(!Nt(e)||!Nt(e.settings))throw new L(`INVALID_BACKUP`,`Backup data must contain a settings object`);return{settings:He(e.settings)}}function It(e,t){e.transaction(()=>{e.setSettings(t.settings)})}var Lt=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await he(v.join(ae(),`foundry-import-`));try{let r=v.join(n,`backup.zip`);await xt(e,r,t);let i=await ht(r,v.join(n,`extracted`)),a=Pt(JSON.parse(await _e(i[`manifest.json`],`utf8`))),o=await _e(i[T]);if(o.byteLength!==a.data.bytes||ce(`sha256`).update(o).digest(`hex`)!==a.data.sha256)throw new L(`INVALID_BACKUP`,`Backup checksum does not match`);let s=Ft(JSON.parse(o.toString(`utf8`)));try{It(this.storage,s)}catch{throw new L(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof L?e:e instanceof vt?e.code===`INVALID_PASSPHRASE`?new L(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new L(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new L(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await At(n)}}};function Rt(e){d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448)}function R(e){if(r.platform===`win32`)return;let t=f(e,`r`);try{u(t)}finally{o(t)}}function zt(e,t){Rt(v.dirname(e));let n=`${e}.${y()}.tmp`;try{let r=f(n,`wx`,384);try{_(r,`${JSON.stringify(t,null,2)}\n`),u(r)}finally{o(r)}ee(n,e),R(v.dirname(e))}finally{h(n,{force:!0})}}const Bt=[`providers`,`captures`,`fetchJobs`];function Vt(e){try{let t=JSON.parse(p(v.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return r.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-g(e).mtimeMs>3e4}}var Ht=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Rt(e);for(let e of Bt)e!==`providers`&&Rt(this.collectionPath(e))}collectionPath(e){return v.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return v.relative(this.path,v.join(this.collectionPath(e),`${ce(`sha256`).update(t).digest(`hex`)}.json`))}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=v.join(this.path,`.lock`),n=Date.now();for(;;)try{d(t,{mode:448});try{_(v.join(t,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384})}catch(e){throw h(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(),e()}finally{this.lockDepth=0,h(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=g(e);if(!Vt(e))return;let n=v.join(e,`recovering`);try{d(n)}catch(e){if(e.code===`EEXIST`){let e=g(n);Vt(n)&&g(n).ino===e.ino&&h(n,{recursive:!0,force:!0})}return}if(_(v.join(n,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384,flag:`wx`}),g(e).ino!==t.ino||!Vt(e)){h(n,{recursive:!0,force:!0});return}h(e,{recursive:!0,force:!0})}catch{}}recover(){let e=v.join(this.path,`.transaction.json`);if(!l(e))return;let t=JSON.parse(p(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=v.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!l(e)){let e=l(t)?m(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,v.join(`providers`,e)))},...e.map(e=>({file:v.join(`providers`,e),value:null}))]};zt(v.join(this.path,`.transaction.json`),n),this.applyJournal(n)}l(t)&&m(t).length===0&&(te(t),R(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(p(v.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)}applyJournal(e){for(let t of e.changes){let e=v.resolve(this.path,t.file),n=v.relative(this.path,e);if(n.startsWith(`..`)||v.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(h(e,{force:!0}),R(v.dirname(e))):zt(e,t.value)}h(v.join(this.path,`.transaction.json`),{force:!0}),R(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=v.join(this.path,t);if(!l(e))return;n=JSON.parse(p(e,`utf8`))}let r=n;if(this.recordPath(e,r.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(r)}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(m(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>v.relative(this.path,v.join(t,e.name))));if(this.changes){let e=v.relative(this.path,t);for(let t of this.changes.keys())v.dirname(t)===e&&n.add(t)}let r=[];for(let t of n){let n=this.readRecord(e,t);n&&r.push(n)}return r})}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 He(this.changes.get(`settings.json`));let e=v.join(this.path,`settings.json`);return l(e)?He(JSON.parse(p(e,`utf8`))):structuredClone(E)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);let n=this.recordPath(e,t.id);if(e===`providers`){let n=this.all(e),r=n.findIndex(e=>e.id===t.id);r===-1?n.push(t):n[r]=t,this.changes.set(`providers.json`,structuredClone(n))}else this.changes.set(n,structuredClone(t))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,He(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);if(this.changes.size>0){let e={changes:[...this.changes].map(([e,t])=>({file:e,value:t}))};zt(v.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}})}close(){this.closed=!0}};function Ut(e=rt()){let t=new Ht(e);try{return t.transaction(()=>{let n=t.readSettings();l(v.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function Wt(){return it(),Ut()}async function z(e){let t;try{let n=Wt();t={storage:n,settingsService:new st(n),settingsSkillCopyService:new lt,dataExportService:new Mt(n),dataImportService:new Lt(n)},Kt(await e(t))}catch(e){let t=qt(e);console.error(JSON.stringify({error:t},null,2)),r.exitCode=1}finally{t?.storage.close()}}function Gt(e){let t=e??r.env.FOUNDRY_PASSPHRASE;if(!t)throw new B(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Kt(e){console.log(JSON.stringify(e,null,2))}function qt(e){return e instanceof Error?{code:Jt(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Jt(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Yt=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 z(async({dataExportService:t})=>{let n=await t.createExport(Gt(e.passphrase)),r=Zt(e.output);return await Qt(n.contents,r,e.force),{filePath:r}})}}),Xt=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},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return z(async({dataImportService:t})=>(await t.importData(v.resolve(e.file),Gt(e.passphrase)),{status:`imported`}))}});function Zt(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,r=v.resolve(n);return r.toLowerCase().endsWith(`.foundry-backup`)?r:`${r}.foundry-backup`}async function Qt(e,t,n){await me(v.dirname(t),{recursive:!0,mode:448});let i=v.join(v.dirname(t),`.${v.basename(t)}.${y()}.tmp`);try{if(await be(i,e,{mode:384}),r.platform!==`win32`&&await de(i,384),n){await b(i,t);return}if(l(t))throw $t(t);try{await pe(i,t)}catch(e){throw en(e)?$t(t):e}}finally{await x(i,{force:!0})}}function $t(e){return new B(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function en(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const V={"color-theme":{field:`theme`,values:Fe},language:{field:`language`,values:Ie},"time-zone":{field:`timezone`,values:Re},"time-format":{field:`timeFormat`,values:Le}},tn=[...Object.keys(V),`config-folder`],nn=Object.entries(V).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
2
|
+
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:process";import{spawn as i}from"node:child_process";import{chmodSync as a,closeSync as o,createReadStream as s,createWriteStream as c,existsSync as l,fsyncSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,renameSync as ee,rmSync as h,rmdirSync as te,statSync as g,watch as ne,writeFileSync as _}from"node:fs";import re,{homedir as ie,tmpdir as ae}from"node:os";import v from"node:path";import{createCipheriv as oe,createDecipheriv as se,createHash as ce,randomBytes as le,randomUUID as y,scrypt as ue}from"node:crypto";import{chmod as de,cp as fe,link as pe,mkdir as me,mkdtemp as he,open as ge,readFile as _e,readdir as ve,rename as b,rm as x,stat as ye,writeFile as be}from"node:fs/promises";import{fileURLToPath as xe}from"node:url";import{Buffer as S}from"node:buffer";import{pipeline as C}from"node:stream/promises";import Se from"yauzl";import Ce from"yazl";import{Readable as we,Transform as Te}from"node:stream";import{serve as Ee}from"@hono/node-server";import{serveStatic as De}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{StringDecoder as Oe}from"node:string_decoder";import{createZstdDecompress as ke}from"node:zlib";import{streamSSE as Ae}from"hono/streaming";import{FirecrawlClient as je}from"firecrawl";import{parse as Me}from"tldts";import{createServer as Ne}from"node:net";var Pe=`7.0.1`;const Fe=[`system`,`light`,`dark`],Ie=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Le=[`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`],Re=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],ze=[`firecrawl`],T=`data/foundry.json`,Be=`settings.changed`,Ve=[`agents`,`claude`],E={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function He(e){let t=A(e)?e:{},n=A(t.workspace)?t.workspace:{},r=A(n.appearance)?n.appearance:{},i=A(n[`language-region`])?n[`language-region`]:{},a=A(t.features)?t.features:{},o=A(a.library)?a.library:{},s=A(o.captures)?o.captures:{},c=A(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":O(r[`color-theme`],Fe,E.workspace.appearance[`color-theme`])},"language-region":{language:O(i.language,Ie,E.workspace[`language-region`].language),"time-format":O(i[`time-format`],Le,E.workspace[`language-region`][`time-format`]),"time-zone":O(i[`time-zone`],Re,E.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:qe(s.fetcher),maxAttempts:Ye(s.maxAttempts,10,1),fetchConcurrency:Ye(s.fetchConcurrency,5,2),firecrawl:{apiKey:Qe(c.apiKey)}}}}}}function Ue(e){if(!A(e))throw new D(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=k(e.theme,Fe,`theme`)),`language`in e&&(t.language=k(e.language,Ie,`language`)),`timeFormat`in e&&(t.timeFormat=k(e.timeFormat,Le,`timeFormat`)),`timezone`in e&&(t.timezone=k(e.timezone,Re,`timezone`)),`captures`in e&&(t.captures=Ke(e.captures)),t}function We(e,t){let n=e.features.library.captures,r=t.captures;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`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function Ge(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var D=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function Ke(e){if(!A(e))throw new D(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:k(e.fetcher,ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Xe(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=Xe(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=Ze(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function qe(e){return Je(e,ze)}function Je(e,t){return typeof e==`string`&&t.includes(e)?e:null}function O(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function k(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new D(`Invalid ${n}`);return e}function Ye(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Xe(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new D(`${n} must be an integer from 1 to ${t}`);return e}function Ze(e,t){if(typeof e!=`string`)throw new D(`${t} must be a string`);return e.trim()}function Qe(e){return typeof e==`string`?e:``}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $e(e){if(!tt(e)||!Array.isArray(e.targets))throw new et(`targets must be an array`);if(e.targets.length===0)throw new et(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Ve.includes(e))throw new et(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var et=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function tt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nt(e){let t=r.platform===`darwin`?`open`:r.platform===`win32`?`explorer`:`xdg-open`,n=i(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function rt(){return v.join(re.homedir(),`.foundry`)}function it(){let e=rt();return d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448),e}function j(e){return e.readSettings()}function at(e){return Ge(j(e))}function ot(e,t){return t.transaction(()=>{let n=We(j(t),e);return t.setSettings(n),Ge(n)})}var st=class{storage;configFolder;openFolder;constructor(e,t=rt(),n=nt){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...at(this.storage),configFolder:this.configFolder}}update(e){return{...ot(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const ct=v.dirname(xe(import.meta.url)),M=`foundry`;var lt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ie()}={}){this.configuredSkillRoot=e,this.homeDirectory=v.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??ut();if(!l(v.join(t,`SKILL.md`)))throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=v.join(n,M),i=v.join(n,`.${M}-${y()}.tmp`),a=v.join(n,`.${M}-${y()}.backup`);try{return await me(n,{recursive:!0}),await fe(t,i,{recursive:!0,errorOnExist:!0}),await dt(i,r,a),{target:e,destination:r}}catch(e){throw await x(i,{recursive:!0,force:!0}),e instanceof N?e:new N(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return v.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:v.join(this.getTargetParent(e),M)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},N=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function ut(){let e=[v.resolve(ct,`skills`,M),v.resolve(ct,`..`,`..`,`..`,`skills`,M),v.resolve(r.cwd(),`skills`,M)].find(e=>l(v.join(e,`SKILL.md`)));if(!e)throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function dt(e,t,n){let r=l(t);r&&await b(t,n);try{await b(e,t),r&&await x(n,{recursive:!0,force:!0})}catch(e){throw r&&!l(t)&&l(n)&&await b(n,t),e}}const ft=`manifest.json`,pt=/* @__PURE__ */ new Set([ft,T]);async function mt(e,t){let n=new Ce.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await C(n.outputStream,c(t,{mode:384}))}async function ht(e,t){let n=await gt(e),r=/* @__PURE__ */ new Map;try{await new Promise((e,i)=>{let a=e=>{i(e instanceof Error?e:Error(String(e)))},o=async e=>{if(!pt.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||r.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let i=v.join(t,e.fileName);await me(v.dirname(i),{recursive:!0,mode:448}),await C(await _t(n,e),c(i,{mode:384})),r.set(e.fileName,i),n.readEntry()};n.on(`error`,a),n.on(`end`,e),n.on(`entry`,e=>{o(e).catch(a)}),n.readEntry()})}catch(e){throw await x(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(ft)||!r.has(`data/foundry.json`))throw await x(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function gt(e){return new Promise((t,n)=>{Se.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function _t(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var vt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const P=S.from(`FOUNDRYX`,`ascii`),F=`aes-256-gcm`,yt=`scrypt`,I={N:131072,r:8,p:1};async function bt(e,t,n){let r=le(16),i=le(12),a={version:1,cipher:F,kdf:{name:yt,salt:r.toString(`base64`),...I,keyLength:32},nonce:i.toString(`base64`)},o=S.from(JSON.stringify(a),`utf8`),l=St(o.byteLength),u=S.concat([l,o]),d=await Ct(n,r,I);try{let n=await ge(t,`w`,384);try{await n.write(u)}finally{await n.close()}await C(s(e),wt(d,i,u),c(t,{flags:`r+`,mode:384,start:u.byteLength})),await de(t,384)}catch(e){throw await x(t,{force:!0}),new vt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function xt(e,t,n){let r;try{let i=(await ye(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await ge(e,`r`),o,l,u;try{if(o=await Dt(a,13,0),!o.subarray(0,P.byteLength).equals(P))throw Error(`The export file signature is invalid`);if(o.readUInt8(P.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(P.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`);l=await Dt(a,e,13),u=await Dt(a,16,i-16)}finally{await a.close()}let d=Et(JSON.parse(l.toString(`utf8`)));r=await Ct(n,d.salt,d.header.kdf);let f=S.concat([o,l]);await C(s(e,{start:13+l.byteLength,end:i-16-1}),Tt(r,d.nonce,f,u),c(t,{mode:384})),await de(t,384)}catch(e){throw await x(t,{force:!0}),e instanceof vt?e:new vt(kt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,kt(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 St(e){let t=S.alloc(13);return P.copy(t,0),t.writeUInt8(1,P.byteLength),t.writeUInt32BE(e,P.byteLength+1),t}function Ct(e,t,n){return new Promise((r,i)=>{ue(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function wt(e,t,n){let r=oe(F,e,t,{authTagLength:16});return r.setAAD(n),new Te({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,S.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Tt(e,t,n,r){let i=se(F,e,t,{authTagLength:16});return i.setAAD(n),new Te({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 Et(e){if(!Ot(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==F||!Ot(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==yt||typeof t.salt!=`string`||t.N!==I.N||t.r!==I.r||t.p!==I.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=S.from(t.salt,`base64`),r=S.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:F,kdf:{name:yt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Dt(e,t,n){let r=S.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Ot(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function At(e){try{await x(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function jt(e){return{settings:e.readSettings()}}var Mt=class{storage;constructor(e){this.storage=e}async createExport(e){let t=jt(this.storage),n=await he(v.join(ae(),`foundry-export-`));try{let r=(/* @__PURE__ */ new Date()).toISOString(),i=JSON.stringify(t,null,2),a=v.join(n,`foundry.json`),o=v.join(n,`manifest.json`),s=v.join(n,`foundry.zip`),c=v.join(n,`foundry.foundry-backup`),l={format:`foundry.data`,archiveVersion:1,appVersion:Pe,createdAt:r,data:{path:T,bytes:S.byteLength(i,`utf8`),sha256:ce(`sha256`).update(i).digest(`hex`)}};return await be(a,i,{mode:384}),await be(o,JSON.stringify(l,null,2),{mode:384}),await mt([{entryPath:`manifest.json`,filePath:o},{entryPath:T,filePath:a}],s),await bt(s,c,e),{fileName:`foundry-${r.replaceAll(`:`,`-`)}.foundry-backup`,contents:await _e(c)}}finally{await At(n)}}},L=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pt(e){if(!Nt(e)||e.format!==`foundry.data`||e.archiveVersion!==1||!Nt(e.data)||e.data.path!==`data/foundry.json`||typeof e.data.bytes!=`number`||!Number.isSafeInteger(e.data.bytes)||e.data.bytes<=0||typeof e.data.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.data.sha256))throw new L(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:T,bytes:e.data.bytes,sha256:e.data.sha256}}}function Ft(e){if(!Nt(e)||!Nt(e.settings))throw new L(`INVALID_BACKUP`,`Backup data must contain a settings object`);return{settings:He(e.settings)}}function It(e,t){e.transaction(()=>{e.setSettings(t.settings)})}var Lt=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await he(v.join(ae(),`foundry-import-`));try{let r=v.join(n,`backup.zip`);await xt(e,r,t);let i=await ht(r,v.join(n,`extracted`)),a=Pt(JSON.parse(await _e(i[`manifest.json`],`utf8`))),o=await _e(i[T]);if(o.byteLength!==a.data.bytes||ce(`sha256`).update(o).digest(`hex`)!==a.data.sha256)throw new L(`INVALID_BACKUP`,`Backup checksum does not match`);let s=Ft(JSON.parse(o.toString(`utf8`)));try{It(this.storage,s)}catch{throw new L(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof L?e:e instanceof vt?e.code===`INVALID_PASSPHRASE`?new L(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new L(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new L(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await At(n)}}};function Rt(e){d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448)}function R(e){if(r.platform===`win32`)return;let t=f(e,`r`);try{u(t)}finally{o(t)}}function zt(e,t){Rt(v.dirname(e));let n=`${e}.${y()}.tmp`;try{let r=f(n,`wx`,384);try{_(r,`${JSON.stringify(t,null,2)}\n`),u(r)}finally{o(r)}ee(n,e),R(v.dirname(e))}finally{h(n,{force:!0})}}const Bt=[`providers`,`captures`,`fetchJobs`];function Vt(e){try{let t=JSON.parse(p(v.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return r.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-g(e).mtimeMs>3e4}}var Ht=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Rt(e);for(let e of Bt)e!==`providers`&&Rt(this.collectionPath(e))}collectionPath(e){return v.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return v.relative(this.path,v.join(this.collectionPath(e),`${ce(`sha256`).update(t).digest(`hex`)}.json`))}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=v.join(this.path,`.lock`),n=Date.now();for(;;)try{d(t,{mode:448});try{_(v.join(t,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384})}catch(e){throw h(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(),e()}finally{this.lockDepth=0,h(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=g(e);if(!Vt(e))return;let n=v.join(e,`recovering`);try{d(n)}catch(e){if(e.code===`EEXIST`){let e=g(n);Vt(n)&&g(n).ino===e.ino&&h(n,{recursive:!0,force:!0})}return}if(_(v.join(n,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384,flag:`wx`}),g(e).ino!==t.ino||!Vt(e)){h(n,{recursive:!0,force:!0});return}h(e,{recursive:!0,force:!0})}catch{}}recover(){let e=v.join(this.path,`.transaction.json`);if(!l(e))return;let t=JSON.parse(p(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=v.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!l(e)){let e=l(t)?m(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,v.join(`providers`,e)))},...e.map(e=>({file:v.join(`providers`,e),value:null}))]};zt(v.join(this.path,`.transaction.json`),n),this.applyJournal(n)}l(t)&&m(t).length===0&&(te(t),R(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(p(v.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)}applyJournal(e){for(let t of e.changes){let e=v.resolve(this.path,t.file),n=v.relative(this.path,e);if(n.startsWith(`..`)||v.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(h(e,{force:!0}),R(v.dirname(e))):zt(e,t.value)}h(v.join(this.path,`.transaction.json`),{force:!0}),R(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=v.join(this.path,t);if(!l(e))return;n=JSON.parse(p(e,`utf8`))}let r=n;if(this.recordPath(e,r.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(r)}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(m(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>v.relative(this.path,v.join(t,e.name))));if(this.changes){let e=v.relative(this.path,t);for(let t of this.changes.keys())v.dirname(t)===e&&n.add(t)}let r=[];for(let t of n){let n=this.readRecord(e,t);n&&r.push(n)}return r})}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 He(this.changes.get(`settings.json`));let e=v.join(this.path,`settings.json`);return l(e)?He(JSON.parse(p(e,`utf8`))):structuredClone(E)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);let n=this.recordPath(e,t.id);if(e===`providers`){let n=this.all(e),r=n.findIndex(e=>e.id===t.id);r===-1?n.push(t):n[r]=t,this.changes.set(`providers.json`,structuredClone(n))}else this.changes.set(n,structuredClone(t))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,He(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);if(this.changes.size>0){let e={changes:[...this.changes].map(([e,t])=>({file:e,value:t}))};zt(v.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}})}close(){this.closed=!0}};function Ut(e=rt()){let t=new Ht(e);try{return t.transaction(()=>{let n=t.readSettings();l(v.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function Wt(){return it(),Ut()}async function z(e){let t;try{let n=Wt();t={storage:n,settingsService:new st(n),settingsSkillCopyService:new lt,dataExportService:new Mt(n),dataImportService:new Lt(n)},Kt(await e(t))}catch(e){let t=qt(e);console.error(JSON.stringify({error:t},null,2)),r.exitCode=1}finally{t?.storage.close()}}function Gt(e){let t=e??r.env.FOUNDRY_PASSPHRASE;if(!t)throw new B(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Kt(e){console.log(JSON.stringify(e,null,2))}function qt(e){return e instanceof Error?{code:Jt(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Jt(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Yt=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 z(async({dataExportService:t})=>{let n=await t.createExport(Gt(e.passphrase)),r=Zt(e.output);return await Qt(n.contents,r,e.force),{filePath:r}})}}),Xt=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},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return z(async({dataImportService:t})=>(await t.importData(v.resolve(e.file),Gt(e.passphrase)),{status:`imported`}))}});function Zt(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,r=v.resolve(n);return r.toLowerCase().endsWith(`.foundry-backup`)?r:`${r}.foundry-backup`}async function Qt(e,t,n){await me(v.dirname(t),{recursive:!0,mode:448});let i=v.join(v.dirname(t),`.${v.basename(t)}.${y()}.tmp`);try{if(await be(i,e,{mode:384}),r.platform!==`win32`&&await de(i,384),n){await b(i,t);return}if(l(t))throw $t(t);try{await pe(i,t)}catch(e){throw en(e)?$t(t):e}}finally{await x(i,{force:!0})}}function $t(e){return new B(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function en(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const V={"color-theme":{field:`theme`,values:Fe},language:{field:`language`,values:Ie},"time-zone":{field:`timezone`,values:Re},"time-format":{field:`timeFormat`,values:Le}},tn=[...Object.keys(V),`config-folder`],nn=Object.entries(V).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
3
3
|
`);function rn(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const an=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${tn.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return z(({settingsService:t})=>{let n=rn(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${tn.join(`, `)}`);return n[e.key]})}}),on=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(V).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${nn}`,required:!0}},run({args:e}){return z(({settingsService:t})=>{if(e.key===`config-folder`)throw new B(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(V,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(V).join(`, `)}`);let n=V[e.key];if(!n.values.includes(e.value))throw new B(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=rn(t.update(Ue({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),sn=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return z(({settingsService:e})=>e.openConfigFolder())}}),cn=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 z(({settingsSkillCopyService:t})=>{let n=$e({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),ln=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:an,set:on,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:sn}}),export:Yt,import:Xt,"download-skill":cn}});function un(e){if(!pn(e)||typeof e.url!=`string`)throw new H(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function dn(e){return e===`no-successful`?`no-successful`:`all`}function fn(e){if(!pn(e)||typeof e.userNote!=`string`)throw new H(`userNote must be a string`);return e.userNote}var H=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var U=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function mn(e,t=()=>{}){let n=new w;return n.get(`/`,t=>{let n=dn(t.req.query(`filter`));return t.json(e.list(n))}),n.get(`/counts`,t=>t.json(e.counts())),n.post(`/`,async n=>{try{let r=un(await hn(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return W(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return W(t,e)}}),n.post(`/:id/recapture`,n=>{try{let r=n.req.param(`id`),i=e.recapture(r);return t({captureId:r,action:`recaptured`}),n.json(i,202)}catch(e){return W(n,e)}}),n.delete(`/:id`,n=>{try{let r=n.req.param(`id`);return e.delete(r),t({captureId:r,action:`deleted`}),n.body(null,204)}catch(e){return W(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=fn(await hn(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return W(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return W(t,e)}}),n}async function hn(e){try{return await e.req.json()}catch{throw new H(`Request body must be valid JSON`)}}function W(e,t){if(t instanceof H)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof U)return e.json({error:{code:t.code,message:t.message}},gn(t.code));throw t}function gn(e){switch(e){case`CAPTURE_NOT_FOUND`:return 404;case`CAPTURE_ALREADY_EXISTS`:case`ACTIVE_JOB_EXISTS`:return 409;case`FETCHER_NOT_CONFIGURED`:return 503;default:return 400}}const _n=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],vn=[`active`,`disabled`,`deleted`];var G=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},yn=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function bn(e){if(!Dn(e))throw new G(`Provider input must be an object`);let t=K(e.name,`name`),n=Tn(e.protocol),r=En(e.baseURL),i=e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0}),a=wn(e.customModels);return{...e.avatar!==void 0&&{avatar:xn(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function xn(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 G(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Sn(e){if(!Dn(e))throw new G(`Provider connection must be an object`);return{protocol:Tn(e.protocol),baseURL:En(e.baseURL),apiKey:e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Cn(e){if(typeof e!=`string`||!vn.includes(e))throw new G(`Invalid provider status`);return e}function wn(e){if(e===void 0)return[];if(!Array.isArray(e))throw new G(`customModels must be an array`);return e.map(e=>{if(!Dn(e))throw new G(`Each custom model must be an object`);return{id:K(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:K(e.displayName,`customModels.displayName`)}})}function Tn(e){if(typeof e!=`string`||!_n.includes(e))throw new G(`Invalid provider protocol`);return e}function En(e){let t=K(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new G(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function K(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new G(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new G(`${t} is required`);return r}function Dn(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 On(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(kn(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 An(i)}function kn(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function An(e){if(!Mn(e)||!Array.isArray(e.data))throw new q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Mn(e)||typeof e.id!=`string`||e.id.length===0)throw new q(`Provider returned an invalid model entry`);let t=jn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function jn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Nn=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Pn=class{storage;constructor(e){this.storage=e}list(e=/* @__PURE__ */ new Set){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(t=>({...Fn(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Fn(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 Nn;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??y(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Fn(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new yn;let r=this.storage.get(`providers`,e);if(!r)throw new Nn;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Fn(a)})}};function Fn(e){return{...e,avatar:e.avatar??null,status:e.status}}function In(e,t=()=>{}){let n=new w;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 J(t,e)}}),n.post(`/models`,async t=>{try{let n=Sn(await Ln(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return J(t,e)}}),n.post(`/`,async n=>{try{let r=bn(await Ln(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return J(n,e)}}),n.put(`/:id`,async n=>{try{let r=bn(await Ln(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return J(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Ln(n),i=Cn(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 J(n,e)}}),n}async function Ln(e){try{return await e.req.json()}catch{throw new G(`Request body must be valid JSON`)}}function J(e,t){if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Nn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof yn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},502);throw t}function Rn(e){let t=j(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))zn(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function zn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Bn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Pn(e)}list(){return this.repository.list(Rn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Nn;return On(t)}fetchModelsForConnection(e){return On(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Rn(this.storage)))}};function Vn(e,t=()=>{},n=new lt){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Ue(await Hn(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Un(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=$e(await Hn(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Un(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Hn(e){try{return await e.req.json()}catch{throw new D(`Request body must be valid JSON`)}}function Un(e,t){if(t instanceof D||t instanceof et)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof N)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}var Wn=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function Gn(e){let t=new w;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return Kn(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return Kn(t,e)}}),t}function Kn(e,t){if(t instanceof Wn)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function qn(){let e=r.env.CLAUDE_CONFIG_DIR?.trim();return e?v.resolve(e):v.join(re.homedir(),`.claude`)}const Jn=1048576;async function Yn(e){let t;try{t=await ve(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let r of t){let t=v.join(e,r.name);if(r.isDirectory()){let e=await Yn(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else r.isFile()&&/\.jsonl(?:\.zst)?$/u.test(r.name)&&n.files.push(t)}let r=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!r.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function Xn(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Y(r)?t(r):n=!0},i=async e=>{let t=new Oe(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
4
4
|
`,e);for(;a!==-1;)r(n.slice(e,a)),e=a+1,a=n.indexOf(`
|
|
5
5
|
`,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await C(s(e,{highWaterMark:Jn}),ke({chunkSize:Jn}),i):await C(s(e,{highWaterMark:Jn}),i),{hasMalformedLines:n}}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e){return typeof e==`string`?e:``}function Zn(e){let t=Date.parse(X(e));return Number.isFinite(t)?t:null}function Qn(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function $n(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Y).filter(e=>[`text`,`input_text`,`output_text`].includes(X(e.type))).map(e=>X(e.text)).join(`
|