@dhzh/foundry 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -119,12 +119,12 @@ Foundry keeps user data outside the repository in `<home>/.foundry`. `<home>` is
119
119
  `~` on macOS/Linux and `%USERPROFILE%` on Windows:
120
120
 
121
121
  - `settings.json`: application settings
122
- - `providers/<record-key>.json`: providers and credentials
122
+ - `providers.json`: an array of providers, credentials, and optional base64 avatars
123
123
  - `captures/<record-key>.json`: captures
124
124
  - `fetch-jobs/<record-key>.json`: fetch jobs, configuration snapshots and responses
125
125
  - `.data-transfer/`: temporary export and import files
126
126
 
127
- Record filenames use a SHA-256 key of the record ID for portable, collision-safe
127
+ Capture and fetch-job filenames use a SHA-256 key of the record ID for portable, collision-safe
128
128
  paths; the original ID is preserved inside each document.
129
129
 
130
130
  Feature commands initialize JSON storage before running. `foundry web` does the
@@ -138,6 +138,9 @@ A new installation starts directly with default JSON settings and empty
138
138
  collections directly under `.foundry`, without a `data/` subdirectory. Startup
139
139
  does not inspect or import old SQLite databases. Unrelated files are left alone.
140
140
  Node's built-in SQLite reader is used only by the read-only Codex session view.
141
+ Existing `providers/` records are automatically migrated into `providers.json`
142
+ under the process lock using the recovery journal. Provider avatars accept PNG,
143
+ JPEG, GIF, WebP, or SVG images up to 2 MB; clearing an avatar restores the default icon.
141
144
 
142
145
  Encrypted exports and imports use JSON snapshots in `data/foundry.json`.
143
146
  SQLite-based backup archives are not supported.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import{defineCommand as t,runMain as n,showUsage as r}from"citty";import{setTimeout as i}from"node:timers/promises";import{chmod as a,copyFile as o,cp as s,link as c,mkdir as l,open as u,readFile as d,rename as f,rm as p,stat as m,writeFile as ee}from"node:fs/promises";import h from"node:process";import{createCipheriv as te,createDecipheriv as ne,createHash as re,randomBytes as ie,randomUUID as g,scrypt as ae}from"node:crypto";import{FirecrawlClient as oe}from"firecrawl";import{parse as se}from"tldts";import{chmodSync as ce,closeSync as le,createReadStream as ue,createWriteStream as de,existsSync as _,fsyncSync as fe,lstatSync as pe,mkdirSync as me,openSync as he,readFileSync as v,readSync as ge,readdirSync as _e,renameSync as ve,rmSync as y,statSync as b,writeFileSync as ye}from"node:fs";import x from"node:path";import{pipeline as S}from"node:stream/promises";import be from"yauzl";import xe from"yazl";import{Buffer as C}from"node:buffer";import{Readable as Se,Transform as Ce}from"node:stream";import{matchedRoutes as we}from"hono/route";import{spawn as Te}from"node:child_process";import Ee,{homedir as De}from"node:os";import{fileURLToPath as Oe}from"node:url";import{StringDecoder as ke}from"node:string_decoder";import{serve as Ae}from"@hono/node-server";import{serveStatic as je}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{streamSSE as Me}from"hono/streaming";import{createServer as Ne}from"node:net";var Pe=`6.0.0`;function Fe(e){if(!ze(e)||typeof e.url!=`string`)throw new Re(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Ie(e){return e===`no-successful`?`no-successful`:`all`}function Le(e){if(!ze(e)||typeof e.userNote!=`string`)throw new Re(`userNote must be a string`);return e.userNote}var Re=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function ze(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var T=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Be=class{storage;constructor(e){this.storage=e}findCapture(e){let t=this.storage.get(`captures`,e);return t&&!t.deletedAt?t:null}newJob(e,t){let n=(/* @__PURE__ */ new Date()).toISOString();return{id:g(),captureId:e,fetcher:t.fetcher,configSnapshot:t,rawResponse:null,creditsUsed:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}}list(e){return this.storage.all(`captures`).filter(t=>!t.deletedAt&&(e!==`no-successful`||!t.latestSuccessfulJobId)).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Ve(e))}counts(){let e=this.storage.all(`captures`).filter(e=>!e.deletedAt);return{all:e.length,noSuccessful:e.filter(e=>!e.latestSuccessfulJobId).length}}get(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.storage.get(`fetchJobs`,t.latestSuccessfulJobId):void 0;return{capture:Ve(t),rawResponse:n?.captureId===e&&!n.deletedAt?n.rawResponse:null}})}findActiveByURL(e){return this.storage.all(`captures`).find(t=>t.url===e&&!t.deletedAt)??null}createWithJob(e,t,n){return this.storage.transaction(()=>{if(this.findActiveByURL(e))throw new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:g(),url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null},a=this.newJob(i.id,n);return this.storage.put(`captures`,i),this.storage.put(`fetchJobs`,a),{capture:Ve(i),jobId:a.id}})}hasActiveJob(e){return this.storage.all(`fetchJobs`).some(t=>t.captureId===e&&!t.deletedAt&&[`pending`,`running`].includes(t.status))}createJob(e,t){return this.storage.transaction(()=>{if(!this.findCapture(e))throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:He(n),jobId:n.id}})}delete(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return!1;if(this.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`captures`,{...t,deletedAt:n,updatedAt:n});for(let t of this.storage.all(`fetchJobs`))t.captureId===e&&!t.deletedAt&&this.storage.put(`fetchJobs`,{...t,deletedAt:n,updatedAt:n});return!0})}updateNote(e,t){return this.storage.transaction(()=>{let n=this.findCapture(e);if(!n)return null;let r={...n,userNote:t.trim()||null,updatedAt:(/* @__PURE__ */ new Date()).toISOString()};return this.storage.put(`captures`,r),Ve(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>He(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?He(n.job):null}getJobContext(e){return this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);if(!t||t.deletedAt)return null;let n=this.findCapture(t.captureId);return n?{job:t,capture:n}:null})}markRunning(e){this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);t?.status===`pending`&&this.storage.put(`fetchJobs`,{...t,status:`running`,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}markSucceeded(e,t,n,r,i){this.storage.transaction(()=>{let a=this.storage.get(`fetchJobs`,e),o=this.findCapture(t);if(!a||!o||a.captureId!==t)throw Error(`Invalid capture job`);let s=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`fetchJobs`,{...a,status:`succeeded`,rawResponse:r,creditsUsed:i,errorCode:null,errorMessage:null,updatedAt:s}),this.storage.put(`captures`,{...o,...n&&{title:n},latestSuccessfulJobId:e,updatedAt:s})})}markFailed(e,t,n){this.storage.transaction(()=>{let r=this.storage.get(`fetchJobs`,e);r&&this.storage.put(`fetchJobs`,{...r,status:`failed`,creditsUsed:null,errorCode:t,errorMessage:n,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}recoverRunningJobs(){return this.storage.transaction(()=>{let e=this.storage.all(`fetchJobs`).filter(e=>e.status===`running`&&!e.deletedAt);for(let t of e)this.storage.put(`fetchJobs`,{...t,status:`pending`});return e.length})}pendingJobIDs(){return this.storage.all(`fetchJobs`).filter(e=>e.status===`pending`&&!e.deletedAt).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)).map(e=>e.id)}};function Ve(e){let{deletedAt:t,...n}=e;return n}function He(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,creditsUsed:e.creditsUsed,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt,updatedAt:e.updatedAt}}const Ue=[`system`,`light`,`dark`],We=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ge=[`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`],Ke=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],qe=[`firecrawl`],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 Je(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{},a=O(t.features)?t.features:{},o=O(a.library)?a.library:{},s=O(o.captures)?o.captures:{},c=O(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":tt(r[`color-theme`],Ue,E.workspace.appearance[`color-theme`])},"language-region":{language:tt(i.language,We,E.workspace[`language-region`].language),"time-format":tt(i[`time-format`],Ge,E.workspace[`language-region`][`time-format`]),"time-zone":tt(i[`time-zone`],Ke,E.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:$e(s.fetcher),maxAttempts:rt(s.maxAttempts,10,1),fetchConcurrency:rt(s.fetchConcurrency,5,2),firecrawl:{apiKey:ot(c.apiKey)}}}}}}function Ye(e){if(!O(e))throw new D(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=nt(e.theme,Ue,`theme`)),`language`in e&&(t.language=nt(e.language,We,`language`)),`timeFormat`in e&&(t.timeFormat=nt(e.timeFormat,Ge,`timeFormat`)),`timezone`in e&&(t.timezone=nt(e.timezone,Ke,`timezone`)),`captures`in e&&(t.captures=Qe(e.captures)),t}function Xe(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 Ze(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 Qe(e){if(!O(e))throw new D(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:nt(e.fetcher,qe,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=it(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=it(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=at(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function $e(e){return et(e,qe)}function et(e,t){return typeof e==`string`&&t.includes(e)?e:null}function tt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function nt(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new D(`Invalid ${n}`);return e}function rt(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function it(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 at(e,t){if(typeof e!=`string`)throw new D(`${t} must be a string`);return e.trim()}function ot(e){return typeof e==`string`?e:``}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function st(e){return e.readSettings()}function ct(e){return Ze(st(e))}function lt(e,t){return t.transaction(()=>{let n=Xe(st(t),e);return t.setSettings(n),Ze(n)})}var k=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function ut(e){if(e instanceof k)return e;let t=dt(e);return t===null?mt(e)?new k(`timeout`,`The configured fetcher timed out`):ht(e)?new k(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new k(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new k(`http_${t}`,ft(e)??`The configured fetcher returned ${t}`,t)}function dt(e){if(!A(e))return null;let t=gt(e.status);return t===null?A(e.response)?gt(e.response.status):null:t}function ft(e){if(!A(e))return null;if(A(e.response)){let t=pt(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:pt(e.details)}function pt(e){return A(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function mt(e){if(!(e instanceof Error))return!1;let t=_t(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function ht(e){if(e instanceof TypeError)return!0;if(!A(e))return!1;let t=_t(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!A(e.response)}function gt(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function _t(e){let t=e.code;return typeof t==`string`?t:null}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var vt=class extends oe{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function yt(e,t,n={}){let r=new vt({apiKey:e,maxRetries:Math.max(1,Math.trunc(t)),...n.apiUrl&&{apiUrl:n.apiUrl},...n.backoffFactor!==void 0&&{backoffFactor:n.backoffFactor}});return{search:e=>r.searchEnvelope(e)}}async function bt(e,t,n=1,r=yt(t,n)){try{let t=xt(e),n=await r.search(St(t));if(!j(n))throw new k(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new k(`fetcher_error`,Rt(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new k(`invalid_response`,`The configured fetcher returned an invalid response`);let i=Lt(n);if(i===null)throw new k(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=At(e,kt(n));return{title:a?Ft(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw ut(e)}}function xt(e){return{query:Ct(e),limit:5,sources:[`web`],highlights:!1,ignoreInvalidURLs:!0,timeout:12e4,pageOptions:{formats:[`summary`],onlyMainContent:!0,onlyCleanContent:!1,maxAge:1728e5,timeout:6e4,removeBase64Images:!0,blockAds:!0,proxy:`auto`,storeInCache:!0}}}function St(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function Ct(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=wt(t.pathname),i=Ot(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function wt(e){let t=e.split(`/`).map(e=>Tt(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||Dt(n))continue;let r=Et(n);if(r)return r}return null}function Tt(e){try{return decodeURIComponent(e)}catch{return e}}function Et(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function Dt(e){return/^(?:index|home|latest)$/i.test(e)||/^\d+$/.test(e)||/^v?\d+(?:\.\d+)+$/i.test(e)||/^[a-z]{2}(?:[-_][a-z]{2})?$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(e)||/^[0-9a-f]{20,}$/i.test(e)}function Ot(e){return se(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function kt(e){return!j(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!j(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:j(e.metadata)?e.metadata:{}}])}function At(e,t){let n=Mt(e);if(n){let e=t.find(e=>jt(e).some(e=>Mt(e)===n));if(e)return e}let r=Nt(e),i=r===null?[]:t.filter(e=>jt(e).some(e=>Nt(e)===r));return i.find(e=>Pt(e))??(i.length>0?i[0]:null)}function jt(e){return[e.url,It(e,`sourceURL`),It(e,`url`)].filter(e=>!!e)}function Mt(e){try{let t=new URL(e);return t.hash=``,t.searchParams.sort(),t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)),t.href}catch{return null}}function Nt(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function Pt(e){return jt(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function Ft(e){return e.title?.trim()||It(e,`ogTitle`)?.trim()||It(e,`title`)?.trim()||null}function It(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function Lt(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function Rt(e){return j(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zt(e,t){return bt(e,t.apiKey,t.maxAttempts)}var Bt=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{},r=zt){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){if(this.paused)return;let e=st(this.storage).features.library.captures.fetchConcurrency;for(;this.runningCount<e&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.runningCount+=1,this.runJob(e).finally(()=>{--this.runningCount,this.knownJobIDs.delete(e),this.schedule()})}}async runJob(e){let t=this.repository.getJobContext(e);if(!t||t.job.status!==`pending`&&t.job.status!==`running`)return;let n;try{n=Vt(t.job.configSnapshot)}catch(n){let r=n instanceof Error?n.message:`Invalid fetch job configuration`;this.failJob(e,t.job.captureId,`invalid_config`,r);return}this.repository.markRunning(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`running`});try{let r=await this.fetchCaptureImplementation(t.capture.url,n);this.repository.markSucceeded(e,t.capture.id,r.title,r.rawResponse,r.creditsUsed),this.onChanged({captureId:t.capture.id,jobId:e,status:`succeeded`})}catch(n){let r=ut(n);this.failJob(e,t.capture.id,r.code,r.message)}}failJob(e,t,n,r){this.repository.markFailed(e,n,r),this.onChanged({captureId:t,jobId:e,status:`failed`,errorMessage:r})}start(){this.repository.recoverRunningJobs();for(let e of this.repository.pendingJobIDs())this.enqueue(e)}enqueue(e){if(this.knownJobIDs.has(e))return;let t=this.repository.getJobContext(e);t&&(this.knownJobIDs.add(e),this.queue.push(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`pending`}),this.schedule())}notifySettingsChanged(){this.schedule()}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule()}};function Vt(e){let t=e;if(!Ht(t)||t.fetcher!==`firecrawl`||typeof t.apiKey!=`string`||!t.apiKey||typeof t.maxAttempts!=`number`)throw Error(`Invalid fetch job configuration`);return{fetcher:t.fetcher,apiKey:t.apiKey,maxAttempts:Math.min(10,Math.max(1,Math.trunc(t.maxAttempts)))}}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ut=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=st(this.storage).features.library.captures;if(!e.fetcher)return null;let t=e[e.fetcher].apiKey.trim();return t?{fetcher:e.fetcher,apiKey:t,maxAttempts:e.maxAttempts}:null}list(e){return this.repository.list(e)}counts(){return this.repository.counts()}get(e){let t=this.repository.get(e);if(!t)throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Wt(e.url);if(!t)throw new T(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new T(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before adding a capture`);try{let r=this.repository.createWithJob(t,e.userNote?.trim()||null,n);return this.runner.enqueue(r.jobId),r.capture}catch(e){throw this.repository.findActiveByURL(t)?new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new T(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before re-capturing`);let n=this.repository.createJob(e,t);return this.runner.enqueue(n.jobId),n.job}delete(e){if(this.get(e),this.repository.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}getJob(e,t){return this.get(e),this.repository.getJob(e,t)}};function Wt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Gt(e,t,n){let r=new Be(e),i=new Bt(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new Ut(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const Kt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],qt=[`active`,`disabled`,`deleted`];var M=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Jt=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function Yt(e){if(!tn(e))throw new M(`Provider input must be an object`);return{name:N(e.name,`name`),protocol:$t(e.protocol),baseURL:en(e.baseURL),apiKey:e.apiKey===void 0?``:N(e.apiKey,`apiKey`,{allowEmpty:!0}),customModels:Qt(e.customModels)}}function Xt(e){if(!tn(e))throw new M(`Provider connection must be an object`);return{protocol:$t(e.protocol),baseURL:en(e.baseURL),apiKey:e.apiKey===void 0?``:N(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Zt(e){if(typeof e!=`string`||!qt.includes(e))throw new M(`Invalid provider status`);return e}function Qt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new M(`customModels must be an array`);return e.map(e=>{if(!tn(e))throw new M(`Each custom model must be an object`);return{id:N(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:N(e.displayName,`customModels.displayName`)}})}function $t(e){if(typeof e!=`string`||!Kt.includes(e))throw new M(`Invalid provider protocol`);return e}function en(e){let t=N(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new M(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function N(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new M(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new M(`${t} is required`);return r}function tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function P(e,t){if(!e)throw Error(t)}function rn(e){return e===null||typeof e==`string`}function an(e){P(nn(e)&&e.formatVersion===1,`Unsupported Foundry JSON data format`),P(nn(e.settings),`Invalid settings`),Je(e.settings);for(let t of[`providers`,`captures`,`fetchJobs`]){let n=e[t];P(Array.isArray(n),`Invalid storage collection`);let r=/* @__PURE__ */ new Set;for(let e of n)P(nn(e)&&typeof e.id==`string`&&e.id.length>0&&e.id.length<=200&&!r.has(e.id),`Invalid or duplicate record ID`),r.add(e.id),P(typeof e.createdAt==`string`&&Number.isFinite(Date.parse(e.createdAt))&&typeof e.updatedAt==`string`&&Number.isFinite(Date.parse(e.updatedAt)),`Invalid record timestamp`),P(e.deletedAt===null||typeof e.deletedAt==`string`&&Number.isFinite(Date.parse(e.deletedAt)),`Invalid deletion timestamp`)}let t=e;for(let e of t.providers)try{P([`active`,`disabled`,`deleted`].includes(e.status),`Invalid status`),P(typeof e.apiKey==`string`,`Invalid API key`),Yt(e)}catch{throw Error(`A provider record is invalid`)}let n=/* @__PURE__ */ new Set,r=new Map(t.captures.map(e=>[e.id,e])),i=new Map(t.fetchJobs.map(e=>[e.id,e]));for(let e of t.captures){try{P([`http:`,`https:`].includes(new URL(e.url).protocol),`Invalid protocol`)}catch{throw Error(`A capture URL is invalid`)}if(P(rn(e.title)&&rn(e.userNote)&&rn(e.latestSuccessfulJobId),`A capture record is invalid`),e.deletedAt||(P(!n.has(e.url),`Duplicate active capture URL`),n.add(e.url),!e.latestSuccessfulJobId))continue;let t=i.get(e.latestSuccessfulJobId);P(t?.captureId===e.id&&t.status===`succeeded`&&!t.deletedAt,`A capture points to an invalid successful fetch job`)}let a=/* @__PURE__ */ new Set;for(let e of t.fetchJobs)P(r.has(e.captureId)&&[`pending`,`running`,`succeeded`,`failed`].includes(e.status)&&e.fetcher===`firecrawl`,`A fetch job record is invalid`),P(nn(e.configSnapshot),`A fetch job configuration is invalid`),P(e.creditsUsed===null||typeof e.creditsUsed==`number`&&Number.isFinite(e.creditsUsed),`A fetch job credit value is invalid`),P(rn(e.errorCode)&&rn(e.errorMessage),`A fetch job record is invalid`),!e.deletedAt&&[`pending`,`running`].includes(e.status)&&(P(!a.has(e.captureId),`Duplicate active fetch jobs`),a.add(e.captureId))}var F=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function on(e){return e instanceof F?e:new F(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const I=`data/foundry.json`,sn=`manifest.json`;function cn(e){if(!pn(e)||e.format!==`foundry.snapshot`)throw new F(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=fn(e.archiveVersion,`archiveVersion`);if(t!==3)throw new F(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=dn(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new F(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!pn(e.data)||e.database!==void 0||e.settings!==void 0)throw new F(`INVALID_ARCHIVE`,`JSON data metadata is invalid`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:dn(e.appVersion,`appVersion`),createdAt:n,data:{...un(e.data,I),formatVersion:fn(e.data.formatVersion,`data.formatVersion`)}}}function ln(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function un(e,t){if(!pn(e)||e.path!==t)throw new F(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=dn(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new F(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:fn(e.bytes,`bytes`),sha256:n}}function dn(e,t){if(typeof e!=`string`||e.length===0)throw new F(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function fn(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new F(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const mn=/* @__PURE__ */ new Set([sn,I]);async function hn(e,t){let n=new xe.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await S(n.outputStream,de(t,{mode:384}))}async function gn(e,t){let n=await _n(e),r=/* @__PURE__ */ new Map,i=0;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!mn.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 a=e.fileName===`manifest.json`?1048576:4294967296;if(i+=e.uncompressedSize,e.uncompressedSize>a||i>4294967296)throw Error(`The Foundry archive is too large`);let o=x.join(t,e.fileName);await l(x.dirname(o),{recursive:!0}),await S(await vn(n,e),de(o,{mode:384})),r.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 p(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(`manifest.json`)||!r.has(`data/foundry.json`))throw await p(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function _n(e){return new Promise((t,n)=>{be.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function vn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const L=C.from(`FOUNDRYX`,`ascii`),R=`aes-256-gcm`,yn=`scrypt`,z={N:131072,r:8,p:1};async function bn(e,t,n){let r=ie(16),i=ie(12),o={version:1,cipher:R,kdf:{name:yn,salt:r.toString(`base64`),...z,keyLength:32},nonce:i.toString(`base64`)},s=C.from(JSON.stringify(o),`utf8`),c=Sn(s.byteLength),l=C.concat([c,s]),d=await Cn(n,r,z);try{let n=await u(t,`w`,384);try{await n.write(l)}finally{await n.close()}await S(ue(e),wn(d,i,l),de(t,{flags:`r+`,mode:384,start:l.byteLength})),await a(t,384)}catch(e){throw await p(t,{force:!0}),new F(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function xn(e,t,n){let r;try{let i=(await m(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let o=await u(e,`r`),s,c,l;try{if(s=await Dn(o,13,0),!s.subarray(0,L.byteLength).equals(L))throw Error(`The export file signature is invalid`);if(s.readUInt8(L.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(L.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`);c=await Dn(o,e,13),l=await Dn(o,16,i-16)}finally{await o.close()}let d=En(JSON.parse(c.toString(`utf8`)));r=await Cn(n,d.salt,d.header.kdf);let f=C.concat([s,c]);await S(ue(e,{start:13+c.byteLength,end:i-16-1}),Tn(r,d.nonce,f,l),de(t,{mode:384})),await a(t,384)}catch(e){throw await p(t,{force:!0}),e instanceof F?e:new F(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function Sn(e){let t=C.alloc(13);return L.copy(t,0),t.writeUInt8(1,L.byteLength),t.writeUInt32BE(e,L.byteLength+1),t}function Cn(e,t,n){return new Promise((r,i)=>{ae(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function wn(e,t,n){let r=te(R,e,t,{authTagLength:16});return r.setAAD(n),new Ce({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,C.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Tn(e,t,n,r){let i=ne(R,e,t,{authTagLength:16});return i.setAAD(n),new Ce({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 En(e){if(!On(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==R||!On(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==yn||typeof t.salt!=`string`||t.N!==z.N||t.r!==z.r||t.p!==z.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=C.from(t.salt,`base64`),r=C.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:R,kdf:{name:yn,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Dn(e,t,n){let r=C.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function On(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var kn=class{storage;runner;temporaryRoot;appVersion;workspaceMutationGate;onStatusChanged;busy=!1;stagedImports=/* @__PURE__ */ new Map;constructor(e,t,n,r,i,a=()=>{}){this.storage=e,this.runner=t,this.temporaryRoot=n,this.appVersion=r,this.workspaceMutationGate=i,this.onStatusChanged=a}async runExclusive(e){if(this.busy||!this.workspaceMutationGate.tryBeginTransfer())throw new F(`BUSY`,`Another data transfer is in progress`);this.busy=!0;try{return this.onStatusChanged(this.getStatus()),await e()}finally{this.busy=!1,this.workspaceMutationGate.endTransfer(),this.onStatusChanged(this.getStatus())}}async createWorkDirectory(e){await l(this.temporaryRoot,{recursive:!0,mode:448}),await Fn(this.temporaryRoot);let t=x.join(this.temporaryRoot,`${e}-${g()}`);return await l(t,{mode:448}),await Fn(t),t}async removeQuietly(e){try{await p(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:x.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){y(this.temporaryRoot,{recursive:!0,force:!0}),me(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:this.storage.all(`fetchJobs`).filter(e=>jn(e)).length,isBusy:this.busy}}async createExport(e){return An(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=x.join(t,`foundry.json`),r=x.join(t,sn),i=x.join(t,`foundry.zip`),a=x.join(this.temporaryRoot,`foundry-${g()}.foundry-backup`);this.runner.pause();try{let t=this.storage.snapshot();B(t),an(t),await ee(n,JSON.stringify(t),{mode:384});let o={format:`foundry.snapshot`,archiveVersion:3,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),data:{...await Nn(n,I),formatVersion:1}};return await ee(r,JSON.stringify(o,null,2),{mode:384}),await hn([{entryPath:sn,filePath:r},{entryPath:I,filePath:n}],i),await bn(i,a,e),{filePath:a,...Mn(t)}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=x.basename(e)){return An(t),this.runExclusive(async()=>{B(this.storage.snapshot());let r=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(r.map(e=>this.removeQuietly(e.directory)));let i=g(),a=await this.createWorkDirectory(`import-${i}`),o=x.join(a,`archive.zip`);try{await xn(e,o,t);let r=await gn(o,x.join(a,`extracted`)),s=cn(JSON.parse(await d(r[sn],`utf8`)));if(s.data.formatVersion>1)throw new F(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let c=/* @__PURE__ */ new Set([sn,I]);await Pn(r[I],s.data);let l=JSON.parse(await d(r[I],`utf8`));if(an(l),l.formatVersion!==s.data.formatVersion)throw new F(`INVALID_ARCHIVE`,`The JSON data format does not match its manifest`);if(Object.keys(r).some(e=>!c.has(e)))throw new F(`INVALID_ARCHIVE`,`Unexpected archive file`);B(l);let u=x.join(a,`staged.json`);await ee(u,JSON.stringify(l),{mode:384});let f={importId:i,fileName:x.basename(n),exportedAt:s.createdAt,appVersion:s.appVersion,dataFormatVersion:l.formatVersion,settingsVersion:1,...Mn(l)};return this.stagedImports.set(i,{snapshotPath:u,directory:a,preview:f}),await p(o,{force:!0}),f}catch(e){throw await this.removeQuietly(a),e instanceof F?e:new F(`INVALID_ARCHIVE`,e instanceof Error?e.message:`The Foundry export could not be inspected`,{cause:e})}})}async cancelImport(e){let t=this.stagedImports.get(e);t&&(this.stagedImports.delete(e),await this.removeQuietly(t.directory))}async commitImport(e){let t=this.stagedImports.get(e);if(!t)throw new F(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();try{let n=JSON.parse(await d(t.snapshotPath,`utf8`));an(n),B(n),this.storage.transaction(()=>{B(this.storage.snapshot()),this.storage.replace(n)}),this.stagedImports.delete(e),await this.removeQuietly(t.directory)}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){x.dirname(e)===this.temporaryRoot&&await p(e,{force:!0})}};function An(e){if(!e)throw new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function jn(e){return!e.deletedAt&&[`pending`,`running`].includes(e.status)}function B(e){if(e.fetchJobs.some(e=>jn(e)))throw new F(`ACTIVE_JOBS`,`Finish active fetch jobs before transferring data`)}function Mn(e){return{providerCount:e.providers.length,captureCount:e.captures.length,jobCount:e.fetchJobs.length}}async function Nn(e,t){let n=re(`sha256`);for await(let t of ue(e))n.update(t);return{path:t,bytes:(await m(e)).size,sha256:n.digest(`hex`)}}async function Pn(e,t){let n=await Nn(e,t.path);if(n.bytes!==t.bytes||n.sha256!==t.sha256)throw new F(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function Fn(e){return h.platform===`win32`?Promise.resolve():a(e,448)}const In=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var Ln=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function Rn(e){return async(t,n)=>{if(e.isTransferActive&&In.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&zn(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function zn(e){return we(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var V=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Bn(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(Vn(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new V(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new V(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new V(`Provider returned invalid JSON`)}return Hn(i)}function Vn(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Hn(e){if(!Wn(e)||!Array.isArray(e.data))throw new V(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Wn(e)||typeof e.id!=`string`||e.id.length===0)throw new V(`Provider returned an invalid model entry`);let t=Un(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Un(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Wn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var H=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Gn=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=>({...Kn(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Kn(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 H;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??g(),status:`active`,createdAt:r,deletedAt:null,...n,...e,updatedAt:r};return this.storage.put(`providers`,i),Kn(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Jt;let r=this.storage.get(`providers`,e);if(!r)throw new H;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Kn(a)})}};function Kn(e){return{...e,status:e.status}}function qn(e){let t=st(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Jn(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Jn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Yn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Gn(e)}list(){return this.repository.list(qn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new H;return Bn(t)}fetchModelsForConnection(e){return Bn(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,qn(this.storage)))}};function Xn(e){let t=h.platform===`darwin`?`open`:h.platform===`win32`?`explorer`:`xdg-open`,n=Te(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Zn(){return x.join(Ee.homedir(),`.foundry`)}function Qn(){let e=Zn();return me(e,{recursive:!0,mode:448}),h.platform!==`win32`&&ce(e,448),e}function $n(){return x.join(Zn(),`.data-transfer`)}var er=class{storage;configFolder;openFolder;constructor(e,t=Zn(),n=Xn){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...ct(this.storage),configFolder:this.configFolder}}update(e){return{...lt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const tr=x.dirname(Oe(import.meta.url)),U=`foundry`;var nr=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=De()}={}){this.configuredSkillRoot=e,this.homeDirectory=x.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??rr();if(!_(x.join(t,`SKILL.md`)))throw new W(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=x.join(n,U),i=x.join(n,`.${U}-${g()}.tmp`),a=x.join(n,`.${U}-${g()}.backup`);try{return await l(n,{recursive:!0}),await s(t,i,{recursive:!0,errorOnExist:!0}),await ir(i,r,a),{target:e,destination:r}}catch(e){throw await p(i,{recursive:!0,force:!0}),e instanceof W?e:new W(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return x.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:x.join(this.getTargetParent(e),U)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},W=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function rr(){let e=[x.resolve(tr,`skills`,U),x.resolve(tr,`..`,`..`,`..`,`skills`,U),x.resolve(h.cwd(),`skills`,U)].find(e=>_(x.join(e,`SKILL.md`)));if(!e)throw new W(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function ir(e,t,n){let r=_(t);r&&await f(t,n);try{await f(e,t),r&&await p(n,{recursive:!0,force:!0})}catch(e){throw r&&!_(t)&&_(n)&&await f(n,t),e}}function ar(){let e=h.env.CLAUDE_CONFIG_DIR?.trim();return e?x.resolve(e):x.join(Ee.homedir(),`.claude`)}var G=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};const or=`.jsonl`;function sr(e){let t=x.join(e,`projects`);if(!_(t))throw new G(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n;try{n=_e(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>x.join(t,e.name))}catch(e){throw new G(`CLAUDE_READ_FAILED`,e instanceof Error?e.message:`Unable to read Claude Code sessions`)}let r=[],i=/* @__PURE__ */ new Set;for(let e of n){let n=cr(e);for(let a of n.entries){let o=ur(t,e,a);if(!o||i.has(o))continue;let s=fr(o,a,n.originalPath);i.add(o),s&&r.push(s)}for(let t of dr(e)){if(i.has(t))continue;let e=fr(t,null,n.originalPath);i.add(t),e&&r.push(e)}}return{sessions:r}}function cr(e){let t=x.join(e,`sessions-index.json`);if(!_(t))return{originalPath:null,entries:[]};let n;try{n=JSON.parse(v(t,`utf8`))}catch{return{originalPath:null,entries:[]}}if(!K(n)||!Array.isArray(n.entries))return{originalPath:null,entries:[]};let r=[];for(let e of n.entries){let t=lr(e);t&&r.push(t)}return{originalPath:q(n.originalPath),entries:r}}function lr(e){if(!K(e))return null;let t=xr(e.sessionId);return vr(t)?{sessionId:t,filePath:q(e.fullPath),firstPrompt:q(e.firstPrompt),summary:q(e.summary),gitBranch:q(e.gitBranch),projectPath:q(e.projectPath),isSidechain:e.isSidechain===!0,createdAtMs:Cr(e.created)??Sr(e.fileMtime),updatedAtMs:Cr(e.modified)??Sr(e.fileMtime)}:null}function ur(e,t,n){let r=x.join(t,`${n.sessionId}${or}`);return _r(r)?r:n.filePath&&x.isAbsolute(n.filePath)&&yr(e,n.filePath)&&_r(n.filePath)?n.filePath:null}function dr(e){let t;try{t=_e(e,{withFileTypes:!0})}catch{return[]}return t.filter(e=>e.isFile()&&e.name.endsWith(or)).map(t=>x.join(e,t.name))}function fr(e,t,n){let r;try{r=b(e)}catch{return null}let i;try{i=pr(e)}catch{return null}let a=t?.sessionId??x.basename(e,or),o=br([t?.projectPath,n,i.cwd]),s=t?.createdAtMs??i.createdAtMs??r.mtimeMs,c=t?.updatedAtMs??i.updatedAtMs??r.mtimeMs;return{id:a,title:br([i.customTitle,t?.summary,i.firstPrompt,t?.firstPrompt,i.lastPrompt,a.slice(0,8)]),projectPath:o,createdAtMs:s,updatedAtMs:Math.max(s,c),sizeBytes:r.size,tokensUsed:i.tokensUsed,model:i.model,cwd:br([i.cwd,o]),gitBranch:br([i.gitBranch,t?.gitBranch])||null,subagent:t?.isSidechain===!0||i.isSidechain}}function pr(e){let t=``,n=null,r=null,i=null,a=null,o=null,s=0,c=null,l=null,u=!1;return mr(e,e=>{if(!e.trim())return;let d;try{d=JSON.parse(e)}catch{return}if(!K(d))return;let f=Cr(d.timestamp);f!==null&&(c=c===null?f:Math.min(c,f),l=l===null?f:Math.max(l,f)),t||=xr(d.cwd),d.isSidechain===!0&&(u=!0),d.type===`custom-title`?i=q(d.customTitle)??i:d.type===`last-prompt`&&(a=q(d.lastPrompt)??a);let p=K(d.message)?d.message:null;if(!p||(d.type===`user`&&d.isMeta!==!0&&p.role===`user`&&(r||=q(hr(p.content))),d.type!==`assistant`||p.role!==`assistant`))return;n=q(d.gitBranch)??n;let m=q(p.model);m&&m!==`<synthetic>`&&(o=m),s+=gr(p.usage)}),{cwd:t,gitBranch:n,firstPrompt:r,customTitle:i,lastPrompt:a,model:o,tokensUsed:s,createdAtMs:c,updatedAtMs:l,isSidechain:u}}function mr(e,t){let n=he(e,`r`),r=new ke(`utf8`),i=C.allocUnsafe(262144),a=``;try{let e=ge(n,i,0,i.length,null);for(;e>0;){a+=r.write(i.subarray(0,e));let o=0,s=a.indexOf(`
2
+ import{createRequire as e}from"node:module";import{defineCommand as t,runMain as n,showUsage as r}from"citty";import{setTimeout as i}from"node:timers/promises";import{chmod as a,copyFile as o,cp as s,link as c,mkdir as l,open as u,readFile as d,rename as f,rm as p,stat as ee,writeFile as te}from"node:fs/promises";import m from"node:process";import{createCipheriv as ne,createDecipheriv as re,createHash as ie,randomBytes as ae,randomUUID as h,scrypt as oe}from"node:crypto";import{FirecrawlClient as se}from"firecrawl";import{parse as ce}from"tldts";import{chmodSync as le,closeSync as ue,createReadStream as de,createWriteStream as g,existsSync as _,fsyncSync as fe,lstatSync as pe,mkdirSync as me,openSync as he,readFileSync as v,readSync as ge,readdirSync as y,renameSync as _e,rmSync as b,rmdirSync as ve,statSync as x,writeFileSync as ye}from"node:fs";import S from"node:path";import{pipeline as be}from"node:stream/promises";import xe from"yauzl";import Se from"yazl";import{Buffer as C}from"node:buffer";import{Readable as Ce,Transform as we}from"node:stream";import{matchedRoutes as Te}from"hono/route";import{spawn as Ee}from"node:child_process";import De,{homedir as Oe}from"node:os";import{fileURLToPath as ke}from"node:url";import{StringDecoder as Ae}from"node:string_decoder";import{serve as je}from"@hono/node-server";import{serveStatic as Me}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{streamSSE as Ne}from"hono/streaming";import{createServer as Pe}from"node:net";var Fe=`6.1.0`;function Ie(e){if(!Be(e)||typeof e.url!=`string`)throw new ze(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Le(e){return e===`no-successful`?`no-successful`:`all`}function Re(e){if(!Be(e)||typeof e.userNote!=`string`)throw new ze(`userNote must be a string`);return e.userNote}var ze=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Be(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var T=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Ve=class{storage;constructor(e){this.storage=e}findCapture(e){let t=this.storage.get(`captures`,e);return t&&!t.deletedAt?t:null}newJob(e,t){let n=(/* @__PURE__ */ new Date()).toISOString();return{id:h(),captureId:e,fetcher:t.fetcher,configSnapshot:t,rawResponse:null,creditsUsed:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}}list(e){return this.storage.all(`captures`).filter(t=>!t.deletedAt&&(e!==`no-successful`||!t.latestSuccessfulJobId)).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>He(e))}counts(){let e=this.storage.all(`captures`).filter(e=>!e.deletedAt);return{all:e.length,noSuccessful:e.filter(e=>!e.latestSuccessfulJobId).length}}get(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.storage.get(`fetchJobs`,t.latestSuccessfulJobId):void 0;return{capture:He(t),rawResponse:n?.captureId===e&&!n.deletedAt?n.rawResponse:null}})}findActiveByURL(e){return this.storage.all(`captures`).find(t=>t.url===e&&!t.deletedAt)??null}createWithJob(e,t,n){return this.storage.transaction(()=>{if(this.findActiveByURL(e))throw new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:h(),url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null},a=this.newJob(i.id,n);return this.storage.put(`captures`,i),this.storage.put(`fetchJobs`,a),{capture:He(i),jobId:a.id}})}hasActiveJob(e){return this.storage.all(`fetchJobs`).some(t=>t.captureId===e&&!t.deletedAt&&[`pending`,`running`].includes(t.status))}createJob(e,t){return this.storage.transaction(()=>{if(!this.findCapture(e))throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Ue(n),jobId:n.id}})}delete(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return!1;if(this.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`captures`,{...t,deletedAt:n,updatedAt:n});for(let t of this.storage.all(`fetchJobs`))t.captureId===e&&!t.deletedAt&&this.storage.put(`fetchJobs`,{...t,deletedAt:n,updatedAt:n});return!0})}updateNote(e,t){return this.storage.transaction(()=>{let n=this.findCapture(e);if(!n)return null;let r={...n,userNote:t.trim()||null,updatedAt:(/* @__PURE__ */ new Date()).toISOString()};return this.storage.put(`captures`,r),He(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt.localeCompare(e.createdAt)).map(e=>Ue(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Ue(n.job):null}getJobContext(e){return this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);if(!t||t.deletedAt)return null;let n=this.findCapture(t.captureId);return n?{job:t,capture:n}:null})}markRunning(e){this.storage.transaction(()=>{let t=this.storage.get(`fetchJobs`,e);t?.status===`pending`&&this.storage.put(`fetchJobs`,{...t,status:`running`,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}markSucceeded(e,t,n,r,i){this.storage.transaction(()=>{let a=this.storage.get(`fetchJobs`,e),o=this.findCapture(t);if(!a||!o||a.captureId!==t)throw Error(`Invalid capture job`);let s=(/* @__PURE__ */ new Date()).toISOString();this.storage.put(`fetchJobs`,{...a,status:`succeeded`,rawResponse:r,creditsUsed:i,errorCode:null,errorMessage:null,updatedAt:s}),this.storage.put(`captures`,{...o,...n&&{title:n},latestSuccessfulJobId:e,updatedAt:s})})}markFailed(e,t,n){this.storage.transaction(()=>{let r=this.storage.get(`fetchJobs`,e);r&&this.storage.put(`fetchJobs`,{...r,status:`failed`,creditsUsed:null,errorCode:t,errorMessage:n,updatedAt:(/* @__PURE__ */ new Date()).toISOString()})})}recoverRunningJobs(){return this.storage.transaction(()=>{let e=this.storage.all(`fetchJobs`).filter(e=>e.status===`running`&&!e.deletedAt);for(let t of e)this.storage.put(`fetchJobs`,{...t,status:`pending`});return e.length})}pendingJobIDs(){return this.storage.all(`fetchJobs`).filter(e=>e.status===`pending`&&!e.deletedAt).toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt)).map(e=>e.id)}};function He(e){let{deletedAt:t,...n}=e;return n}function Ue(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,creditsUsed:e.creditsUsed,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt,updatedAt:e.updatedAt}}const We=[`system`,`light`,`dark`],Ge=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ke=[`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`],qe=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Je=[`firecrawl`],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 Ye(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{},a=O(t.features)?t.features:{},o=O(a.library)?a.library:{},s=O(o.captures)?o.captures:{},c=O(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":nt(r[`color-theme`],We,E.workspace.appearance[`color-theme`])},"language-region":{language:nt(i.language,Ge,E.workspace[`language-region`].language),"time-format":nt(i[`time-format`],Ke,E.workspace[`language-region`][`time-format`]),"time-zone":nt(i[`time-zone`],qe,E.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:et(s.fetcher),maxAttempts:it(s.maxAttempts,10,1),fetchConcurrency:it(s.fetchConcurrency,5,2),firecrawl:{apiKey:st(c.apiKey)}}}}}}function Xe(e){if(!O(e))throw new D(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=rt(e.theme,We,`theme`)),`language`in e&&(t.language=rt(e.language,Ge,`language`)),`timeFormat`in e&&(t.timeFormat=rt(e.timeFormat,Ke,`timeFormat`)),`timezone`in e&&(t.timezone=rt(e.timezone,qe,`timezone`)),`captures`in e&&(t.captures=$e(e.captures)),t}function Ze(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 Qe(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 $e(e){if(!O(e))throw new D(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:rt(e.fetcher,Je,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=at(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=at(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=ot(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function et(e){return tt(e,Je)}function tt(e,t){return typeof e==`string`&&t.includes(e)?e:null}function nt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function rt(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new D(`Invalid ${n}`);return e}function it(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function at(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 ot(e,t){if(typeof e!=`string`)throw new D(`${t} must be a string`);return e.trim()}function st(e){return typeof e==`string`?e:``}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ct(e){return e.readSettings()}function lt(e){return Qe(ct(e))}function ut(e,t){return t.transaction(()=>{let n=Ze(ct(t),e);return t.setSettings(n),Qe(n)})}var k=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function dt(e){if(e instanceof k)return e;let t=ft(e);return t===null?ht(e)?new k(`timeout`,`The configured fetcher timed out`):gt(e)?new k(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new k(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new k(`http_${t}`,pt(e)??`The configured fetcher returned ${t}`,t)}function ft(e){if(!A(e))return null;let t=_t(e.status);return t===null?A(e.response)?_t(e.response.status):null:t}function pt(e){if(!A(e))return null;if(A(e.response)){let t=mt(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:mt(e.details)}function mt(e){return A(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function ht(e){if(!(e instanceof Error))return!1;let t=vt(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function gt(e){if(e instanceof TypeError)return!0;if(!A(e))return!1;let t=vt(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!A(e.response)}function _t(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function vt(e){let t=e.code;return typeof t==`string`?t:null}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var yt=class extends se{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function bt(e,t,n={}){let r=new yt({apiKey:e,maxRetries:Math.max(1,Math.trunc(t)),...n.apiUrl&&{apiUrl:n.apiUrl},...n.backoffFactor!==void 0&&{backoffFactor:n.backoffFactor}});return{search:e=>r.searchEnvelope(e)}}async function xt(e,t,n=1,r=bt(t,n)){try{let t=St(e),n=await r.search(Ct(t));if(!j(n))throw new k(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new k(`fetcher_error`,zt(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new k(`invalid_response`,`The configured fetcher returned an invalid response`);let i=Rt(n);if(i===null)throw new k(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=jt(e,At(n));return{title:a?It(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw dt(e)}}function St(e){return{query:wt(e),limit:5,sources:[`web`],highlights:!1,ignoreInvalidURLs:!0,timeout:12e4,pageOptions:{formats:[`summary`],onlyMainContent:!0,onlyCleanContent:!1,maxAge:1728e5,timeout:6e4,removeBase64Images:!0,blockAds:!0,proxy:`auto`,storeInCache:!0}}}function Ct(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function wt(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=Tt(t.pathname),i=kt(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function Tt(e){let t=e.split(`/`).map(e=>Et(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||Ot(n))continue;let r=Dt(n);if(r)return r}return null}function Et(e){try{return decodeURIComponent(e)}catch{return e}}function Dt(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function Ot(e){return/^(?:index|home|latest)$/i.test(e)||/^\d+$/.test(e)||/^v?\d+(?:\.\d+)+$/i.test(e)||/^[a-z]{2}(?:[-_][a-z]{2})?$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(e)||/^[0-9a-f]{20,}$/i.test(e)}function kt(e){return ce(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function At(e){return!j(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!j(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:j(e.metadata)?e.metadata:{}}])}function jt(e,t){let n=Nt(e);if(n){let e=t.find(e=>Mt(e).some(e=>Nt(e)===n));if(e)return e}let r=Pt(e),i=r===null?[]:t.filter(e=>Mt(e).some(e=>Pt(e)===r));return i.find(e=>Ft(e))??(i.length>0?i[0]:null)}function Mt(e){return[e.url,Lt(e,`sourceURL`),Lt(e,`url`)].filter(e=>!!e)}function Nt(e){try{let t=new URL(e);return t.hash=``,t.searchParams.sort(),t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)),t.href}catch{return null}}function Pt(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function Ft(e){return Mt(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function It(e){return e.title?.trim()||Lt(e,`ogTitle`)?.trim()||Lt(e,`title`)?.trim()||null}function Lt(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function Rt(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function zt(e){return j(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bt(e,t){return xt(e,t.apiKey,t.maxAttempts)}var Vt=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{},r=Bt){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){if(this.paused)return;let e=ct(this.storage).features.library.captures.fetchConcurrency;for(;this.runningCount<e&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.runningCount+=1,this.runJob(e).finally(()=>{--this.runningCount,this.knownJobIDs.delete(e),this.schedule()})}}async runJob(e){let t=this.repository.getJobContext(e);if(!t||t.job.status!==`pending`&&t.job.status!==`running`)return;let n;try{n=Ht(t.job.configSnapshot)}catch(n){let r=n instanceof Error?n.message:`Invalid fetch job configuration`;this.failJob(e,t.job.captureId,`invalid_config`,r);return}this.repository.markRunning(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`running`});try{let r=await this.fetchCaptureImplementation(t.capture.url,n);this.repository.markSucceeded(e,t.capture.id,r.title,r.rawResponse,r.creditsUsed),this.onChanged({captureId:t.capture.id,jobId:e,status:`succeeded`})}catch(n){let r=dt(n);this.failJob(e,t.capture.id,r.code,r.message)}}failJob(e,t,n,r){this.repository.markFailed(e,n,r),this.onChanged({captureId:t,jobId:e,status:`failed`,errorMessage:r})}start(){this.repository.recoverRunningJobs();for(let e of this.repository.pendingJobIDs())this.enqueue(e)}enqueue(e){if(this.knownJobIDs.has(e))return;let t=this.repository.getJobContext(e);t&&(this.knownJobIDs.add(e),this.queue.push(e),this.onChanged({captureId:t.capture.id,jobId:e,status:`pending`}),this.schedule())}notifySettingsChanged(){this.schedule()}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule()}};function Ht(e){let t=e;if(!Ut(t)||t.fetcher!==`firecrawl`||typeof t.apiKey!=`string`||!t.apiKey||typeof t.maxAttempts!=`number`)throw Error(`Invalid fetch job configuration`);return{fetcher:t.fetcher,apiKey:t.apiKey,maxAttempts:Math.min(10,Math.max(1,Math.trunc(t.maxAttempts)))}}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wt=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=ct(this.storage).features.library.captures;if(!e.fetcher)return null;let t=e[e.fetcher].apiKey.trim();return t?{fetcher:e.fetcher,apiKey:t,maxAttempts:e.maxAttempts}:null}list(e){return this.repository.list(e)}counts(){return this.repository.counts()}get(e){let t=this.repository.get(e);if(!t)throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Gt(e.url);if(!t)throw new T(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new T(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before adding a capture`);try{let r=this.repository.createWithJob(t,e.userNote?.trim()||null,n);return this.runner.enqueue(r.jobId),r.capture}catch(e){throw this.repository.findActiveByURL(t)?new T(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new T(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before re-capturing`);let n=this.repository.createJob(e,t);return this.runner.enqueue(n.jobId),n.job}delete(e){if(this.get(e),this.repository.hasActiveJob(e))throw new T(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new T(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}getJob(e,t){return this.get(e),this.repository.getJob(e,t)}};function Gt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Kt(e,t,n){let r=new Ve(e),i=new Vt(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new Wt(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const qt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Jt=[`active`,`disabled`,`deleted`];var M=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Yt=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function N(e){if(!nn(e))throw new M(`Provider input must be an object`);let t=P(e.name,`name`),n=en(e.protocol),r=tn(e.baseURL),i=e.apiKey===void 0?``:P(e.apiKey,`apiKey`,{allowEmpty:!0}),a=$t(e.customModels);return{...e.avatar!==void 0&&{avatar:Xt(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Xt(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 M(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Zt(e){if(!nn(e))throw new M(`Provider connection must be an object`);return{protocol:en(e.protocol),baseURL:tn(e.baseURL),apiKey:e.apiKey===void 0?``:P(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Qt(e){if(typeof e!=`string`||!Jt.includes(e))throw new M(`Invalid provider status`);return e}function $t(e){if(e===void 0)return[];if(!Array.isArray(e))throw new M(`customModels must be an array`);return e.map(e=>{if(!nn(e))throw new M(`Each custom model must be an object`);return{id:P(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:P(e.displayName,`customModels.displayName`)}})}function en(e){if(typeof e!=`string`||!qt.includes(e))throw new M(`Invalid provider protocol`);return e}function tn(e){let t=P(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new M(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function P(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new M(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new M(`${t} is required`);return r}function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e,t){if(!e)throw Error(t)}function an(e){return e===null||typeof e==`string`}function on(e){F(rn(e)&&e.formatVersion===1,`Unsupported Foundry JSON data format`),F(rn(e.settings),`Invalid settings`),Ye(e.settings);for(let t of[`providers`,`captures`,`fetchJobs`]){let n=e[t];F(Array.isArray(n),`Invalid storage collection`);let r=/* @__PURE__ */ new Set;for(let e of n)F(rn(e)&&typeof e.id==`string`&&e.id.length>0&&e.id.length<=200&&!r.has(e.id),`Invalid or duplicate record ID`),r.add(e.id),F(typeof e.createdAt==`string`&&Number.isFinite(Date.parse(e.createdAt))&&typeof e.updatedAt==`string`&&Number.isFinite(Date.parse(e.updatedAt)),`Invalid record timestamp`),F(e.deletedAt===null||typeof e.deletedAt==`string`&&Number.isFinite(Date.parse(e.deletedAt)),`Invalid deletion timestamp`)}let t=e;for(let e of t.providers)try{F([`active`,`disabled`,`deleted`].includes(e.status),`Invalid status`),F(typeof e.apiKey==`string`,`Invalid API key`),N(e)}catch{throw Error(`A provider record is invalid`)}let n=/* @__PURE__ */ new Set,r=new Map(t.captures.map(e=>[e.id,e])),i=new Map(t.fetchJobs.map(e=>[e.id,e]));for(let e of t.captures){try{F([`http:`,`https:`].includes(new URL(e.url).protocol),`Invalid protocol`)}catch{throw Error(`A capture URL is invalid`)}if(F(an(e.title)&&an(e.userNote)&&an(e.latestSuccessfulJobId),`A capture record is invalid`),e.deletedAt||(F(!n.has(e.url),`Duplicate active capture URL`),n.add(e.url),!e.latestSuccessfulJobId))continue;let t=i.get(e.latestSuccessfulJobId);F(t?.captureId===e.id&&t.status===`succeeded`&&!t.deletedAt,`A capture points to an invalid successful fetch job`)}let a=/* @__PURE__ */ new Set;for(let e of t.fetchJobs)F(r.has(e.captureId)&&[`pending`,`running`,`succeeded`,`failed`].includes(e.status)&&e.fetcher===`firecrawl`,`A fetch job record is invalid`),F(rn(e.configSnapshot),`A fetch job configuration is invalid`),F(e.creditsUsed===null||typeof e.creditsUsed==`number`&&Number.isFinite(e.creditsUsed),`A fetch job credit value is invalid`),F(an(e.errorCode)&&an(e.errorMessage),`A fetch job record is invalid`),!e.deletedAt&&[`pending`,`running`].includes(e.status)&&(F(!a.has(e.captureId),`Duplicate active fetch jobs`),a.add(e.captureId))}var I=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function sn(e){return e instanceof I?e:new I(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const L=`data/foundry.json`,cn=`manifest.json`;function ln(e){if(!mn(e)||e.format!==`foundry.snapshot`)throw new I(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=pn(e.archiveVersion,`archiveVersion`);if(t!==3)throw new I(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=fn(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new I(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!mn(e.data)||e.database!==void 0||e.settings!==void 0)throw new I(`INVALID_ARCHIVE`,`JSON data metadata is invalid`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:fn(e.appVersion,`appVersion`),createdAt:n,data:{...dn(e.data,L),formatVersion:pn(e.data.formatVersion,`data.formatVersion`)}}}function un(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function dn(e,t){if(!mn(e)||e.path!==t)throw new I(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=fn(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new I(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:pn(e.bytes,`bytes`),sha256:n}}function fn(e,t){if(typeof e!=`string`||e.length===0)throw new I(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function pn(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new I(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const hn=/* @__PURE__ */ new Set([cn,L]);async function gn(e,t){let n=new Se.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await be(n.outputStream,g(t,{mode:384}))}async function _n(e,t){let n=await vn(e),r=/* @__PURE__ */ new Map,i=0;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!hn.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 a=e.fileName===`manifest.json`?1048576:4294967296;if(i+=e.uncompressedSize,e.uncompressedSize>a||i>4294967296)throw Error(`The Foundry archive is too large`);let o=S.join(t,e.fileName);await l(S.dirname(o),{recursive:!0}),await be(await yn(n,e),g(o,{mode:384})),r.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 p(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(`manifest.json`)||!r.has(`data/foundry.json`))throw await p(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function vn(e){return new Promise((t,n)=>{xe.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function yn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const R=C.from(`FOUNDRYX`,`ascii`),bn=`aes-256-gcm`,xn=`scrypt`,Sn={N:131072,r:8,p:1};async function Cn(e,t,n){let r=ae(16),i=ae(12),o={version:1,cipher:bn,kdf:{name:xn,salt:r.toString(`base64`),...Sn,keyLength:32},nonce:i.toString(`base64`)},s=C.from(JSON.stringify(o),`utf8`),c=Tn(s.byteLength),l=C.concat([c,s]),d=await En(n,r,Sn);try{let n=await u(t,`w`,384);try{await n.write(l)}finally{await n.close()}await be(de(e),Dn(d,i,l),g(t,{flags:`r+`,mode:384,start:l.byteLength})),await a(t,384)}catch(e){throw await p(t,{force:!0}),new I(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function wn(e,t,n){let r;try{let i=(await ee(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let o=await u(e,`r`),s,c,l;try{if(s=await An(o,13,0),!s.subarray(0,R.byteLength).equals(R))throw Error(`The export file signature is invalid`);if(s.readUInt8(R.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(R.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`);c=await An(o,e,13),l=await An(o,16,i-16)}finally{await o.close()}let d=kn(JSON.parse(c.toString(`utf8`)));r=await En(n,d.salt,d.header.kdf);let f=C.concat([s,c]);await be(de(e,{start:13+c.byteLength,end:i-16-1}),On(r,d.nonce,f,l),g(t,{mode:384})),await a(t,384)}catch(e){throw await p(t,{force:!0}),e instanceof I?e:new I(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function Tn(e){let t=C.alloc(13);return R.copy(t,0),t.writeUInt8(1,R.byteLength),t.writeUInt32BE(e,R.byteLength+1),t}function En(e,t,n){return new Promise((r,i)=>{oe(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Dn(e,t,n){let r=ne(bn,e,t,{authTagLength:16});return r.setAAD(n),new we({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,C.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function On(e,t,n,r){let i=re(bn,e,t,{authTagLength:16});return i.setAAD(n),new we({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 kn(e){if(!jn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==bn||!jn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==xn||typeof t.salt!=`string`||t.N!==Sn.N||t.r!==Sn.r||t.p!==Sn.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=C.from(t.salt,`base64`),r=C.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:bn,kdf:{name:xn,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function An(e,t,n){let r=C.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function jn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Mn=class{storage;runner;temporaryRoot;appVersion;workspaceMutationGate;onStatusChanged;busy=!1;stagedImports=/* @__PURE__ */ new Map;constructor(e,t,n,r,i,a=()=>{}){this.storage=e,this.runner=t,this.temporaryRoot=n,this.appVersion=r,this.workspaceMutationGate=i,this.onStatusChanged=a}async runExclusive(e){if(this.busy||!this.workspaceMutationGate.tryBeginTransfer())throw new I(`BUSY`,`Another data transfer is in progress`);this.busy=!0;try{return this.onStatusChanged(this.getStatus()),await e()}finally{this.busy=!1,this.workspaceMutationGate.endTransfer(),this.onStatusChanged(this.getStatus())}}async createWorkDirectory(e){await l(this.temporaryRoot,{recursive:!0,mode:448}),await Rn(this.temporaryRoot);let t=S.join(this.temporaryRoot,`${e}-${h()}`);return await l(t,{mode:448}),await Rn(t),t}async removeQuietly(e){try{await p(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:S.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){b(this.temporaryRoot,{recursive:!0,force:!0}),me(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:this.storage.all(`fetchJobs`).filter(e=>Pn(e)).length,isBusy:this.busy}}async createExport(e){return Nn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=S.join(t,`foundry.json`),r=S.join(t,cn),i=S.join(t,`foundry.zip`),a=S.join(this.temporaryRoot,`foundry-${h()}.foundry-backup`);this.runner.pause();try{let t=this.storage.snapshot();z(t),on(t),await te(n,JSON.stringify(t),{mode:384});let o={format:`foundry.snapshot`,archiveVersion:3,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),data:{...await In(n,L),formatVersion:1}};return await te(r,JSON.stringify(o,null,2),{mode:384}),await gn([{entryPath:cn,filePath:r},{entryPath:L,filePath:n}],i),await Cn(i,a,e),{filePath:a,...Fn(t)}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=S.basename(e)){return Nn(t),this.runExclusive(async()=>{z(this.storage.snapshot());let r=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(r.map(e=>this.removeQuietly(e.directory)));let i=h(),a=await this.createWorkDirectory(`import-${i}`),o=S.join(a,`archive.zip`);try{await wn(e,o,t);let r=await _n(o,S.join(a,`extracted`)),s=ln(JSON.parse(await d(r[cn],`utf8`)));if(s.data.formatVersion>1)throw new I(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let c=/* @__PURE__ */ new Set([cn,L]);await Ln(r[L],s.data);let l=JSON.parse(await d(r[L],`utf8`));if(on(l),l.formatVersion!==s.data.formatVersion)throw new I(`INVALID_ARCHIVE`,`The JSON data format does not match its manifest`);if(Object.keys(r).some(e=>!c.has(e)))throw new I(`INVALID_ARCHIVE`,`Unexpected archive file`);z(l);let u=S.join(a,`staged.json`);await te(u,JSON.stringify(l),{mode:384});let f={importId:i,fileName:S.basename(n),exportedAt:s.createdAt,appVersion:s.appVersion,dataFormatVersion:l.formatVersion,settingsVersion:1,...Fn(l)};return this.stagedImports.set(i,{snapshotPath:u,directory:a,preview:f}),await p(o,{force:!0}),f}catch(e){throw await this.removeQuietly(a),e instanceof I?e:new I(`INVALID_ARCHIVE`,e instanceof Error?e.message:`The Foundry export could not be inspected`,{cause:e})}})}async cancelImport(e){let t=this.stagedImports.get(e);t&&(this.stagedImports.delete(e),await this.removeQuietly(t.directory))}async commitImport(e){let t=this.stagedImports.get(e);if(!t)throw new I(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();try{let n=JSON.parse(await d(t.snapshotPath,`utf8`));on(n),z(n),this.storage.transaction(()=>{z(this.storage.snapshot()),this.storage.replace(n)}),this.stagedImports.delete(e),await this.removeQuietly(t.directory)}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){S.dirname(e)===this.temporaryRoot&&await p(e,{force:!0})}};function Nn(e){if(!e)throw new I(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function Pn(e){return!e.deletedAt&&[`pending`,`running`].includes(e.status)}function z(e){if(e.fetchJobs.some(e=>Pn(e)))throw new I(`ACTIVE_JOBS`,`Finish active fetch jobs before transferring data`)}function Fn(e){return{providerCount:e.providers.length,captureCount:e.captures.length,jobCount:e.fetchJobs.length}}async function In(e,t){let n=ie(`sha256`);for await(let t of de(e))n.update(t);return{path:t,bytes:(await ee(e)).size,sha256:n.digest(`hex`)}}async function Ln(e,t){let n=await In(e,t.path);if(n.bytes!==t.bytes||n.sha256!==t.sha256)throw new I(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function Rn(e){return m.platform===`win32`?Promise.resolve():a(e,448)}const zn=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var Bn=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function Vn(e){return async(t,n)=>{if(e.isTransferActive&&zn.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&Hn(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function Hn(e){return Te(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var B=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Un(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(Wn(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new B(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new B(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new B(`Provider returned invalid JSON`)}return Gn(i)}function Wn(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Gn(e){if(!qn(e)||!Array.isArray(e.data))throw new B(`Provider response does not contain a model list`);return e.data.map(e=>{if(!qn(e)||typeof e.id!=`string`||e.id.length===0)throw new B(`Provider returned an invalid model entry`);let t=Kn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Kn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function qn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var V=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Jn=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=>({...Yn(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Yn(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 V;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??h(),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),Yn(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Yt;let r=this.storage.get(`providers`,e);if(!r)throw new V;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Yn(a)})}};function Yn(e){return{...e,avatar:e.avatar??null,status:e.status}}function Xn(e){let t=ct(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 Qn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Jn(e)}list(){return this.repository.list(Xn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new V;return Un(t)}fetchModelsForConnection(e){return Un(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Xn(this.storage)))}};function $n(e){let t=m.platform===`darwin`?`open`:m.platform===`win32`?`explorer`:`xdg-open`,n=Ee(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function er(){return S.join(De.homedir(),`.foundry`)}function tr(){let e=er();return me(e,{recursive:!0,mode:448}),m.platform!==`win32`&&le(e,448),e}function nr(){return S.join(er(),`.data-transfer`)}var rr=class{storage;configFolder;openFolder;constructor(e,t=er(),n=$n){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...lt(this.storage),configFolder:this.configFolder}}update(e){return{...ut(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const ir=S.dirname(ke(import.meta.url)),H=`foundry`;var ar=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=Oe()}={}){this.configuredSkillRoot=e,this.homeDirectory=S.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??or();if(!_(S.join(t,`SKILL.md`)))throw new U(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=S.join(n,H),i=S.join(n,`.${H}-${h()}.tmp`),a=S.join(n,`.${H}-${h()}.backup`);try{return await l(n,{recursive:!0}),await s(t,i,{recursive:!0,errorOnExist:!0}),await sr(i,r,a),{target:e,destination:r}}catch(e){throw await p(i,{recursive:!0,force:!0}),e instanceof U?e:new U(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return S.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:S.join(this.getTargetParent(e),H)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},U=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function or(){let e=[S.resolve(ir,`skills`,H),S.resolve(ir,`..`,`..`,`..`,`skills`,H),S.resolve(m.cwd(),`skills`,H)].find(e=>_(S.join(e,`SKILL.md`)));if(!e)throw new U(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function sr(e,t,n){let r=_(t);r&&await f(t,n);try{await f(e,t),r&&await p(n,{recursive:!0,force:!0})}catch(e){throw r&&!_(t)&&_(n)&&await f(n,t),e}}function cr(){let e=m.env.CLAUDE_CONFIG_DIR?.trim();return e?S.resolve(e):S.join(De.homedir(),`.claude`)}var W=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};const lr=`.jsonl`;function ur(e){let t=S.join(e,`projects`);if(!_(t))throw new W(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n;try{n=y(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>S.join(t,e.name))}catch(e){throw new W(`CLAUDE_READ_FAILED`,e instanceof Error?e.message:`Unable to read Claude Code sessions`)}let r=[],i=/* @__PURE__ */ new Set;for(let e of n){let n=dr(e);for(let a of n.entries){let o=pr(t,e,a);if(!o||i.has(o))continue;let s=hr(o,a,n.originalPath);i.add(o),s&&r.push(s)}for(let t of mr(e)){if(i.has(t))continue;let e=hr(t,null,n.originalPath);i.add(t),e&&r.push(e)}}return{sessions:r}}function dr(e){let t=S.join(e,`sessions-index.json`);if(!_(t))return{originalPath:null,entries:[]};let n;try{n=JSON.parse(v(t,`utf8`))}catch{return{originalPath:null,entries:[]}}if(!G(n)||!Array.isArray(n.entries))return{originalPath:null,entries:[]};let r=[];for(let e of n.entries){let t=fr(e);t&&r.push(t)}return{originalPath:K(n.originalPath),entries:r}}function fr(e){if(!G(e))return null;let t=wr(e.sessionId);return xr(t)?{sessionId:t,filePath:K(e.fullPath),firstPrompt:K(e.firstPrompt),summary:K(e.summary),gitBranch:K(e.gitBranch),projectPath:K(e.projectPath),isSidechain:e.isSidechain===!0,createdAtMs:Er(e.created)??Tr(e.fileMtime),updatedAtMs:Er(e.modified)??Tr(e.fileMtime)}:null}function pr(e,t,n){let r=S.join(t,`${n.sessionId}${lr}`);return br(r)?r:n.filePath&&S.isAbsolute(n.filePath)&&Sr(e,n.filePath)&&br(n.filePath)?n.filePath:null}function mr(e){let t;try{t=y(e,{withFileTypes:!0})}catch{return[]}return t.filter(e=>e.isFile()&&e.name.endsWith(lr)).map(t=>S.join(e,t.name))}function hr(e,t,n){let r;try{r=x(e)}catch{return null}let i;try{i=gr(e)}catch{return null}let a=t?.sessionId??S.basename(e,lr),o=Cr([t?.projectPath,n,i.cwd]),s=t?.createdAtMs??i.createdAtMs??r.mtimeMs,c=t?.updatedAtMs??i.updatedAtMs??r.mtimeMs;return{id:a,title:Cr([i.customTitle,t?.summary,i.firstPrompt,t?.firstPrompt,i.lastPrompt,a.slice(0,8)]),projectPath:o,createdAtMs:s,updatedAtMs:Math.max(s,c),sizeBytes:r.size,tokensUsed:i.tokensUsed,model:i.model,cwd:Cr([i.cwd,o]),gitBranch:Cr([i.gitBranch,t?.gitBranch])||null,subagent:t?.isSidechain===!0||i.isSidechain}}function gr(e){let t=``,n=null,r=null,i=null,a=null,o=null,s=0,c=null,l=null,u=!1;return _r(e,e=>{if(!e.trim())return;let d;try{d=JSON.parse(e)}catch{return}if(!G(d))return;let f=Er(d.timestamp);f!==null&&(c=c===null?f:Math.min(c,f),l=l===null?f:Math.max(l,f)),t||=wr(d.cwd),d.isSidechain===!0&&(u=!0),d.type===`custom-title`?i=K(d.customTitle)??i:d.type===`last-prompt`&&(a=K(d.lastPrompt)??a);let p=G(d.message)?d.message:null;if(!p||(d.type===`user`&&d.isMeta!==!0&&p.role===`user`&&(r||=K(vr(p.content))),d.type!==`assistant`||p.role!==`assistant`))return;n=K(d.gitBranch)??n;let ee=K(p.model);ee&&ee!==`<synthetic>`&&(o=ee),s+=yr(p.usage)}),{cwd:t,gitBranch:n,firstPrompt:r,customTitle:i,lastPrompt:a,model:o,tokensUsed:s,createdAtMs:c,updatedAtMs:l,isSidechain:u}}function _r(e,t){let n=he(e,`r`),r=new Ae(`utf8`),i=C.allocUnsafe(262144),a=``;try{let e=ge(n,i,0,i.length,null);for(;e>0;){a+=r.write(i.subarray(0,e));let o=0,s=a.indexOf(`
3
3
  `,o);for(;s!==-1;)t(a.slice(o,s)),o=s+1,s=a.indexOf(`
4
- `,o);a=a.slice(o),e=ge(n,i,0,i.length,null)}a+=r.end(),a.length>0&&t(a)}finally{le(n)}}function hr(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)K(n)&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
5
- `)}function gr(e){return K(e)?[e.input_tokens,e.output_tokens,e.cache_creation_input_tokens,e.cache_read_input_tokens].reduce((e,t)=>e+Math.max(0,Sr(t)??0),0):0}function _r(e){if(!e.endsWith(or))return!1;try{return pe(e).isFile()}catch{return!1}}function vr(e){return e.length>0&&e===x.basename(e)&&e!==`.`&&e!==`..`}function yr(e,t){let n=x.relative(e,t);return n.length>0&&n!==`..`&&!n.startsWith(`..${x.sep}`)&&!x.isAbsolute(n)}function br(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xr(e){return typeof e==`string`?e:``}function q(e){return typeof e==`string`&&e.trim().length>0?e.trim():null}function Sr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Cr(e){if(typeof e==`number`)return!Number.isFinite(e)||e<=0?null:e<1e10?e*1e3:e;if(typeof e!=`string`||e.trim().length===0)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function wr(){let e=h.env.CODEX_HOME?.trim();return e?x.resolve(e):x.join(Ee.homedir(),`.codex`)}const Tr=/^rollout-\d{4}-\d{2}-\d{2}T[\d-]+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/u;function Er(e){let t=Ar(e);if(t.length===0)throw new G(`CODEX_DATA_NOT_FOUND`,`Codex state database was not found`);let n=[];for(let e of t){let t=null;try{t=Mr(e),Nr(t,`threads`)&&n.push({path:e,modifiedAt:b(e).mtimeMs})}catch{}finally{t?.close()}}if(n.length===0)throw new G(`UNSUPPORTED_CODEX_SCHEMA`,`Codex state database does not contain a supported threads table`);return n.toSorted((e,t)=>t.modifiedAt-e.modifiedAt)[0].path}function Dr(e){let t=Mr(e);try{let e=new Set(t.prepare(`PRAGMA table_info(threads)`).all().map(e=>e.name));if(!e.has(`id`)||!e.has(`updated_at`))throw new G(`UNSUPPORTED_CODEX_SCHEMA`,`Codex threads table is missing required columns`);let n=(t,n=`NULL`)=>e.has(t)?`"${t}"`:n,r=`SELECT ${[`${n(`id`)} AS id`,`${n(`title`,`''`)} AS title`,`${n(`name`)} AS name`,`${n(`first_user_message`)} AS first_user_message`,`${n(`preview`)} AS preview`,`${n(`cwd`,`''`)} AS cwd`,`${n(`updated_at`)} AS updated_at`,`${n(`updated_at_ms`)} AS updated_at_ms`,`${n(`created_at`)} AS created_at`,`${n(`created_at_ms`)} AS created_at_ms`,`${n(`archived`,`0`)} AS archived`,`${n(`source`,`''`)} AS source`,`${n(`model`)} AS model`,`${n(`model_provider`)} AS model_provider`,`${n(`tokens_used`,`0`)} AS tokens_used`,`${n(`rollout_path`)} AS rollout_path`,`${n(`git_branch`)} AS git_branch`].join(`, `)} FROM threads`;return t.prepare(r).all().map(e=>{let t=X(e.updated_at_ms)??(X(e.updated_at)??0)*1e3,n=X(e.created_at_ms)??(X(e.created_at)??0)*1e3;return{id:J(e.id),title:J(e.title),name:Y(e.name),firstUserMessage:Y(e.first_user_message),preview:Y(e.preview),cwd:J(e.cwd),updatedAtMs:t,createdAtMs:n,archived:X(e.archived)===1,source:J(e.source),model:Y(e.model),modelProvider:Y(e.model_provider),tokensUsed:X(e.tokens_used)??0,rolloutPath:Y(e.rollout_path),gitBranch:Y(e.git_branch)}}).filter(e=>e.id.length>0)}catch(e){throw e instanceof G?e:new G(`CODEX_READ_FAILED`,e instanceof Error?e.message:`Unable to read Codex threads`)}finally{t.close()}}function Or(e){let t=x.join(e,`.codex-global-state.json`);if(!_(t))return Pr();let n;try{n=JSON.parse(v(t,`utf8`))}catch{return Pr()}if(!Fr(n))return Pr();let r=/* @__PURE__ */ new Map,i=Fr(n[`local-projects`])?n[`local-projects`]:null;if(i)for(let[e,t]of Object.entries(i)){if(!Fr(t))continue;let n=J(t.id)||e,i=J(t.name)||n,a=Array.isArray(t.rootPaths)?t.rootPaths.filter(e=>typeof e==`string`):[];r.set(n,{id:n,name:i,roots:a})}let a=/* @__PURE__ */ new Map,o=Fr(n[`thread-project-assignments`])?n[`thread-project-assignments`]:null;if(o)for(let[e,t]of Object.entries(o))Fr(t)&&typeof t.projectId==`string`&&a.set(e,t.projectId);let s=new Set(Array.isArray(n[`projectless-thread-ids`])?n[`projectless-thread-ids`].filter(e=>typeof e==`string`):[]),c=i?[]:[{code:`PROJECTS_UNAVAILABLE`}];return{projects:r.values().toArray(),assignments:a,projectless:s,warnings:c}}function kr(e){let t=[],n=jr(x.join(e,`sessions`),t);n+=jr(x.join(e,`archived_sessions`),t);let r=/* @__PURE__ */ new Map;for(let e of t){let t=Tr.exec(x.basename(e));if(!t)continue;let i;try{i=b(e).size}catch{n+=1;continue}let a=t[1],o=r.get(a)??{bytes:0,segments:0};r.set(a,{bytes:o.bytes+i,segments:o.segments+1})}return{files:r,unreadable:n}}function Ar(e){let t=[];for(let n of[e,x.join(e,`sqlite`)]){let e;try{e=_e(n,{withFileTypes:!0})}catch{continue}for(let r of e)r.isFile()&&/^state.*\.sqlite$/u.test(r.name)&&t.push(x.join(n,r.name))}return t}function jr(e,t){if(!_(e))return 0;let n;try{n=_e(e,{withFileTypes:!0})}catch{return 1}let r=0;for(let i of n){let n=x.join(e,i.name);i.isDirectory()?r+=jr(n,t):i.isFile()&&Tr.test(i.name)&&t.push(n)}return r}function Mr(t){let{DatabaseSync:n}=e(import.meta.url)(`node:sqlite`),r=new n(t,{readOnly:!0});return r.exec(`PRAGMA busy_timeout = 5000`),r}function Nr(e,t){return e.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).get(t)!==void 0}function Pr(){return{projects:[],assignments:/* @__PURE__ */ new Map,projectless:/* @__PURE__ */ new Set,warnings:[{code:`PROJECTS_UNAVAILABLE`}]}}function Fr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e){return typeof e==`string`?e:``}function Y(e){return typeof e==`string`&&e.trim().length>0?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}var Ir=class{codexHome;claudeHome;constructor(e=wr(),t=ar()){this.codexHome=e,this.claudeHome=t}getCodexSnapshot(){let e=Dr(Er(this.codexHome)),t=Or(this.codexHome),n=kr(this.codexHome),r=new Map(t.projects.map(e=>[e.id,e])),i=e.map(e=>Lr(e,t,r,n.files)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`codex`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.projects,threads:i,warnings:[...t.warnings,...n.unreadable>0?[{code:`ROLLOUT_FILES_UNREADABLE`,count:n.unreadable}]:[]]}}getClaudeSnapshot(){let e=sr(this.claudeHome),t=/* @__PURE__ */ new Map,n=e.sessions.map(e=>Br(e,t)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`claude`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.values().toArray(),threads:n,warnings:[]}}};function Lr(e,t,n,r){let i=t.assignments.get(e.id),a=i?n.get(i):void 0,o=a?`assigned`:t.projectless.has(e.id)?`projectless`:`unassigned`,s=r.get(e.id)??Ur(e.rolloutPath),c=e.updatedAtMs>0?e.updatedAtMs:e.createdAtMs,l=e.createdAtMs>0?e.createdAtMs:c;return{id:e.id,title:Rr(e),projectId:a?.id??null,projectBucket:o,archived:e.archived,subagent:Wr(e.source),createdAt:new Date(l).toISOString(),updatedAt:new Date(c).toISOString(),sizeBytes:s?.bytes??0,segmentCount:s?.segments??0,tokensUsed:Math.max(0,Math.trunc(e.tokensUsed)),model:e.model??e.modelProvider,cwd:e.cwd,gitBranch:e.gitBranch}}function Rr(e){return zr([e.name,e.title,e.firstUserMessage,e.preview,e.id.slice(0,8)])}function zr(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function Br(e,t){let n=Vr(e.projectPath);if(n){let r=t.get(n);r?r.roots.includes(e.projectPath)||r.roots.push(e.projectPath):t.set(n,{id:n,name:Hr(e.projectPath),roots:[e.projectPath]})}return{id:e.id,title:e.title,projectId:n,projectBucket:n?`assigned`:`projectless`,archived:!1,subagent:e.subagent,createdAt:new Date(e.createdAtMs).toISOString(),updatedAt:new Date(e.updatedAtMs).toISOString(),sizeBytes:e.sizeBytes,segmentCount:1,tokensUsed:e.tokensUsed,model:e.model,cwd:e.cwd,gitBranch:e.gitBranch}}function Vr(e){return e?`claude:${e}`:null}function Hr(e){return e.split(/[\\/]/u).filter(Boolean).at(-1)??e}function Ur(e){if(!e)return null;for(let t of[e,`${e}.zst`])try{return{bytes:b(t).size,segments:1}}catch{}return null}function Wr(e){let t=e.trim();if(!t.startsWith(`{`))return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&!Array.isArray(e)&&`subagent`in e}catch{return t.includes(`"subagent"`)}}var Gr=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:g(),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 Kr(e){let t=new Gr,n=new Ln,r=Gt(e,t),i=new kn(e,r.runner,$n(),Pe,n,e=>t.publish(`data-transfer.status.changed`,e)),a=new Yn(e),o=new er(e),s=new nr,c=new Ir;return{services:{captureRuntime:r,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c},apiOptions:{captureService:r.service,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c,workspaceMutationGate:n,eventHub:t,onSettingsChanged:r.notifySettingsChanged},start(){i.cleanupStaleTransfers(),r.start()}}}function qr(e){me(e,{recursive:!0,mode:448}),h.platform!==`win32`&&ce(e,448)}function Jr(e){if(h.platform===`win32`)return;let t=he(e,`r`);try{fe(t)}finally{le(t)}}function Yr(e,t){qr(x.dirname(e));let n=`${e}.${g()}.tmp`;try{let r=he(n,`wx`,384);try{ye(r,`${JSON.stringify(t,null,2)}\n`),fe(r)}finally{le(r)}ve(n,e),Jr(x.dirname(e))}finally{y(n,{force:!0})}}const Xr=[`providers`,`captures`,`fetchJobs`];function Zr(e){try{let t=JSON.parse(v(x.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return h.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-b(e).mtimeMs>3e4}}var Qr=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,qr(e);for(let e of Xr)qr(this.collectionPath(e))}collectionPath(e){return x.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return x.relative(this.path,x.join(this.collectionPath(e),`${re(`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=x.join(this.path,`.lock`),n=Date.now();for(;;)try{me(t,{mode:448});try{ye(x.join(t,`owner.json`),JSON.stringify({pid:h.pid}),{mode:384})}catch(e){throw y(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,e()}finally{this.lockDepth=0,y(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=b(e);if(!Zr(e))return;let n=x.join(e,`recovering`);try{me(n)}catch(e){if(e.code===`EEXIST`){let e=b(n);Zr(n)&&b(n).ino===e.ino&&y(n,{recursive:!0,force:!0})}return}if(ye(x.join(n,`owner.json`),JSON.stringify({pid:h.pid}),{mode:384,flag:`wx`}),b(e).ino!==t.ino||!Zr(e)){y(n,{recursive:!0,force:!0});return}y(e,{recursive:!0,force:!0})}catch{}}recover(){let e=x.join(this.path,`.transaction.json`);if(!_(e))return;let t=JSON.parse(v(e,`utf8`));this.applyJournal(t)}applyJournal(e){for(let t of e.changes){let e=x.resolve(this.path,t.file),n=x.relative(this.path,e);if(n.startsWith(`..`)||x.isAbsolute(n)||!/^(?:settings\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(y(e,{force:!0}),Jr(x.dirname(e))):Yr(e,t.value)}y(x.join(this.path,`.transaction.json`),{force:!0}),Jr(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=x.join(this.path,t);if(!_(e))return;n=JSON.parse(v(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(()=>{let t=this.collectionPath(e),n=new Set(_e(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>x.relative(this.path,x.join(t,e.name))));if(this.changes){let e=x.relative(this.path,t);for(let t of this.changes.keys())x.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(()=>this.readRecord(e,this.recordPath(e,t)))}readSettings(){return this.locked(()=>{if(this.changes?.has(`settings.json`))return structuredClone(this.changes.get(`settings.json`));let e=x.join(this.path,`settings.json`);return _(e)?Je(JSON.parse(v(e,`utf8`))):structuredClone(E)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(this.recordPath(e,t.id),structuredClone(t))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,Je(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t=!1;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}))};Yr(x.join(this.path,`.transaction.json`),e),t=!0,this.applyJournal(e)}return n}catch(e){throw t&&this.recover(),e}finally{this.changes=null}})}snapshot(){return this.locked(()=>({formatVersion:1,settings:this.readSettings(),providers:this.all(`providers`),captures:this.all(`captures`),fetchJobs:this.all(`fetchJobs`)}))}replace(e){this.transaction(()=>{for(let t of Xr){let n=this.all(t);for(let e of n)this.changes?.set(this.recordPath(t,e.id),null);let r=e[t];for(let e of r)this.put(t,e)}this.setSettings(e.settings)})}close(){this.closed=!0}};function $r(e=Zn()){let t=new Qr(e);try{return t.transaction(()=>{let n=t.readSettings();_(x.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function ei(){return Qn(),$r()}const ti={input:{type:`string`,description:`JSON payload; use "-" to read it from stdin`,valueHint:`json`},"input-file":{type:`string`,description:`Path to a JSON payload file`,valueHint:`path`}};async function Z(e){let t;try{let n=ei();t={storage:n,runtime:Kr(n)},ai(await e(t))}catch(e){let t=oi(e);console.error(JSON.stringify({error:t},null,2)),h.exitCode=1}finally{t?.storage.close()}}async function ni(e){if(e.input!==void 0&&e.inputFile!==void 0)throw new Q(`CONFLICTING_INPUT`,`Use either --input or --input-file, not both`);if(e.input===void 0&&e.inputFile===void 0)throw new Q(`INPUT_REQUIRED`,`Provide a JSON payload with --input or --input-file`);let t;try{t=e.inputFile===void 0?e.input===`-`?await ri():e.input??``:e.inputFile===`-`?await ri():await d(e.inputFile,`utf8`)}catch(e){throw new Q(`INPUT_READ_FAILED`,e instanceof Error?e.message:`Unable to read JSON input`)}try{return JSON.parse(t)}catch{throw new Q(`INVALID_JSON`,`Input must be valid JSON`)}}async function ri(){let e=[];for await(let t of h.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function ii(e){let t=e??h.env.FOUNDRY_PASSPHRASE;if(!t)throw new Q(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function ai(e){console.log(JSON.stringify(e,null,2))}function oi(e){return e instanceof Error?{code:si(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function si(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function ci(e,t){return e.listJobs(t.id)[0]}async function li(e,t,n){let r=await ui(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,rawResponse:i.rawResponse,job:r}}async function ui(e,t,n){let r=di(e,t,n);for(;r.status!==`succeeded`&&r.status!==`failed`;)await i(250),r=di(e,t,n);return r}function di(e,t,n){let r=e.getJob(t,n);if(!r)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return r}const fi=t({meta:{name:`list`,description:`List fetch jobs for a capture`,alias:[`ls`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.listJobs(e[`capture-id`]))}}),pi=t({meta:{name:`get`,description:`Read one fetch job owned by a capture`,alias:[`show`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0},"job-id":{type:`positional`,description:`Fetch job ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.captureRuntime.service.getJob(e[`capture-id`],e[`job-id`]);if(!n)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return n})}}),mi=t({meta:{name:`recapture`,description:`Run a new fetch job for a capture and wait for completion`},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e[`capture-id`]);return ui(n,e[`capture-id`],r.id)})}}),hi=t({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:fi,get:pi,recapture:mi}}),gi=t({meta:{name:`list`,description:`List captures`,alias:[`ls`]},args:{filter:{type:`enum`,description:`Capture filter`,options:[`all`,`no-successful`],default:`all`}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.list(Ie(e.filter)))}}),_i=t({meta:{name:`counts`,description:`Read capture counts`},run(){return Z(({runtime:e})=>e.services.captureRuntime.service.counts())}}),vi=t({meta:{name:`get`,description:`Read a capture and its latest successful fetcher response`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.get(e.id))}}),yi=t({meta:{name:`create`,description:`Capture a URL`,alias:[`add`]},args:{url:{type:`positional`,description:`HTTP or HTTPS URL`,required:!0},note:{type:`string`,description:`User note`,valueHint:`text`}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.create(Fe({url:e.url,userNote:e.note}));return li(n,r,ci(n,r))})}}),bi=t({meta:{name:`recapture`,description:`Create a new fetch job for an existing capture`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e.id),i=n.get(e.id).capture;return li(n,i,r)})}}),xi=t({meta:{name:`note`,description:`Replace a capture user note`},args:{id:{type:`positional`,description:`Capture ID`,required:!0},note:{type:`positional`,description:`New note; use an empty string to clear it`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.updateNote(e.id,e.note))}}),Si=t({meta:{name:`delete`,description:`Delete a capture and its fetch jobs`,alias:[`remove`,`rm`]},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>(t.services.captureRuntime.service.delete(e.id),{deleted:!0,id:e.id}))}}),Ci=t({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:gi,counts:_i,get:vi,create:yi,recapture:bi,note:xi,delete:Si,jobs:hi}}),wi=t({meta:{name:`status`,description:`Read data-transfer and fetch-job status`},run(){return Z(({runtime:e})=>e.services.dataTransferService.getStatus())}}),Ti=t({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({runtime:t})=>{let n=t.services.dataTransferService,r=ii(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=ki(e.output);try{await Ai(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),Ei=t({meta:{name:`inspect`,description:`Validate a Foundry backup without importing it`},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({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(x.resolve(e.file),ii(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),Di=t({meta:{name:`import`,description:`Validate and replace local Foundry data from a backup`,alias:[`restore`]},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({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(x.resolve(e.file),ii(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),Oi=t({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:wi,export:Ti,inspect:Ei,import:Di}});function ki(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return ln(x.resolve(n))}async function Ai(e,t,n){await l(x.dirname(t),{recursive:!0,mode:448});let r=x.join(x.dirname(t),`.${x.basename(t)}.${g()}.tmp`);try{if(await o(e.filePath,r),h.platform!==`win32`&&await a(r,384),n){await f(r,t);return}if(_(t))throw ji(t);try{await c(r,t)}catch(e){throw Mi(e)?ji(t):e}}finally{await p(r,{force:!0})}}function ji(e){return new Q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Mi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Ni=t({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return Z(({runtime:e})=>e.services.providerService.list())}}),Pi=t({meta:{name:`get`,description:`Read one provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.providerService.get(e.id);if(!n)throw new H;return n})}}),Fi=t({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Yt(await ni(e));return t.services.providerService.save(n)})}}),Ii=t({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...ti},run({args:e}){return Z(async({runtime:t})=>{let n=Yt(await ni(e));return t.services.providerService.save(n,e.id)})}}),Li=t({meta:{name:`set-status`,description:`Change a provider status`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},status:{type:`enum`,description:`New provider status`,options:[...qt],required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.setStatus(e.id,Zt(e.status)))}}),Ri=t({meta:{name:`models`,description:`Discover models for a saved provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.fetchModels(e.id))}}),zi=t({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Xt(await ni(e));return t.services.providerService.fetchModelsForConnection(n)})}}),Bi=t({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:Ni,get:Pi,create:Fi,update:Ii,"set-status":Li,models:Ri,"models-for-connection":zi}}),Vi=[`agents`,`claude`];function Hi(e){if(!Wi(e)||!Array.isArray(e.targets))throw new Ui(`targets must be an array`);if(e.targets.length===0)throw new Ui(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Vi.includes(e))throw new Ui(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Ui=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Wi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gi=t({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return Z(({runtime:e})=>e.services.settingsService.read())}}),Ki=t({meta:{name:`update`,description:`Apply a settings patch`},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Ye(await ni(e));return t.services.settingsService.update(n)})}}),qi=t({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Z(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),Ji=t({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(({runtime:t})=>{let n=Hi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),Yi=t({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:Gi,update:Ki,open:qi,"download-skill":Ji}});function Xi(e,t=()=>{}){let n=new w;return n.get(`/`,t=>{let n=Ie(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=Fe(await Zi(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return $(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return $(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 $(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 $(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Le(await Zi(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return $(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return $(t,e)}}),n}async function Zi(e){try{return await e.req.json()}catch{throw new Re(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof Re)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof T)return e.json({error:{code:t.code,message:t.message}},Qi(t.code));throw t}function Qi(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}}function $i(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new w;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await ra(t),r=await e.createExport(n),i=ue(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(Se.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${x.basename(r.filePath)}"`,"x-foundry-provider-count":String(r.providerCount),"x-foundry-capture-count":String(r.captureCount),"x-foundry-job-count":String(r.jobCount)})}catch(e){return ia(t,e)}}),r.post(`/inspect`,async t=>{let r;try{if(t.req.header(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/octet-stream`)throw new F(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);ta(t,n);let i=na(t,`x-foundry-passphrase`);if(!i)throw new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=na(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await ea(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return ia(t,e)}finally{await r?.cleanup()}}),r.post(`/imports/:id/commit`,async n=>{try{return await e.commitImport(n.req.param(`id`)),t(),n.json({status:`imported`})}catch(e){return ia(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return ia(t,e)}}),r}async function ea(e,t,n){let r=e.req.raw.body;if(!r)throw new F(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new Ce({transform(e,t,r){i+=e.byteLength,i>n?r(new F(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await S(Se.fromWeb(r),a,de(t,{mode:384}))}catch(e){throw e instanceof F?e:new F(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new F(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function ta(e,t){let n=e.req.header(`content-length`);if(n===void 0)return;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new F(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new F(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function na(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new F(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function ra(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof F?e:new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function ia(e,t){let n=on(t);return e.json({error:{code:n.code,message:n.message}},aa(n.code))}function aa(e){switch(e){case`IMPORT_NOT_FOUND`:return 404;case`ACTIVE_JOBS`:case`BUSY`:return 409;case`IO_ERROR`:return 500;default:return 400}}function oa(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 ca(t,e)}}),n.post(`/models`,async t=>{try{let n=Xt(await sa(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ca(t,e)}}),n.post(`/`,async n=>{try{let r=Yt(await sa(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ca(n,e)}}),n.put(`/:id`,async n=>{try{let r=Yt(await sa(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ca(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await sa(n),i=Zt(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 ca(n,e)}}),n}async function sa(e){try{return await e.req.json()}catch{throw new M(`Request body must be valid JSON`)}}function ca(e,t){if(t instanceof M)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof H)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Jt)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}},502);throw t}function la(e,t=()=>{},n=new nr){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Ye(await ua(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return da(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=Hi(await ua(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return da(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function ua(e){try{return await e.req.json()}catch{throw new D(`Request body must be valid JSON`)}}function da(e,t){if(t instanceof D||t instanceof Ui)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof W)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function fa(e){let t=new w;return t.get(`/codex`,t=>{try{return t.json(e.getCodexSnapshot())}catch(e){return pa(t,e)}}),t.get(`/claude`,t=>{try{return t.json(e.getClaudeSnapshot())}catch(e){return pa(t,e)}}),t}function pa(e,t){if(t instanceof G)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`UNSUPPORTED_CODEX_SCHEMA`:return e.json({error:{code:t.code,message:t.message}},422);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 ma(e){let t=new w;return t.get(`/`,t=>Me(t,async n=>{await ha(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||ga(n,e)}),c=setInterval(()=>{r||_a(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 ha(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function ga(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function _a(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function va(e){return e===`/api`||e.startsWith(`/api/`)}function ya(e,t={}){let n=new w,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Ln,i=t.providerService??new Yn(e),a=t.settingsService??new er(e),o=t.settingsSkillCopyService??new nr,s=t.sessionService??new Ir;return n.use(`/api/*`,Rn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Pe,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,ma(t.eventHub)),n.route(`/api/providers`,oa(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,la(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),n.route(`/api/sessions`,fa(s)),t.captureService&&n.route(`/api/captures`,Xi(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,$i(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>va(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),va(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function ba(e,t,n){let r=ya(t,n),i=je({root:e});r.use(`*`,(e,t)=>va(e.req.path)?t():i(e,t));let a=je({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!va(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&x.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:xa,join:Sa,resolve:Ca}=x,wa=xa(Oe(import.meta.url));function Ta(){let e=[Ca(wa,`web`),Ca(h.cwd(),`dist/web`)].find(e=>_(Sa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ea({storage:e,webRoot:t=Ta(),onListening:n}){let r=Kr(e),i=ba(t,e,r.apiOptions);r.start();let a=Ae({fetch:i.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return a.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),h.exitCode=1}),a}function Da(e,t){return new Promise((n,r)=>{let i=Ne();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function Oa(e){let t=`xdg-open`,n=[e];h.platform===`darwin`?t=`open`:h.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=Te(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ka=t({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await Da(`127.0.0.1`,11111)}catch(e){Aa(e);return}Ea({storage:ei(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Oa(t)}})}});function Aa(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),h.exitCode=1}function ja(){let e,n=t({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await r(e)}});return e=t({meta:{name:`foundry`,version:Pe,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:n,web:ka,settings:Yi,providers:Bi,captures:Ci,"data-transfer":Oi}}),e}n(ja());export{};
4
+ `,o);a=a.slice(o),e=ge(n,i,0,i.length,null)}a+=r.end(),a.length>0&&t(a)}finally{ue(n)}}function vr(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)G(n)&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
5
+ `)}function yr(e){return G(e)?[e.input_tokens,e.output_tokens,e.cache_creation_input_tokens,e.cache_read_input_tokens].reduce((e,t)=>e+Math.max(0,Tr(t)??0),0):0}function br(e){if(!e.endsWith(lr))return!1;try{return pe(e).isFile()}catch{return!1}}function xr(e){return e.length>0&&e===S.basename(e)&&e!==`.`&&e!==`..`}function Sr(e,t){let n=S.relative(e,t);return n.length>0&&n!==`..`&&!n.startsWith(`..${S.sep}`)&&!S.isAbsolute(n)}function Cr(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wr(e){return typeof e==`string`?e:``}function K(e){return typeof e==`string`&&e.trim().length>0?e.trim():null}function Tr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Er(e){if(typeof e==`number`)return!Number.isFinite(e)||e<=0?null:e<1e10?e*1e3:e;if(typeof e!=`string`||e.trim().length===0)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Dr(){let e=m.env.CODEX_HOME?.trim();return e?S.resolve(e):S.join(De.homedir(),`.codex`)}const Or=/^rollout-\d{4}-\d{2}-\d{2}T[\d-]+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/u;function kr(e){let t=Nr(e);if(t.length===0)throw new W(`CODEX_DATA_NOT_FOUND`,`Codex state database was not found`);let n=[];for(let e of t){let t=null;try{t=Fr(e),Ir(t,`threads`)&&n.push({path:e,modifiedAt:x(e).mtimeMs})}catch{}finally{t?.close()}}if(n.length===0)throw new W(`UNSUPPORTED_CODEX_SCHEMA`,`Codex state database does not contain a supported threads table`);return n.toSorted((e,t)=>t.modifiedAt-e.modifiedAt)[0].path}function Ar(e){let t=Fr(e);try{let e=new Set(t.prepare(`PRAGMA table_info(threads)`).all().map(e=>e.name));if(!e.has(`id`)||!e.has(`updated_at`))throw new W(`UNSUPPORTED_CODEX_SCHEMA`,`Codex threads table is missing required columns`);let n=(t,n=`NULL`)=>e.has(t)?`"${t}"`:n,r=`SELECT ${[`${n(`id`)} AS id`,`${n(`title`,`''`)} AS title`,`${n(`name`)} AS name`,`${n(`first_user_message`)} AS first_user_message`,`${n(`preview`)} AS preview`,`${n(`cwd`,`''`)} AS cwd`,`${n(`updated_at`)} AS updated_at`,`${n(`updated_at_ms`)} AS updated_at_ms`,`${n(`created_at`)} AS created_at`,`${n(`created_at_ms`)} AS created_at_ms`,`${n(`archived`,`0`)} AS archived`,`${n(`source`,`''`)} AS source`,`${n(`model`)} AS model`,`${n(`model_provider`)} AS model_provider`,`${n(`tokens_used`,`0`)} AS tokens_used`,`${n(`rollout_path`)} AS rollout_path`,`${n(`git_branch`)} AS git_branch`].join(`, `)} FROM threads`;return t.prepare(r).all().map(e=>{let t=X(e.updated_at_ms)??(X(e.updated_at)??0)*1e3,n=X(e.created_at_ms)??(X(e.created_at)??0)*1e3;return{id:J(e.id),title:J(e.title),name:Y(e.name),firstUserMessage:Y(e.first_user_message),preview:Y(e.preview),cwd:J(e.cwd),updatedAtMs:t,createdAtMs:n,archived:X(e.archived)===1,source:J(e.source),model:Y(e.model),modelProvider:Y(e.model_provider),tokensUsed:X(e.tokens_used)??0,rolloutPath:Y(e.rollout_path),gitBranch:Y(e.git_branch)}}).filter(e=>e.id.length>0)}catch(e){throw e instanceof W?e:new W(`CODEX_READ_FAILED`,e instanceof Error?e.message:`Unable to read Codex threads`)}finally{t.close()}}function jr(e){let t=S.join(e,`.codex-global-state.json`);if(!_(t))return Lr();let n;try{n=JSON.parse(v(t,`utf8`))}catch{return Lr()}if(!q(n))return Lr();let r=/* @__PURE__ */ new Map,i=q(n[`local-projects`])?n[`local-projects`]:null;if(i)for(let[e,t]of Object.entries(i)){if(!q(t))continue;let n=J(t.id)||e,i=J(t.name)||n,a=Array.isArray(t.rootPaths)?t.rootPaths.filter(e=>typeof e==`string`):[];r.set(n,{id:n,name:i,roots:a})}let a=/* @__PURE__ */ new Map,o=q(n[`thread-project-assignments`])?n[`thread-project-assignments`]:null;if(o)for(let[e,t]of Object.entries(o))q(t)&&typeof t.projectId==`string`&&a.set(e,t.projectId);let s=new Set(Array.isArray(n[`projectless-thread-ids`])?n[`projectless-thread-ids`].filter(e=>typeof e==`string`):[]),c=i?[]:[{code:`PROJECTS_UNAVAILABLE`}];return{projects:r.values().toArray(),assignments:a,projectless:s,warnings:c}}function Mr(e){let t=[],n=Pr(S.join(e,`sessions`),t);n+=Pr(S.join(e,`archived_sessions`),t);let r=/* @__PURE__ */ new Map;for(let e of t){let t=Or.exec(S.basename(e));if(!t)continue;let i;try{i=x(e).size}catch{n+=1;continue}let a=t[1],o=r.get(a)??{bytes:0,segments:0};r.set(a,{bytes:o.bytes+i,segments:o.segments+1})}return{files:r,unreadable:n}}function Nr(e){let t=[];for(let n of[e,S.join(e,`sqlite`)]){let e;try{e=y(n,{withFileTypes:!0})}catch{continue}for(let r of e)r.isFile()&&/^state.*\.sqlite$/u.test(r.name)&&t.push(S.join(n,r.name))}return t}function Pr(e,t){if(!_(e))return 0;let n;try{n=y(e,{withFileTypes:!0})}catch{return 1}let r=0;for(let i of n){let n=S.join(e,i.name);i.isDirectory()?r+=Pr(n,t):i.isFile()&&Or.test(i.name)&&t.push(n)}return r}function Fr(t){let{DatabaseSync:n}=e(import.meta.url)(`node:sqlite`),r=new n(t,{readOnly:!0});return r.exec(`PRAGMA busy_timeout = 5000`),r}function Ir(e,t){return e.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).get(t)!==void 0}function Lr(){return{projects:[],assignments:/* @__PURE__ */ new Map,projectless:/* @__PURE__ */ new Set,warnings:[{code:`PROJECTS_UNAVAILABLE`}]}}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e){return typeof e==`string`?e:``}function Y(e){return typeof e==`string`&&e.trim().length>0?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}var Rr=class{codexHome;claudeHome;constructor(e=Dr(),t=cr()){this.codexHome=e,this.claudeHome=t}getCodexSnapshot(){let e=Ar(kr(this.codexHome)),t=jr(this.codexHome),n=Mr(this.codexHome),r=new Map(t.projects.map(e=>[e.id,e])),i=e.map(e=>zr(e,t,r,n.files)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`codex`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.projects,threads:i,warnings:[...t.warnings,...n.unreadable>0?[{code:`ROLLOUT_FILES_UNREADABLE`,count:n.unreadable}]:[]]}}getClaudeSnapshot(){let e=ur(this.claudeHome),t=/* @__PURE__ */ new Map,n=e.sessions.map(e=>Hr(e,t)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`claude`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.values().toArray(),threads:n,warnings:[]}}};function zr(e,t,n,r){let i=t.assignments.get(e.id),a=i?n.get(i):void 0,o=a?`assigned`:t.projectless.has(e.id)?`projectless`:`unassigned`,s=r.get(e.id)??Gr(e.rolloutPath),c=e.updatedAtMs>0?e.updatedAtMs:e.createdAtMs,l=e.createdAtMs>0?e.createdAtMs:c;return{id:e.id,title:Br(e),projectId:a?.id??null,projectBucket:o,archived:e.archived,subagent:Kr(e.source),createdAt:new Date(l).toISOString(),updatedAt:new Date(c).toISOString(),sizeBytes:s?.bytes??0,segmentCount:s?.segments??0,tokensUsed:Math.max(0,Math.trunc(e.tokensUsed)),model:e.model??e.modelProvider,cwd:e.cwd,gitBranch:e.gitBranch}}function Br(e){return Vr([e.name,e.title,e.firstUserMessage,e.preview,e.id.slice(0,8)])}function Vr(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function Hr(e,t){let n=Ur(e.projectPath);if(n){let r=t.get(n);r?r.roots.includes(e.projectPath)||r.roots.push(e.projectPath):t.set(n,{id:n,name:Wr(e.projectPath),roots:[e.projectPath]})}return{id:e.id,title:e.title,projectId:n,projectBucket:n?`assigned`:`projectless`,archived:!1,subagent:e.subagent,createdAt:new Date(e.createdAtMs).toISOString(),updatedAt:new Date(e.updatedAtMs).toISOString(),sizeBytes:e.sizeBytes,segmentCount:1,tokensUsed:e.tokensUsed,model:e.model,cwd:e.cwd,gitBranch:e.gitBranch}}function Ur(e){return e?`claude:${e}`:null}function Wr(e){return e.split(/[\\/]/u).filter(Boolean).at(-1)??e}function Gr(e){if(!e)return null;for(let t of[e,`${e}.zst`])try{return{bytes:x(t).size,segments:1}}catch{}return null}function Kr(e){let t=e.trim();if(!t.startsWith(`{`))return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&!Array.isArray(e)&&`subagent`in e}catch{return t.includes(`"subagent"`)}}var qr=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:h(),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 Jr(e){let t=new qr,n=new Bn,r=Kt(e,t),i=new Mn(e,r.runner,nr(),Fe,n,e=>t.publish(`data-transfer.status.changed`,e)),a=new Qn(e),o=new rr(e),s=new ar,c=new Rr;return{services:{captureRuntime:r,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c},apiOptions:{captureService:r.service,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c,workspaceMutationGate:n,eventHub:t,onSettingsChanged:r.notifySettingsChanged},start(){i.cleanupStaleTransfers(),r.start()}}}function Yr(e){me(e,{recursive:!0,mode:448}),m.platform!==`win32`&&le(e,448)}function Xr(e){if(m.platform===`win32`)return;let t=he(e,`r`);try{fe(t)}finally{ue(t)}}function Zr(e,t){Yr(S.dirname(e));let n=`${e}.${h()}.tmp`;try{let r=he(n,`wx`,384);try{ye(r,`${JSON.stringify(t,null,2)}\n`),fe(r)}finally{ue(r)}_e(n,e),Xr(S.dirname(e))}finally{b(n,{force:!0})}}const Qr=[`providers`,`captures`,`fetchJobs`];function $r(e){try{let t=JSON.parse(v(S.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return m.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-x(e).mtimeMs>3e4}}var ei=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Yr(e);for(let e of Qr)e!==`providers`&&Yr(this.collectionPath(e))}collectionPath(e){return S.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return S.relative(this.path,S.join(this.collectionPath(e),`${ie(`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=S.join(this.path,`.lock`),n=Date.now();for(;;)try{me(t,{mode:448});try{ye(S.join(t,`owner.json`),JSON.stringify({pid:m.pid}),{mode:384})}catch(e){throw b(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,b(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=x(e);if(!$r(e))return;let n=S.join(e,`recovering`);try{me(n)}catch(e){if(e.code===`EEXIST`){let e=x(n);$r(n)&&x(n).ino===e.ino&&b(n,{recursive:!0,force:!0})}return}if(ye(S.join(n,`owner.json`),JSON.stringify({pid:m.pid}),{mode:384,flag:`wx`}),x(e).ino!==t.ino||!$r(e)){b(n,{recursive:!0,force:!0});return}b(e,{recursive:!0,force:!0})}catch{}}recover(){let e=S.join(this.path,`.transaction.json`);if(!_(e))return;let t=JSON.parse(v(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=S.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!_(e)){let e=_(t)?y(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,S.join(`providers`,e)))},...e.map(e=>({file:S.join(`providers`,e),value:null}))]};Zr(S.join(this.path,`.transaction.json`),n),this.applyJournal(n)}_(t)&&y(t).length===0&&(ve(t),Xr(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(v(S.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=S.resolve(this.path,t.file),n=S.relative(this.path,e);if(n.startsWith(`..`)||S.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(b(e,{force:!0}),Xr(S.dirname(e))):Zr(e,t.value)}b(S.join(this.path,`.transaction.json`),{force:!0}),Xr(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=S.join(this.path,t);if(!_(e))return;n=JSON.parse(v(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(y(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>S.relative(this.path,S.join(t,e.name))));if(this.changes){let e=S.relative(this.path,t);for(let t of this.changes.keys())S.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 structuredClone(this.changes.get(`settings.json`));let e=S.join(this.path,`settings.json`);return _(e)?Ye(JSON.parse(v(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`,Ye(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t=!1;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}))};Zr(S.join(this.path,`.transaction.json`),e),t=!0,this.applyJournal(e)}return n}catch(e){throw t&&this.recover(),e}finally{this.changes=null}})}snapshot(){return this.locked(()=>({formatVersion:1,settings:this.readSettings(),providers:this.all(`providers`),captures:this.all(`captures`),fetchJobs:this.all(`fetchJobs`)}))}replace(e){this.transaction(()=>{for(let t of Qr){if(t===`providers`){this.changes?.set(`providers.json`,structuredClone(e.providers));continue}let n=this.all(t);for(let e of n)this.changes?.set(this.recordPath(t,e.id),null);let r=e[t];for(let e of r)this.put(t,e)}this.setSettings(e.settings)})}close(){this.closed=!0}};function ti(e=er()){let t=new ei(e);try{return t.transaction(()=>{let n=t.readSettings();_(S.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function ni(){return tr(),ti()}const ri={input:{type:`string`,description:`JSON payload; use "-" to read it from stdin`,valueHint:`json`},"input-file":{type:`string`,description:`Path to a JSON payload file`,valueHint:`path`}};async function Z(e){let t;try{let n=ni();t={storage:n,runtime:Jr(n)},si(await e(t))}catch(e){let t=ci(e);console.error(JSON.stringify({error:t},null,2)),m.exitCode=1}finally{t?.storage.close()}}async function ii(e){if(e.input!==void 0&&e.inputFile!==void 0)throw new Q(`CONFLICTING_INPUT`,`Use either --input or --input-file, not both`);if(e.input===void 0&&e.inputFile===void 0)throw new Q(`INPUT_REQUIRED`,`Provide a JSON payload with --input or --input-file`);let t;try{t=e.inputFile===void 0?e.input===`-`?await ai():e.input??``:e.inputFile===`-`?await ai():await d(e.inputFile,`utf8`)}catch(e){throw new Q(`INPUT_READ_FAILED`,e instanceof Error?e.message:`Unable to read JSON input`)}try{return JSON.parse(t)}catch{throw new Q(`INVALID_JSON`,`Input must be valid JSON`)}}async function ai(){let e=[];for await(let t of m.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function oi(e){let t=e??m.env.FOUNDRY_PASSPHRASE;if(!t)throw new Q(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function si(e){console.log(JSON.stringify(e,null,2))}function ci(e){return e instanceof Error?{code:li(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function li(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function ui(e,t){return e.listJobs(t.id)[0]}async function di(e,t,n){let r=await fi(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,rawResponse:i.rawResponse,job:r}}async function fi(e,t,n){let r=pi(e,t,n);for(;r.status!==`succeeded`&&r.status!==`failed`;)await i(250),r=pi(e,t,n);return r}function pi(e,t,n){let r=e.getJob(t,n);if(!r)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return r}const mi=t({meta:{name:`list`,description:`List fetch jobs for a capture`,alias:[`ls`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.listJobs(e[`capture-id`]))}}),hi=t({meta:{name:`get`,description:`Read one fetch job owned by a capture`,alias:[`show`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0},"job-id":{type:`positional`,description:`Fetch job ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.captureRuntime.service.getJob(e[`capture-id`],e[`job-id`]);if(!n)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return n})}}),gi=t({meta:{name:`recapture`,description:`Run a new fetch job for a capture and wait for completion`},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e[`capture-id`]);return fi(n,e[`capture-id`],r.id)})}}),_i=t({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:mi,get:hi,recapture:gi}}),vi=t({meta:{name:`list`,description:`List captures`,alias:[`ls`]},args:{filter:{type:`enum`,description:`Capture filter`,options:[`all`,`no-successful`],default:`all`}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.list(Le(e.filter)))}}),yi=t({meta:{name:`counts`,description:`Read capture counts`},run(){return Z(({runtime:e})=>e.services.captureRuntime.service.counts())}}),bi=t({meta:{name:`get`,description:`Read a capture and its latest successful fetcher response`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.get(e.id))}}),xi=t({meta:{name:`create`,description:`Capture a URL`,alias:[`add`]},args:{url:{type:`positional`,description:`HTTP or HTTPS URL`,required:!0},note:{type:`string`,description:`User note`,valueHint:`text`}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.create(Ie({url:e.url,userNote:e.note}));return di(n,r,ui(n,r))})}}),Si=t({meta:{name:`recapture`,description:`Create a new fetch job for an existing capture`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e.id),i=n.get(e.id).capture;return di(n,i,r)})}}),Ci=t({meta:{name:`note`,description:`Replace a capture user note`},args:{id:{type:`positional`,description:`Capture ID`,required:!0},note:{type:`positional`,description:`New note; use an empty string to clear it`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.updateNote(e.id,e.note))}}),wi=t({meta:{name:`delete`,description:`Delete a capture and its fetch jobs`,alias:[`remove`,`rm`]},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>(t.services.captureRuntime.service.delete(e.id),{deleted:!0,id:e.id}))}}),Ti=t({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:vi,counts:yi,get:bi,create:xi,recapture:Si,note:Ci,delete:wi,jobs:_i}}),Ei=t({meta:{name:`status`,description:`Read data-transfer and fetch-job status`},run(){return Z(({runtime:e})=>e.services.dataTransferService.getStatus())}}),Di=t({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({runtime:t})=>{let n=t.services.dataTransferService,r=oi(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=ji(e.output);try{await Mi(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),Oi=t({meta:{name:`inspect`,description:`Validate a Foundry backup without importing it`},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({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(S.resolve(e.file),oi(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),ki=t({meta:{name:`import`,description:`Validate and replace local Foundry data from a backup`,alias:[`restore`]},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({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(S.resolve(e.file),oi(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),Ai=t({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:Ei,export:Di,inspect:Oi,import:ki}});function ji(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return un(S.resolve(n))}async function Mi(e,t,n){await l(S.dirname(t),{recursive:!0,mode:448});let r=S.join(S.dirname(t),`.${S.basename(t)}.${h()}.tmp`);try{if(await o(e.filePath,r),m.platform!==`win32`&&await a(r,384),n){await f(r,t);return}if(_(t))throw Ni(t);try{await c(r,t)}catch(e){throw Pi(e)?Ni(t):e}}finally{await p(r,{force:!0})}}function Ni(e){return new Q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Pi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Fi=t({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return Z(({runtime:e})=>e.services.providerService.list())}}),Ii=t({meta:{name:`get`,description:`Read one provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.providerService.get(e.id);if(!n)throw new V;return n})}}),Li=t({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:ri,run({args:e}){return Z(async({runtime:t})=>{let n=N(await ii(e));return t.services.providerService.save(n)})}}),Ri=t({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...ri},run({args:e}){return Z(async({runtime:t})=>{let n=N(await ii(e));return t.services.providerService.save(n,e.id)})}}),zi=t({meta:{name:`set-status`,description:`Change a provider status`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},status:{type:`enum`,description:`New provider status`,options:[...Jt],required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.setStatus(e.id,Qt(e.status)))}}),Bi=t({meta:{name:`models`,description:`Discover models for a saved provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.fetchModels(e.id))}}),Vi=t({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:ri,run({args:e}){return Z(async({runtime:t})=>{let n=Zt(await ii(e));return t.services.providerService.fetchModelsForConnection(n)})}}),Hi=t({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:Fi,get:Ii,create:Li,update:Ri,"set-status":zi,models:Bi,"models-for-connection":Vi}}),Ui=[`agents`,`claude`];function Wi(e){if(!Ki(e)||!Array.isArray(e.targets))throw new Gi(`targets must be an array`);if(e.targets.length===0)throw new Gi(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Ui.includes(e))throw new Gi(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Gi=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Ki(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const qi=t({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return Z(({runtime:e})=>e.services.settingsService.read())}}),Ji=t({meta:{name:`update`,description:`Apply a settings patch`},args:ri,run({args:e}){return Z(async({runtime:t})=>{let n=Xe(await ii(e));return t.services.settingsService.update(n)})}}),Yi=t({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Z(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),Xi=t({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(({runtime:t})=>{let n=Wi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),Zi=t({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:qi,update:Ji,open:Yi,"download-skill":Xi}});function Qi(e,t=()=>{}){let n=new w;return n.get(`/`,t=>{let n=Le(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=Ie(await $i(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return $(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return $(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 $(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 $(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Re(await $i(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return $(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return $(t,e)}}),n}async function $i(e){try{return await e.req.json()}catch{throw new ze(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof ze)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof T)return e.json({error:{code:t.code,message:t.message}},ea(t.code));throw t}function ea(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}}function ta(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new w;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await aa(t),r=await e.createExport(n),i=de(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(Ce.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${S.basename(r.filePath)}"`,"x-foundry-provider-count":String(r.providerCount),"x-foundry-capture-count":String(r.captureCount),"x-foundry-job-count":String(r.jobCount)})}catch(e){return oa(t,e)}}),r.post(`/inspect`,async t=>{let r;try{if(t.req.header(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/octet-stream`)throw new I(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);ra(t,n);let i=ia(t,`x-foundry-passphrase`);if(!i)throw new I(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=ia(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await na(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return oa(t,e)}finally{await r?.cleanup()}}),r.post(`/imports/:id/commit`,async n=>{try{return await e.commitImport(n.req.param(`id`)),t(),n.json({status:`imported`})}catch(e){return oa(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return oa(t,e)}}),r}async function na(e,t,n){let r=e.req.raw.body;if(!r)throw new I(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new we({transform(e,t,r){i+=e.byteLength,i>n?r(new I(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await be(Ce.fromWeb(r),a,g(t,{mode:384}))}catch(e){throw e instanceof I?e:new I(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new I(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function ra(e,t){let n=e.req.header(`content-length`);if(n===void 0)return;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new I(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new I(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function ia(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new I(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function aa(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new I(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof I?e:new I(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function oa(e,t){let n=sn(t);return e.json({error:{code:n.code,message:n.message}},sa(n.code))}function sa(e){switch(e){case`IMPORT_NOT_FOUND`:return 404;case`ACTIVE_JOBS`:case`BUSY`:return 409;case`IO_ERROR`:return 500;default:return 400}}function ca(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 ua(t,e)}}),n.post(`/models`,async t=>{try{let n=Zt(await la(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ua(t,e)}}),n.post(`/`,async n=>{try{let r=N(await la(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ua(n,e)}}),n.put(`/:id`,async n=>{try{let r=N(await la(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ua(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await la(n),i=Qt(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 ua(n,e)}}),n}async function la(e){try{return await e.req.json()}catch{throw new M(`Request body must be valid JSON`)}}function ua(e,t){if(t instanceof M)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof V)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Yt)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}},502);throw t}function da(e,t=()=>{},n=new ar){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Xe(await fa(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return pa(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=Wi(await fa(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return pa(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function fa(e){try{return await e.req.json()}catch{throw new D(`Request body must be valid JSON`)}}function pa(e,t){if(t instanceof D||t instanceof Gi)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}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function ma(e){let t=new w;return t.get(`/codex`,t=>{try{return t.json(e.getCodexSnapshot())}catch(e){return ha(t,e)}}),t.get(`/claude`,t=>{try{return t.json(e.getClaudeSnapshot())}catch(e){return ha(t,e)}}),t}function ha(e,t){if(t instanceof W)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`UNSUPPORTED_CODEX_SCHEMA`:return e.json({error:{code:t.code,message:t.message}},422);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 ga(e){let t=new w;return t.get(`/`,t=>Ne(t,async n=>{await _a(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||va(n,e)}),c=setInterval(()=>{r||ya(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 _a(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function va(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function ya(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function ba(e){return e===`/api`||e.startsWith(`/api/`)}function xa(e,t={}){let n=new w,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Bn,i=t.providerService??new Qn(e),a=t.settingsService??new rr(e),o=t.settingsSkillCopyService??new ar,s=t.sessionService??new Rr;return n.use(`/api/*`,Vn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Fe,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,ga(t.eventHub)),n.route(`/api/providers`,ca(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,da(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),n.route(`/api/sessions`,ma(s)),t.captureService&&n.route(`/api/captures`,Qi(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,ta(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>ba(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),ba(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Sa(e,t,n){let r=xa(t,n),i=Me({root:e});r.use(`*`,(e,t)=>ba(e.req.path)?t():i(e,t));let a=Me({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!ba(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&S.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:Ca,join:wa,resolve:Ta}=S,Ea=Ca(ke(import.meta.url));function Da(){let e=[Ta(Ea,`web`),Ta(m.cwd(),`dist/web`)].find(e=>_(wa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Oa({storage:e,webRoot:t=Da(),onListening:n}){let r=Jr(e),i=Sa(t,e,r.apiOptions);r.start();let a=je({fetch:i.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return a.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),m.exitCode=1}),a}function ka(e,t){return new Promise((n,r)=>{let i=Pe();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function Aa(e){let t=`xdg-open`,n=[e];m.platform===`darwin`?t=`open`:m.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=Ee(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ja=t({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 ka(`127.0.0.1`,11111)}catch(e){Ma(e);return}Oa({storage:ni(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Aa(t)}})}});function Ma(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),m.exitCode=1}function Na(){let e,n=t({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await r(e)}});return e=t({meta:{name:`foundry`,version:Fe,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:n,web:ja,settings:Zi,providers:Hi,captures:Ti,"data-transfer":Ai}}),e}n(Na());export{};
@@ -34,6 +34,9 @@ supports `add`.
34
34
 
35
35
  Rules:
36
36
 
37
+ - `avatar`: optional base64 image data URL (`data:image/png;base64,...`, JPEG,
38
+ GIF, WebP, or SVG), up to 2 MB decoded. Omit to preserve the existing avatar on
39
+ update; pass `null` to restore the default icon.
37
40
  - `name`: required, trimmed, non-empty.
38
41
  - `protocol`: required; one of `openai-responses`,
39
42
  `anthropic-messages`, `openai-compatible-chat-completions`.
@@ -138,3 +141,6 @@ When `baseURL` includes a path such as `/v1`, include a trailing slash
138
141
  invalid model payload.
139
142
 
140
143
  Provider responses include stored credentials. Do not expose them unnecessarily.
144
+
145
+ All provider records are stored together in `<home>/.foundry/providers.json`.
146
+ Use CLI commands to preserve transactions and process locking.