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