@dhzh/foundry 3.1.3 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # Foundry
2
2
 
3
- Foundry is an AI-native local personal workbench distributed as a CLI. Running
4
- `foundry` prepares local storage, starts a Hono server, serves the bundled
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
5
+ agent skill copy are available as JSON CLI commands for both people and agents.
6
+ `foundry web` prepares local storage, starts a Hono server, serves the bundled
5
7
  React Web UI, and opens it in the default browser.
6
8
 
7
9
  The package is intentionally CLI-only. It does not expose a JavaScript library
@@ -17,6 +19,8 @@ entry point.
17
19
  - Configure appearance, language and region, capture behavior, and concurrency.
18
20
  - Export and import an encrypted `.foundry-backup` snapshot containing the
19
21
  database and application settings.
22
+ - Copy the bundled agent skill into `<home>/.agents/skills/foundry`,
23
+ `<home>/.claude/skills/foundry`, or both from the CLI or Settings > Advanced.
20
24
 
21
25
  ## Requirements
22
26
 
@@ -32,24 +36,67 @@ build scripts. The required allowlist is already declared in
32
36
  ```bash
33
37
  pnpm install
34
38
  pnpm build
35
- pnpm start
39
+ pnpm start web
36
40
  ```
37
41
 
38
- `pnpm start` runs the built CLI from `dist/index.mjs`. Build first after changing
39
- the CLI, server, or Web UI.
42
+ `pnpm start` runs the built CLI from `dist/index.mjs`; `pnpm start web` starts
43
+ the Web UI. Build first after changing the CLI, server, or Web UI.
40
44
 
41
- The CLI listens on `http://127.0.0.1:11111`, prints the URL, and opens the
45
+ `foundry web` listens on `http://127.0.0.1:11111`, prints the URL, and opens the
42
46
  browser by default:
43
47
 
44
48
  ```bash
45
- foundry
46
- foundry --no-open
49
+ foundry web
50
+ foundry web --no-open
47
51
  foundry --help
48
52
  foundry --version
49
53
  ```
50
54
 
51
- The host and port are currently fixed. There are no CLI or environment-variable
52
- port overrides.
55
+ Running bare `foundry` only prints help. It does not initialize storage or start
56
+ the Web UI. The Web host and port are fixed; there are no CLI or
57
+ environment-variable port overrides.
58
+
59
+ ## CLI
60
+
61
+ Feature commands write JSON to stdout and errors to stderr:
62
+
63
+ ```bash
64
+ foundry settings get
65
+ foundry settings update --input '{"theme":"dark"}'
66
+
67
+ foundry providers list
68
+ foundry providers create --input '{"name":"Local","protocol":"openai-compatible-chat-completions","baseURL":"http://127.0.0.1:11434/v1","apiKey":"","customModels":[]}'
69
+ foundry providers set-status <id> --status disabled
70
+
71
+ foundry captures list
72
+ foundry captures create https://example.com/article --note "Read later"
73
+ foundry captures get <capture-id>
74
+
75
+ foundry captures jobs list <capture-id>
76
+ foundry captures jobs get <capture-id> <job-id>
77
+ foundry captures jobs recapture <capture-id>
78
+
79
+ foundry data-transfer status
80
+ foundry data-transfer export --output ./foundry.foundry-backup
81
+ foundry data-transfer inspect ./foundry.foundry-backup
82
+ foundry data-transfer import ./foundry.foundry-backup
83
+
84
+ foundry settings download-skill --target .agents,.claude
85
+ ```
86
+
87
+ Use `--input-file <path>` or `--input -` for large JSON payloads. Data-transfer
88
+ passphrases can be passed with `--passphrase` or `FOUNDRY_PASSPHRASE`.
89
+ `data-transfer import` validates and replaces the local database and settings in
90
+ one command.
91
+
92
+ Skill targets are fixed relative to the user home directory. Here `<home>` is
93
+ `~` on macOS/Linux and `%USERPROFILE%` on Windows:
94
+
95
+ - `.agents` -> `<home>/.agents/skills/foundry`
96
+ - `.claude` -> `<home>/.claude/skills/foundry`
97
+
98
+ Selecting both copies to both locations. Replacing one selected target does not
99
+ change the other.
53
100
 
54
101
  ## Local Development
55
102
 
@@ -65,24 +112,31 @@ pnpm dev:web
65
112
 
66
113
  Vite proxies `/api` from the Web dev server to the API server. There is
67
114
  intentionally no CLI development command; use the two development servers to
68
- test page behavior, then use `pnpm build && pnpm start` to verify the production
69
- server and static assets.
115
+ test page behavior, then use `pnpm build && pnpm start web` to verify the
116
+ production server and static assets.
70
117
 
71
118
  ## Data and Storage
72
119
 
73
- Foundry keeps user data outside the repository in `~/.foundry`:
120
+ Foundry keeps user data outside the repository in `<home>/.foundry`. `<home>` is
121
+ `~` on macOS/Linux and `%USERPROFILE%` on Windows:
74
122
 
75
123
  - `foundry.sqlite`: providers and their credentials, captures, and scrape jobs
76
124
  - `settings.json`: application settings and capture-fetcher credentials
77
125
  - `.data-transfer/`: temporary export and import files
78
126
 
79
- The CLI initializes the directory, opens the SQLite database, and applies
80
- Drizzle migrations before the server starts. A database created by a newer
81
- schema version is rejected instead of being modified.
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.
82
131
 
83
132
  On POSIX systems, Foundry creates the data directory with `0700` permissions and
84
133
  sensitive files with `0600` permissions.
85
134
 
135
+ Agent skill copies are user-level rather than Foundry runtime data:
136
+
137
+ - `<home>/.agents/skills/foundry`
138
+ - `<home>/.claude/skills/foundry`
139
+
86
140
  ## Build Output
87
141
 
88
142
  ```bash
@@ -97,15 +151,19 @@ dist/
97
151
  |-- drizzle/
98
152
  | |-- *.sql
99
153
  | `-- meta/
154
+ |-- skills/
155
+ | `-- foundry/
156
+ | |-- SKILL.md
157
+ | `-- references/
100
158
  `-- web/
101
159
  |-- assets/
102
160
  |-- index.html
103
161
  `-- favicon.png
104
162
  ```
105
163
 
106
- `tsdown` cleans `dist`, bundles the CLI, and copies the Drizzle migrations.
107
- Vite then writes the Web UI directly to `dist/web`. Do not add a manual copy
108
- step for the Web UI.
164
+ `tsdown` cleans `dist`, bundles the CLI, and copies the Drizzle migrations and
165
+ agent skill. Vite then writes the Web UI directly to `dist/web`. Do not add a
166
+ manual copy step for the Web UI.
109
167
 
110
168
  ## Commands
111
169
 
@@ -114,7 +172,8 @@ step for the Web UI.
114
172
  | `pnpm dev:api` | Run the API server at `22222` |
115
173
  | `pnpm dev:web` | Run the Vite Web UI at `33333` |
116
174
  | `pnpm build` | Build the CLI and Web UI |
117
- | `pnpm start` | Run the production CLI at `11111` |
175
+ | `pnpm start web` | Run the production Web UI at `11111` |
176
+ | `pnpm start` | Print the built CLI help |
118
177
  | `pnpm test` | Run behavioral tests |
119
178
  | `pnpm test:coverage` | Run tests with V8 coverage |
120
179
  | `pnpm db:generate` | Generate a Drizzle migration after schema changes |
@@ -128,15 +187,19 @@ Older Node.js versions cannot run the installed pnpm or project toolchain.
128
187
  ```text
129
188
  app/web/ React, Vite, Astryx, and StyleX Web UI
130
189
  src/
131
- |-- cli/ CLI arguments and browser opening
132
- |-- features/ Providers, captures, settings, and data transfer
190
+ |-- cli/ CLI commands, JSON I/O, and browser opening
191
+ |-- features/ Feature services, validation, repositories, and routes
133
192
  |-- lib/ Small server-side utilities
134
193
  |-- server/ Hono API, static serving, and server entry points
135
194
  `-- storage/ SQLite, Drizzle schema, paths, and migrations
195
+ skills/foundry/ Agent-facing CLI usage skill and references
136
196
  drizzle/ Generated migration SQL and metadata
137
197
  test/ Behavioral API and feature tests
138
198
  ```
139
199
 
200
+ `skills/foundry/SKILL.md` is the agent-facing Foundry CLI usage skill. Its
201
+ feature references live in `skills/foundry/references`.
202
+
140
203
  The API is mounted under `/api`. The production server serves files from
141
204
  `dist/web` and falls back to `dist/web/index.html` for client-side routes.
142
205
 
@@ -152,7 +215,8 @@ Verify package contents with:
152
215
  pnpm pack --dry-run
153
216
  ```
154
217
 
155
- The tarball must include the CLI, Web assets, and Drizzle migrations.
218
+ The tarball must include the CLI, Web assets, Drizzle migrations, and bundled
219
+ agent skill.
156
220
 
157
221
  ## License
158
222
 
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{defineCommand as e,runMain as t}from"citty";import n from"node:process";import{serve as r}from"@hono/node-server";import{serveStatic as i}from"@hono/node-server/serve-static";import a from"node:path";import{Hono as o}from"hono";import{chmodSync as s,createReadStream as c,createWriteStream as l,existsSync as u,mkdirSync as d,readFileSync as f,renameSync as ee,rmSync as te,writeFileSync as ne}from"node:fs";import{Readable as re,Transform as ie}from"node:stream";import{pipeline as p}from"node:stream/promises";import{chmod as m,mkdir as ae,open as oe,readFile as se,rm as h,stat as ce,writeFile as le}from"node:fs/promises";import ue from"yauzl";import de from"yazl";import{matchedRoutes as fe}from"hono/route";import{createCipheriv as pe,createDecipheriv as me,createHash as he,randomBytes as ge,randomUUID as g,scrypt as _e}from"node:crypto";import{and as _,count as v,desc as ve,eq as y,inArray as ye,isNull as b,ne as be,sql as xe}from"drizzle-orm";import{index as Se,integer as x,sqliteTable as Ce,text as S,uniqueIndex as we}from"drizzle-orm/sqlite-core";import Te from"node:os";import{spawn as Ee}from"node:child_process";import{streamSSE as De}from"hono/streaming";import Oe from"better-sqlite3";import{drizzle as ke}from"drizzle-orm/better-sqlite3";import{migrate as Ae}from"drizzle-orm/better-sqlite3/migrator";import{fileURLToPath as je}from"node:url";import{Buffer as C}from"node:buffer";import{createServer as Me}from"node:net";var Ne=`3.1.3`;function Pe(e){if(!Re(e)||typeof e.url!=`string`)throw new Le(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Fe(e){return e===`no-successful`?`no-successful`:`all`}function Ie(e){if(!Re(e)||typeof e.userNote!=`string`)throw new Le(`userNote must be a string`);return e.userNote}var Le=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var w=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function ze(e,t=()=>{}){let n=new o;return n.get(`/`,t=>{let n=Fe(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=Pe(await Be(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return T(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return T(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 T(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 T(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Ie(await Be(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return T(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return T(t,e)}}),n}async function Be(e){try{return await e.req.json()}catch{throw new Le(`Request body must be valid JSON`)}}function T(e,t){if(t instanceof Le)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}},Ve(t.code));throw t}function Ve(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}}var E=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`DataTransferError`}};function He(e){return e instanceof E?e:new E(`IO_ERROR`,e instanceof Error?e.message:`The data transfer failed`,{cause:e})}const D=`database/foundry.sqlite`,O=`settings.json`,k=`manifest.json`;function Ue(e){if(!j(e)||e.format!==`foundry.snapshot`)throw new E(`INVALID_ARCHIVE`,`The file is not a Foundry export`);let t=A(e.archiveVersion,`archiveVersion`);if(t!==1)throw new E(`UNSUPPORTED_ARCHIVE`,`The archive version is not supported`);let n=Ge(e.createdAt,`createdAt`);if(Number.isNaN(Date.parse(n)))throw new E(`INVALID_ARCHIVE`,`createdAt is invalid`);if(!j(e.database)||!j(e.settings))throw new E(`INVALID_ARCHIVE`,`Archive file metadata is missing`);let r=A(e.settings.version,`settings.version`);if(r>1)throw new E(`UNSUPPORTED_ARCHIVE`,`The settings version is newer than this Foundry version`);return{format:`foundry.snapshot`,archiveVersion:t,appVersion:Ge(e.appVersion,`appVersion`),createdAt:n,database:{...We(e.database,D),schemaVersion:A(e.database.schemaVersion,`database.schemaVersion`)},settings:{...We(e.settings,O),version:r}}}function We(e,t){if(!j(e)||e.path!==t)throw new E(`INVALID_ARCHIVE`,`File metadata path is invalid`);let n=Ge(e.sha256,`sha256`);if(!/^[a-f0-9]{64}$/u.test(n))throw new E(`INVALID_ARCHIVE`,`File checksum is invalid`);return{path:t,bytes:A(e.bytes,`bytes`),sha256:n}}function Ge(e,t){if(typeof e!=`string`||e.length===0)throw new E(`INVALID_ARCHIVE`,`${t} must be a non-empty string`);return e}function A(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new E(`INVALID_ARCHIVE`,`${t} must be a non-negative integer`);return e}function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ke=/* @__PURE__ */ new Set([k,D,O]);async function qe(e,t){let n=new de.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await p(n.outputStream,l(t,{mode:384}))}async function Je(e,t){let n=await Ye(e),r=/* @__PURE__ */ new Map,i=0;try{await new Promise((e,o)=>{let s=e=>{o(e instanceof Error?e:Error(String(e)))},c=async e=>{if(!Ke.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 o=e.fileName===`manifest.json`?1048576:4294967296;if(i+=e.uncompressedSize,e.uncompressedSize>o||i>4294967296)throw Error(`The Foundry archive is too large`);let s=a.join(t,e.fileName);await ae(a.dirname(s),{recursive:!0}),await p(await Xe(n,e),l(s,{mode:384})),r.set(e.fileName,s),n.readEntry()};n.on(`error`,s),n.on(`end`,e),n.on(`entry`,e=>{c(e).catch(s)}),n.readEntry()})}catch(e){throw await h(t,{recursive:!0,force:!0}),e}finally{n.close()}for(let e of Ke)if(!r.has(e))throw await h(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function Ye(e){return new Promise((t,n)=>{ue.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Xe(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}function Ze(e,t=()=>{},{maximumUploadBytes:n=4296015872}={}){let r=new o;return r.get(`/status`,t=>t.json(e.getStatus())),r.post(`/export`,async t=>{try{let n=await tt(t),r=await e.createExport(n),i=c(r.filePath);return i.on(`close`,()=>{e.removeExportFile(r.filePath)}),t.body(re.toWeb(i),200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${a.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 M(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 E(`INVALID_ARCHIVE`,`The Foundry backup must be uploaded as application/octet-stream`);$e(t,n);let i=et(t,`x-foundry-passphrase`);if(!i)throw new E(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);let a=et(t,`x-foundry-filename`)?.trim()||`foundry.foundry-backup`;return r=await e.createUploadTarget(),await Qe(t,r.filePath,n),t.json(await e.inspectImport(r.filePath,i,a))}catch(e){return M(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 M(n,e)}}),r.delete(`/imports/:id`,async t=>{try{return await e.cancelImport(t.req.param(`id`)),t.body(null,204)}catch(e){return M(t,e)}}),r}async function Qe(e,t,n){let r=e.req.raw.body;if(!r)throw new E(`INVALID_ARCHIVE`,`A Foundry backup file is required`);let i=0,a=new ie({transform(e,t,r){i+=e.byteLength,i>n?r(new E(`INVALID_ARCHIVE`,`The Foundry archive is too large`)):r(null,e)}});try{await p(re.fromWeb(r),a,l(t,{mode:384}))}catch(e){throw e instanceof E?e:new E(`IO_ERROR`,`Unable to receive the Foundry archive`,{cause:e})}if(i===0)throw new E(`INVALID_ARCHIVE`,`A Foundry backup file is required`)}function $e(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 E(`INVALID_ARCHIVE`,`The upload length is invalid`);if(r>t)throw new E(`INVALID_ARCHIVE`,`The Foundry archive is too large`)}function et(e,t){let n=e.req.header(t);if(n!==void 0)try{return decodeURIComponent(n)}catch{throw new E(`INVALID_ARCHIVE`,`The ${t} header is invalid`)}}async function tt(e){try{let t=await e.req.json();if(typeof t!=`object`||!t||!(`passphrase`in t)||typeof t.passphrase!=`string`)throw new E(`PASSPHRASE_REQUIRED`,`Enter a passphrase`);return t.passphrase}catch(e){throw e instanceof E?e:new E(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}}function M(e,t){let n=He(t);return e.json({error:{code:n.code,message:n.message}},nt(n.code))}function nt(e){switch(e){case`IMPORT_NOT_FOUND`:return 404;case`ACTIVE_JOBS`:case`BUSY`:return 409;case`IO_ERROR`:return 500;default:return 400}}const rt=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var it=class{transferActive=!1;get isTransferActive(){return this.transferActive}tryBeginTransfer(){return!this.transferActive&&(this.transferActive=!0,!0)}endTransfer(){this.transferActive=!1}};function at(e){return async(t,n)=>{if(e.isTransferActive&&rt.has(t.req.method)&&!t.req.path.startsWith(`/api/data-transfer/`)&&ot(t))return t.json({error:{code:`DATA_TRANSFER_BUSY`,message:`Another data transfer is in progress`}},409);await n()}}function ot(e){return fe(e).some(e=>e.path.startsWith(`/api/`)&&e.path!==`/api/*`)}const st=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],ct=[`active`,`disabled`,`deleted`];var N=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},lt=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function ut(e){if(!gt(e))throw new N(`Provider input must be an object`);return{name:P(e.name,`name`),protocol:mt(e.protocol),baseURL:ht(e.baseURL),apiKey:e.apiKey===void 0?``:P(e.apiKey,`apiKey`,{allowEmpty:!0}),customModels:pt(e.customModels)}}function dt(e){if(!gt(e))throw new N(`Provider connection must be an object`);return{protocol:mt(e.protocol),baseURL:ht(e.baseURL),apiKey:e.apiKey===void 0?``:P(e.apiKey,`apiKey`,{allowEmpty:!0})}}function ft(e){if(typeof e!=`string`||!ct.includes(e))throw new N(`Invalid provider status`);return e}function pt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new N(`customModels must be an array`);return e.map(e=>{if(!gt(e))throw new N(`Each custom model must be an object`);return{id:P(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:P(e.displayName,`customModels.displayName`)}})}function mt(e){if(typeof e!=`string`||!st.includes(e))throw new N(`Invalid provider protocol`);return e}function ht(e){let t=P(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new N(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function P(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new N(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new N(`${t} is required`);return r}function gt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var F=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function _t(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(vt(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new F(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new F(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new F(`Provider returned invalid JSON`)}return yt(i)}function vt(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function yt(e){if(!xt(e)||!Array.isArray(e.data))throw new F(`Provider response does not contain a model list`);return e.data.map(e=>{if(!xt(e)||typeof e.id!=`string`||e.id.length===0)throw new F(`Provider returned an invalid model entry`);let t=bt(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function bt(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const I=Ce(`providers`,{id:S(`id`).primaryKey().notNull(),name:S(`name`).notNull(),protocol:S(`protocol`).notNull(),baseURL:S(`base_url`).notNull(),apiKey:S(`api_key`).notNull().default(``),customModels:S(`custom_models`).notNull().default(`[]`),status:S(`status`).notNull().default(`active`),createdAt:x(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:x(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:x(`deleted_at`,{mode:`timestamp_ms`})}),L=Ce(`captures`,{id:S(`id`).primaryKey().notNull(),url:S(`url`).notNull(),title:S(`title`),userNote:S(`user_note`),latestSuccessfulJobId:S(`latest_successful_job_id`),createdAt:x(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:x(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:x(`deleted_at`,{mode:`timestamp_ms`})},e=>[we(`captures_url_active_unique`).on(e.url).where(xe`${e.deletedAt} is null`),Se(`captures_created_at_idx`).on(e.createdAt)]),R=Ce(`scrape_jobs`,{id:S(`id`).primaryKey().notNull(),captureId:S(`capture_id`).notNull().references(()=>L.id),fetcher:S(`fetcher`).notNull(),configSnapshot:S(`config_snapshot`).notNull(),rawResponseJson:S(`raw_response_json`),status:S(`status`).notNull().default(`pending`),errorCode:S(`error_code`),errorMessage:S(`error_message`),createdAt:x(`created_at`,{mode:`timestamp_ms`}).notNull(),updatedAt:x(`updated_at`,{mode:`timestamp_ms`}).notNull(),deletedAt:x(`deleted_at`,{mode:`timestamp_ms`})},e=>[we(`scrape_jobs_one_active_per_capture`).on(e.captureId).where(xe`${e.status} in ('pending', 'running') and ${e.deletedAt} is null`),Se(`scrape_jobs_capture_created_at_idx`).on(e.captureId,e.createdAt)]);var z=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},St=class{db;constructor(e){this.db=e}list(e=/* @__PURE__ */ new Set){return this.db.select().from(I).where(be(I.status,`deleted`)).orderBy(ve(I.updatedAt)).all().map(t=>({...B(t),isInUse:e.has(t.id)}))}get(e){let t=this.db.select().from(I).where(y(I.id,e)).get();return t?B(t):null}getConnection(e){let t=this.db.select().from(I).where(y(I.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(I).where(y(I.id,t)).get():void 0;if(t&&!n)throw new z;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 B(n&&t?this.db.update(I).set(i).where(y(I.id,t)).returning().get():this.db.insert(I).values({id:g(),...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 lt;let r=this.db.update(I).set({status:t,deletedAt:t===`deleted`?/* @__PURE__ */ new Date:null,updatedAt:/* @__PURE__ */ new Date}).where(y(I.id,e)).returning().all();if(r.length===0)throw new z;return B(r[0])}};function B(e){return{id:e.id,name:e.name,protocol:e.protocol,baseURL:e.baseURL,apiKey:e.apiKey,customModels:pt(JSON.parse(e.customModels)),status:e.status,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),deletedAt:e.deletedAt?.toISOString()??null}}function Ct(e,t=()=>{}){let n=new o;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return V(t,e)}}),n.post(`/models`,async t=>{try{let n=dt(await wt(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return V(t,e)}}),n.post(`/`,async n=>{try{let r=ut(await wt(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return V(n,e)}}),n.put(`/:id`,async n=>{try{let r=ut(await wt(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return V(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await wt(n),i=ft(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 V(n,e)}}),n}async function wt(e){try{return await e.req.json()}catch{throw new N(`Request body must be valid JSON`)}}function V(e,t){if(t instanceof N)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof z)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof lt)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof F)return e.json({error:{code:t.code,message:t.message}},502);throw t}function H(){return a.join(Te.homedir(),`.foundry`)}function Tt(){let e=H();return d(e,{recursive:!0,mode:448}),n.platform!==`win32`&&s(e,448),e}function Et(){return a.join(H(),`foundry.sqlite`)}function U(){return a.join(H(),`settings.json`)}function Dt(){return a.join(H(),`.data-transfer`)}const Ot=[`system`,`light`,`dark`],kt=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],At=[`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`],jt=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Mt=[`firecrawl`,`deepseek`],W={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 Nt(e){let t=q(e)?e:{},n=q(t.workspace)?t.workspace:{},r=q(n.appearance)?n.appearance:{},i=q(n[`language-region`])?n[`language-region`]:{},a=q(t.features)?t.features:{},o=q(a.library)?a.library:{},s=q(o.captures)?o.captures:{},c=q(s.firecrawl)?s.firecrawl:{},l=q(s.deepseek)?s.deepseek:{};return{workspace:{appearance:{"color-theme":Bt(r[`color-theme`],Ot,W.workspace.appearance[`color-theme`])},"language-region":{language:Bt(i.language,kt,W.workspace[`language-region`].language),"time-format":Bt(i[`time-format`],At,W.workspace[`language-region`][`time-format`]),"time-zone":Bt(i[`time-zone`],jt,W.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:Rt(s.fetcher),maxAttempts:Vt(s.maxAttempts,10,1),scrapeConcurrency:Vt(s.scrapeConcurrency,5,2),firecrawl:{apiKey:Wt(c.apiKey)},deepseek:{apiKey:Wt(l.apiKey)}}}}}}function Pt(e){if(!q(e))throw new G(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=K(e.theme,Ot,`theme`)),`language`in e&&(t.language=K(e.language,kt,`language`)),`timeFormat`in e&&(t.timeFormat=K(e.timeFormat,At,`timeFormat`)),`timezone`in e&&(t.timezone=K(e.timezone,jt,`timezone`)),`captures`in e&&(t.captures=Lt(e.captures)),t}function Ft(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 It(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 G=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function Lt(e){if(!q(e))throw new G(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:K(e.fetcher,Mt,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Ht(e.maxAttempts,10,`captures.maxAttempts`)),`scrapeConcurrency`in e&&(t.scrapeConcurrency=Ht(e.scrapeConcurrency,5,`captures.scrapeConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=Ut(e.firecrawlApiKey,`captures.firecrawlApiKey`)),`deepseekApiKey`in e&&(t.deepseekApiKey=Ut(e.deepseekApiKey,`captures.deepseekApiKey`)),t}function Rt(e){return zt(e,Mt)}function zt(e,t){return typeof e==`string`&&t.includes(e)?e:null}function Bt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function K(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new G(`Invalid ${n}`);return e}function Vt(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Ht(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new G(`${n} must be an integer from 1 to ${t}`);return e}function Ut(e,t){if(typeof e!=`string`)throw new G(`${t} must be a string`);return e.trim()}function Wt(e){return typeof e==`string`?e:``}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e=U()){try{return Nt(JSON.parse(f(e,`utf8`)))}catch{return Nt(W)}}function Gt(e=U()){return It(J(e))}function Kt(e,t=U()){let n=Ft(J(t),e);return qt(n,t),It(n)}function qt(e,t=U()){d(a.dirname(t),{recursive:!0});let n=`${t}.tmp`;ne(n,`${JSON.stringify(e,null,2)}\n`,{mode:384}),ee(n,t)}function Jt(e=U()){let t=J(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))Yt(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function Yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Xt=class{settingsPath;repository;constructor(e,t=U()){this.settingsPath=t,this.repository=new St(e.db)}list(){return this.repository.list(Jt(this.settingsPath))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new z;return _t(t)}fetchModelsForConnection(e){return _t(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t,Jt(this.settingsPath))}};function Zt(e,t=()=>{}){let n=new o;return n.get(`/`,t=>t.json(e.read())),n.patch(`/`,async n=>{try{let r=Pt(await Qt(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return $t(n,e)}}),n.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),n}async function Qt(e){try{return await e.req.json()}catch{throw new G(`Request body must be valid JSON`)}}function $t(e,t){if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},400);throw t}function en(e){let t=n.platform===`darwin`?`open`:n.platform===`win32`?`explorer`:`xdg-open`,r=Ee(t,[e],{detached:!0,stdio:`ignore`});r.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),r.unref()}var tn=class{settingsPath;configFolder;openFolder;constructor(e=U(),t=H(),n=en){this.settingsPath=e,this.configFolder=t,this.openFolder=n}read(){return{...Gt(this.settingsPath),configFolder:this.configFolder}}update(e){return{...Kt(e,this.settingsPath),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};function nn(e){let t=new o;return t.get(`/`,t=>De(t,async n=>{await rn(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||an(n,e)}),c=setInterval(()=>{r||on(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 rn(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function an(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function on(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}function sn(e){return e===`/api`||e.startsWith(`/api/`)}function cn(e,t={}){let n=new o,r=t.workspaceMutationGate??t.dataTransferService?.workspaceMutationGate??new it,i=t.providerService??new Xt(e,t.settingsPath),a=t.settingsService??new tn(t.settingsPath);return n.use(`/api/*`,at(r)),n.get(`/api/health`,t=>t.json({status:`ok`,version:Ne,database:{schemaVersion:e.schemaVersion}})),t.eventHub&&n.route(`/api/events`,nn(t.eventHub)),n.route(`/api/providers`,Ct(i,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Zt(a,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(`settings.changed`,e)})),t.captureService&&n.route(`/api/captures`,ze(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),t.dataTransferService&&n.route(`/api/data-transfer`,Ze(t.dataTransferService,()=>{t.eventHub?.publish(`data-transfer.imported`,{})})),n.notFound(e=>sn(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),sn(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function ln(e,t,n){let r=cn(t,n),o=i({root:e});r.use(`*`,(e,t)=>sn(e.req.path)?t():o(e,t));let s=i({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!sn(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&a.posix.extname(e.req.path)===``?s(e,t):t()),r}var un=class{db;constructor(e){this.db=e}findCapture(e){return this.db.select().from(L).where(_(y(L.id,e),b(L.deletedAt))).get()??null}findJob(e){return this.db.select().from(R).where(y(R.id,e)).get()??null}list(e){let t=e===`no-successful`?_(b(L.deletedAt),b(L.latestSuccessfulJobId)):b(L.deletedAt);return this.db.select().from(L).where(t).orderBy(ve(L.createdAt)).all().map(e=>dn(e))}counts(){let e=b(L.deletedAt);return{all:this.db.select({value:v()}).from(L).where(e).get()?.value??0,noSuccessful:this.db.select({value:v()}).from(L).where(_(e,b(L.latestSuccessfulJobId))).get()?.value??0}}get(e){let t=this.findCapture(e);if(!t)return null;let n=t.latestSuccessfulJobId?this.db.select().from(R).where(_(y(R.id,t.latestSuccessfulJobId),y(R.captureId,e),b(R.deletedAt))).get():void 0;return{capture:dn(t),content:n?pn(n):null}}findActiveByURL(e){return this.db.select().from(L).where(_(y(L.url,e),b(L.deletedAt))).get()??null}createWithJob(e,t,n){let r=/* @__PURE__ */ new Date,i=g(),a=g();this.db.transaction(o=>{o.insert(L).values({id:i,url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null}).run(),o.insert(R).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:dn(o),jobId:a}}hasActiveJob(e){return!!this.db.select({id:R.id}).from(R).where(_(y(R.captureId,e),ye(R.status,[`pending`,`running`]),b(R.deletedAt))).get()}createJob(e,t){let n=/* @__PURE__ */ new Date,r=g();this.db.insert(R).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:fn(i),jobId:r}}delete(e){let t=/* @__PURE__ */ new Date;return this.db.update(L).set({deletedAt:t,updatedAt:t}).where(_(y(L.id,e),b(L.deletedAt))).returning().all().length!==0&&(this.db.update(R).set({deletedAt:t,updatedAt:t}).where(_(y(R.captureId,e),b(R.deletedAt))).run(),!0)}updateNote(e,t){let n=t.trim()||null,r=this.db.update(L).set({userNote:n,updatedAt:/* @__PURE__ */ new Date}).where(_(y(L.id,e),b(L.deletedAt))).returning().all();return r.length===0?null:dn(r[0])}listJobs(e){return this.db.select().from(R).where(_(y(R.captureId,e),b(R.deletedAt))).orderBy(ve(R.createdAt)).all().map(e=>fn(e))}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(R).set({status:`running`,updatedAt:/* @__PURE__ */ new Date}).where(_(y(R.id,e),y(R.status,`pending`))).run()}markSucceeded(e,t,n,r){let i=/* @__PURE__ */ new Date;this.db.transaction(a=>{a.update(R).set({status:`succeeded`,rawResponseJson:JSON.stringify(r),errorCode:null,errorMessage:null,updatedAt:i}).where(y(R.id,e)).run(),a.update(L).set({...n&&{title:n},latestSuccessfulJobId:e,updatedAt:i}).where(y(L.id,t)).run()})}markFailed(e,t,n){this.db.update(R).set({status:`failed`,errorCode:t,errorMessage:n,updatedAt:/* @__PURE__ */ new Date}).where(y(R.id,e)).run()}recoverRunningJobs(){let e=this.db.select({id:R.id}).from(R).where(_(y(R.status,`running`),b(R.deletedAt))).all();return e.length>0&&this.db.update(R).set({status:`pending`}).where(_(y(R.status,`running`),b(R.deletedAt))).run(),e.length}pendingJobIDs(){return this.db.select({id:R.id}).from(R).where(_(y(R.status,`pending`),b(R.deletedAt))).orderBy(R.createdAt).all().map(e=>e.id)}};function dn(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 fn(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 pn(e){if(!e.rawResponseJson)return null;try{let t=JSON.parse(e.rawResponseJson);if(!hn(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`?mn(n):n}}catch{return null}}function mn(e){return e.replaceAll(/\\(.)/g,(e,t)=>/\p{P}/u.test(t)?t:e)}function hn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Y=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 gn(e){return e===408||e===429||e>=500}function _n(e){return e instanceof Y?e:e instanceof Error&&e.name===`TimeoutError`?new Y(`timeout`,`The page fetch timed out`,!0):e instanceof TypeError?new Y(`network_error`,e.message,!0):new Y(`fetch_failed`,e instanceof Error?e.message:`The page fetch failed`,!1)}async function vn(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 Y(`http_${r.status}`,`DeepSeek returned ${r.status}`,gn(r.status),r.status);let i=await r.json();if(!yn(i)||typeof i.title!=`string`||typeof i.content!=`string`)throw new Y(`invalid_response`,`DeepSeek returned an invalid response`,!1);return{title:i.title.trim()||null,rawResponse:i}}catch(e){throw _n(e)}}function yn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function bn(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 Y(`http_${r.status}`,`Firecrawl returned ${r.status}`,gn(r.status),r.status);let i=xn(await r.json());if(!i)throw new Y(`invalid_response`,`Firecrawl returned an invalid response`,!1);return i}catch(e){throw _n(e)}}function xn(e){if(!Sn(e))return null;let t=Sn(e.data)?e.data:e;if((typeof t.markdown==`string`?t.markdown:null)===null)return null;let n=Sn(t.metadata)?t.metadata:{};return{title:(typeof n.title==`string`?n.title.trim():``)||null,rawResponse:t}}function Sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cn(e,t,n=fetch){return t.fetcher===`firecrawl`?bn(e,t.apiKey,n):vn(e,t.apiKey,n)}var wn=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=J(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=Tn(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 Cn(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=_n(i);if(r>=n.maxAttempts||!a.isRetryable){this.failJob(e,t.capture.id,a.code,a.message);return}await Dn(En(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 Tn(e){let t=JSON.parse(e);if(!On(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 En(e){let t=1e3*2**(e-1);return Math.min(3e4,t)+Math.floor(Math.random()*250)}function Dn(e){return new Promise(t=>{setTimeout(t,e)})}function On(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var kn=class{repository;settingsPath;runner;constructor(e,t,n){this.repository=e,this.settingsPath=t,this.runner=n}executionConfig(){let e=J(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 w(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=An(e.url);if(!t)throw new w(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new w(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new w(`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 w(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new w(`ACTIVE_JOB_EXISTS`,`This capture already has an active scrape job`);let t=this.executionConfig();if(!t)throw new w(`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 w(`ACTIVE_JOB_EXISTS`,`This capture already has an active scrape job`);if(!this.repository.delete(e))throw new w(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new w(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}};function An(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function jn(e,t,n){let r=new un(e.db),i=new wn(r,t,e=>n?.publish(`capture.job.changed`,e));return{service:new kn(r,t,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}const Mn=a.dirname(je(import.meta.url));function Nn(e){let t=new Oe(e,{fileMustExist:!0,readonly:!0});try{return Number(t.pragma(`user_version`,{simple:!0}))}finally{t.close()}}function Pn(e=Et(),t=In()){d(a.dirname(e),{recursive:!0});let r=new Oe(e,{timeout:5e3});n.platform!==`win32`&&s(e,384),r.pragma(`foreign_keys = ON`);let i=Number(r.pragma(`user_version`,{simple:!0}));if(i>1)throw r.close(),Error(`The Foundry database was created by a newer application version`);let o=ke({client:r});try{Ae(o,{migrationsFolder:t}),i!==1&&r.pragma(`user_version = 1`)}catch(e){throw r.close(),e}return{client:r,db:o,path:e,schemaVersion:1}}function Fn(){return Tt(),Pn()}function In(){let e=[a.resolve(Mn,`drizzle`),a.resolve(Mn,`../../drizzle`),a.resolve(n.cwd(),`drizzle`)].find(e=>u(a.join(e,`meta`,`_journal.json`)));if(!e)throw Error(`Foundry database migrations were not found`);return e}const X=C.from(`FOUNDRYX`,`ascii`),Z=`aes-256-gcm`,Ln=`scrypt`,Q={N:131072,r:8,p:1};async function Rn(e,t,n){let r=ge(16),i=ge(12),a={version:1,cipher:Z,kdf:{name:Ln,salt:r.toString(`base64`),...Q,keyLength:32},nonce:i.toString(`base64`)},o=C.from(JSON.stringify(a),`utf8`),s=Bn(o.byteLength),u=C.concat([s,o]),d=await Vn(n,r,Q);try{let n=await oe(t,`w`,384);try{await n.write(u)}finally{await n.close()}await p(c(e),Hn(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await m(t,384)}catch(e){throw await h(t,{force:!0}),new E(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function zn(e,t,n){let r;try{let i=(await ce(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await oe(e,`r`),o,s,u;try{if(o=await Gn(a,13,0),!o.subarray(0,X.byteLength).equals(X))throw Error(`The export file signature is invalid`);if(o.readUInt8(X.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(X.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await Gn(a,e,13),u=await Gn(a,16,i-16)}finally{await a.close()}let d=Wn(JSON.parse(s.toString(`utf8`)));r=await Vn(n,d.salt,d.header.kdf);let f=C.concat([o,s]);await p(c(e,{start:13+s.byteLength,end:i-16-1}),Un(r,d.nonce,f,u),l(t,{mode:384})),await m(t,384)}catch(e){throw await h(t,{force:!0}),e instanceof E?e:new E(`INVALID_PASSPHRASE`,`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function Bn(e){let t=C.alloc(13);return X.copy(t,0),t.writeUInt8(1,X.byteLength),t.writeUInt32BE(e,X.byteLength+1),t}function Vn(e,t,n){return new Promise((r,i)=>{_e(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Hn(e,t,n){let r=pe(Z,e,t,{authTagLength:16});return r.setAAD(n),new ie({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 Un(e,t,n,r){let i=me(Z,e,t,{authTagLength:16});return i.setAAD(n),new ie({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 Wn(e){if(!Kn(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==Z||!Kn(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Ln||typeof t.salt!=`string`||t.N!==Q.N||t.r!==Q.r||t.p!==Q.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:Z,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 Gn(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 Kn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var qn=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 E(`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 ae(this.temporaryRoot,{recursive:!0,mode:448}),await rr(this.temporaryRoot);let t=a.join(this.temporaryRoot,`${e}-${g()}`);return await ae(t,{recursive:!1,mode:448}),await rr(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 h(e,{recursive:!0,force:!0})}catch{}}async createUploadTarget(){let e=await this.createWorkDirectory(`upload`);return{filePath:a.join(e,`archive.foundry-backup`),cleanup:()=>this.removeQuietly(e)}}cleanupStaleTransfers(){te(this.temporaryRoot,{recursive:!0,force:!0}),d(this.temporaryRoot,{recursive:!0,mode:448}),this.stagedImports.clear()}getStatus(){return{activeJobCount:Yn(this.database.db),isBusy:this.busy}}async createExport(e){return Jn(e),this.runExclusive(async()=>{let t=await this.createWorkDirectory(`export`),n=a.join(t,`foundry.sqlite`),r=a.join(t,O),i=a.join(t,k),o=a.join(t,`foundry.zip`),s=a.join(this.temporaryRoot,`foundry-${Date.now()}.foundry-backup`);this.runner.pause();try{$(this.database.db),await this.database.client.backup(n),await ir(n),qt(J(this.settingsPath),r),await ir(r);let t=Xn(this.database.db),a=Nn(n);if(a!==1)throw new E(`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 Qn(n,D),schemaVersion:a},settings:{...await Qn(r,O),version:1}};return await le(i,`${JSON.stringify(c,null,2)}\n`,{mode:384}),await qe([{entryPath:k,filePath:i},{entryPath:D,filePath:n},{entryPath:O,filePath:r}],o),await Rn(o,s,e),await ir(s),{filePath:s,providerCount:t.providers,captureCount:t.captures,jobCount:t.jobs}}finally{this.runner.resume(),await this.removeQuietly(t)}})}async inspectImport(e,t,n=a.basename(e)){return Jn(t),this.runExclusive(async()=>{$(this.database.db),await this.clearStagedImports();let r=g(),i=await this.createWorkDirectory(`import-${r}`),o=a.join(i,`archive.zip`),s=a.join(i,`extracted`),c;try{await ae(s,{recursive:!1,mode:448}),await zn(e,o,t);let l=await Je(o,s),u=Ue(JSON.parse(await se(l[k],`utf8`)));if(u.database.schemaVersion>1)throw new E(`NEWER_SCHEMA`,`The archive was created by a newer Foundry version`);let d=l[D],f=l[O];if(await $n(d,u.database),await $n(f,u.settings),Nn(d)!==u.database.schemaVersion)throw new E(`INVALID_ARCHIVE`,`The archived database schema does not match its manifest`);er(d),J(f),c=Pn(d),$(c.db),tr(c.db),nr(c.db);let ee=Xn(c.db),te={importId:r,fileName:a.basename(n),exportedAt:u.createdAt,appVersion:u.appVersion,databaseSchemaVersion:u.database.schemaVersion,settingsVersion:u.settings.version,providerCount:ee.providers,captureCount:ee.captures,jobCount:ee.jobs};return this.stagedImports.set(r,{databasePath:d,directory:i,preview:te,settingsPath:f}),await h(o,{force:!0}),te}catch(e){throw this.stagedImports.delete(r),await this.removeQuietly(i),e instanceof E?e:new E(`INVALID_ARCHIVE`,`The Foundry export could not be inspected`,{cause:e})}finally{c?.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 E(`IMPORT_NOT_FOUND`,`The import session has expired`);return this.runExclusive(async()=>{this.runner.pause();let n=J(this.settingsPath),r=!1;try{$(this.database.db);let n=Pn(t.databasePath);try{$(n.db),tr(n.db),nr(n.db);let e=n.db.select().from(I).all(),i=n.db.select().from(L).all(),a=n.db.select().from(R).all();qt(J(t.settingsPath),this.settingsPath),r=!0,this.database.db.transaction(t=>{t.delete(R).run(),t.delete(L).run(),t.delete(I).run(),e.length>0&&t.insert(I).values(e).run(),i.length>0&&t.insert(L).values(i).run(),a.length>0&&t.insert(R).values(a).run()})}finally{n.client.close()}this.stagedImports.delete(e),await this.removeQuietly(t.directory)}catch(e){throw r&&qt(n,this.settingsPath),e}finally{this.runner.resume(),this.runner.notifySettingsChanged()}})}async removeExportFile(e){a.dirname(e)===this.temporaryRoot&&await h(e,{force:!0})}};function Jn(e){if(e.length===0)throw new E(`PASSPHRASE_REQUIRED`,`Enter a passphrase`)}function Yn(e){return e.select({total:v()}).from(R).where(_(ye(R.status,[`pending`,`running`]),b(R.deletedAt))).get()?.total??0}function $(e){if(Yn(e)>0)throw new E(`ACTIVE_JOBS`,`Finish active scrape jobs before transferring data`)}function Xn(e){return{providers:e.select({total:v()}).from(I).get()?.total??0,captures:e.select({total:v()}).from(L).get()?.total??0,jobs:e.select({total:v()}).from(R).get()?.total??0}}async function Zn(e){let t=he(`sha256`);for await(let n of c(e))t.update(n);return t.digest(`hex`)}async function Qn(e,t){return{path:t,bytes:(await ce(e)).size,sha256:await Zn(e)}}async function $n(e,t){if((await ce(e)).size!==t.bytes||await Zn(e)!==t.sha256)throw new E(`INVALID_ARCHIVE`,`An archived file failed its integrity validation`)}function er(e){let t=new Oe(e,{fileMustExist:!0,readonly:!0});try{if(t.pragma(`integrity_check`,{simple:!0})!==`ok`)throw new E(`INVALID_ARCHIVE`,`The archived database failed its integrity check`);if(t.pragma(`foreign_key_check`).length>0)throw new E(`INVALID_ARCHIVE`,`The archived database contains invalid references`)}finally{t.close()}}function tr(e){for(let t of e.select().from(L).all()){if(!t.latestSuccessfulJobId||t.deletedAt)continue;let n=e.select({captureId:R.captureId,status:R.status}).from(R).where(y(R.id,t.latestSuccessfulJobId)).get();if(n?.captureId!==t.id||n.status!==`succeeded`)throw new E(`INVALID_ARCHIVE`,`A capture points to an invalid successful scrape job`)}}function nr(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(I).all()){if(!t.has(n.status))throw new E(`INVALID_ARCHIVE`,`A provider record is invalid`);try{ut({name:n.name,protocol:n.protocol,baseURL:n.baseURL,customModels:JSON.parse(n.customModels)})}catch{throw new E(`INVALID_ARCHIVE`,`A provider record is invalid`)}}for(let t of e.select().from(L).all())try{let e=new URL(t.url);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new E(`INVALID_ARCHIVE`,`A capture URL is invalid`)}for(let t of e.select().from(R).all())if(!n.has(t.status)||!r.has(t.fetcher))throw new E(`INVALID_ARCHIVE`,`A scrape job record is invalid`)}function rr(e){return n.platform===`win32`?Promise.resolve():m(e,448)}function ir(e){return n.platform===`win32`?Promise.resolve():m(e,384)}var ar=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 or(e){let t=U(),n=new ar,r=new it,i=jn(e,t,n),a=new qn(e,t,i.runner,Dt(),Ne,r,e=>n.publish(`data-transfer.status.changed`,e)),o=new Xt(e,t),s=new tn(t);return{apiOptions:{settingsPath:t,captureService:i.service,dataTransferService:a,providerService:o,settingsService:s,workspaceMutationGate:r,eventHub:n,onSettingsChanged:i.notifySettingsChanged},start(){a.cleanupStaleTransfers(),i.start()}}}const{dirname:sr,join:cr,resolve:lr}=a,ur=sr(je(import.meta.url));function dr(){let e=[lr(ur,`web`),lr(n.cwd(),`dist/web`)].find(e=>u(cr(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function fr({database:e,webRoot:t=dr(),onListening:i}){let a=or(e),o=ln(t,e,a.apiOptions);a.start();let s=r({fetch:o.fetch,hostname:`127.0.0.1`,port:11111},()=>{i?.({url:`http://localhost:11111`,webRoot:t})});return s.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),n.exitCode=1}),s}function pr(e,t){return new Promise((n,r)=>{let i=Me();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function mr(e){let t=`xdg-open`,r=[e];n.platform===`darwin`?t=`open`:n.platform===`win32`&&(t=`cmd`,r=[`/c`,`start`,`""`,e]);let i=Ee(t,r,{detached:!0,stdio:`ignore`});i.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),i.unref()}const hr=e({meta:{name:`foundry`,version:Ne,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 pr(`127.0.0.1`,11111)}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`Unable to start Foundry: ${t}`),n.exitCode=1;return}fr({database:Fn(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&mr(t)}})}});t(hr);export{};
2
+ import{defineCommand as e,runMain as t,showUsage as n}from"citty";import{setTimeout as r}from"node:timers/promises";import{chmod as i,copyFile as a,cp as o,link as s,mkdir as c,open as l,readFile as u,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{};
@@ -0,0 +1,118 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # Foundry
7
+
8
+ Foundry is a local CLI workbench. Use the installed `foundry` command and treat
9
+ its JSON output as the authoritative state.
10
+
11
+ If `foundry` is not available on `PATH`, report that prerequisite to the user.
12
+ This skill documents product usage, not application development or packaging.
13
+
14
+ ## Route By Task
15
+
16
+ Read only the references needed for the current request.
17
+
18
+ | User intent | Read |
19
+ | --- | --- |
20
+ | Invocation, JSON conventions, IDs, stdin, the Web UI | [references/cli-conventions.md](references/cli-conventions.md) |
21
+ | Appearance, language, timezone, capture fetcher configuration | [references/settings.md](references/settings.md) |
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) |
24
+ | Encrypted export, preview, or destructive restore | [references/data-transfer.md](references/data-transfer.md) |
25
+
26
+ ## Core Model
27
+
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
32
+ is `foundry captures jobs ...`; there is no global jobs command.
33
+ - A successful capture command returns `capture.id`, `job.id`,
34
+ `job.status`, and `content.markdown`.
35
+ - CLI timestamps are ISO-8601 strings. The CLI does not apply the user's display
36
+ time format or timezone; that formatting belongs to the Web UI.
37
+ - Capture and provider records intentionally expose stored API keys in JSON
38
+ because Foundry is local-only. Never repeat a credential unless the user
39
+ explicitly needs the value.
40
+
41
+ ## Operating Rules
42
+
43
+ 1. Read current state before a nontrivial mutation.
44
+ 2. Reuse IDs returned by create/list/get commands.
45
+ 3. Treat provider `update` as full replacement, not partial patching.
46
+ 4. Check `job.status` after capture operations. A command can exit successfully
47
+ with a completed job whose status is `failed`.
48
+ 5. Run `data-transfer inspect` before `data-transfer import`; import replaces the
49
+ current database and settings.
50
+ 6. Prefer `FOUNDRY_PASSPHRASE` over `--passphrase` so backup secrets do not enter
51
+ shell history.
52
+ 7. Use CLI commands instead of editing files under `<home>/.foundry` directly.
53
+
54
+ ## Command Tree
55
+
56
+ ```text
57
+ foundry web [--no-open]
58
+
59
+ foundry settings get
60
+ foundry settings update --input '<json>'
61
+ foundry settings open
62
+ foundry settings download-skill --target .agents,.claude
63
+
64
+ foundry providers list
65
+ foundry providers get <provider-id>
66
+ foundry providers create --input '<json>'
67
+ foundry providers update <provider-id> --input '<json>'
68
+ foundry providers set-status <provider-id> --status active|disabled|deleted
69
+ foundry providers models <provider-id>
70
+ foundry providers models-for-connection --input '<json>'
71
+
72
+ foundry captures list [--filter all|no-successful]
73
+ foundry captures counts
74
+ foundry captures get <capture-id>
75
+ foundry captures create <url> [--note <text>]
76
+ foundry captures recapture <capture-id>
77
+ foundry captures note <capture-id> <text>
78
+ foundry captures delete <capture-id>
79
+
80
+ foundry captures jobs list <capture-id>
81
+ foundry captures jobs get <capture-id> <job-id>
82
+ foundry captures jobs recapture <capture-id>
83
+
84
+ foundry data-transfer status
85
+ foundry data-transfer export --output <path> [--force]
86
+ foundry data-transfer inspect <path>
87
+ foundry data-transfer import <path>
88
+
89
+ ```
90
+
91
+ `provider`, `capture`, and `data` are aliases for the corresponding command
92
+ groups. Run `foundry <command> --help` when the installed version may differ
93
+ from these references.
94
+
95
+ ## Workflow: Capture A Page
96
+
97
+ 1. Read `settings get`; if no capture fetcher is selected or its API key is
98
+ empty, update settings first.
99
+ 2. Run `captures create <url> --note <text>`.
100
+ 3. Inspect the returned `job.status`.
101
+ 4. On success, use the returned `content.markdown` directly or fetch it again
102
+ later with `captures get <capture-id>`.
103
+ 5. On failure, read the job reference and investigate through
104
+ `captures jobs get`.
105
+
106
+ ## Workflow: Change A Provider Safely
107
+
108
+ 1. Run `providers get <provider-id>`.
109
+ 2. Merge the requested changes into the complete existing provider object.
110
+ 3. Preserve `apiKey` and `customModels` unless the user intends to replace them.
111
+ 4. Run `providers update <provider-id> --input '<complete-json>'`.
112
+
113
+ ## Workflow: Restore Data
114
+
115
+ 1. Run `data-transfer status`; active jobs block transfers.
116
+ 2. Run `data-transfer inspect <path>` and report the preview.
117
+ 3. Proceed with `data-transfer import <path>` only when replacing current
118
+ Foundry data is the explicit intent.