@dhzh/foundry 4.0.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Foundry
2
2
 
3
3
  Foundry is an AI-native local personal workbench distributed as a CLI. Its
4
- settings, providers, captures, scrape jobs, encrypted data transfer, and bundled
4
+ settings, providers, captures, fetch jobs, encrypted data transfer, and bundled
5
5
  agent skill copy are available as JSON CLI commands for both people and agents.
6
6
  `foundry web` prepares local storage, starts a Hono server, serves the bundled
7
7
  React Web UI, and opens it in the default browser.
@@ -14,11 +14,11 @@ entry point.
14
14
  - Manage model providers using OpenAI Responses, Anthropic Messages, or
15
15
  OpenAI-compatible Chat Completions protocols.
16
16
  - Discover provider models and keep custom model IDs alongside remote models.
17
- - Capture links with Firecrawl or DeepSeek, run background jobs with retries,
18
- and review scrape history and captured Markdown.
17
+ - Save links as agent-facing index cards using the configured capture fetcher,
18
+ run background jobs with retries, and inspect the raw fetcher response.
19
19
  - Configure appearance, language and region, capture behavior, and concurrency.
20
20
  - Export and import an encrypted `.foundry-backup` snapshot containing the
21
- database and application settings.
21
+ JSON records and application settings.
22
22
  - Copy the bundled agent skill into `<home>/.agents/skills/foundry`,
23
23
  `<home>/.claude/skills/foundry`, or both from the CLI or Settings > Advanced.
24
24
 
@@ -27,9 +27,7 @@ entry point.
27
27
  - Node.js 24.22.1 or newer
28
28
  - pnpm 12.15 or newer
29
29
 
30
- The project uses `better-sqlite3`, so pnpm must be allowed to run native package
31
- build scripts. The required allowlist is already declared in
32
- `pnpm-workspace.yaml`.
30
+ Foundry stores its own data as JSON files. No native SQLite package is required.
33
31
 
34
32
  ## Run From Source
35
33
 
@@ -86,7 +84,7 @@ foundry settings download-skill --target .agents,.claude
86
84
 
87
85
  Use `--input-file <path>` or `--input -` for large JSON payloads. Data-transfer
88
86
  passphrases can be passed with `--passphrase` or `FOUNDRY_PASSPHRASE`.
89
- `data-transfer import` validates and replaces the local database and settings in
87
+ `data-transfer import` validates and replaces local JSON records and settings in
90
88
  one command.
91
89
 
92
90
  Skill targets are fixed relative to the user home directory. Here `<home>` is
@@ -120,14 +118,29 @@ production server and static assets.
120
118
  Foundry keeps user data outside the repository in `<home>/.foundry`. `<home>` is
121
119
  `~` on macOS/Linux and `%USERPROFILE%` on Windows:
122
120
 
123
- - `foundry.sqlite`: providers and their credentials, captures, and scrape jobs
124
- - `settings.json`: application settings and capture-fetcher credentials
121
+ - `settings.json`: application settings
122
+ - `providers/<record-key>.json`: providers and credentials
123
+ - `captures/<record-key>.json`: captures
124
+ - `fetch-jobs/<record-key>.json`: fetch jobs, configuration snapshots and responses
125
125
  - `.data-transfer/`: temporary export and import files
126
126
 
127
- Feature commands initialize the directory, open the SQLite database, and apply
128
- Drizzle migrations before running. `foundry web` does the same before the server
129
- starts. A database created by a newer schema version is rejected instead of
130
- being modified.
127
+ Record filenames use a SHA-256 key of the record ID for portable, collision-safe
128
+ paths; the original ID is preserved inside each document.
129
+
130
+ Feature commands initialize JSON storage before running. `foundry web` does the
131
+ same before the server starts. A process lock serializes writers and protects
132
+ consistent reads. Writes use temporary-file replacement and a durable redo
133
+ journal; interrupted committed writes are completed on the next open. Each read
134
+ loads the requested JSON files directly; no cross-request cache or manifest is
135
+ required.
136
+
137
+ A new installation starts directly with default JSON settings and empty
138
+ collections directly under `.foundry`, without a `data/` subdirectory. Startup
139
+ does not inspect or import old SQLite databases. Unrelated files are left alone.
140
+ Node's built-in SQLite reader is used only by the read-only Codex session view.
141
+
142
+ Encrypted exports and imports use JSON snapshots in `data/foundry.json`.
143
+ SQLite-based backup archives are not supported.
131
144
 
132
145
  On POSIX systems, Foundry creates the data directory with `0700` permissions and
133
146
  sensitive files with `0600` permissions.
@@ -148,9 +161,6 @@ The build produces:
148
161
  ```text
149
162
  dist/
150
163
  |-- index.mjs
151
- |-- drizzle/
152
- | |-- *.sql
153
- | `-- meta/
154
164
  |-- skills/
155
165
  | `-- foundry/
156
166
  | |-- SKILL.md
@@ -161,7 +171,7 @@ dist/
161
171
  `-- favicon.png
162
172
  ```
163
173
 
164
- `tsdown` cleans `dist`, bundles the CLI, and copies the Drizzle migrations and
174
+ `tsdown` cleans `dist`, bundles the CLI, and copies the bundled
165
175
  agent skill. Vite then writes the Web UI directly to `dist/web`. Do not add a
166
176
  manual copy step for the Web UI.
167
177
 
@@ -176,8 +186,6 @@ manual copy step for the Web UI.
176
186
  | `pnpm start` | Print the built CLI help |
177
187
  | `pnpm test` | Run behavioral tests |
178
188
  | `pnpm test:coverage` | Run tests with V8 coverage |
179
- | `pnpm db:generate` | Generate a Drizzle migration after schema changes |
180
- | `pnpm db:migrate` | Apply migrations manually to the local database |
181
189
 
182
190
  Run the project scripts with the Node.js version declared in `package.json`.
183
191
  Older Node.js versions cannot run the installed pnpm or project toolchain.
@@ -191,9 +199,8 @@ src/
191
199
  |-- features/ Feature services, validation, repositories, and routes
192
200
  |-- lib/ Small server-side utilities
193
201
  |-- server/ Hono API, static serving, and server entry points
194
- `-- storage/ SQLite, Drizzle schema, paths, and migrations
202
+ `-- storage/ JSON records, process locking, and transaction recovery
195
203
  skills/foundry/ Agent-facing CLI usage skill and references
196
- drizzle/ Generated migration SQL and metadata
197
204
  test/ Behavioral API and feature tests
198
205
  ```
199
206
 
@@ -215,7 +222,7 @@ Verify package contents with:
215
222
  pnpm pack --dry-run
216
223
  ```
217
224
 
218
- The tarball must include the CLI, Web assets, Drizzle migrations, and bundled
225
+ The tarball must include the CLI, Web assets, and bundled
219
226
  agent skill.
220
227
 
221
228
  ## License
package/dist/index.mjs CHANGED
@@ -1,2 +1,5 @@
1
1
  #!/usr/bin/env node
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,rename as d,rm as f,stat as p,writeFile as ee}from"node:fs/promises";import m from"node:process";import{createCipheriv as te,createDecipheriv as ne,createHash as re,randomBytes as ie,randomUUID as h,scrypt as ae}from"node:crypto";import{and as g,count as _,desc as oe,eq as v,inArray as se,isNull as y,ne as ce,sql as le}from"drizzle-orm";import{index as ue,integer as b,sqliteTable as de,text as x,uniqueIndex as fe}from"drizzle-orm/sqlite-core";import{chmodSync as pe,createReadStream as me,createWriteStream as S,existsSync as C,mkdirSync as he,readFileSync as ge,renameSync as _e,rmSync as ve,writeFileSync as ye}from"node:fs";import w from"node:path";import be,{homedir as xe}from"node:os";import Se from"better-sqlite3";import{drizzle as Ce}from"drizzle-orm/better-sqlite3";import{migrate as we}from"drizzle-orm/better-sqlite3/migrator";import{fileURLToPath as Te}from"node:url";import{pipeline as Ee}from"node:stream/promises";import De from"yauzl";import Oe from"yazl";import{Buffer as T}from"node:buffer";import{Readable as ke,Transform as Ae}from"node:stream";import{matchedRoutes as je}from"hono/route";import{spawn as Me}from"node:child_process";import{serve as Ne}from"@hono/node-server";import{serveStatic as Pe}from"@hono/node-server/serve-static";import{Hono as E}from"hono";import{streamSSE as Fe}from"hono/streaming";import{createServer as Ie}from"node:net";var Le=`4.0.1`;function Re(e){if(!He(e)||typeof e.url!=`string`)throw new Ve(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function ze(e){return e===`no-successful`?`no-successful`:`all`}function Be(e){if(!He(e)||typeof e.userNote!=`string`)throw new Ve(`userNote must be a string`);return e.userNote}var Ve=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function He(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const D=de(`providers`,{id:x(`id`).primaryKey().notNull(),name:x(`name`).notNull(),protocol:x(`protocol`).notNull(),baseURL:x(`base_url`).notNull(),apiKey:x(`api_key`).notNull().default(``),customModels:x(`custom_models`).notNull().default(`[]`),status:x(`status`).notNull().default(`active`),createdAt:b(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:b(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:b(`deleted_at`,{mode:`timestamp_ms`})}),O=de(`captures`,{id:x(`id`).primaryKey().notNull(),url:x(`url`).notNull(),title:x(`title`),userNote:x(`user_note`),latestSuccessfulJobId:x(`latest_successful_job_id`),createdAt:b(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:b(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:b(`deleted_at`,{mode:`timestamp_ms`})},e=>[fe(`captures_url_active_unique`).on(e.url).where(le`${e.deletedAt} is null`),ue(`captures_created_at_idx`).on(e.createdAt)]),k=de(`scrape_jobs`,{id:x(`id`).primaryKey().notNull(),captureId:x(`capture_id`).notNull().references(()=>O.id),fetcher:x(`fetcher`).notNull(),configSnapshot:x(`config_snapshot`).notNull(),rawResponseJson:x(`raw_response_json`),status:x(`status`).notNull().default(`pending`),errorCode:x(`error_code`),errorMessage:x(`error_message`),createdAt:b(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:b(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:b(`deleted_at`,{mode:`timestamp_ms`})},e=>[fe(`scrape_jobs_one_active_per_capture`).on(e.captureId).where(le`${e.status} in ('pending', 'running') and ${e.deletedAt} is null`),ue(`scrape_jobs_capture_created_at_idx`).on(e.captureId,e.createdAt)]);var Ue=class{db;constructor(e){this.db=e}findCapture(e){return this.db.select().from(O).where(g(v(O.id,e),y(O.deletedAt))).get()??null}findJob(e){return this.db.select().from(k).where(v(k.id,e)).get()??null}list(e){let t=e===`no-successful`?g(y(O.deletedAt),y(O.latestSuccessfulJobId)):y(O.deletedAt);return this.db.select().from(O).where(t).orderBy(oe(O.createdAt)).all().map(e=>We(e))}counts(){let e=y(O.deletedAt);return{all:this.db.select({value:_()}).from(O).where(e).get()?.value??0,noSuccessful:this.db.select({value:_()}).from(O).where(g(e,y(O.latestSuccessfulJobId))).get()?.value??0}}get(e){let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.db.select().from(k).where(g(v(k.id,t.latestSuccessfulJobId),v(k.captureId,e),y(k.deletedAt))).get():void 0;return{capture:We(t),content:n?Ke(n):null}}findActiveByURL(e){return this.db.select().from(O).where(g(v(O.url,e),y(O.deletedAt))).get()??null}createWithJob(e,t,n){let r=/* @__PURE__ */ new Date,i=h(),a=h();this.db.transaction(o=>{o.insert(O).values({id:i,url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null}).run(),o.insert(k).values({id:a,captureId:i,fetcher:n.fetcher,configSnapshot:JSON.stringify(n),rawResponseJson:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:r,updatedAt:r,deletedAt:null}).run()});let o=this.findCapture(i);if(!o)throw Error(`Capture was not created`);return{capture:We(o),jobId:a}}hasActiveJob(e){return!!this.db.select({id:k.id}).from(k).where(g(v(k.captureId,e),se(k.status,[`pending`,`running`]),y(k.deletedAt))).get()}createJob(e,t){let n=/* @__PURE__ */ new Date,r=h();this.db.insert(k).values({id:r,captureId:e,fetcher:t.fetcher,configSnapshot:JSON.stringify(t),rawResponseJson:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}).run();let i=this.findJob(r);if(!i)throw Error(`Scrape job was not created`);return{job:Ge(i),jobId:r}}delete(e){let t=/* @__PURE__ */ new Date;return this.db.update(O).set({deletedAt:t,updatedAt:t}).where(g(v(O.id,e),y(O.deletedAt))).returning().all().length!==0&&(this.db.update(k).set({deletedAt:t,updatedAt:t}).where(g(v(k.captureId,e),y(k.deletedAt))).run(),!0)}updateNote(e,t){let n=t.trim()||null,r=this.db.update(O).set({userNote:n,updatedAt:/* @__PURE__ */ new Date}).where(g(v(O.id,e),y(O.deletedAt))).returning().all();return r.length===0?null:We(r[0])}listJobs(e){return this.db.select().from(k).where(g(v(k.captureId,e),y(k.deletedAt))).orderBy(oe(k.createdAt)).all().map(e=>Ge(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Ge(n.job):null}getJobContext(e){let t=this.findJob(e);if(!t||t.deletedAt)return null;let n=this.findCapture(t.captureId);return n?{job:t,capture:n}:null}markRunning(e){this.db.update(k).set({status:`running`,updatedAt:/* @__PURE__ */ new Date}).where(g(v(k.id,e),v(k.status,`pending`))).run()}markSucceeded(e,t,n,r){let i=/* @__PURE__ */ new Date;this.db.transaction(a=>{a.update(k).set({status:`succeeded`,rawResponseJson:JSON.stringify(r),errorCode:null,errorMessage:null,updatedAt:i}).where(v(k.id,e)).run(),a.update(O).set({...n&&{title:n},latestSuccessfulJobId:e,updatedAt:i}).where(v(O.id,t)).run()})}markFailed(e,t,n){this.db.update(k).set({status:`failed`,errorCode:t,errorMessage:n,updatedAt:/* @__PURE__ */ new Date}).where(v(k.id,e)).run()}recoverRunningJobs(){let e=this.db.select({id:k.id}).from(k).where(g(v(k.status,`running`),y(k.deletedAt))).all();return e.length>0&&this.db.update(k).set({status:`pending`}).where(g(v(k.status,`running`),y(k.deletedAt))).run(),e.length}pendingJobIDs(){return this.db.select({id:k.id}).from(k).where(g(v(k.status,`pending`),y(k.deletedAt))).orderBy(k.createdAt).all().map(e=>e.id)}};function We(e){return{id:e.id,url:e.url,title:e.title,userNote:e.userNote,latestSuccessfulJobId:e.latestSuccessfulJobId,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}function Ge(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}function Ke(e){if(!e.rawResponseJson)return null;try{let t=JSON.parse(e.rawResponseJson);if(!Je(t))return null;let n=typeof t.markdown==`string`?t.markdown:typeof t.content==`string`?t.content:null;return n===null?null:{jobId:e.id,markdown:e.fetcher===`deepseek`?qe(n):n}}catch{return null}}function qe(e){return e.replaceAll(/\\(.)/g,(e,t)=>/\p{P}/u.test(t)?t:e)}function Je(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(){return w.join(be.homedir(),`.foundry`)}function Ye(){let e=A();return he(e,{recursive:!0,mode:448}),m.platform!==`win32`&&pe(e,448),e}function Xe(){return w.join(A(),`foundry.sqlite`)}function j(){return w.join(A(),`settings.json`)}function Ze(){return w.join(A(),`.data-transfer`)}const Qe=[`system`,`light`,`dark`],$e=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],et=[`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`],tt=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],nt=[`firecrawl`,`deepseek`],rt={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,scrapeConcurrency:2,firecrawl:{apiKey:``},deepseek:{apiKey:``}}}}};function it(e){let t=P(e)?e:{},n=P(t.workspace)?t.workspace:{},r=P(n.appearance)?n.appearance:{},i=P(n[`language-region`])?n[`language-region`]:{},a=P(t.features)?t.features:{},o=P(a.library)?a.library:{},s=P(o.captures)?o.captures:{},c=P(s.firecrawl)?s.firecrawl:{},l=P(s.deepseek)?s.deepseek:{};return{workspace:{appearance:{"color-theme":dt(r[`color-theme`],Qe,rt.workspace.appearance[`color-theme`])},"language-region":{language:dt(i.language,$e,rt.workspace[`language-region`].language),"time-format":dt(i[`time-format`],et,rt.workspace[`language-region`][`time-format`]),"time-zone":dt(i[`time-zone`],tt,rt.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:lt(s.fetcher),maxAttempts:ft(s.maxAttempts,10,1),scrapeConcurrency:ft(s.scrapeConcurrency,5,2),firecrawl:{apiKey:ht(c.apiKey)},deepseek:{apiKey:ht(l.apiKey)}}}}}}function at(e){if(!P(e))throw new M(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=N(e.theme,Qe,`theme`)),`language`in e&&(t.language=N(e.language,$e,`language`)),`timeFormat`in e&&(t.timeFormat=N(e.timeFormat,et,`timeFormat`)),`timezone`in e&&(t.timezone=N(e.timezone,tt,`timezone`)),`captures`in e&&(t.captures=ct(e.captures)),t}function ot(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,scrapeConcurrency:r?.scrapeConcurrency??n.scrapeConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey},deepseek:{apiKey:r?.deepseekApiKey??n.deepseek.apiKey}}}}}}function st(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,scrapeConcurrency:t.scrapeConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey},deepseek:{apiKey:t.deepseek.apiKey}}}}}}var M=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function ct(e){if(!P(e))throw new M(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:N(e.fetcher,nt,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=pt(e.maxAttempts,10,`captures.maxAttempts`)),`scrapeConcurrency`in e&&(t.scrapeConcurrency=pt(e.scrapeConcurrency,5,`captures.scrapeConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=mt(e.firecrawlApiKey,`captures.firecrawlApiKey`)),`deepseekApiKey`in e&&(t.deepseekApiKey=mt(e.deepseekApiKey,`captures.deepseekApiKey`)),t}function lt(e){return ut(e,nt)}function ut(e,t){return typeof e==`string`&&t.includes(e)?e:null}function dt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function N(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new M(`Invalid ${n}`);return e}function ft(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function pt(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new M(`${n} must be an integer from 1 to ${t}`);return e}function mt(e,t){if(typeof e!=`string`)throw new M(`${t} must be a string`);return e.trim()}function ht(e){return typeof e==`string`?e:``}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e=j()){try{return it(JSON.parse(ge(e,`utf8`)))}catch{return it(rt)}}function gt(e=j()){return st(F(e))}function _t(e,t=j()){let n=ot(F(t),e);return vt(n,t),st(n)}function vt(e,t=j()){he(w.dirname(t),{recursive:!0});let n=`${t}.tmp`;ye(n,`${JSON.stringify(e,null,2)}\n`,{mode:384}),_e(n,t)}var I=class extends Error{code;isRetryable;statusCode;constructor(e,t,n,r){super(t),this.code=e,this.isRetryable=n,this.statusCode=r,this.name=`FetcherError`}};function yt(e){return e===408||e===429||e>=500}function bt(e){return e instanceof I?e:e instanceof Error&&e.name===`TimeoutError`?new I(`timeout`,`The page fetch timed out`,!0):e instanceof TypeError?new I(`network_error`,e.message,!0):new I(`fetch_failed`,e instanceof Error?e.message:`The page fetch failed`,!1)}async function xt(e,t,n=fetch){try{let r=await n(`https://api.deepseek.com/v1/tools/fetch`,{method:`POST`,headers:{authorization:`Bearer ${t}`,"content-type":`application/json`},body:JSON.stringify({url:e}),signal:AbortSignal.timeout(6e4)});if(!r.ok)throw new I(`http_${r.status}`,`DeepSeek returned ${r.status}`,yt(r.status),r.status);let i=await r.json();if(!St(i)||typeof i.title!=`string`||typeof i.content!=`string`)throw new I(`invalid_response`,`DeepSeek returned an invalid response`,!1);return{title:i.title.trim()||null,rawResponse:i}}catch(e){throw bt(e)}}function St(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Ct(e,t,n=fetch){try{let r=await n(`https://api.firecrawl.dev/v1/scrape`,{method:`POST`,headers:{authorization:`Bearer ${t}`,"content-type":`application/json`},body:JSON.stringify({url:e,formats:[`markdown`]}),signal:AbortSignal.timeout(6e4)});if(!r.ok)throw new I(`http_${r.status}`,`Firecrawl returned ${r.status}`,yt(r.status),r.status);let i=wt(await r.json());if(!i)throw new I(`invalid_response`,`Firecrawl returned an invalid response`,!1);return i}catch(e){throw bt(e)}}function wt(e){if(!Tt(e))return null;let t=Tt(e.data)?e.data:e;if((typeof t.markdown==`string`?t.markdown:null)===null)return null;let n=Tt(t.metadata)?t.metadata:{};return{title:(typeof n.title==`string`?n.title.trim():``)||null,rawResponse:t}}function Tt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Et(e,t,n=fetch){return t.fetcher===`firecrawl`?Ct(e,t.apiKey,n):xt(e,t.apiKey,n)}var Dt=class{repository;settingsPath;onChanged;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;paused=!1;constructor(e,t,n=()=>{}){this.repository=e,this.settingsPath=t,this.onChanged=n}schedule(){if(this.paused)return;let e=F(this.settingsPath).features.library.captures.scrapeConcurrency;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=Ot(t.job.configSnapshot)}catch(n){let r=n instanceof Error?n.message:`Invalid scrape 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`});for(let r=1;r<=n.maxAttempts;r+=1)try{let r=await Et(t.capture.url,n);this.repository.markSucceeded(e,t.capture.id,r.title,r.rawResponse),this.onChanged({captureId:t.capture.id,jobId:e,status:`succeeded`});return}catch(i){let a=bt(i);if(r>=n.maxAttempts||!a.isRetryable){this.failJob(e,t.capture.id,a.code,a.message);return}await At(kt(r))}}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 Ot(e){let t=JSON.parse(e);if(!jt(t)||t.fetcher!==`firecrawl`&&t.fetcher!==`deepseek`||typeof t.apiKey!=`string`||!t.apiKey||typeof t.maxAttempts!=`number`)throw Error(`Invalid scrape job configuration`);return{fetcher:t.fetcher,apiKey:t.apiKey,maxAttempts:Math.min(10,Math.max(1,Math.trunc(t.maxAttempts)))}}function kt(e){let t=1e3*2**(e-1);return Math.min(3e4,t)+Math.floor(Math.random()*250)}function At(e){return new Promise(t=>{setTimeout(t,e)})}function jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var L=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}},Mt=class{repository;settingsPath;runner;constructor(e,t,n){this.repository=e,this.settingsPath=t,this.runner=n}executionConfig(){let e=F(this.settingsPath).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 L(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Nt(e.url);if(!t)throw new L(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new L(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new L(`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 L(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new L(`ACTIVE_JOB_EXISTS`,`This capture already has an active scrape job`);let t=this.executionConfig();if(!t)throw new L(`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 L(`ACTIVE_JOB_EXISTS`,`This capture already has an active scrape job`);if(!this.repository.delete(e))throw new L(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new L(`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 Nt(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Pt(e,t,n){let r=new Ue(e.db),i=new Dt(r,t,e=>n?.publish(`capture.job.changed`,e));return{service:new Mt(r,t,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const Ft=w.dirname(Te(import.meta.url));function It(e){let t=new Se(e,{fileMustExist:!0,readonly:!0});try{return Number(t.pragma(`user_version`,{simple:!0}))}finally{t.close()}}function Lt(e=Xe(),t=zt()){he(w.dirname(e),{recursive:!0});let n=new Se(e,{timeout:5e3});m.platform!==`win32`&&pe(e,384),n.pragma(`foreign_keys = ON`);let r=Number(n.pragma(`user_version`,{simple:!0}));if(r>1)throw n.close(),Error(`The Foundry database was created by a newer application version`);let i=Ce({client:n});try{we(i,{migrationsFolder:t}),r!==1&&n.pragma(`user_version = 1`)}catch(e){throw n.close(),e}return{client:n,db:i,path:e,schemaVersion:1}}function Rt(){return Ye(),Lt()}function zt(){let e=[w.resolve(Ft,`drizzle`),w.resolve(Ft,`../../drizzle`),w.resolve(m.cwd(),`drizzle`)].find(e=>C(w.join(e,`meta`,`_journal.json`)));if(!e)throw Error(`Foundry database migrations were not found`);return e}const Bt=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Vt=[`active`,`disabled`,`deleted`];var R=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Ht=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function z(e){if(!Jt(e))throw new R(`Provider input must be an object`);return{name:B(e.name,`name`),protocol:Kt(e.protocol),baseURL:qt(e.baseURL),apiKey:e.apiKey===void 0?``:B(e.apiKey,`apiKey`,{allowEmpty:!0}),customModels:Gt(e.customModels)}}function Ut(e){if(!Jt(e))throw new R(`Provider connection must be an object`);return{protocol:Kt(e.protocol),baseURL:qt(e.baseURL),apiKey:e.apiKey===void 0?``:B(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Wt(e){if(typeof e!=`string`||!Vt.includes(e))throw new R(`Invalid provider status`);return e}function Gt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new R(`customModels must be an array`);return e.map(e=>{if(!Jt(e))throw new R(`Each custom model must be an object`);return{id:B(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:B(e.displayName,`customModels.displayName`)}})}function Kt(e){if(typeof e!=`string`||!Bt.includes(e))throw new R(`Invalid provider protocol`);return e}function qt(e){let t=B(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new R(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function B(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new R(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new R(`${t} is required`);return r}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var V=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function Yt(e){return e instanceof V?e:new V(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const H=`database/foundry.sqlite`,U=`settings.json`,Xt=`manifest.json`;function Zt(e){if(!nn(e)||e.format!==`foundry.snapshot`)throw new V(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=tn(e.archiveVersion,`archiveVersion`);if(t!==1)throw new V(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=en(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new V(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!nn(e.database)||!nn(e.settings))throw new V(`INVALID_ARCHIVE`,`Archive file metadata is missing`);let r=tn(e.settings.version,`settings.version`);if(r>1)throw new V(`UNSUPPORTED_ARCHIVE`,`The settings version is newer than this Foundry version`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:en(e.appVersion,`appVersion`),createdAt:n,database:{...$t(e.database,H),schemaVersion:tn(e.database.schemaVersion,`database.schemaVersion`)},settings:{...$t(e.settings,U),version:r}}}function Qt(e){return e.toLowerCase().endsWith(`.foundry-backup`)?e:`${e}.foundry-backup`}function $t(e,t){if(!nn(e)||e.path!==t)throw new V(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=en(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new V(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:tn(e.bytes,`bytes`),sha256:n}}function en(e,t){if(typeof e!=`string`||e.length===0)throw new V(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function tn(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new V(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const rn=/* @__PURE__ */ new Set([Xt,H,U]);async function an(e,t){let n=new Oe.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await Ee(n.outputStream,S(t,{mode:384}))}async function on(e,t){let n=await sn(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(!rn.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=w.join(t,e.fileName);await c(w.dirname(o),{recursive:!0}),await Ee(await cn(n,e),S(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 f(t,{recursive:!0,force:!0}),e}finally{n.close()}for(let e of rn)if(!r.has(e))throw await f(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function sn(e){return new Promise((t,n)=>{De.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function cn(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}const W=T.from(`FOUNDRYX`,`ascii`),G=`aes-256-gcm`,ln=`scrypt`,K={N:131072,r:8,p:1};async function un(e,t,n){let r=ie(16),a=ie(12),o={version:1,cipher:G,kdf:{name:ln,salt:r.toString(`base64`),...K,keyLength:32},nonce:a.toString(`base64`)},s=T.from(JSON.stringify(o),`utf8`),c=fn(s.byteLength),u=T.concat([c,s]),d=await pn(n,r,K);try{let n=await l(t,`w`,384);try{await n.write(u)}finally{await n.close()}await Ee(me(e),mn(d,a,u),S(t,{flags:`r+`,mode:384,start:u.byteLength})),await i(t,384)}catch(e){throw await f(t,{force:!0}),new V(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function dn(e,t,n){let r;try{let a=(await p(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 _n(o,13,0),!s.subarray(0,W.byteLength).equals(W))throw Error(`The export file signature is invalid`);if(s.readUInt8(W.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=s.readUInt32BE(W.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 _n(o,e,13),u=await _n(o,16,a-16)}finally{await o.close()}let d=gn(JSON.parse(c.toString(`utf8`)));r=await pn(n,d.salt,d.header.kdf);let f=T.concat([s,c]);await Ee(me(e,{start:13+c.byteLength,end:a-16-1}),hn(r,d.nonce,f,u),S(t,{mode:384})),await i(t,384)}catch(e){throw await f(t,{force:!0}),e instanceof V?e:new V(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function fn(e){let t=T.alloc(13);return W.copy(t,0),t.writeUInt8(1,W.byteLength),t.writeUInt32BE(e,W.byteLength+1),t}function pn(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 mn(e,t,n){let r=te(G,e,t,{authTagLength:16});return r.setAAD(n),new Ae({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,T.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function hn(e,t,n,r){let i=ne(G,e,t,{authTagLength:16});return i.setAAD(n),new Ae({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 gn(e){if(!vn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==G||!vn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==ln||typeof t.salt!=`string`||t.N!==K.N||t.r!==K.r||t.p!==K.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=T.from(t.salt,`base64`),r=T.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:G,kdf:{name:ln,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function _n(e,t,n){let r=T.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var yn=class{database;settingsPath;runner;temporaryRoot;appVersion;workspaceMutationGate;onStatusChanged;busy=!1;stagedImports=/* @__PURE__ */ new Map;constructor(e,t,n,r,i,a,o=()=>{}){this.database=e,this.settingsPath=t,this.runner=n,this.temporaryRoot=r,this.appVersion=i,this.workspaceMutationGate=a,this.onStatusChanged=o}async runExclusive(e){if(this.busy||!this.workspaceMutationGate.tryBeginTransfer())throw new V(`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 kn(this.temporaryRoot);let t=w.join(this.temporaryRoot,`${e}-${h()}`);return await c(t,{recursive:!1,mode:448}),await kn(t),t}async clearStagedImports(){let e=this.stagedImports.values().toArray();this.stagedImports.clear(),await Promise.all(e.map(e=>this.removeQuietly(e.directory)))}async removeQuietly(e){try{await f(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:w.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){ve(this.temporaryRoot,{recursive:!0,force:!0}),he(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:xn(this.database.db),isBusy:this.busy}}async createExport(e){return bn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=w.join(t,`foundry.sqlite`),r=w.join(t,U),i=w.join(t,Xt),a=w.join(t,`foundry.zip`),o=w.join(this.temporaryRoot,`foundry-${Date.now()}.foundry-backup`);this.runner.pause();try{q(this.database.db),await this.database.client.backup(n),await An(n),vt(F(this.settingsPath),r),await An(r);let t=Sn(this.database.db),s=It(n);if(s!==1)throw new V(`IO_ERROR`,`The database snapshot has an unexpected schema version`);let c={format:`foundry.snapshot`,archiveVersion:1,appVersion:this.appVersion,createdAt:(/* @__PURE__ */ new Date()).toISOString(),database:{...await wn(n,H),schemaVersion:s},settings:{...await wn(r,U),version:1}};return await ee(i,`${JSON.stringify(c,null,2)}\n`,{mode:384}),await an([{entryPath:Xt,filePath:i},{entryPath:H,filePath:n},{entryPath:U,filePath:r}],a),await un(a,o,e),await An(o),{filePath:o,providerCount:t.providers,captureCount:t.captures,jobCount:t.jobs}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=w.basename(e)){return bn(t),this.runExclusive(async()=>{q(this.database.db),await this.clearStagedImports();let r=h(),i=await this.createWorkDirectory(`import-${r}`),a=w.join(i,`archive.zip`),o=w.join(i,`extracted`),s;try{await c(o,{recursive:!1,mode:448}),await dn(e,a,t);let l=await on(a,o),d=Zt(JSON.parse(await u(l[Xt],`utf8`)));if(d.database.schemaVersion>1)throw new V(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let p=l[H],ee=l[U];if(await Tn(p,d.database),await Tn(ee,d.settings),It(p)!==d.database.schemaVersion)throw new V(`INVALID_ARCHIVE`,`The archived database schema does not match its manifest`);En(p),F(ee),s=Lt(p),q(s.db),Dn(s.db),On(s.db);let m=Sn(s.db),te={importId:r,fileName:w.basename(n),exportedAt:d.createdAt,appVersion:d.appVersion,databaseSchemaVersion:d.database.schemaVersion,settingsVersion:d.settings.version,providerCount:m.providers,captureCount:m.captures,jobCount:m.jobs};return this.stagedImports.set(r,{databasePath:p,directory:i,preview:te,settingsPath:ee}),await f(a,{force:!0}),te}catch(e){throw this.stagedImports.delete(r),await this.removeQuietly(i),e instanceof V?e:new V(`INVALID_ARCHIVE`,`The Foundry export could not be inspected`,{cause:e})}finally{s?.client.close()}})}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 V(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();let n=F(this.settingsPath),r=!1;try{q(this.database.db);let n=Lt(t.databasePath);try{q(n.db),Dn(n.db),On(n.db);let e=n.db.select().from(D).all(),i=n.db.select().from(O).all(),a=n.db.select().from(k).all();vt(F(t.settingsPath),this.settingsPath),r=!0,this.database.db.transaction(t=>{t.delete(k).run(),t.delete(O).run(),t.delete(D).run(),e.length>0&&t.insert(D).values(e).run(),i.length>0&&t.insert(O).values(i).run(),a.length>0&&t.insert(k).values(a).run()})}finally{n.client.close()}this.stagedImports.delete(e),await this.removeQuietly(t.directory)}catch(e){throw r&&vt(n,this.settingsPath),e}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){w.dirname(e)===this.temporaryRoot&&await f(e,{force:!0})}};function bn(e){if(e.length===0)throw new V(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function xn(e){return e.select({total:_()}).from(k).where(g(se(k.status,[`pending`,`running`]),y(k.deletedAt))).get()?.total??0}function q(e){if(xn(e)>0)throw new V(`ACTIVE_JOBS`,`Finish active scrape jobs before transferring data`)}function Sn(e){return{providers:e.select({total:_()}).from(D).get()?.total??0,captures:e.select({total:_()}).from(O).get()?.total??0,jobs:e.select({total:_()}).from(k).get()?.total??0}}async function Cn(e){let t=re(`sha256`);for await(let n of me(e))t.update(n);return t.digest(`hex`)}async function wn(e,t){return{path:t,bytes:(await p(e)).size,sha256:await Cn(e)}}async function Tn(e,t){if((await p(e)).size!==t.bytes||await Cn(e)!==t.sha256)throw new V(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function En(e){let t=new Se(e,{fileMustExist:!0,readonly:!0});try{if(t.pragma(`integrity_check`,{simple:!0})!==`ok`)throw new V(`INVALID_ARCHIVE`,`The archived database failed its integrity check`);if(t.pragma(`foreign_key_check`).length>0)throw new V(`INVALID_ARCHIVE`,`The archived database contains invalid references`)}finally{t.close()}}function Dn(e){for(let t of e.select().from(O).all()){if(!t.latestSuccessfulJobId||t.deletedAt)continue;let n=e.select({captureId:k.captureId,status:k.status}).from(k).where(v(k.id,t.latestSuccessfulJobId)).get();if(n?.captureId!==t.id||n.status!==`succeeded`)throw new V(`INVALID_ARCHIVE`,`A capture points to an invalid successful scrape job`)}}function On(e){let t=/* @__PURE__ */ new Set([`active`,`disabled`,`deleted`]),n=/* @__PURE__ */ new Set([`pending`,`running`,`succeeded`,`failed`]),r=/* @__PURE__ */ new Set([`firecrawl`,`deepseek`]);for(let n of e.select().from(D).all()){if(!t.has(n.status))throw new V(`INVALID_ARCHIVE`,`A provider record is invalid`);try{z({name:n.name,protocol:n.protocol,baseURL:n.baseURL,customModels:JSON.parse(n.customModels)})}catch{throw new V(`INVALID_ARCHIVE`,`A provider record is invalid`)}}for(let t of e.select().from(O).all())try{let e=new URL(t.url);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new V(`INVALID_ARCHIVE`,`A capture URL is invalid`)}for(let t of e.select().from(k).all())if(!n.has(t.status)||!r.has(t.fetcher))throw new V(`INVALID_ARCHIVE`,`A scrape job record is invalid`)}function kn(e){return m.platform===`win32`?Promise.resolve():i(e,448)}function An(e){return m.platform===`win32`?Promise.resolve():i(e,384)}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 je(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}var J=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 J(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new J(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new J(`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 J(`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 J(`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 Y=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Bn=class{db;constructor(e){this.db=e}list(e=/* @__PURE__ */ new Set){return this.db.select().from(D).where(ce(D.status,`deleted`)).orderBy(oe(D.updatedAt)).all().map(t=>({...Vn(t),isInUse:e.has(t.id)}))}get(e){let t=this.db.select().from(D).where(v(D.id,e)).get();return t?Vn(t):null}getConnection(e){let t=this.db.select().from(D).where(v(D.id,e)).get();return!t||t.status===`deleted`?null:{protocol:t.protocol,baseURL:t.baseURL,apiKey:t.apiKey}}save(e,t){let n=t?this.db.select().from(D).where(v(D.id,t)).get():void 0;if(t&&!n)throw new Y;let r=/* @__PURE__ */ new Date,i={name:e.name,protocol:e.protocol,baseURL:e.baseURL,apiKey:e.apiKey,customModels:JSON.stringify(e.customModels),updatedAt:r};return Vn(n&&t?this.db.update(D).set(i).where(v(D.id,t)).returning().get():this.db.insert(D).values({id:h(),...i,status:`active`,createdAt:r,deletedAt:null}).returning().get())}setStatus(e,t,n=/* @__PURE__ */ new Set){if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Ht;let r=this.db.update(D).set({status:t,deletedAt:t===`deleted`?/* @__PURE__ */ new Date:null,updatedAt:/* @__PURE__ */ new Date}).where(v(D.id,e)).returning().all();if(r.length===0)throw new Y;return Vn(r[0])}};function Vn(e){return{id:e.id,name:e.name,protocol:e.protocol,baseURL:e.baseURL,apiKey:e.apiKey,customModels:Gt(JSON.parse(e.customModels)),status:e.status,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),deletedAt:e.deletedAt?.toISOString()??null}}function Hn(e=j()){let t=F(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Un(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wn=class{settingsPath;repository;constructor(e,t=j()){this.settingsPath=t,this.repository=new Bn(e.db)}list(){return this.repository.list(Hn(this.settingsPath))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Y;return Fn(t)}fetchModelsForConnection(e){return Fn(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t,Hn(this.settingsPath))}};function Gn(e){let t=m.platform===`darwin`?`open`:m.platform===`win32`?`explorer`:`xdg-open`,n=Me(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}var Kn=class{settingsPath;configFolder;openFolder;constructor(e=j(),t=A(),n=Gn){this.settingsPath=e,this.configFolder=t,this.openFolder=n}read(){return{...gt(this.settingsPath),configFolder:this.configFolder}}update(e){return{..._t(e,this.settingsPath),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const qn=w.dirname(Te(import.meta.url)),X=`foundry`;var Jn=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=xe()}={}){this.configuredSkillRoot=e,this.homeDirectory=w.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Xn();if(!C(w.join(t,`SKILL.md`)))throw new Yn(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=w.join(n,X),i=w.join(n,`.${X}-${h()}.tmp`),a=w.join(n,`.${X}-${h()}.backup`);try{return await c(n,{recursive:!0}),await o(t,i,{recursive:!0,errorOnExist:!0}),await Zn(i,r,a),{target:e,destination:r}}catch(e){throw await f(i,{recursive:!0,force:!0}),e instanceof Yn?e:new Yn(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return w.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:w.join(this.getTargetParent(e),X)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},Yn=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function Xn(){let e=[w.resolve(qn,`skills`,X),w.resolve(qn,`..`,`..`,`..`,`skills`,X),w.resolve(m.cwd(),`skills`,X)].find(e=>C(w.join(e,`SKILL.md`)));if(!e)throw new Yn(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function Zn(e,t,n){let r=C(t);r&&await d(t,n);try{await d(e,t),r&&await f(n,{recursive:!0,force:!0})}catch(e){throw r&&!C(t)&&C(n)&&await d(n,t),e}}var Qn=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:h(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function $n(e){let t=j(),n=new Qn,r=new Mn,i=Pt(e,t,n),a=new yn(e,t,i.runner,Ze(),Le,r,e=>n.publish(`data-transfer.status.changed`,e)),o=new Wn(e,t),s=new Kn(t),c=new Jn;return{services:{captureRuntime:i,dataTransferService:a,providerService:o,settingsService:s,settingsSkillCopyService:c},apiOptions:{settingsPath:t,captureService:i.service,dataTransferService:a,providerService:o,settingsService:s,settingsSkillCopyService:c,workspaceMutationGate:r,eventHub:n,onSettingsChanged:i.notifySettingsChanged},start(){a.cleanupStaleTransfers(),i.start()}}}const er={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=Rt();t={database:n,runtime:$n(n)},ir(await e(t))}catch(e){let t=ar(e);console.error(JSON.stringify({error:t},null,2)),m.exitCode=1}finally{t?.database.client.close()}}async function tr(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 nr():e.input??``:e.inputFile===`-`?await nr():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 nr(){let e=[];for await(let t of m.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function rr(e){let t=e??m.env.FOUNDRY_PASSPHRASE;if(!t)throw new Q(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function ir(e){console.log(JSON.stringify(e,null,2))}function ar(e){return e instanceof Error?{code:or(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function or(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function sr(e,t){return e.listJobs(t.id)[0]}async function cr(e,t,n){let r=await lr(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,content:i.content,job:r}}async function lr(e,t,n){let i=ur(e,t,n);for(;i.status!==`succeeded`&&i.status!==`failed`;)await r(250),i=ur(e,t,n);return i}function ur(e,t,n){let r=e.getJob(t,n);if(!r)throw new Q(`JOB_NOT_FOUND`,`Scrape job not found`);return r}const dr=e({meta:{name:`list`,description:`List scrape 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`]))}}),fr=e({meta:{name:`get`,description:`Read one scrape job owned by a capture`,alias:[`show`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0},"job-id":{type:`positional`,description:`Scrape 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`,`Scrape job not found`);return n})}}),pr=e({meta:{name:`recapture`,description:`Run a new scrape 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 lr(n,e[`capture-id`],r.id)})}}),mr=e({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:dr,get:fr,recapture:pr}}),hr=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(ze(e.filter)))}}),gr=e({meta:{name:`counts`,description:`Read capture counts`},run(){return Z(({runtime:e})=>e.services.captureRuntime.service.counts())}}),_r=e({meta:{name:`get`,description:`Read a capture and its latest Markdown content`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.get(e.id))}}),vr=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(Re({url:e.url,userNote:e.note}));return cr(n,r,sr(n,r))})}}),yr=e({meta:{name:`recapture`,description:`Create a new scrape 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 cr(n,i,r)})}}),br=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 scrape 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}))}}),Sr=e({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:hr,counts:gr,get:_r,create:vr,recapture:yr,note:br,delete:xr,jobs:mr}}),Cr=e({meta:{name:`status`,description:`Read data-transfer and scrape-job status`},run(){return Z(({runtime:e})=>e.services.dataTransferService.getStatus())}}),wr=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=rr(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=Or(e.output);try{await kr(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),Tr=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(w.resolve(e.file),rr(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),Er=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(w.resolve(e.file),rr(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),Dr=e({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:Cr,export:wr,inspect:Tr,import:Er}});function Or(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return Qt(w.resolve(n))}async function kr(e,t,n){await c(w.dirname(t),{recursive:!0,mode:448});let r=w.join(w.dirname(t),`.${w.basename(t)}.${h()}.tmp`);try{if(await a(e.filePath,r),m.platform!==`win32`&&await i(r,384),n){await d(r,t);return}if(C(t))throw Ar(t);try{await s(r,t)}catch(e){throw jr(e)?Ar(t):e}}finally{await f(r,{force:!0})}}function Ar(e){return new Q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function jr(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Mr=e({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return Z(({runtime:e})=>e.services.providerService.list())}}),Nr=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 Y;return n})}}),Pr=e({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:er,run({args:e}){return Z(async({runtime:t})=>{let n=z(await tr(e));return t.services.providerService.save(n)})}}),Fr=e({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...er},run({args:e}){return Z(async({runtime:t})=>{let n=z(await tr(e));return t.services.providerService.save(n,e.id)})}}),Ir=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:[...Vt],required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.setStatus(e.id,Wt(e.status)))}}),Lr=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))}}),Rr=e({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:er,run({args:e}){return Z(async({runtime:t})=>{let n=Ut(await tr(e));return t.services.providerService.fetchModelsForConnection(n)})}}),zr=e({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:Mr,get:Nr,create:Pr,update:Fr,"set-status":Ir,models:Lr,"models-for-connection":Rr}}),Br=[`agents`,`claude`];function Vr(e){if(!Ur(e)||!Array.isArray(e.targets))throw new Hr(`targets must be an array`);if(e.targets.length===0)throw new Hr(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Br.includes(e))throw new Hr(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Hr=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Ur(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Wr=e({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return Z(({runtime:e})=>e.services.settingsService.read())}}),Gr=e({meta:{name:`update`,description:`Apply a settings patch`},args:er,run({args:e}){return Z(async({runtime:t})=>{let n=at(await tr(e));return t.services.settingsService.update(n)})}}),Kr=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Z(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),qr=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=Vr({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),Jr=e({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:Wr,update:Gr,open:Kr,"download-skill":qr}});function Yr(e,t=()=>{}){let n=new E;return n.get(`/`,t=>{let n=ze(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=Re(await Xr(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=Be(await Xr(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 Xr(e){try{return await e.req.json()}catch{throw new Ve(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof Ve)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof L)return e.json({error:{code:t.code,message:t.message}},Zr(t.code));throw t}function Zr(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 Qr(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new E;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await ni(t),r=await e.createExport(n),i=me(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(ke.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${w.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 ri(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 V(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);ei(t,n);let i=ti(t,`x-foundry-passphrase`);if(!i)throw new V(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=ti(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await $r(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return ri(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 ri(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return ri(t,e)}}),r}async function $r(e,t,n){let r=e.req.raw.body;if(!r)throw new V(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new Ae({transform(e,t,r){i+=e.byteLength,i>n?r(new V(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await Ee(ke.fromWeb(r),a,S(t,{mode:384}))}catch(e){throw e instanceof V?e:new V(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new V(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function ei(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 V(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new V(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function ti(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new V(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function ni(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new V(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof V?e:new V(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function ri(e,t){let n=Yt(t);return e.json({error:{code:n.code,message:n.message}},ii(n.code))}function ii(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 ai(e,t=()=>{}){let n=new E;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 si(t,e)}}),n.post(`/models`,async t=>{try{let n=Ut(await oi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return si(t,e)}}),n.post(`/`,async n=>{try{let r=z(await oi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return si(n,e)}}),n.put(`/:id`,async n=>{try{let r=z(await oi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return si(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await oi(n),i=Wt(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 si(n,e)}}),n}async function oi(e){try{return await e.req.json()}catch{throw new R(`Request body must be valid JSON`)}}function si(e,t){if(t instanceof R)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Y)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Ht)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof J)return e.json({error:{code:t.code,message:t.message}},502);throw t}function ci(e,t=()=>{},n=new Jn){let r=new E;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=at(await li(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return ui(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=Vr(await li(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return ui(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function li(e){try{return await e.req.json()}catch{throw new M(`Request body must be valid JSON`)}}function ui(e,t){if(t instanceof M||t instanceof Hr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Yn)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function di(e){let t=new E;return t.get(`/`,t=>Fe(t,async n=>{await fi(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||pi(n,e)}),c=setInterval(()=>{r||mi(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 fi(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function pi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function mi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function hi(e){return e===`/api`||e.startsWith(`/api/`)}function gi(e,t={}){let n=new E,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Mn,i=t.providerService??new Wn(e,t.settingsPath),a=t.settingsService??new Kn(t.settingsPath),o=t.settingsSkillCopyService??new Jn;return n.use(`/api/*`,Nn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Le,database:{schemaVersion:e.schemaVersion}})),t.eventHub&&n.route(`/api/events`,di(t.eventHub)),n.route(`/api/providers`,ai(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,ci(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),t.captureService&&n.route(`/api/captures`,Yr(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,Qr(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>hi(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),hi(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function _i(e,t,n){let r=gi(t,n),i=Pe({root:e});r.use(`*`,(e,t)=>hi(e.req.path)?t():i(e,t));let a=Pe({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!hi(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&w.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:vi,join:yi,resolve:bi}=w,xi=vi(Te(import.meta.url));function Si(){let e=[bi(xi,`web`),bi(m.cwd(),`dist/web`)].find(e=>C(yi(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ci({database:e,webRoot:t=Si(),onListening:n}){let r=$n(e),i=_i(t,e,r.apiOptions);r.start();let a=Ne({fetch:i.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return a.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),m.exitCode=1}),a}function wi(e,t){return new Promise((n,r)=>{let i=Ie();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function Ti(e){let t=`xdg-open`,n=[e];m.platform===`darwin`?t=`open`:m.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=Me(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const Ei=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 wi(`127.0.0.1`,11111)}catch(e){Di(e);return}Ci({database:Rt(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Ti(t)}})}});function Di(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),m.exitCode=1}function Oi(){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:Le,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:r,web:Ei,settings:Jr,providers:zr,captures:Sr,"data-transfer":Dr}}),t}t(Oi());export{};
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
+ `,o);for(;s!==-1;)t(a.slice(o,s)),o=s+1,s=a.indexOf(`
4
+ `,o);a=a.slice(o),e=ge(n,i,0,i.length,null)}a+=r.end(),a.length>0&&t(a)}finally{le(n)}}function hr(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)K(n)&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
5
+ `)}function gr(e){return K(e)?[e.input_tokens,e.output_tokens,e.cache_creation_input_tokens,e.cache_read_input_tokens].reduce((e,t)=>e+Math.max(0,Sr(t)??0),0):0}function _r(e){if(!e.endsWith(or))return!1;try{return pe(e).isFile()}catch{return!1}}function vr(e){return e.length>0&&e===x.basename(e)&&e!==`.`&&e!==`..`}function yr(e,t){let n=x.relative(e,t);return n.length>0&&n!==`..`&&!n.startsWith(`..${x.sep}`)&&!x.isAbsolute(n)}function br(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xr(e){return typeof e==`string`?e:``}function q(e){return typeof e==`string`&&e.trim().length>0?e.trim():null}function Sr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Cr(e){if(typeof e==`number`)return!Number.isFinite(e)||e<=0?null:e<1e10?e*1e3:e;if(typeof e!=`string`||e.trim().length===0)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function wr(){let e=h.env.CODEX_HOME?.trim();return e?x.resolve(e):x.join(Ee.homedir(),`.codex`)}const Tr=/^rollout-\d{4}-\d{2}-\d{2}T[\d-]+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/u;function Er(e){let t=Ar(e);if(t.length===0)throw new G(`CODEX_DATA_NOT_FOUND`,`Codex state database was not found`);let n=[];for(let e of t){let t=null;try{t=Mr(e),Nr(t,`threads`)&&n.push({path:e,modifiedAt:b(e).mtimeMs})}catch{}finally{t?.close()}}if(n.length===0)throw new G(`UNSUPPORTED_CODEX_SCHEMA`,`Codex state database does not contain a supported threads table`);return n.toSorted((e,t)=>t.modifiedAt-e.modifiedAt)[0].path}function Dr(e){let t=Mr(e);try{let e=new Set(t.prepare(`PRAGMA table_info(threads)`).all().map(e=>e.name));if(!e.has(`id`)||!e.has(`updated_at`))throw new G(`UNSUPPORTED_CODEX_SCHEMA`,`Codex threads table is missing required columns`);let n=(t,n=`NULL`)=>e.has(t)?`"${t}"`:n,r=`SELECT ${[`${n(`id`)} AS id`,`${n(`title`,`''`)} AS title`,`${n(`name`)} AS name`,`${n(`first_user_message`)} AS first_user_message`,`${n(`preview`)} AS preview`,`${n(`cwd`,`''`)} AS cwd`,`${n(`updated_at`)} AS updated_at`,`${n(`updated_at_ms`)} AS updated_at_ms`,`${n(`created_at`)} AS created_at`,`${n(`created_at_ms`)} AS created_at_ms`,`${n(`archived`,`0`)} AS archived`,`${n(`source`,`''`)} AS source`,`${n(`model`)} AS model`,`${n(`model_provider`)} AS model_provider`,`${n(`tokens_used`,`0`)} AS tokens_used`,`${n(`rollout_path`)} AS rollout_path`,`${n(`git_branch`)} AS git_branch`].join(`, `)} FROM threads`;return t.prepare(r).all().map(e=>{let t=X(e.updated_at_ms)??(X(e.updated_at)??0)*1e3,n=X(e.created_at_ms)??(X(e.created_at)??0)*1e3;return{id:J(e.id),title:J(e.title),name:Y(e.name),firstUserMessage:Y(e.first_user_message),preview:Y(e.preview),cwd:J(e.cwd),updatedAtMs:t,createdAtMs:n,archived:X(e.archived)===1,source:J(e.source),model:Y(e.model),modelProvider:Y(e.model_provider),tokensUsed:X(e.tokens_used)??0,rolloutPath:Y(e.rollout_path),gitBranch:Y(e.git_branch)}}).filter(e=>e.id.length>0)}catch(e){throw e instanceof G?e:new G(`CODEX_READ_FAILED`,e instanceof Error?e.message:`Unable to read Codex threads`)}finally{t.close()}}function Or(e){let t=x.join(e,`.codex-global-state.json`);if(!_(t))return Pr();let n;try{n=JSON.parse(v(t,`utf8`))}catch{return Pr()}if(!Fr(n))return Pr();let r=/* @__PURE__ */ new Map,i=Fr(n[`local-projects`])?n[`local-projects`]:null;if(i)for(let[e,t]of Object.entries(i)){if(!Fr(t))continue;let n=J(t.id)||e,i=J(t.name)||n,a=Array.isArray(t.rootPaths)?t.rootPaths.filter(e=>typeof e==`string`):[];r.set(n,{id:n,name:i,roots:a})}let a=/* @__PURE__ */ new Map,o=Fr(n[`thread-project-assignments`])?n[`thread-project-assignments`]:null;if(o)for(let[e,t]of Object.entries(o))Fr(t)&&typeof t.projectId==`string`&&a.set(e,t.projectId);let s=new Set(Array.isArray(n[`projectless-thread-ids`])?n[`projectless-thread-ids`].filter(e=>typeof e==`string`):[]),c=i?[]:[{code:`PROJECTS_UNAVAILABLE`}];return{projects:r.values().toArray(),assignments:a,projectless:s,warnings:c}}function kr(e){let t=[],n=jr(x.join(e,`sessions`),t);n+=jr(x.join(e,`archived_sessions`),t);let r=/* @__PURE__ */ new Map;for(let e of t){let t=Tr.exec(x.basename(e));if(!t)continue;let i;try{i=b(e).size}catch{n+=1;continue}let a=t[1],o=r.get(a)??{bytes:0,segments:0};r.set(a,{bytes:o.bytes+i,segments:o.segments+1})}return{files:r,unreadable:n}}function Ar(e){let t=[];for(let n of[e,x.join(e,`sqlite`)]){let e;try{e=_e(n,{withFileTypes:!0})}catch{continue}for(let r of e)r.isFile()&&/^state.*\.sqlite$/u.test(r.name)&&t.push(x.join(n,r.name))}return t}function jr(e,t){if(!_(e))return 0;let n;try{n=_e(e,{withFileTypes:!0})}catch{return 1}let r=0;for(let i of n){let n=x.join(e,i.name);i.isDirectory()?r+=jr(n,t):i.isFile()&&Tr.test(i.name)&&t.push(n)}return r}function Mr(t){let{DatabaseSync:n}=e(import.meta.url)(`node:sqlite`),r=new n(t,{readOnly:!0});return r.exec(`PRAGMA busy_timeout = 5000`),r}function Nr(e,t){return e.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`).get(t)!==void 0}function Pr(){return{projects:[],assignments:/* @__PURE__ */ new Map,projectless:/* @__PURE__ */ new Set,warnings:[{code:`PROJECTS_UNAVAILABLE`}]}}function Fr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e){return typeof e==`string`?e:``}function Y(e){return typeof e==`string`&&e.trim().length>0?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}var Ir=class{codexHome;claudeHome;constructor(e=wr(),t=ar()){this.codexHome=e,this.claudeHome=t}getCodexSnapshot(){let e=Dr(Er(this.codexHome)),t=Or(this.codexHome),n=kr(this.codexHome),r=new Map(t.projects.map(e=>[e.id,e])),i=e.map(e=>Lr(e,t,r,n.files)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`codex`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.projects,threads:i,warnings:[...t.warnings,...n.unreadable>0?[{code:`ROLLOUT_FILES_UNREADABLE`,count:n.unreadable}]:[]]}}getClaudeSnapshot(){let e=sr(this.claudeHome),t=/* @__PURE__ */ new Map,n=e.sessions.map(e=>Br(e,t)).toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return{source:`claude`,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),projects:t.values().toArray(),threads:n,warnings:[]}}};function Lr(e,t,n,r){let i=t.assignments.get(e.id),a=i?n.get(i):void 0,o=a?`assigned`:t.projectless.has(e.id)?`projectless`:`unassigned`,s=r.get(e.id)??Ur(e.rolloutPath),c=e.updatedAtMs>0?e.updatedAtMs:e.createdAtMs,l=e.createdAtMs>0?e.createdAtMs:c;return{id:e.id,title:Rr(e),projectId:a?.id??null,projectBucket:o,archived:e.archived,subagent:Wr(e.source),createdAt:new Date(l).toISOString(),updatedAt:new Date(c).toISOString(),sizeBytes:s?.bytes??0,segmentCount:s?.segments??0,tokensUsed:Math.max(0,Math.trunc(e.tokensUsed)),model:e.model??e.modelProvider,cwd:e.cwd,gitBranch:e.gitBranch}}function Rr(e){return zr([e.name,e.title,e.firstUserMessage,e.preview,e.id.slice(0,8)])}function zr(e){for(let t of e){let e=(t??``).replaceAll(/\s+/gu,` `).trim();if(e.length>0)return e.slice(0,240)}return``}function Br(e,t){let n=Vr(e.projectPath);if(n){let r=t.get(n);r?r.roots.includes(e.projectPath)||r.roots.push(e.projectPath):t.set(n,{id:n,name:Hr(e.projectPath),roots:[e.projectPath]})}return{id:e.id,title:e.title,projectId:n,projectBucket:n?`assigned`:`projectless`,archived:!1,subagent:e.subagent,createdAt:new Date(e.createdAtMs).toISOString(),updatedAt:new Date(e.updatedAtMs).toISOString(),sizeBytes:e.sizeBytes,segmentCount:1,tokensUsed:e.tokensUsed,model:e.model,cwd:e.cwd,gitBranch:e.gitBranch}}function Vr(e){return e?`claude:${e}`:null}function Hr(e){return e.split(/[\\/]/u).filter(Boolean).at(-1)??e}function Ur(e){if(!e)return null;for(let t of[e,`${e}.zst`])try{return{bytes:b(t).size,segments:1}}catch{}return null}function Wr(e){let t=e.trim();if(!t.startsWith(`{`))return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&!Array.isArray(e)&&`subagent`in e}catch{return t.includes(`"subagent"`)}}var Gr=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:g(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function Kr(e){let t=new Gr,n=new Ln,r=Gt(e,t),i=new kn(e,r.runner,$n(),Pe,n,e=>t.publish(`data-transfer.status.changed`,e)),a=new Yn(e),o=new er(e),s=new nr,c=new Ir;return{services:{captureRuntime:r,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c},apiOptions:{captureService:r.service,dataTransferService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c,workspaceMutationGate:n,eventHub:t,onSettingsChanged:r.notifySettingsChanged},start(){i.cleanupStaleTransfers(),r.start()}}}function qr(e){me(e,{recursive:!0,mode:448}),h.platform!==`win32`&&ce(e,448)}function Jr(e){if(h.platform===`win32`)return;let t=he(e,`r`);try{fe(t)}finally{le(t)}}function Yr(e,t){qr(x.dirname(e));let n=`${e}.${g()}.tmp`;try{let r=he(n,`wx`,384);try{ye(r,`${JSON.stringify(t,null,2)}\n`),fe(r)}finally{le(r)}ve(n,e),Jr(x.dirname(e))}finally{y(n,{force:!0})}}const Xr=[`providers`,`captures`,`fetchJobs`];function Zr(e){try{let t=JSON.parse(v(x.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return h.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-b(e).mtimeMs>3e4}}var Qr=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,qr(e);for(let e of Xr)qr(this.collectionPath(e))}collectionPath(e){return x.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return x.relative(this.path,x.join(this.collectionPath(e),`${re(`sha256`).update(t).digest(`hex`)}.json`))}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=x.join(this.path,`.lock`),n=Date.now();for(;;)try{me(t,{mode:448});try{ye(x.join(t,`owner.json`),JSON.stringify({pid:h.pid}),{mode:384})}catch(e){throw y(t,{recursive:!0,force:!0}),e}break}catch(e){if(e.code!==`EEXIST`)throw e;if(this.recoverLock(t),Date.now()-n>1e4)throw Error(`Foundry storage is busy in another process`,{cause:e});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}try{return this.recover(),this.lockDepth=1,e()}finally{this.lockDepth=0,y(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=b(e);if(!Zr(e))return;let n=x.join(e,`recovering`);try{me(n)}catch(e){if(e.code===`EEXIST`){let e=b(n);Zr(n)&&b(n).ino===e.ino&&y(n,{recursive:!0,force:!0})}return}if(ye(x.join(n,`owner.json`),JSON.stringify({pid:h.pid}),{mode:384,flag:`wx`}),b(e).ino!==t.ino||!Zr(e)){y(n,{recursive:!0,force:!0});return}y(e,{recursive:!0,force:!0})}catch{}}recover(){let e=x.join(this.path,`.transaction.json`);if(!_(e))return;let t=JSON.parse(v(e,`utf8`));this.applyJournal(t)}applyJournal(e){for(let t of e.changes){let e=x.resolve(this.path,t.file),n=x.relative(this.path,e);if(n.startsWith(`..`)||x.isAbsolute(n)||!/^(?:settings\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(y(e,{force:!0}),Jr(x.dirname(e))):Yr(e,t.value)}y(x.join(this.path,`.transaction.json`),{force:!0}),Jr(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=x.join(this.path,t);if(!_(e))return;n=JSON.parse(v(e,`utf8`))}let r=n;if(this.recordPath(e,r.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(r)}all(e){return this.locked(()=>{let t=this.collectionPath(e),n=new Set(_e(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>x.relative(this.path,x.join(t,e.name))));if(this.changes){let e=x.relative(this.path,t);for(let t of this.changes.keys())x.dirname(t)===e&&n.add(t)}let r=[];for(let t of n){let n=this.readRecord(e,t);n&&r.push(n)}return r})}get(e,t){return this.locked(()=>this.readRecord(e,this.recordPath(e,t)))}readSettings(){return this.locked(()=>{if(this.changes?.has(`settings.json`))return structuredClone(this.changes.get(`settings.json`));let e=x.join(this.path,`settings.json`);return _(e)?Je(JSON.parse(v(e,`utf8`))):structuredClone(E)})}put(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(this.recordPath(e,t.id),structuredClone(t))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,Je(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t=!1;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);if(this.changes.size>0){let e={changes:[...this.changes].map(([e,t])=>({file:e,value:t}))};Yr(x.join(this.path,`.transaction.json`),e),t=!0,this.applyJournal(e)}return n}catch(e){throw t&&this.recover(),e}finally{this.changes=null}})}snapshot(){return this.locked(()=>({formatVersion:1,settings:this.readSettings(),providers:this.all(`providers`),captures:this.all(`captures`),fetchJobs:this.all(`fetchJobs`)}))}replace(e){this.transaction(()=>{for(let t of Xr){let n=this.all(t);for(let e of n)this.changes?.set(this.recordPath(t,e.id),null);let r=e[t];for(let e of r)this.put(t,e)}this.setSettings(e.settings)})}close(){this.closed=!0}};function $r(e=Zn()){let t=new Qr(e);try{return t.transaction(()=>{let n=t.readSettings();_(x.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function ei(){return Qn(),$r()}const ti={input:{type:`string`,description:`JSON payload; use "-" to read it from stdin`,valueHint:`json`},"input-file":{type:`string`,description:`Path to a JSON payload file`,valueHint:`path`}};async function Z(e){let t;try{let n=ei();t={storage:n,runtime:Kr(n)},ai(await e(t))}catch(e){let t=oi(e);console.error(JSON.stringify({error:t},null,2)),h.exitCode=1}finally{t?.storage.close()}}async function ni(e){if(e.input!==void 0&&e.inputFile!==void 0)throw new Q(`CONFLICTING_INPUT`,`Use either --input or --input-file, not both`);if(e.input===void 0&&e.inputFile===void 0)throw new Q(`INPUT_REQUIRED`,`Provide a JSON payload with --input or --input-file`);let t;try{t=e.inputFile===void 0?e.input===`-`?await ri():e.input??``:e.inputFile===`-`?await ri():await d(e.inputFile,`utf8`)}catch(e){throw new Q(`INPUT_READ_FAILED`,e instanceof Error?e.message:`Unable to read JSON input`)}try{return JSON.parse(t)}catch{throw new Q(`INVALID_JSON`,`Input must be valid JSON`)}}async function ri(){let e=[];for await(let t of h.stdin)e.push(typeof t==`string`?t:t.toString(`utf8`));return e.join(``)}function ii(e){let t=e??h.env.FOUNDRY_PASSPHRASE;if(!t)throw new Q(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var Q=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function ai(e){console.log(JSON.stringify(e,null,2))}function oi(e){return e instanceof Error?{code:si(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function si(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}function ci(e,t){return e.listJobs(t.id)[0]}async function li(e,t,n){let r=await ui(e,t.id,n.id),i=e.get(t.id);return{capture:i.capture,rawResponse:i.rawResponse,job:r}}async function ui(e,t,n){let r=di(e,t,n);for(;r.status!==`succeeded`&&r.status!==`failed`;)await i(250),r=di(e,t,n);return r}function di(e,t,n){let r=e.getJob(t,n);if(!r)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return r}const fi=t({meta:{name:`list`,description:`List fetch jobs for a capture`,alias:[`ls`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.listJobs(e[`capture-id`]))}}),pi=t({meta:{name:`get`,description:`Read one fetch job owned by a capture`,alias:[`show`]},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0},"job-id":{type:`positional`,description:`Fetch job ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.captureRuntime.service.getJob(e[`capture-id`],e[`job-id`]);if(!n)throw new Q(`JOB_NOT_FOUND`,`Fetch job not found`);return n})}}),mi=t({meta:{name:`recapture`,description:`Run a new fetch job for a capture and wait for completion`},args:{"capture-id":{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e[`capture-id`]);return ui(n,e[`capture-id`],r.id)})}}),hi=t({meta:{name:`jobs`,description:`Inspect and run jobs for a capture`},subCommands:{list:fi,get:pi,recapture:mi}}),gi=t({meta:{name:`list`,description:`List captures`,alias:[`ls`]},args:{filter:{type:`enum`,description:`Capture filter`,options:[`all`,`no-successful`],default:`all`}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.list(Ie(e.filter)))}}),_i=t({meta:{name:`counts`,description:`Read capture counts`},run(){return Z(({runtime:e})=>e.services.captureRuntime.service.counts())}}),vi=t({meta:{name:`get`,description:`Read a capture and its latest successful fetcher response`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.get(e.id))}}),yi=t({meta:{name:`create`,description:`Capture a URL`,alias:[`add`]},args:{url:{type:`positional`,description:`HTTP or HTTPS URL`,required:!0},note:{type:`string`,description:`User note`,valueHint:`text`}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.create(Fe({url:e.url,userNote:e.note}));return li(n,r,ci(n,r))})}}),bi=t({meta:{name:`recapture`,description:`Create a new fetch job for an existing capture`},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.captureRuntime.service,r=n.recapture(e.id),i=n.get(e.id).capture;return li(n,i,r)})}}),xi=t({meta:{name:`note`,description:`Replace a capture user note`},args:{id:{type:`positional`,description:`Capture ID`,required:!0},note:{type:`positional`,description:`New note; use an empty string to clear it`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.captureRuntime.service.updateNote(e.id,e.note))}}),Si=t({meta:{name:`delete`,description:`Delete a capture and its fetch jobs`,alias:[`remove`,`rm`]},args:{id:{type:`positional`,description:`Capture ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>(t.services.captureRuntime.service.delete(e.id),{deleted:!0,id:e.id}))}}),Ci=t({meta:{name:`captures`,description:`Manage captured pages`,alias:[`capture`]},subCommands:{list:gi,counts:_i,get:vi,create:yi,recapture:bi,note:xi,delete:Si,jobs:hi}}),wi=t({meta:{name:`status`,description:`Read data-transfer and fetch-job status`},run(){return Z(({runtime:e})=>e.services.dataTransferService.getStatus())}}),Ti=t({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.dataTransferService,r=ii(e.passphrase);n.cleanupStaleTransfers();let i=await n.createExport(r),a=ki(e.output);try{await Ai(i,a,e.force)}finally{await n.removeExportFile(i.filePath)}return{...i,filePath:a}})}}),Ei=t({meta:{name:`inspect`,description:`Validate a Foundry backup without importing it`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(x.resolve(e.file),ii(e.passphrase));try{return r}finally{await n.cancelImport(r.importId)}})}}),Di=t({meta:{name:`import`,description:`Validate and replace local Foundry data from a backup`,alias:[`restore`]},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return Z(async({runtime:t})=>{let n=t.services.dataTransferService;n.cleanupStaleTransfers();let r=await n.inspectImport(x.resolve(e.file),ii(e.passphrase));return await n.commitImport(r.importId),{status:`imported`,preview:r}})}}),Oi=t({meta:{name:`data-transfer`,description:`Export or import encrypted Foundry backups`,alias:[`data`]},subCommands:{status:wi,export:Ti,inspect:Ei,import:Di}});function ki(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`;return ln(x.resolve(n))}async function Ai(e,t,n){await l(x.dirname(t),{recursive:!0,mode:448});let r=x.join(x.dirname(t),`.${x.basename(t)}.${g()}.tmp`);try{if(await o(e.filePath,r),h.platform!==`win32`&&await a(r,384),n){await f(r,t);return}if(_(t))throw ji(t);try{await c(r,t)}catch(e){throw Mi(e)?ji(t):e}}finally{await p(r,{force:!0})}}function ji(e){return new Q(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Mi(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const Ni=t({meta:{name:`list`,description:`List providers and model credentials`,alias:[`ls`]},run(){return Z(({runtime:e})=>e.services.providerService.list())}}),Pi=t({meta:{name:`get`,description:`Read one provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=t.services.providerService.get(e.id);if(!n)throw new H;return n})}}),Fi=t({meta:{name:`create`,description:`Create a provider from a JSON payload`,alias:[`add`]},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Yt(await ni(e));return t.services.providerService.save(n)})}}),Ii=t({meta:{name:`update`,description:`Replace a provider using a JSON payload`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},...ti},run({args:e}){return Z(async({runtime:t})=>{let n=Yt(await ni(e));return t.services.providerService.save(n,e.id)})}}),Li=t({meta:{name:`set-status`,description:`Change a provider status`},args:{id:{type:`positional`,description:`Provider ID`,required:!0},status:{type:`enum`,description:`New provider status`,options:[...qt],required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.setStatus(e.id,Zt(e.status)))}}),Ri=t({meta:{name:`models`,description:`Discover models for a saved provider`},args:{id:{type:`positional`,description:`Provider ID`,required:!0}},run({args:e}){return Z(({runtime:t})=>t.services.providerService.fetchModels(e.id))}}),zi=t({meta:{name:`models-for-connection`,description:`Discover models before saving a provider`},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Xt(await ni(e));return t.services.providerService.fetchModelsForConnection(n)})}}),Bi=t({meta:{name:`providers`,description:`Manage model providers`,alias:[`provider`]},subCommands:{list:Ni,get:Pi,create:Fi,update:Ii,"set-status":Li,models:Ri,"models-for-connection":zi}}),Vi=[`agents`,`claude`];function Hi(e){if(!Wi(e)||!Array.isArray(e.targets))throw new Ui(`targets must be an array`);if(e.targets.length===0)throw new Ui(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Vi.includes(e))throw new Ui(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Ui=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Wi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gi=t({meta:{name:`get`,description:`Read Foundry settings as JSON`,alias:[`show`]},run(){return Z(({runtime:e})=>e.services.settingsService.read())}}),Ki=t({meta:{name:`update`,description:`Apply a settings patch`},args:ti,run({args:e}){return Z(async({runtime:t})=>{let n=Ye(await ni(e));return t.services.settingsService.update(n)})}}),qi=t({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return Z(({runtime:e})=>e.services.settingsService.openConfigFolder())}}),Ji=t({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return Z(({runtime:t})=>{let n=Hi({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.services.settingsSkillCopyService.copyToTargets(n.targets)})}}),Yi=t({meta:{name:`settings`,description:`Read or update Foundry settings`},subCommands:{get:Gi,update:Ki,open:qi,"download-skill":Ji}});function Xi(e,t=()=>{}){let n=new w;return n.get(`/`,t=>{let n=Ie(t.req.query(`filter`));return t.json(e.list(n))}),n.get(`/counts`,t=>t.json(e.counts())),n.post(`/`,async n=>{try{let r=Fe(await Zi(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return $(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return $(t,e)}}),n.post(`/:id/recapture`,n=>{try{let r=n.req.param(`id`),i=e.recapture(r);return t({captureId:r,action:`recaptured`}),n.json(i,202)}catch(e){return $(n,e)}}),n.delete(`/:id`,n=>{try{let r=n.req.param(`id`);return e.delete(r),t({captureId:r,action:`deleted`}),n.body(null,204)}catch(e){return $(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Le(await Zi(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return $(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return $(t,e)}}),n}async function Zi(e){try{return await e.req.json()}catch{throw new Re(`Request body must be valid JSON`)}}function $(e,t){if(t instanceof Re)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof T)return e.json({error:{code:t.code,message:t.message}},Qi(t.code));throw t}function Qi(e){switch(e){case`CAPTURE_NOT_FOUND`:return 404;case`CAPTURE_ALREADY_EXISTS`:case`ACTIVE_JOB_EXISTS`:return 409;case`FETCHER_NOT_CONFIGURED`:return 503;default:return 400}}function $i(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new w;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await ra(t),r=await e.createExport(n),i=ue(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(Se.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${x.basename(r.filePath)}"`,"x-foundry-provider-count":String(r.providerCount),"x-foundry-capture-count":String(r.captureCount),"x-foundry-job-count":String(r.jobCount)})}catch(e){return ia(t,e)}}),r.post(`/inspect`,async t=>{let r;try{if(t.req.header(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/octet-stream`)throw new F(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);ta(t,n);let i=na(t,`x-foundry-passphrase`);if(!i)throw new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=na(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await ea(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return ia(t,e)}finally{await r?.cleanup()}}),r.post(`/imports/:id/commit`,async n=>{try{return await e.commitImport(n.req.param(`id`)),t(),n.json({status:`imported`})}catch(e){return ia(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return ia(t,e)}}),r}async function ea(e,t,n){let r=e.req.raw.body;if(!r)throw new F(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new Ce({transform(e,t,r){i+=e.byteLength,i>n?r(new F(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await S(Se.fromWeb(r),a,de(t,{mode:384}))}catch(e){throw e instanceof F?e:new F(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new F(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function ta(e,t){let n=e.req.header(`content-length`);if(n===void 0)return;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new F(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new F(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function na(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new F(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function ra(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof F?e:new F(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function ia(e,t){let n=on(t);return e.json({error:{code:n.code,message:n.message}},aa(n.code))}function aa(e){switch(e){case`IMPORT_NOT_FOUND`:return 404;case`ACTIVE_JOBS`:case`BUSY`:return 409;case`IO_ERROR`:return 500;default:return 400}}function oa(e,t=()=>{}){let n=new w;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return ca(t,e)}}),n.post(`/models`,async t=>{try{let n=Xt(await sa(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ca(t,e)}}),n.post(`/`,async n=>{try{let r=Yt(await sa(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ca(n,e)}}),n.put(`/:id`,async n=>{try{let r=Yt(await sa(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ca(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await sa(n),i=Zt(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return ca(n,e)}}),n}async function sa(e){try{return await e.req.json()}catch{throw new M(`Request body must be valid JSON`)}}function ca(e,t){if(t instanceof M)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof H)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Jt)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof V)return e.json({error:{code:t.code,message:t.message}},502);throw t}function la(e,t=()=>{},n=new nr){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Ye(await ua(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return da(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=Hi(await ua(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return da(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function ua(e){try{return await e.req.json()}catch{throw new D(`Request body must be valid JSON`)}}function da(e,t){if(t instanceof D||t instanceof Ui)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof W)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function fa(e){let t=new w;return t.get(`/codex`,t=>{try{return t.json(e.getCodexSnapshot())}catch(e){return pa(t,e)}}),t.get(`/claude`,t=>{try{return t.json(e.getClaudeSnapshot())}catch(e){return pa(t,e)}}),t}function pa(e,t){if(t instanceof G)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`UNSUPPORTED_CODEX_SCHEMA`:return e.json({error:{code:t.code,message:t.message}},422);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function ma(e){let t=new w;return t.get(`/`,t=>Me(t,async n=>{await ha(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||ga(n,e)}),c=setInterval(()=>{r||_a(n)},15e3),l=()=>{o()};t.req.raw.signal.addEventListener(`abort`,l,{once:!0}),n.onAbort(o),t.req.raw.signal.aborted&&o(),await i,clearInterval(c),s(),t.req.raw.signal.removeEventListener(`abort`,l)})),t}function ha(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function ga(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function _a(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function va(e){return e===`/api`||e.startsWith(`/api/`)}function ya(e,t={}){let n=new w,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new Ln,i=t.providerService??new Yn(e),a=t.settingsService??new er(e),o=t.settingsSkillCopyService??new nr,s=t.sessionService??new Ir;return n.use(`/api/*`,Rn(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Pe,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,ma(t.eventHub)),n.route(`/api/providers`,oa(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,la(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)},o)),n.route(`/api/sessions`,fa(s)),t.captureService&&n.route(`/api/captures`,Xi(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,$i(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>va(e.req.path)?e.json({error:{code:`NOT_FOUND`,message:`API route not found`}},404):e.text(`Not Found`,404)),n.onError((e,t)=>(console.error(e),va(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function ba(e,t,n){let r=ya(t,n),i=je({root:e});r.use(`*`,(e,t)=>va(e.req.path)?t():i(e,t));let a=je({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!va(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&x.posix.extname(e.req.path)===``?a(e,t):t()),r}const{dirname:xa,join:Sa,resolve:Ca}=x,wa=xa(Oe(import.meta.url));function Ta(){let e=[Ca(wa,`web`),Ca(h.cwd(),`dist/web`)].find(e=>_(Sa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ea({storage:e,webRoot:t=Ta(),onListening:n}){let r=Kr(e),i=ba(t,e,r.apiOptions);r.start();let a=Ae({fetch:i.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return a.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),h.exitCode=1}),a}function Da(e,t){return new Promise((n,r)=>{let i=Ne();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function Oa(e){let t=`xdg-open`,n=[e];h.platform===`darwin`?t=`open`:h.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=Te(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const ka=t({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await Da(`127.0.0.1`,11111)}catch(e){Aa(e);return}Ea({storage:ei(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Oa(t)}})}});function Aa(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),h.exitCode=1}function ja(){let e,n=t({meta:{name:`help`,description:`Show Foundry CLI help`,hidden:!0},async run(){await r(e)}});return e=t({meta:{name:`foundry`,version:Pe,description:`Manage local Foundry data or start the Web UI`},default:`help`,subCommands:{help:n,web:ka,settings:Yi,providers:Bi,captures:Ci,"data-transfer":Oi}}),e}n(ja());export{};
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: foundry
3
- description: Operate the local Foundry CLI for settings, model providers, saved page captures and their scrape jobs, or encrypted backup export/import. Use when a task asks to inspect or change Foundry data, capture web content into Foundry, investigate capture jobs, or transfer Foundry data; start the Web UI only when the user explicitly needs it.
3
+ description: Operate the local Foundry CLI for settings, model providers, saved link captures and their fetch jobs, or encrypted backup export/import. Use when a task asks to inspect or change Foundry data, save a URL as an agent-facing bookmark, investigate capture jobs, or transfer Foundry data; start the Web UI only when the user explicitly needs it.
4
4
  ---
5
5
 
6
6
  # Foundry
@@ -20,18 +20,19 @@ Read only the references needed for the current request.
20
20
  | Invocation, JSON conventions, IDs, stdin, the Web UI | [references/cli-conventions.md](references/cli-conventions.md) |
21
21
  | Appearance, language, timezone, capture fetcher configuration | [references/settings.md](references/settings.md) |
22
22
  | List, create, update, disable, or discover models for providers | [references/providers.md](references/providers.md) |
23
- | Captures, capture detail, notes, recapture, or child scrape jobs | [references/captures.md](references/captures.md) |
23
+ | Captures, capture detail, notes, recapture, or child fetch jobs | [references/captures.md](references/captures.md) |
24
24
  | Encrypted export, preview, or destructive restore | [references/data-transfer.md](references/data-transfer.md) |
25
25
 
26
26
  ## Core Model
27
27
 
28
28
  - A **provider** has a stable provider ID and model-discovery configuration.
29
- - A **capture** has a stable capture ID, URL, note, and latest successful
30
- content job.
31
- - A **scrape job** is a child of exactly one capture. Its canonical command path
29
+ - A **capture** is an agent-facing bookmark: a URL plus a response from the
30
+ configured fetcher that explains what the URL is about.
31
+ - A **fetch job** is a child of exactly one capture. Its canonical command path
32
32
  is `foundry captures jobs ...`; there is no global jobs command.
33
33
  - A successful capture command returns `capture.id`, `job.id`,
34
- `job.status`, and `content.markdown`.
34
+ `job.status`, `job.creditsUsed`, and the raw fetcher response in
35
+ `rawResponse`.
35
36
  - CLI timestamps are ISO-8601 strings. The CLI does not apply the user's display
36
37
  time format or timezone; that formatting belongs to the Web UI.
37
38
  - Capture and provider records intentionally expose stored API keys in JSON
@@ -46,7 +47,7 @@ Read only the references needed for the current request.
46
47
  4. Check `job.status` after capture operations. A command can exit successfully
47
48
  with a completed job whose status is `failed`.
48
49
  5. Run `data-transfer inspect` before `data-transfer import`; import replaces the
49
- current database and settings.
50
+ current JSON records and settings.
50
51
  6. Prefer `FOUNDRY_PASSPHRASE` over `--passphrase` so backup secrets do not enter
51
52
  shell history.
52
53
  7. Use CLI commands instead of editing files under `<home>/.foundry` directly.
@@ -92,13 +93,13 @@ foundry data-transfer import <path>
92
93
  groups. Run `foundry <command> --help` when the installed version may differ
93
94
  from these references.
94
95
 
95
- ## Workflow: Capture A Page
96
+ ## Workflow: Capture A Link
96
97
 
97
98
  1. Read `settings get`; if no capture fetcher is selected or its API key is
98
99
  empty, update settings first.
99
100
  2. Run `captures create <url> --note <text>`.
100
101
  3. Inspect the returned `job.status`.
101
- 4. On success, use the returned `content.markdown` directly or fetch it again
102
+ 4. On success, inspect the returned `rawResponse` or fetch it again
102
103
  later with `captures get <capture-id>`.
103
104
  5. On failure, read the job reference and investigate through
104
105
  `captures jobs get`.