@dhzh/foundry 6.0.0 → 6.2.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 +9 -3
- package/dist/index.mjs +4 -4
- package/dist/skills/foundry/references/providers.md +6 -0
- package/dist/web/assets/{BottomSheet-DQwWhhYI.js → BottomSheet-Dq32EHcT.js} +1 -1
- package/dist/web/assets/{ItemSwipeLayer-CeyoMSkM.js → ItemSwipeLayer-dZkEr9ZY.js} +1 -1
- package/dist/web/assets/{MenuBottomSheet-BuaZeZUh.js → MenuBottomSheet-DHhbAGxB.js} +1 -1
- package/dist/web/assets/{index-Bjtcyz6x.css → index-BkZfZMlH.css} +102 -0
- package/dist/web/assets/index-C0fugt10.js +105 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-B90pNaUa.js +0 -105
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
|
|
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
|
-
|
|
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
|
|
@@ -137,7 +137,13 @@ required.
|
|
|
137
137
|
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
|
+
The read-only Sessions view reads Codex and Claude Code JSONL transcripts, including
|
|
141
|
+
Zstandard-compressed files. It does not read their databases, global state, or
|
|
142
|
+
session indexes. Threads are grouped by the working directory recorded in their
|
|
143
|
+
transcripts; Codex project membership and later UI-only renames are not imported.
|
|
144
|
+
Existing `providers/` records are automatically migrated into `providers.json`
|
|
145
|
+
under the process lock using the recovery journal. Provider avatars accept PNG,
|
|
146
|
+
JPEG, GIF, WebP, or SVG images up to 2 MB; clearing an avatar restores the default icon.
|
|
141
147
|
|
|
142
148
|
Encrypted exports and imports use JSON snapshots in `data/foundry.json`.
|
|
143
149
|
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(`
|
|
3
|
-
`,
|
|
4
|
-
`,
|
|
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{};
|
|
2
|
+
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import{setTimeout as r}from"node:timers/promises";import{chmod as i,copyFile as a,cp as o,link as s,mkdir as c,open as l,readFile as u,readdir as d,rename as f,rm as p,stat as m,writeFile as h}from"node:fs/promises";import g from"node:process";import{createCipheriv as ee,createDecipheriv as te,createHash as _,randomBytes as ne,randomUUID as v,scrypt as re}from"node:crypto";import{FirecrawlClient as ie}from"firecrawl";import{parse as ae}from"tldts";import{chmodSync as oe,closeSync as se,createReadStream as y,createWriteStream as ce,existsSync as b,fsyncSync as le,mkdirSync as x,openSync as ue,readFileSync as S,readdirSync as de,renameSync as fe,rmSync as C,rmdirSync as pe,statSync as w,writeFileSync as me}from"node:fs";import T from"node:path";import{pipeline as E}from"node:stream/promises";import he from"yauzl";import ge from"yazl";import{Buffer as D}from"node:buffer";import{Readable as _e,Transform as ve}from"node:stream";import{matchedRoutes as ye}from"hono/route";import{spawn as be}from"node:child_process";import xe,{homedir as Se}from"node:os";import{fileURLToPath as Ce}from"node:url";import{StringDecoder as we}from"node:string_decoder";import{createZstdDecompress as Te}from"node:zlib";import{serve as Ee}from"@hono/node-server";import{serveStatic as De}from"@hono/node-server/serve-static";import{Hono as O}from"hono";import{streamSSE as Oe}from"hono/streaming";import{createServer as ke}from"node:net";var Ae=`6.2.0`;function je(e){if(!Fe(e)||typeof e.url!=`string`)throw new Pe(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Me(e){return e===`no-successful`?`no-successful`:`all`}function Ne(e){if(!Fe(e)||typeof e.userNote!=`string`)throw new Pe(`userNote must be a string`);return e.userNote}var Pe=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Fe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var k=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Ie=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:v(),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=>Le(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:Le(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 k(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:v(),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:Le(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 k(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new k(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Re(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 k(`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),Le(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=>Re(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Re(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 Le(e){let{deletedAt:t,...n}=e;return n}function Re(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 ze=[`system`,`light`,`dark`],Be=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ve=[`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`],He=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Ue=[`firecrawl`],We={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 Ge(e){let t=M(e)?e:{},n=M(t.workspace)?t.workspace:{},r=M(n.appearance)?n.appearance:{},i=M(n[`language-region`])?n[`language-region`]:{},a=M(t.features)?t.features:{},o=M(a.library)?a.library:{},s=M(o.captures)?o.captures:{},c=M(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":Qe(r[`color-theme`],ze,We.workspace.appearance[`color-theme`])},"language-region":{language:Qe(i.language,Be,We.workspace[`language-region`].language),"time-format":Qe(i[`time-format`],Ve,We.workspace[`language-region`][`time-format`]),"time-zone":Qe(i[`time-zone`],He,We.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:Xe(s.fetcher),maxAttempts:$e(s.maxAttempts,10,1),fetchConcurrency:$e(s.fetchConcurrency,5,2),firecrawl:{apiKey:nt(c.apiKey)}}}}}}function Ke(e){if(!M(e))throw new A(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=j(e.theme,ze,`theme`)),`language`in e&&(t.language=j(e.language,Be,`language`)),`timeFormat`in e&&(t.timeFormat=j(e.timeFormat,Ve,`timeFormat`)),`timezone`in e&&(t.timezone=j(e.timezone,He,`timezone`)),`captures`in e&&(t.captures=Ye(e.captures)),t}function qe(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 Je(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 A=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function Ye(e){if(!M(e))throw new A(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:j(e.fetcher,Ue,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=et(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=et(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=tt(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function Xe(e){return Ze(e,Ue)}function Ze(e,t){return typeof e==`string`&&t.includes(e)?e:null}function Qe(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function j(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new A(`Invalid ${n}`);return e}function $e(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function et(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new A(`${n} must be an integer from 1 to ${t}`);return e}function tt(e,t){if(typeof e!=`string`)throw new A(`${t} must be a string`);return e.trim()}function nt(e){return typeof e==`string`?e:``}function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e){return e.readSettings()}function rt(e){return Je(N(e))}function it(e,t){return t.transaction(()=>{let n=qe(N(t),e);return t.setSettings(n),Je(n)})}var P=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function at(e){if(e instanceof P)return e;let t=ot(e);return t===null?lt(e)?new P(`timeout`,`The configured fetcher timed out`):ut(e)?new P(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new P(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new P(`http_${t}`,st(e)??`The configured fetcher returned ${t}`,t)}function ot(e){if(!F(e))return null;let t=dt(e.status);return t===null?F(e.response)?dt(e.response.status):null:t}function st(e){if(!F(e))return null;if(F(e.response)){let t=ct(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:ct(e.details)}function ct(e){return F(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function lt(e){if(!(e instanceof Error))return!1;let t=ft(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function ut(e){if(e instanceof TypeError)return!0;if(!F(e))return!1;let t=ft(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!F(e.response)}function dt(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function ft(e){let t=e.code;return typeof t==`string`?t:null}function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var pt=class extends ie{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function mt(e,t,n={}){let r=new pt({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 ht(e,t,n=1,r=mt(t,n)){try{let t=gt(e),n=await r.search(_t(t));if(!I(n))throw new P(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new P(`fetcher_error`,Nt(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new P(`invalid_response`,`The configured fetcher returned an invalid response`);let i=Mt(n);if(i===null)throw new P(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=Tt(e,wt(n));return{title:a?At(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw at(e)}}function gt(e){return{query:vt(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 _t(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function vt(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=yt(t.pathname),i=Ct(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function yt(e){let t=e.split(`/`).map(e=>bt(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||St(n))continue;let r=xt(n);if(r)return r}return null}function bt(e){try{return decodeURIComponent(e)}catch{return e}}function xt(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function St(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 Ct(e){return ae(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function wt(e){return!I(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!I(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:I(e.metadata)?e.metadata:{}}])}function Tt(e,t){let n=Dt(e);if(n){let e=t.find(e=>Et(e).some(e=>Dt(e)===n));if(e)return e}let r=Ot(e),i=r===null?[]:t.filter(e=>Et(e).some(e=>Ot(e)===r));return i.find(e=>kt(e))??(i.length>0?i[0]:null)}function Et(e){return[e.url,jt(e,`sourceURL`),jt(e,`url`)].filter(e=>!!e)}function Dt(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 Ot(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function kt(e){return Et(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function At(e){return e.title?.trim()||jt(e,`ogTitle`)?.trim()||jt(e,`title`)?.trim()||null}function jt(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function Mt(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function Nt(e){return I(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pt(e,t){return ht(e,t.apiKey,t.maxAttempts)}var Ft=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{},r=Pt){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){if(this.paused)return;let e=N(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=It(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=at(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 It(e){let t=e;if(!Lt(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 Lt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Rt=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=N(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 k(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=zt(e.url);if(!t)throw new k(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new k(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new k(`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 k(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new k(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new k(`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 k(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new k(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new k(`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 zt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Bt(e,t,n){let r=new Ie(e),i=new Ft(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new Rt(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const Vt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Ht=[`active`,`disabled`,`deleted`];var L=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Ut=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function R(e){if(!Xt(e))throw new L(`Provider input must be an object`);let t=z(e.name,`name`),n=Jt(e.protocol),r=Yt(e.baseURL),i=e.apiKey===void 0?``:z(e.apiKey,`apiKey`,{allowEmpty:!0}),a=qt(e.customModels);return{...e.avatar!==void 0&&{avatar:Wt(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Wt(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 L(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Gt(e){if(!Xt(e))throw new L(`Provider connection must be an object`);return{protocol:Jt(e.protocol),baseURL:Yt(e.baseURL),apiKey:e.apiKey===void 0?``:z(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Kt(e){if(typeof e!=`string`||!Ht.includes(e))throw new L(`Invalid provider status`);return e}function qt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new L(`customModels must be an array`);return e.map(e=>{if(!Xt(e))throw new L(`Each custom model must be an object`);return{id:z(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:z(e.displayName,`customModels.displayName`)}})}function Jt(e){if(typeof e!=`string`||!Vt.includes(e))throw new L(`Invalid provider protocol`);return e}function Yt(e){let t=z(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new L(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function z(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new L(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new L(`${t} is required`);return r}function Xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e,t){if(!e)throw Error(t)}function V(e){return e===null||typeof e==`string`}function Qt(e){B(Zt(e)&&e.formatVersion===1,`Unsupported Foundry JSON data format`),B(Zt(e.settings),`Invalid settings`),Ge(e.settings);for(let t of[`providers`,`captures`,`fetchJobs`]){let n=e[t];B(Array.isArray(n),`Invalid storage collection`);let r=/* @__PURE__ */ new Set;for(let e of n)B(Zt(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),B(typeof e.createdAt==`string`&&Number.isFinite(Date.parse(e.createdAt))&&typeof e.updatedAt==`string`&&Number.isFinite(Date.parse(e.updatedAt)),`Invalid record timestamp`),B(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{B([`active`,`disabled`,`deleted`].includes(e.status),`Invalid status`),B(typeof e.apiKey==`string`,`Invalid API key`),R(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{B([`http:`,`https:`].includes(new URL(e.url).protocol),`Invalid protocol`)}catch{throw Error(`A capture URL is invalid`)}if(B(V(e.title)&&V(e.userNote)&&V(e.latestSuccessfulJobId),`A capture record is invalid`),e.deletedAt||(B(!n.has(e.url),`Duplicate active capture URL`),n.add(e.url),!e.latestSuccessfulJobId))continue;let t=i.get(e.latestSuccessfulJobId);B(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)B(r.has(e.captureId)&&[`pending`,`running`,`succeeded`,`failed`].includes(e.status)&&e.fetcher===`firecrawl`,`A fetch job record is invalid`),B(Zt(e.configSnapshot),`A fetch job configuration is invalid`),B(e.creditsUsed===null||typeof e.creditsUsed==`number`&&Number.isFinite(e.creditsUsed),`A fetch job credit value is invalid`),B(V(e.errorCode)&&V(e.errorMessage),`A fetch job record is invalid`),!e.deletedAt&&[`pending`,`running`].includes(e.status)&&(B(!a.has(e.captureId),`Duplicate active fetch jobs`),a.add(e.captureId))}var H=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function $t(e){return e instanceof H?e:new H(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const U=`data/foundry.json`,W=`manifest.json`;function en(e){if(!on(e)||e.format!==`foundry.snapshot`)throw new H(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=an(e.archiveVersion,`archiveVersion`);if(t!==3)throw new H(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=rn(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new H(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!on(e.data)||e.database!==void 0||e.settings!==void 0)throw new H(`INVALID_ARCHIVE`,`JSON data metadata is invalid`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:rn(e.appVersion,`appVersion`),createdAt:n,data:{...nn(e.data,U),formatVersion:an(e.data.formatVersion,`data.formatVersion`)}}}function tn(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function nn(e,t){if(!on(e)||e.path!==t)throw new H(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=rn(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new H(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:an(e.bytes,`bytes`),sha256:n}}function rn(e,t){if(typeof e!=`string`||e.length===0)throw new H(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function an(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new H(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function on(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const sn=/* @__PURE__ */ new Set([W,U]);async function cn(e,t){let n=new ge.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await E(n.outputStream,ce(t,{mode:384}))}async function ln(e,t){let n=await un(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(!sn.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=T.join(t,e.fileName);await c(T.dirname(o),{recursive:!0}),await E(await dn(n,e),ce(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 un(e){return new Promise((t,n)=>{he.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function dn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const G=D.from(`FOUNDRYX`,`ascii`),K=`aes-256-gcm`,fn=`scrypt`,pn={N:131072,r:8,p:1};async function mn(e,t,n){let r=ne(16),a=ne(12),o={version:1,cipher:K,kdf:{name:fn,salt:r.toString(`base64`),...pn,keyLength:32},nonce:a.toString(`base64`)},s=D.from(JSON.stringify(o),`utf8`),c=gn(s.byteLength),u=D.concat([c,s]),d=await _n(n,r,pn);try{let n=await l(t,`w`,384);try{await n.write(u)}finally{await n.close()}await E(y(e),vn(d,a,u),ce(t,{flags:`r+`,mode:384,start:u.byteLength})),await i(t,384)}catch(e){throw await p(t,{force:!0}),new H(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function hn(e,t,n){let r;try{let a=(await m(e)).size;if(a<=29)throw Error(`The export file is incomplete`);let o=await l(e,`r`),s,c,u;try{if(s=await xn(o,13,0),!s.subarray(0,G.byteLength).equals(G))throw Error(`The export file signature is invalid`);if(s.readUInt8(G.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(G.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(a<=13+e+16)throw Error(`The export file is incomplete`);c=await xn(o,e,13),u=await xn(o,16,a-16)}finally{await o.close()}let d=bn(JSON.parse(c.toString(`utf8`)));r=await _n(n,d.salt,d.header.kdf);let f=D.concat([s,c]);await E(y(e,{start:13+c.byteLength,end:a-16-1}),yn(r,d.nonce,f,u),ce(t,{mode:384})),await i(t,384)}catch(e){throw await p(t,{force:!0}),e instanceof H?e:new H(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function gn(e){let t=D.alloc(13);return G.copy(t,0),t.writeUInt8(1,G.byteLength),t.writeUInt32BE(e,G.byteLength+1),t}function _n(e,t,n){return new Promise((r,i)=>{re(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function vn(e,t,n){let r=ee(K,e,t,{authTagLength:16});return r.setAAD(n),new ve({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,D.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function yn(e,t,n,r){let i=te(K,e,t,{authTagLength:16});return i.setAAD(n),new ve({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 bn(e){if(!Sn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==K||!Sn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==fn||typeof t.salt!=`string`||t.N!==pn.N||t.r!==pn.r||t.p!==pn.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=D.from(t.salt,`base64`),r=D.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:K,kdf:{name:fn,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function xn(e,t,n){let r=D.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Cn=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 H(`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 c(this.temporaryRoot,{recursive:!0,mode:448}),await An(this.temporaryRoot);let t=T.join(this.temporaryRoot,`${e}-${v()}`);return await c(t,{mode:448}),await An(t),t}async removeQuietly(e){try{await p(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:T.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){C(this.temporaryRoot,{recursive:!0,force:!0}),x(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:this.storage.all(`fetchJobs`).filter(e=>Tn(e)).length,isBusy:this.busy}}async createExport(e){return wn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=T.join(t,`foundry.json`),r=T.join(t,W),i=T.join(t,`foundry.zip`),a=T.join(this.temporaryRoot,`foundry-${v()}.foundry-backup`);this.runner.pause();try{let t=this.storage.snapshot();En(t),Qt(t),await h(n,JSON.stringify(t),{mode:384});let o={format:`foundry.snapshot`,archiveVersion:3,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),data:{...await On(n,U),formatVersion:1}};return await h(r,JSON.stringify(o,null,2),{mode:384}),await cn([{entryPath:W,filePath:r},{entryPath:U,filePath:n}],i),await mn(i,a,e),{filePath:a,...Dn(t)}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=T.basename(e)){return wn(t),this.runExclusive(async()=>{En(this.storage.snapshot());let r=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(r.map(e=>this.removeQuietly(e.directory)));let i=v(),a=await this.createWorkDirectory(`import-${i}`),o=T.join(a,`archive.zip`);try{await hn(e,o,t);let r=await ln(o,T.join(a,`extracted`)),s=en(JSON.parse(await u(r[W],`utf8`)));if(s.data.formatVersion>1)throw new H(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let c=/* @__PURE__ */ new Set([W,U]);await kn(r[U],s.data);let l=JSON.parse(await u(r[U],`utf8`));if(Qt(l),l.formatVersion!==s.data.formatVersion)throw new H(`INVALID_ARCHIVE`,`The JSON data format does not match its manifest`);if(Object.keys(r).some(e=>!c.has(e)))throw new H(`INVALID_ARCHIVE`,`Unexpected archive file`);En(l);let d=T.join(a,`staged.json`);await h(d,JSON.stringify(l),{mode:384});let f={importId:i,fileName:T.basename(n),exportedAt:s.createdAt,appVersion:s.appVersion,dataFormatVersion:l.formatVersion,settingsVersion:1,...Dn(l)};return this.stagedImports.set(i,{snapshotPath:d,directory:a,preview:f}),await p(o,{force:!0}),f}catch(e){throw await this.removeQuietly(a),e instanceof H?e:new H(`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 H(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();try{let n=JSON.parse(await u(t.snapshotPath,`utf8`));Qt(n),En(n),this.storage.transaction(()=>{En(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){T.dirname(e)===this.temporaryRoot&&await p(e,{force:!0})}};function wn(e){if(!e)throw new H(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function Tn(e){return!e.deletedAt&&[`pending`,`running`].includes(e.status)}function En(e){if(e.fetchJobs.some(e=>Tn(e)))throw new H(`ACTIVE_JOBS`,`Finish active fetch jobs before transferring data`)}function Dn(e){return{providerCount:e.providers.length,captureCount:e.captures.length,jobCount:e.fetchJobs.length}}async function On(e,t){let n=_(`sha256`);for await(let t of y(e))n.update(t);return{path:t,bytes:(await m(e)).size,sha256:n.digest(`hex`)}}async function kn(e,t){let n=await On(e,t.path);if(n.bytes!==t.bytes||n.sha256!==t.sha256)throw new H(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function An(e){return g.platform===`win32`?Promise.resolve():i(e,448)}const jn=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var Mn=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function Nn(e){return async(t,n)=>{if(e.isTransferActive&&jn.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&Pn(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function Pn(e){return ye(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var q=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Fn(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(In(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new q(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new q(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new q(`Provider returned invalid JSON`)}return Ln(i)}function In(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Ln(e){if(!zn(e)||!Array.isArray(e.data))throw new q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!zn(e)||typeof e.id!=`string`||e.id.length===0)throw new q(`Provider returned an invalid model entry`);let t=Rn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Rn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function zn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Bn=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Vn=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=>({...Hn(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Hn(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 Bn;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??v(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),Hn(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Ut;let r=this.storage.get(`providers`,e);if(!r)throw new Bn;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Hn(a)})}};function Hn(e){return{...e,avatar:e.avatar??null,status:e.status}}function Un(e){let t=N(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Wn(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Wn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Gn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Vn(e)}list(){return this.repository.list(Un(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Bn;return Fn(t)}fetchModelsForConnection(e){return Fn(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Un(this.storage)))}};function Kn(e){let t=g.platform===`darwin`?`open`:g.platform===`win32`?`explorer`:`xdg-open`,n=be(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function qn(){return T.join(xe.homedir(),`.foundry`)}function Jn(){let e=qn();return x(e,{recursive:!0,mode:448}),g.platform!==`win32`&&oe(e,448),e}function Yn(){return T.join(qn(),`.data-transfer`)}var Xn=class{storage;configFolder;openFolder;constructor(e,t=qn(),n=Kn){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...rt(this.storage),configFolder:this.configFolder}}update(e){return{...it(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const Zn=T.dirname(Ce(import.meta.url)),J=`foundry`;var Qn=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=Se()}={}){this.configuredSkillRoot=e,this.homeDirectory=T.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??er();if(!b(T.join(t,`SKILL.md`)))throw new $n(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=T.join(n,J),i=T.join(n,`.${J}-${v()}.tmp`),a=T.join(n,`.${J}-${v()}.backup`);try{return await c(n,{recursive:!0}),await o(t,i,{recursive:!0,errorOnExist:!0}),await tr(i,r,a),{target:e,destination:r}}catch(e){throw await p(i,{recursive:!0,force:!0}),e instanceof $n?e:new $n(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return T.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:T.join(this.getTargetParent(e),J)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},$n=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function er(){let e=[T.resolve(Zn,`skills`,J),T.resolve(Zn,`..`,`..`,`..`,`skills`,J),T.resolve(g.cwd(),`skills`,J)].find(e=>b(T.join(e,`SKILL.md`)));if(!e)throw new $n(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function tr(e,t,n){let r=b(t);r&&await f(t,n);try{await f(e,t),r&&await p(n,{recursive:!0,force:!0})}catch(e){throw r&&!b(t)&&b(n)&&await f(n,t),e}}function nr(){let e=g.env.CLAUDE_CONFIG_DIR?.trim();return e?T.resolve(e):T.join(xe.homedir(),`.claude`)}var rr=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};const ir=1048576;async function ar(e){let t;try{t=await d(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let r of t){let t=T.join(e,r.name);if(r.isDirectory()){let e=await ar(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else r.isFile()&&/\.jsonl(?:\.zst)?$/u.test(r.name)&&n.files.push(t)}let r=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!r.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function or(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Y(r)?t(r):n=!0},i=async e=>{let t=new we(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
3
|
+
`,e);for(;a!==-1;)r(n.slice(e,a)),e=a+1,a=n.indexOf(`
|
|
4
|
+
`,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await E(y(e,{highWaterMark:ir}),Te({chunkSize:ir}),i):await E(y(e,{highWaterMark:ir}),i),{hasMalformedLines:n}}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e){return typeof e==`string`?e:``}function sr(e){let t=Date.parse(X(e));return Number.isFinite(t)?t:null}function cr(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function lr(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Y).filter(e=>[`text`,`input_text`,`output_text`].includes(X(e.type))).map(e=>X(e.text)).join(`
|
|
5
|
+
`):``}function ur(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function dr(e){let t=await ar(T.join(e,`projects`));if(!t.found)throw new rr(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n=t.unreadable,r=/* @__PURE__ */ new Map;for(let e of t.files)try{let t=await fr(e);if((t.hasMalformedLines||!t.thread)&&(n+=1),t.thread){let e=r.get(t.thread.id);(!e||e.updatedAt<t.thread.updatedAt)&&r.set(t.thread.id,t.thread)}}catch{n+=1}return{threads:r.values().toArray(),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function fr(e){let t=await m(e),n=``,r=``,i=null,a=``,o=``,s=``,c=null,l=1/0,u=0,d=e.split(T.sep).includes(`subagents`),f=d,p=/* @__PURE__ */ new Map,h=0,{hasMalformedLines:g}=await or(e,e=>{d||(n||=X(e.sessionId)),r=X(e.cwd)||r,i=X(e.gitBranch)||i,f||=e.isSidechain===!0;let t=sr(e.timestamp);t!==null&&(l=Math.min(l,t),u=Math.max(u,t)),e.type===`custom-title`?o=X(e.customTitle)||o:e.type===`last-prompt`&&(s=X(e.lastPrompt)||s);let m=Y(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&m.role===`user`&&(a||=lr(m.content).trim()),e.type!==`assistant`||m.role!==`assistant`)return;let g=X(m.model);g&&g!==`<synthetic>`&&(c=g);let ee=Y(m.usage)?m.usage:{},te=[ee.input_tokens,ee.output_tokens,ee.cache_creation_input_tokens,ee.cache_read_input_tokens].reduce((e,t)=>e+cr(t),0),_=X(m.id)||X(e.uuid);_?p.set(_,Math.max(p.get(_)??0,te)):h+=te});return n||=T.basename(e).replace(/\.jsonl(?:\.zst)?$/u,``),Number.isFinite(l)?{thread:{id:n,title:ur(o||a||s,n),cwd:r,gitBranch:i,model:c,archived:!1,subagent:f,createdAt:new Date(l).toISOString(),updatedAt:new Date(u).toISOString(),sizeBytes:t.size,segmentCount:1,tokensUsed:p.values().reduce((e,t)=>e+t,h)},hasMalformedLines:g}:{thread:null,hasMalformedLines:!0}}function pr(){let e=g.env.CODEX_HOME?.trim();return e?T.resolve(e):T.join(xe.homedir(),`.codex`)}async function mr(e){let t=await Promise.all([ar(T.join(e,`sessions`)),ar(T.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new rr(`CODEX_DATA_NOT_FOUND`,`Codex session directories were not found`);let n=t.reduce((e,t)=>e+t.unreadable,0),r=/* @__PURE__ */ new Map;for(let[e,i]of t.entries())for(let t of i.files)try{let i=await hr(t,e===1);if((i.hasMalformedLines||!i.segment)&&(n+=1),i.segment){let e=r.get(i.segment.id)??[];e.push(i.segment),r.set(i.segment.id,e)}}catch{n+=1}return{threads:Array.from(r.values(),gr),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function hr(e,t){let n={id:``,title:``,cwd:``,model:null,gitBranch:null,subagent:!1,archived:t,createdAt:1/0,updatedAt:0,sizeBytes:(await m(e)).size,tokensUsed:0},r=``,{hasMalformedLines:i}=await or(e,e=>{let t=sr(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let i=Y(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=X(i.id),n.cwd||=X(i.cwd),n.model??=X(i.model_provider)||null;let e=Y(i.git)?i.git:{};n.gitBranch??=X(e.branch)||null,n.subagent||=!!i.parent_thread_id||Y(i.source)&&`subagent`in i.source||Y(i.thread_source)&&`subagent`in i.thread_source}else if(e.type===`turn_context`)n.cwd=X(i.cwd)||n.cwd,n.model=X(i.model)||n.model;else if(e.type===`response_item`&&i.type===`message`&&i.role===`user`){let e=lr(i.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(r||=e)}else if(e.type===`token_usage_record`){let e=Y(i.thread_token_usage)?i.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,cr(e.total_tokens))}else if(e.type===`event_msg`&&i.type===`token_count`){let e=Y(i.info)?i.info:{},t=Y(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,cr(t.total_tokens))}});return n.title=r,n.id||=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/u.exec(T.basename(e))?.[1]??``,Number.isFinite(n.createdAt)?{segment:n.id?n:null,hasMalformedLines:i}:{segment:null,hasMalformedLines:!0}}function gr(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:ur(e.find(e=>e.title)?.title??``,t.id),cwd:e.findLast(e=>e.cwd)?.cwd??``,model:e.findLast(e=>e.model)?.model??null,gitBranch:e.findLast(e=>e.gitBranch)?.gitBranch??null,archived:e.every(e=>e.archived),subagent:e.some(e=>e.subagent),createdAt:new Date(Math.min(...e.map(e=>e.createdAt))).toISOString(),updatedAt:new Date(Math.max(...e.map(e=>e.updatedAt))).toISOString(),sizeBytes:e.reduce((e,t)=>e+t.sizeBytes,0),segmentCount:e.length,tokensUsed:Math.max(...e.map(e=>e.tokensUsed))}}var _r=class{codexHome;claudeHome;constructor(e=pr(),t=nr()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return vr(`codex`,await mr(this.codexHome))}async getClaudeSnapshot(){return vr(`claude`,await dr(this.claudeHome))}};function vr(e,t){return{source:e,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),threads:t.threads.toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)),warnings:t.warnings}}var yr=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:v(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function br(e){let t=new yr,n=new Mn,r=Bt(e,t),i=new Cn(e,r.runner,Yn(),Ae,n,e=>t.publish(`data-transfer.status.changed`,e)),a=new Gn(e),o=new Xn(e),s=new Qn,c=new _r;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 xr(e){x(e,{recursive:!0,mode:448}),g.platform!==`win32`&&oe(e,448)}function Sr(e){if(g.platform===`win32`)return;let t=ue(e,`r`);try{le(t)}finally{se(t)}}function Cr(e,t){xr(T.dirname(e));let n=`${e}.${v()}.tmp`;try{let r=ue(n,`wx`,384);try{me(r,`${JSON.stringify(t,null,2)}\n`),le(r)}finally{se(r)}fe(n,e),Sr(T.dirname(e))}finally{C(n,{force:!0})}}const wr=[`providers`,`captures`,`fetchJobs`];function Tr(e){try{let t=JSON.parse(S(T.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return g.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-w(e).mtimeMs>3e4}}var Er=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,xr(e);for(let e of wr)e!==`providers`&&xr(this.collectionPath(e))}collectionPath(e){return T.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return T.relative(this.path,T.join(this.collectionPath(e),`${_(`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=T.join(this.path,`.lock`),n=Date.now();for(;;)try{x(t,{mode:448});try{me(T.join(t,`owner.json`),JSON.stringify({pid:g.pid}),{mode:384})}catch(e){throw C(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,C(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=w(e);if(!Tr(e))return;let n=T.join(e,`recovering`);try{x(n)}catch(e){if(e.code===`EEXIST`){let e=w(n);Tr(n)&&w(n).ino===e.ino&&C(n,{recursive:!0,force:!0})}return}if(me(T.join(n,`owner.json`),JSON.stringify({pid:g.pid}),{mode:384,flag:`wx`}),w(e).ino!==t.ino||!Tr(e)){C(n,{recursive:!0,force:!0});return}C(e,{recursive:!0,force:!0})}catch{}}recover(){let e=T.join(this.path,`.transaction.json`);if(!b(e))return;let t=JSON.parse(S(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=T.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!b(e)){let e=b(t)?de(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,T.join(`providers`,e)))},...e.map(e=>({file:T.join(`providers`,e),value:null}))]};Cr(T.join(this.path,`.transaction.json`),n),this.applyJournal(n)}b(t)&&de(t).length===0&&(pe(t),Sr(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(S(T.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=T.resolve(this.path,t.file),n=T.relative(this.path,e);if(n.startsWith(`..`)||T.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(C(e,{force:!0}),Sr(T.dirname(e))):Cr(e,t.value)}C(T.join(this.path,`.transaction.json`),{force:!0}),Sr(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=T.join(this.path,t);if(!b(e))return;n=JSON.parse(S(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(de(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>T.relative(this.path,T.join(t,e.name))));if(this.changes){let e=T.relative(this.path,t);for(let t of this.changes.keys())T.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=T.join(this.path,`settings.json`);return b(e)?Ge(JSON.parse(S(e,`utf8`))):structuredClone(We)})}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`,Ge(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}))};Cr(T.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 wr){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 Dr(e=qn()){let t=new Er(e);try{return t.transaction(()=>{let n=t.readSettings();b(T.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function Or(){return Jn(),Dr()}const kr={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=Or();t={storage:n,runtime:br(n)},Nr(await e(t))}catch(e){let t=Pr(e);console.error(JSON.stringify({error:t},null,2)),g.exitCode=1}finally{t?.storage.close()}}async function Ar(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 jr():e.input??``:e.inputFile===`-`?await jr():await u(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 jr(){let e=[];for await(let t of g.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function Mr(e){let t=e??g.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 Nr(e){console.log(JSON.stringify(e,null,2))}function Pr(e){return e instanceof Error?{code:Fr(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Fr(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function Ir(e,t){return e.listJobs(t.id)[0]}async function Lr(e,t,n){let r=await Rr(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,rawResponse:i.rawResponse,job:r}}async function Rr(e,t,n){let i=zr(e,t,n);for(;i.status!==`succeeded`&&i.status!==`failed`;)await r(250),i=zr(e,t,n);return i}function zr(e,t,n){let r=e.getJob(t,n);if(!r)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return r}const Br=e({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`]))}}),Vr=e({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})}}),Hr=e({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 Rr(n,e[`capture-id`],r.id)})}}),Ur=e({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:Br,get:Vr,recapture:Hr}}),Wr=e({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(Me(e.filter)))}}),Gr=e({meta:{name:`counts`,description:`Read capture counts`},run(){return Z(({runtime:e})=>e.services.captureRuntime.service.counts())}}),Kr=e({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))}}),qr=e({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(je({url:e.url,userNote:e.note}));return Lr(n,r,Ir(n,r))})}}),Jr=e({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 Lr(n,i,r)})}}),Yr=e({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))}}),Xr=e({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}))}}),Zr=e({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:Wr,counts:Gr,get:Kr,create:qr,recapture:Jr,note:Yr,delete:Xr,jobs:Ur}}),Qr=e({meta:{name:`status`,description:`Read data-transfer and fetch-job status`},run(){return Z(({runtime:e})=>e.services.dataTransferService.getStatus())}}),$r=e({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.dataTransferService,r=Mr(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=ri(e.output);try{await ii(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),ei=e({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(T.resolve(e.file),Mr(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),ti=e({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(T.resolve(e.file),Mr(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),ni=e({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:Qr,export:$r,inspect:ei,import:ti}});function ri(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return tn(T.resolve(n))}async function ii(e,t,n){await c(T.dirname(t),{recursive:!0,mode:448});let r=T.join(T.dirname(t),`.${T.basename(t)}.${v()}.tmp`);try{if(await a(e.filePath,r),g.platform!==`win32`&&await i(r,384),n){await f(r,t);return}if(b(t))throw ai(t);try{await s(r,t)}catch(e){throw oi(e)?ai(t):e}}finally{await p(r,{force:!0})}}function ai(e){return new Q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function oi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const si=e({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return Z(({runtime:e})=>e.services.providerService.list())}}),ci=e({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 Bn;return n})}}),li=e({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:kr,run({args:e}){return Z(async({runtime:t})=>{let n=R(await Ar(e));return t.services.providerService.save(n)})}}),ui=e({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...kr},run({args:e}){return Z(async({runtime:t})=>{let n=R(await Ar(e));return t.services.providerService.save(n,e.id)})}}),di=e({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:[...Ht],required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.setStatus(e.id,Kt(e.status)))}}),fi=e({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))}}),pi=e({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:kr,run({args:e}){return Z(async({runtime:t})=>{let n=Gt(await Ar(e));return t.services.providerService.fetchModelsForConnection(n)})}}),mi=e({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:si,get:ci,create:li,update:ui,"set-status":di,models:fi,"models-for-connection":pi}}),hi=[`agents`,`claude`];function gi(e){if(!vi(e)||!Array.isArray(e.targets))throw new _i(`targets must be an array`);if(e.targets.length===0)throw new _i(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!hi.includes(e))throw new _i(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var _i=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function vi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const yi=e({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return Z(({runtime:e})=>e.services.settingsService.read())}}),bi=e({meta:{name:`update`,description:`Apply a settings patch`},args:kr,run({args:e}){return Z(async({runtime:t})=>{let n=Ke(await Ar(e));return t.services.settingsService.update(n)})}}),xi=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Z(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),Si=e({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=gi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),Ci=e({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:yi,update:bi,open:xi,"download-skill":Si}});function wi(e,t=()=>{}){let n=new O;return n.get(`/`,t=>{let n=Me(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=je(await Ti(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=Ne(await Ti(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 Ti(e){try{return await e.req.json()}catch{throw new Pe(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof Pe)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof k)return e.json({error:{code:t.code,message:t.message}},Ei(t.code));throw t}function Ei(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 Di(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new O;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await ji(t),r=await e.createExport(n),i=y(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(_e.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${T.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 Mi(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 H(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);ki(t,n);let i=Ai(t,`x-foundry-passphrase`);if(!i)throw new H(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=Ai(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await Oi(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return Mi(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 Mi(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return Mi(t,e)}}),r}async function Oi(e,t,n){let r=e.req.raw.body;if(!r)throw new H(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new ve({transform(e,t,r){i+=e.byteLength,i>n?r(new H(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await E(_e.fromWeb(r),a,ce(t,{mode:384}))}catch(e){throw e instanceof H?e:new H(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new H(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function ki(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 H(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new H(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function Ai(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new H(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function ji(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new H(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof H?e:new H(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function Mi(e,t){let n=$t(t);return e.json({error:{code:n.code,message:n.message}},Ni(n.code))}function Ni(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 Pi(e,t=()=>{}){let n=new O;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 Ii(t,e)}}),n.post(`/models`,async t=>{try{let n=Gt(await Fi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return Ii(t,e)}}),n.post(`/`,async n=>{try{let r=R(await Fi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return Ii(n,e)}}),n.put(`/:id`,async n=>{try{let r=R(await Fi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return Ii(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Fi(n),i=Kt(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 Ii(n,e)}}),n}async function Fi(e){try{return await e.req.json()}catch{throw new L(`Request body must be valid JSON`)}}function Ii(e,t){if(t instanceof L)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Bn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Ut)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},502);throw t}function Li(e,t=()=>{},n=new Qn){let r=new O;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Ke(await Ri(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return zi(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=gi(await Ri(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return zi(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Ri(e){try{return await e.req.json()}catch{throw new A(`Request body must be valid JSON`)}}function zi(e,t){if(t instanceof A||t instanceof _i)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof $n)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function Bi(e){let t=new O;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return Vi(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return Vi(t,e)}}),t}function Vi(e,t){if(t instanceof rr)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function Hi(e){let t=new O;return t.get(`/`,t=>Oe(t,async n=>{await Ui(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Wi(n,e)}),c=setInterval(()=>{r||Gi(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 Ui(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Wi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Gi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function Ki(e){return e===`/api`||e.startsWith(`/api/`)}function qi(e,t={}){let n=new O,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Mn,i=t.providerService??new Gn(e),a=t.settingsService??new Xn(e),o=t.settingsSkillCopyService??new Qn,s=t.sessionService??new _r;return n.use(`/api/*`,Nn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Ae,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,Hi(t.eventHub)),n.route(`/api/providers`,Pi(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Li(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),n.route(`/api/sessions`,Bi(s)),t.captureService&&n.route(`/api/captures`,wi(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,Di(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>Ki(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),Ki(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Ji(e,t,n){let r=qi(t,n),i=De({root:e});r.use(`*`,(e,t)=>Ki(e.req.path)?t():i(e,t));let a=De({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!Ki(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&T.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:Yi,join:Xi,resolve:Zi}=T,Qi=Yi(Ce(import.meta.url));function $i(){let e=[Zi(Qi,`web`),Zi(g.cwd(),`dist/web`)].find(e=>b(Xi(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=$i(),onListening:n}){let r=br(e),i=Ji(t,e,r.apiOptions);r.start();let a=Ee({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}`),g.exitCode=1}),a}function ta(e,t){return new Promise((n,r)=>{let i=ke();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function na(e){let t=`xdg-open`,n=[e];g.platform===`darwin`?t=`open`:g.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=be(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ra=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await ta(`127.0.0.1`,11111)}catch(e){ia(e);return}ea({storage:Or(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&na(t)}})}});function ia(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),g.exitCode=1}function aa(){let t,r=e({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await n(t)}});return t=e({meta:{name:`foundry`,version:Ae,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:r,web:ra,settings:Ci,providers:mi,captures:Zr,"data-transfer":ni}}),t}t(aa());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.
|