@dhzh/foundry 7.0.1 → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,22 +1,27 @@
1
1
  # Foundry
2
2
 
3
3
  Foundry is a local personal workbench distributed as a CLI with a bundled Web UI.
4
- People and agents can use the CLI to manage settings, export or import encrypted
5
- backups, and install the bundled Foundry Skill.
4
+ People and agents can use the CLI to manage instructions and settings, export or
5
+ import encrypted backups, and install the bundled Foundry Skill.
6
6
 
7
7
  ## Current scope
8
8
 
9
- Settings is the implemented feature in the current Web UI and the only business
10
- command group in the CLI. It covers appearance, language and region, and Advanced
11
- actions. The main layout, sidebar, and placeholder routes remain available for
12
- future work. The root route opens Dashboard; opening Settings without a category
13
- shows Appearance.
9
+ The current Web UI implements Instructions and Settings. The CLI exposes
10
+ `instructions`, `agents`, and `settings` business command groups. Instructions
11
+ supports creating, editing, deleting, and listing Markdown instruction files
12
+ from the Web UI or CLI, and the Web page and CLI assign them to ChatGPT and
13
+ Claude Code.
14
+ Settings covers appearance, language and region, and Advanced actions, including
15
+ encrypted backups and bundled Skill installation. The main layout and sidebar
16
+ remain available, with placeholder routes for features not implemented yet. The
17
+ root route opens Dashboard; opening Settings without a category shows Appearance.
14
18
 
15
19
  Provider, capture, fetch-job, and session backend services and APIs are retained.
16
20
  Their presence does not imply a corresponding page or CLI command in the current
17
21
  product. `app/web/legacy-src` holds remaining reference code; its Settings
18
- implementation has been removed. Keeping the current scope focused on Settings
19
- does not mean removing the application shell or other backend capabilities.
22
+ implementation has been removed. Keeping the current scope focused on
23
+ Instructions and Settings does not mean removing the application shell or other
24
+ backend capabilities.
20
25
 
21
26
  ## Requirements and startup
22
27
 
@@ -78,6 +83,109 @@ Omitted or invalid `panel` values select Appearance. Timezone names are localize
78
83
  the stored values remain IANA timezone identifiers. The full-screen Settings back
79
84
  button returns one step through browser history.
80
85
 
86
+ ## Instructions
87
+
88
+ Create an instruction with a required name and Markdown content:
89
+
90
+ ```bash
91
+ foundry instructions new \
92
+ --name "Release checklist" \
93
+ --content "# Release
94
+
95
+ - Run tests
96
+ - Check the changelog"
97
+ ```
98
+
99
+ Quote content containing spaces or newlines. Names are trimmed and limited to
100
+ 200 characters; content must be non-empty and is capped at 1,000,000 characters.
101
+ The command prints the stored instruction as JSON. The Web UI exposes the same
102
+ creation flow at `#/library/instructions` and renders the stored instructions
103
+ newest first.
104
+
105
+ List all instructions, newest first:
106
+
107
+ ```bash
108
+ foundry instructions list
109
+ ```
110
+
111
+ The command prints a JSON array in the same shape as the creation result. Use
112
+ the Web page or `GET /api/instructions` for the same ordered list.
113
+
114
+ Read one instruction or replace its name and Markdown content:
115
+
116
+ ```bash
117
+ foundry instructions get <id>
118
+ foundry instructions edit <id> \
119
+ --name "Release checklist" \
120
+ --content "# Release
121
+
122
+ - Run tests"
123
+ ```
124
+
125
+ `edit` requires both fields, trims the name, preserves the ID and creation time,
126
+ and advances `updatedAt`. It changes the instruction record only; reapply any
127
+ enabled agent that uses it to rewrite the managed block.
128
+
129
+ Delete an unused instruction:
130
+
131
+ ```bash
132
+ foundry instructions delete <id>
133
+ ```
134
+
135
+ Deletion removes the Markdown file. It is rejected with
136
+ `INSTRUCTION_IN_USE` while any agent assignment still references the
137
+ instruction; clear the assignment from every agent first. The command prints
138
+ the deleted record as JSON.
139
+
140
+ Instructions are stored as individual Markdown files at
141
+ `<home>/.foundry/instructions/<id>.md`. Each file has YAML frontmatter for the
142
+ ID, name, and timestamps; timestamps are Unix epoch milliseconds. The Markdown
143
+ body is preserved unchanged. The API
144
+ provides list/create and `GET`/`PUT`/`DELETE /api/instructions/:id`. In the Web
145
+ UI, selecting an instruction opens the editor directly; right-clicking a row
146
+ opens Edit and Delete actions. See
147
+ [Instructions implementation](docs/instructions.md).
148
+
149
+ ## Agent orchestration
150
+
151
+ The Instructions page composes saved instructions into two fixed agent files:
152
+
153
+ - ChatGPT: `~/.codex/AGENTS.md`
154
+ - Claude Code: `~/.claude/CLAUDE.md`
155
+
156
+ Desktop layouts show instructions on the left and agent cards on the right.
157
+ Drag an instruction into an agent to assign it; drag assigned rows to reorder
158
+ them. Each agent accepts an instruction only once. The switch applies or removes
159
+ Foundry's managed block without affecting other file content, and Reapply
160
+ rewrites the current block.
161
+
162
+ Foundry writes exactly one managed block using the selected markers:
163
+
164
+ ```md
165
+ <!-- foundry:instructions:start -->
166
+
167
+ ...assigned instructions in order...
168
+
169
+ <!-- foundry:instructions:end -->
170
+ ```
171
+
172
+ Assignment state is stored under `<home>/.foundry/agents`. Each file keeps the
173
+ agent `id` at the top level and instruction state under an `instructions`
174
+ namespace. The Web page uses `/api/agents`; the equivalent CLI operations are:
175
+
176
+ ```bash
177
+ foundry agents list
178
+ foundry agents instructions list [agent]
179
+ foundry agents instructions assign chatgpt --instructions <id1>,<id2>
180
+ foundry agents instructions enable chatgpt
181
+ foundry agents instructions reapply chatgpt
182
+ foundry agents instructions disable chatgpt
183
+ foundry agents instructions open chatgpt
184
+ ```
185
+
186
+ See [Agent orchestration](docs/agents.md) for the CLI, API, behavior, and block
187
+ rules.
188
+
81
189
  ## Backups and agent Skill
82
190
 
83
191
  Settings > Advanced provides Export, Import, Config Folder, and Download Skill.
@@ -91,11 +199,12 @@ foundry settings download-skill --target .agents,.claude
91
199
 
92
200
  Backup passphrases use `FOUNDRY_PASSPHRASE` or `--passphrase`. Export rejects an
93
201
  existing destination unless `--force` is supplied. Import normalizes backup data
94
- and replaces the supported data completely. The current backup payload contains
95
- settings, including settings retained for backend features; it is not a copy of
96
- all runtime files. Providers, captures, and fetch jobs are outside this payload.
97
- Web import reloads the page without the hash route and enters the normal root
98
- route. See [backup behavior and format](docs/data-export.md).
202
+ and replaces the supported data completely. The backup payload contains
203
+ settings, instructions, and agent assignments. Providers, captures, fetch jobs,
204
+ and the external `AGENTS.md`/`CLAUDE.md` files are outside this payload; reapply
205
+ enabled agents after import to rewrite their managed blocks. Web import reloads
206
+ the page without the hash route and enters the normal root route. See
207
+ [backup behavior and format](docs/data-export.md).
99
208
 
100
209
  Download Skill installs Foundry's agent usage manual, which teaches agents how
101
210
  to operate the installed Foundry CLI. It copies to selected user-level targets:
@@ -143,8 +252,11 @@ Runtime data lives in `<home>/.foundry`, outside the repository and `dist`:
143
252
  - `settings.json`: normalized application settings
144
253
  - `providers.json`: retained provider records
145
254
  - `captures/` and `fetch-jobs/`: one JSON file per retained record
255
+ - `instructions/`: one Markdown instruction file per record
256
+ - `agents/`: one JSON agent profile per record, including the `instructions`
257
+ capability state
146
258
 
147
- Foundry uses process locking, atomic replacement, and a redo journal for JSON
259
+ Foundry uses process locking, atomic replacement, and a redo journal for storage
148
260
  transactions. Reads load files directly. Startup recovers committed interrupted
149
261
  writes; a new installation uses default settings and empty collections. Foundry
150
262
  does not import old SQLite databases. The retained Sessions backend reads external
@@ -169,6 +281,8 @@ exposes only `./package.json`. Verify with `pnpm pack --dry-run`.
169
281
 
170
282
  - [Development constraints](AGENTS.md): architecture, storage, and verification
171
283
  - [Web development](app/web/README.md) and [design rules](app/web/DESIGN.md)
284
+ - [Instructions implementation](docs/instructions.md): Web list, view, edit, API, CLI, and file format
285
+ - [Agent orchestration](docs/agents.md): fixed agent files, drag state, CLI/API, and managed block rules
172
286
  - [Settings implementation](docs/settings.md): routing, synchronization, and API boundaries
173
287
  - [Data export and import](docs/data-export.md): normalization, replacement, and format
174
288
  - [Foundry Skill](skills/foundry/SKILL.md): installed CLI usage for agents
package/dist/index.mjs CHANGED
@@ -1,6 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:process";import{spawn as i}from"node:child_process";import{chmodSync as a,closeSync as o,createReadStream as s,createWriteStream as c,existsSync as l,fsyncSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,renameSync as ee,rmSync as h,rmdirSync as te,statSync as g,watch as ne,writeFileSync as _}from"node:fs";import re,{homedir as ie,tmpdir as ae}from"node:os";import v from"node:path";import{createCipheriv as oe,createDecipheriv as se,createHash as ce,randomBytes as le,randomUUID as y,scrypt as ue}from"node:crypto";import{chmod as de,cp as fe,link as pe,mkdir as me,mkdtemp as he,open as ge,readFile as _e,readdir as ve,rename as b,rm as x,stat as ye,writeFile as be}from"node:fs/promises";import{fileURLToPath as xe}from"node:url";import{Buffer as S}from"node:buffer";import{pipeline as C}from"node:stream/promises";import Se from"yauzl";import Ce from"yazl";import{Readable as we,Transform as Te}from"node:stream";import{serve as Ee}from"@hono/node-server";import{serveStatic as De}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{StringDecoder as Oe}from"node:string_decoder";import{createZstdDecompress as ke}from"node:zlib";import{streamSSE as Ae}from"hono/streaming";import{FirecrawlClient as je}from"firecrawl";import{parse as Me}from"tldts";import{createServer as Ne}from"node:net";var Pe=`7.0.1`;const Fe=[`system`,`light`,`dark`],Ie=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Le=[`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`],Re=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],ze=[`firecrawl`],T=`data/foundry.json`,Be=`settings.changed`,Ve=[`agents`,`claude`],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 He(e){let t=A(e)?e:{},n=A(t.workspace)?t.workspace:{},r=A(n.appearance)?n.appearance:{},i=A(n[`language-region`])?n[`language-region`]:{},a=A(t.features)?t.features:{},o=A(a.library)?a.library:{},s=A(o.captures)?o.captures:{},c=A(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":O(r[`color-theme`],Fe,E.workspace.appearance[`color-theme`])},"language-region":{language:O(i.language,Ie,E.workspace[`language-region`].language),"time-format":O(i[`time-format`],Le,E.workspace[`language-region`][`time-format`]),"time-zone":O(i[`time-zone`],Re,E.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:qe(s.fetcher),maxAttempts:Ye(s.maxAttempts,10,1),fetchConcurrency:Ye(s.fetchConcurrency,5,2),firecrawl:{apiKey:Qe(c.apiKey)}}}}}}function Ue(e){if(!A(e))throw new D(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=k(e.theme,Fe,`theme`)),`language`in e&&(t.language=k(e.language,Ie,`language`)),`timeFormat`in e&&(t.timeFormat=k(e.timeFormat,Le,`timeFormat`)),`timezone`in e&&(t.timezone=k(e.timezone,Re,`timezone`)),`captures`in e&&(t.captures=Ke(e.captures)),t}function We(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 Ge(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 Ke(e){if(!A(e))throw new D(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:k(e.fetcher,ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=Xe(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=Xe(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=Ze(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function qe(e){return Je(e,ze)}function Je(e,t){return typeof e==`string`&&t.includes(e)?e:null}function O(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function k(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new D(`Invalid ${n}`);return e}function Ye(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function Xe(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 Ze(e,t){if(typeof e!=`string`)throw new D(`${t} must be a string`);return e.trim()}function Qe(e){return typeof e==`string`?e:``}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $e(e){if(!tt(e)||!Array.isArray(e.targets))throw new et(`targets must be an array`);if(e.targets.length===0)throw new et(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Ve.includes(e))throw new et(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var et=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function tt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nt(e){let t=r.platform===`darwin`?`open`:r.platform===`win32`?`explorer`:`xdg-open`,n=i(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function rt(){return v.join(re.homedir(),`.foundry`)}function it(){let e=rt();return d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448),e}function j(e){return e.readSettings()}function at(e){return Ge(j(e))}function ot(e,t){return t.transaction(()=>{let n=We(j(t),e);return t.setSettings(n),Ge(n)})}var st=class{storage;configFolder;openFolder;constructor(e,t=rt(),n=nt){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...at(this.storage),configFolder:this.configFolder}}update(e){return{...ot(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const ct=v.dirname(xe(import.meta.url)),M=`foundry`;var lt=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ie()}={}){this.configuredSkillRoot=e,this.homeDirectory=v.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??ut();if(!l(v.join(t,`SKILL.md`)))throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),r=v.join(n,M),i=v.join(n,`.${M}-${y()}.tmp`),a=v.join(n,`.${M}-${y()}.backup`);try{return await me(n,{recursive:!0}),await fe(t,i,{recursive:!0,errorOnExist:!0}),await dt(i,r,a),{target:e,destination:r}}catch(e){throw await x(i,{recursive:!0,force:!0}),e instanceof N?e:new N(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return v.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:v.join(this.getTargetParent(e),M)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},N=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function ut(){let e=[v.resolve(ct,`skills`,M),v.resolve(ct,`..`,`..`,`..`,`skills`,M),v.resolve(r.cwd(),`skills`,M)].find(e=>l(v.join(e,`SKILL.md`)));if(!e)throw new N(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function dt(e,t,n){let r=l(t);r&&await b(t,n);try{await b(e,t),r&&await x(n,{recursive:!0,force:!0})}catch(e){throw r&&!l(t)&&l(n)&&await b(n,t),e}}const ft=`manifest.json`,pt=/* @__PURE__ */ new Set([ft,T]);async function mt(e,t){let n=new Ce.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await C(n.outputStream,c(t,{mode:384}))}async function ht(e,t){let n=await gt(e),r=/* @__PURE__ */ new Map;try{await new Promise((e,i)=>{let a=e=>{i(e instanceof Error?e:Error(String(e)))},o=async e=>{if(!pt.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 i=v.join(t,e.fileName);await me(v.dirname(i),{recursive:!0,mode:448}),await C(await _t(n,e),c(i,{mode:384})),r.set(e.fileName,i),n.readEntry()};n.on(`error`,a),n.on(`end`,e),n.on(`entry`,e=>{o(e).catch(a)}),n.readEntry()})}catch(e){throw await x(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!r.has(ft)||!r.has(`data/foundry.json`))throw await x(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(r)}function gt(e){return new Promise((t,n)=>{Se.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function _t(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var vt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const P=S.from(`FOUNDRYX`,`ascii`),F=`aes-256-gcm`,yt=`scrypt`,I={N:131072,r:8,p:1};async function bt(e,t,n){let r=le(16),i=le(12),a={version:1,cipher:F,kdf:{name:yt,salt:r.toString(`base64`),...I,keyLength:32},nonce:i.toString(`base64`)},o=S.from(JSON.stringify(a),`utf8`),l=St(o.byteLength),u=S.concat([l,o]),d=await Ct(n,r,I);try{let n=await ge(t,`w`,384);try{await n.write(u)}finally{await n.close()}await C(s(e),wt(d,i,u),c(t,{flags:`r+`,mode:384,start:u.byteLength})),await de(t,384)}catch(e){throw await x(t,{force:!0}),new vt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function xt(e,t,n){let r;try{let i=(await ye(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await ge(e,`r`),o,l,u;try{if(o=await Dt(a,13,0),!o.subarray(0,P.byteLength).equals(P))throw Error(`The export file signature is invalid`);if(o.readUInt8(P.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(P.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`);l=await Dt(a,e,13),u=await Dt(a,16,i-16)}finally{await a.close()}let d=Et(JSON.parse(l.toString(`utf8`)));r=await Ct(n,d.salt,d.header.kdf);let f=S.concat([o,l]);await C(s(e,{start:13+l.byteLength,end:i-16-1}),Tt(r,d.nonce,f,u),c(t,{mode:384})),await de(t,384)}catch(e){throw await x(t,{force:!0}),e instanceof vt?e:new vt(kt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,kt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function St(e){let t=S.alloc(13);return P.copy(t,0),t.writeUInt8(1,P.byteLength),t.writeUInt32BE(e,P.byteLength+1),t}function Ct(e,t,n){return new Promise((r,i)=>{ue(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function wt(e,t,n){let r=oe(F,e,t,{authTagLength:16});return r.setAAD(n),new Te({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,S.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Tt(e,t,n,r){let i=se(F,e,t,{authTagLength:16});return i.setAAD(n),new Te({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 Et(e){if(!Ot(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==F||!Ot(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==yt||typeof t.salt!=`string`||t.N!==I.N||t.r!==I.r||t.p!==I.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=S.from(t.salt,`base64`),r=S.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:F,kdf:{name:yt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Dt(e,t,n){let r=S.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Ot(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function At(e){try{await x(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function jt(e){return{settings:e.readSettings()}}var Mt=class{storage;constructor(e){this.storage=e}async createExport(e){let t=jt(this.storage),n=await he(v.join(ae(),`foundry-export-`));try{let r=(/* @__PURE__ */ new Date()).toISOString(),i=JSON.stringify(t,null,2),a=v.join(n,`foundry.json`),o=v.join(n,`manifest.json`),s=v.join(n,`foundry.zip`),c=v.join(n,`foundry.foundry-backup`),l={format:`foundry.data`,archiveVersion:1,appVersion:Pe,createdAt:r,data:{path:T,bytes:S.byteLength(i,`utf8`),sha256:ce(`sha256`).update(i).digest(`hex`)}};return await be(a,i,{mode:384}),await be(o,JSON.stringify(l,null,2),{mode:384}),await mt([{entryPath:`manifest.json`,filePath:o},{entryPath:T,filePath:a}],s),await bt(s,c,e),{fileName:`foundry-${r.replaceAll(`:`,`-`)}.foundry-backup`,contents:await _e(c)}}finally{await At(n)}}},L=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pt(e){if(!Nt(e)||e.format!==`foundry.data`||e.archiveVersion!==1||!Nt(e.data)||e.data.path!==`data/foundry.json`||typeof e.data.bytes!=`number`||!Number.isSafeInteger(e.data.bytes)||e.data.bytes<=0||typeof e.data.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.data.sha256))throw new L(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:T,bytes:e.data.bytes,sha256:e.data.sha256}}}function Ft(e){if(!Nt(e)||!Nt(e.settings))throw new L(`INVALID_BACKUP`,`Backup data must contain a settings object`);return{settings:He(e.settings)}}function It(e,t){e.transaction(()=>{e.setSettings(t.settings)})}var Lt=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await he(v.join(ae(),`foundry-import-`));try{let r=v.join(n,`backup.zip`);await xt(e,r,t);let i=await ht(r,v.join(n,`extracted`)),a=Pt(JSON.parse(await _e(i[`manifest.json`],`utf8`))),o=await _e(i[T]);if(o.byteLength!==a.data.bytes||ce(`sha256`).update(o).digest(`hex`)!==a.data.sha256)throw new L(`INVALID_BACKUP`,`Backup checksum does not match`);let s=Ft(JSON.parse(o.toString(`utf8`)));try{It(this.storage,s)}catch{throw new L(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof L?e:e instanceof vt?e.code===`INVALID_PASSPHRASE`?new L(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new L(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new L(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await At(n)}}};function Rt(e){d(e,{recursive:!0,mode:448}),r.platform!==`win32`&&a(e,448)}function R(e){if(r.platform===`win32`)return;let t=f(e,`r`);try{u(t)}finally{o(t)}}function zt(e,t){Rt(v.dirname(e));let n=`${e}.${y()}.tmp`;try{let r=f(n,`wx`,384);try{_(r,`${JSON.stringify(t,null,2)}\n`),u(r)}finally{o(r)}ee(n,e),R(v.dirname(e))}finally{h(n,{force:!0})}}const Bt=[`providers`,`captures`,`fetchJobs`];function Vt(e){try{let t=JSON.parse(p(v.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return r.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-g(e).mtimeMs>3e4}}var Ht=class{path;changes=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Rt(e);for(let e of Bt)e!==`providers`&&Rt(this.collectionPath(e))}collectionPath(e){return v.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return v.relative(this.path,v.join(this.collectionPath(e),`${ce(`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=v.join(this.path,`.lock`),n=Date.now();for(;;)try{d(t,{mode:448});try{_(v.join(t,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384})}catch(e){throw h(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,h(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=g(e);if(!Vt(e))return;let n=v.join(e,`recovering`);try{d(n)}catch(e){if(e.code===`EEXIST`){let e=g(n);Vt(n)&&g(n).ino===e.ino&&h(n,{recursive:!0,force:!0})}return}if(_(v.join(n,`owner.json`),JSON.stringify({pid:r.pid}),{mode:384,flag:`wx`}),g(e).ino!==t.ino||!Vt(e)){h(n,{recursive:!0,force:!0});return}h(e,{recursive:!0,force:!0})}catch{}}recover(){let e=v.join(this.path,`.transaction.json`);if(!l(e))return;let t=JSON.parse(p(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=v.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!l(e)){let e=l(t)?m(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,v.join(`providers`,e)))},...e.map(e=>({file:v.join(`providers`,e),value:null}))]};zt(v.join(this.path,`.transaction.json`),n),this.applyJournal(n)}l(t)&&m(t).length===0&&(te(t),R(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(p(v.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=v.resolve(this.path,t.file),n=v.relative(this.path,e);if(n.startsWith(`..`)||v.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:providers|captures|fetch-jobs)[/\\][^/\\]+\.json)$/u.test(n))throw Error(`Invalid storage recovery journal`);t.value===null?(h(e,{force:!0}),R(v.dirname(e))):zt(e,t.value)}h(v.join(this.path,`.transaction.json`),{force:!0}),R(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=v.join(this.path,t);if(!l(e))return;n=JSON.parse(p(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(m(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>v.relative(this.path,v.join(t,e.name))));if(this.changes){let e=v.relative(this.path,t);for(let t of this.changes.keys())v.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 He(this.changes.get(`settings.json`));let e=v.join(this.path,`settings.json`);return l(e)?He(JSON.parse(p(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`,He(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map;let t;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}))};zt(v.join(this.path,`.transaction.json`),e),t={value:n},this.applyJournal(e)}return n}catch(e){if(t)return this.recover(),t.value;throw e}finally{this.changes=null}})}close(){this.closed=!0}};function Ut(e=rt()){let t=new Ht(e);try{return t.transaction(()=>{let n=t.readSettings();l(v.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function Wt(){return it(),Ut()}async function z(e){let t;try{let n=Wt();t={storage:n,settingsService:new st(n),settingsSkillCopyService:new lt,dataExportService:new Mt(n),dataImportService:new Lt(n)},Kt(await e(t))}catch(e){let t=qt(e);console.error(JSON.stringify({error:t},null,2)),r.exitCode=1}finally{t?.storage.close()}}function Gt(e){let t=e??r.env.FOUNDRY_PASSPHRASE;if(!t)throw new B(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Kt(e){console.log(JSON.stringify(e,null,2))}function qt(e){return e instanceof Error?{code:Jt(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Jt(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Yt=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({dataExportService:t})=>{let n=await t.createExport(Gt(e.passphrase)),r=Zt(e.output);return await Qt(n.contents,r,e.force),{filePath:r}})}}),Xt=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},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({dataImportService:t})=>(await t.importData(v.resolve(e.file),Gt(e.passphrase)),{status:`imported`}))}});function Zt(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,r=v.resolve(n);return r.toLowerCase().endsWith(`.foundry-backup`)?r:`${r}.foundry-backup`}async function Qt(e,t,n){await me(v.dirname(t),{recursive:!0,mode:448});let i=v.join(v.dirname(t),`.${v.basename(t)}.${y()}.tmp`);try{if(await be(i,e,{mode:384}),r.platform!==`win32`&&await de(i,384),n){await b(i,t);return}if(l(t))throw $t(t);try{await pe(i,t)}catch(e){throw en(e)?$t(t):e}}finally{await x(i,{force:!0})}}function $t(e){return new B(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function en(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const V={"color-theme":{field:`theme`,values:Fe},language:{field:`language`,values:Ie},"time-zone":{field:`timezone`,values:Re},"time-format":{field:`timeFormat`,values:Le}},tn=[...Object.keys(V),`config-folder`],nn=Object.entries(V).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
3
- `);function rn(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const an=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${tn.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return z(({settingsService:t})=>{let n=rn(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${tn.join(`, `)}`);return n[e.key]})}}),on=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(V).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${nn}`,required:!0}},run({args:e}){return z(({settingsService:t})=>{if(e.key===`config-folder`)throw new B(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(V,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(V).join(`, `)}`);let n=V[e.key];if(!n.values.includes(e.value))throw new B(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=rn(t.update(Ue({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),sn=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return z(({settingsService:e})=>e.openConfigFolder())}}),cn=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(({settingsSkillCopyService:t})=>{let n=$e({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),ln=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:an,set:on,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:sn}}),export:Yt,import:Xt,"download-skill":cn}});function un(e){if(!pn(e)||typeof e.url!=`string`)throw new H(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function dn(e){return e===`no-successful`?`no-successful`:`all`}function fn(e){if(!pn(e)||typeof e.userNote!=`string`)throw new H(`userNote must be a string`);return e.userNote}var H=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var U=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function mn(e,t=()=>{}){let n=new w;return n.get(`/`,t=>{let n=dn(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=un(await hn(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return W(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return W(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 W(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 W(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=fn(await hn(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return W(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return W(t,e)}}),n}async function hn(e){try{return await e.req.json()}catch{throw new H(`Request body must be valid JSON`)}}function W(e,t){if(t instanceof H)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}},gn(t.code));throw t}function gn(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}}const _n=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],vn=[`active`,`disabled`,`deleted`];var G=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},yn=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function bn(e){if(!Dn(e))throw new G(`Provider input must be an object`);let t=K(e.name,`name`),n=Tn(e.protocol),r=En(e.baseURL),i=e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0}),a=wn(e.customModels);return{...e.avatar!==void 0&&{avatar:xn(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function xn(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 G(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Sn(e){if(!Dn(e))throw new G(`Provider connection must be an object`);return{protocol:Tn(e.protocol),baseURL:En(e.baseURL),apiKey:e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Cn(e){if(typeof e!=`string`||!vn.includes(e))throw new G(`Invalid provider status`);return e}function wn(e){if(e===void 0)return[];if(!Array.isArray(e))throw new G(`customModels must be an array`);return e.map(e=>{if(!Dn(e))throw new G(`Each custom model must be an object`);return{id:K(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:K(e.displayName,`customModels.displayName`)}})}function Tn(e){if(typeof e!=`string`||!_n.includes(e))throw new G(`Invalid provider protocol`);return e}function En(e){let t=K(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new G(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function K(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new G(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new G(`${t} is required`);return r}function Dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var q=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function On(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(kn(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new q(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new q(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new q(`Provider returned invalid JSON`)}return An(i)}function kn(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function An(e){if(!Mn(e)||!Array.isArray(e.data))throw new q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Mn(e)||typeof e.id!=`string`||e.id.length===0)throw new q(`Provider returned an invalid model entry`);let t=jn(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function jn(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Nn=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Pn=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=>({...Fn(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?Fn(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 Nn;let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:t??y(),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),Fn(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new yn;let r=this.storage.get(`providers`,e);if(!r)throw new Nn;let i=(/* @__PURE__ */ new Date()).toISOString(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),Fn(a)})}};function Fn(e){return{...e,avatar:e.avatar??null,status:e.status}}function In(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 J(t,e)}}),n.post(`/models`,async t=>{try{let n=Sn(await Ln(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return J(t,e)}}),n.post(`/`,async n=>{try{let r=bn(await Ln(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return J(n,e)}}),n.put(`/:id`,async n=>{try{let r=bn(await Ln(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return J(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Ln(n),i=Cn(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 J(n,e)}}),n}async function Ln(e){try{return await e.req.json()}catch{throw new G(`Request body must be valid JSON`)}}function J(e,t){if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Nn)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof yn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},502);throw t}function Rn(e){let t=j(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 Bn=class{storage;repository;constructor(e){this.storage=e,this.repository=new Pn(e)}list(){return this.repository.list(Rn(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new Nn;return On(t)}fetchModelsForConnection(e){return On(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,Rn(this.storage)))}};function Vn(e,t=()=>{},n=new lt){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=Ue(await Hn(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Un(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=$e(await Hn(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Un(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Hn(e){try{return await e.req.json()}catch{throw new D(`Request body must be valid JSON`)}}function Un(e,t){if(t instanceof D||t instanceof et)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof N)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}var Wn=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function Gn(e){let t=new w;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return Kn(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return Kn(t,e)}}),t}function Kn(e,t){if(t instanceof Wn)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function qn(){let e=r.env.CLAUDE_CONFIG_DIR?.trim();return e?v.resolve(e):v.join(re.homedir(),`.claude`)}const Jn=1048576;async function Yn(e){let t;try{t=await ve(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let r of t){let t=v.join(e,r.name);if(r.isDirectory()){let e=await Yn(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else r.isFile()&&/\.jsonl(?:\.zst)?$/u.test(r.name)&&n.files.push(t)}let r=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!r.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function Xn(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Y(r)?t(r):n=!0},i=async e=>{let t=new Oe(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
2
+ import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:path";import i from"node:process";import{spawn as a}from"node:child_process";import{chmodSync as o,closeSync as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,mkdirSync as f,openSync as p,readFileSync as m,readdirSync as h,renameSync as ee,rmSync as g,rmdirSync as _,statSync as v,watch as te,writeFileSync as ne}from"node:fs";import re,{homedir as ie,tmpdir as ae}from"node:os";import{createCipheriv as oe,createDecipheriv as se,createHash as ce,randomBytes as le,randomUUID as y,scrypt as ue}from"node:crypto";import{chmod as de,cp as fe,link as pe,mkdir as me,mkdtemp as he,open as ge,readFile as _e,readdir as ve,rename as ye,rm as b,stat as be,writeFile as xe}from"node:fs/promises";import{fileURLToPath as Se}from"node:url";import{Buffer as x}from"node:buffer";import{pipeline as S}from"node:stream/promises";import Ce from"yauzl";import we from"yazl";import{Readable as Te,Transform as Ee}from"node:stream";import{parse as De,stringify as Oe}from"yaml";import{serve as ke}from"@hono/node-server";import{serveStatic as Ae}from"@hono/node-server/serve-static";import{Hono as C}from"hono";import{StringDecoder as je}from"node:string_decoder";import{createZstdDecompress as Me}from"node:zlib";import{streamSSE as Ne}from"hono/streaming";import{FirecrawlClient as Pe}from"firecrawl";import{parse as Fe}from"tldts";import{createServer as Ie}from"node:net";var Le=`7.1.1`,w=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function Re(e){if(!Be(e)||!Array.isArray(e.instructionIds))throw new w(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new w(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new w(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function ze(e){if(!Be(e)||typeof e.enabled!=`boolean`)throw new w(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Be(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ve=[`chatgpt`,`claude-code`];function He(e){return[{id:`chatgpt`,name:`ChatGPT`,icon:`openai`,instructionFile:`~/.codex/AGENTS.md`,filePath:r.join(e,`.codex`,`AGENTS.md`)},{id:`claude-code`,name:`Claude Code`,icon:`claudecode`,instructionFile:`~/.claude/CLAUDE.md`,filePath:r.join(e,`.claude`,`CLAUDE.md`)}]}function Ue(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=a(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function We(){return r.join(re.homedir(),`.foundry`)}function Ge(){let e=We();return f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const Ke=[`system`,`light`,`dark`],qe=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Je=[`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`],Ye=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Xe=[`firecrawl`],Ze=`data/foundry.json`,Qe=`settings.changed`,$e=[`agents`,`claude`],et={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 tt(e){let t=D(e)?e:{},n=D(t.workspace)?t.workspace:{},r=D(n.appearance)?n.appearance:{},i=D(n[`language-region`])?n[`language-region`]:{},a=D(t.features)?t.features:{},o=D(a.library)?a.library:{},s=D(o.captures)?o.captures:{},c=D(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":ct(r[`color-theme`],Ke,et.workspace.appearance[`color-theme`])},"language-region":{language:ct(i.language,qe,et.workspace[`language-region`].language),"time-format":ct(i[`time-format`],Je,et.workspace[`language-region`][`time-format`]),"time-zone":ct(i[`time-zone`],Ye,et.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:ot(s.fetcher),maxAttempts:lt(s.maxAttempts,10,1),fetchConcurrency:lt(s.fetchConcurrency,5,2),firecrawl:{apiKey:ft(c.apiKey)}}}}}}function nt(e){if(!D(e))throw new T(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=E(e.theme,Ke,`theme`)),`language`in e&&(t.language=E(e.language,qe,`language`)),`timeFormat`in e&&(t.timeFormat=E(e.timeFormat,Je,`timeFormat`)),`timezone`in e&&(t.timezone=E(e.timezone,Ye,`timezone`)),`captures`in e&&(t.captures=at(e.captures)),t}function rt(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 it(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var T=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function at(e){if(!D(e))throw new T(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:E(e.fetcher,Xe,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=ut(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=ut(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=dt(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function ot(e){return st(e,Xe)}function st(e,t){return typeof e==`string`&&t.includes(e)?e:null}function ct(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function E(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new T(`Invalid ${n}`);return e}function lt(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function ut(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new T(`${n} must be an integer from 1 to ${t}`);return e}function dt(e,t){if(typeof e!=`string`)throw new T(`${t} must be a string`);return e.trim()}function ft(e){return typeof e==`string`?e:``}function D(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O(e){return e.readSettings()}function pt(e){return it(O(e))}function mt(e,t){return t.transaction(()=>{let n=rt(O(t),e);return t.setSettings(n),it(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=We(),n=Ue){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...pt(this.storage),configFolder:this.configFolder}}update(e){return{...mt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const gt=r.dirname(Se(import.meta.url)),k=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ie()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??vt();if(!u(r.join(t,`SKILL.md`)))throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,k),a=r.join(n,`.${k}-${y()}.tmp`),o=r.join(n,`.${k}-${y()}.backup`);try{return await me(n,{recursive:!0}),await fe(t,a,{recursive:!0,errorOnExist:!0}),await yt(a,i,o),{target:e,destination:i}}catch(e){throw await b(a,{recursive:!0,force:!0}),e instanceof A?e:new A(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return r.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:r.join(this.getTargetParent(e),k)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},A=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function vt(){let e=[r.resolve(gt,`skills`,k),r.resolve(gt,`..`,`..`,`..`,`skills`,k),r.resolve(i.cwd(),`skills`,k)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function yt(e,t,n){let r=u(t);r&&await ye(t,n);try{await ye(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await ye(n,t),e}}const bt=`manifest.json`,xt=/* @__PURE__ */ new Set([bt,Ze]);async function St(e,t){let n=new we.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await S(n.outputStream,l(t,{mode:384}))}async function Ct(e,t){let n=await wt(e),i=/* @__PURE__ */ new Map;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!xt.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||i.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let a=r.join(t,e.fileName);await me(r.dirname(a),{recursive:!0,mode:448}),await S(await Tt(n,e),l(a,{mode:384})),i.set(e.fileName,a),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await b(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(bt)||!i.has(`data/foundry.json`))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function wt(e){return new Promise((t,n)=>{Ce.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Tt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Et=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const j=x.from(`FOUNDRYX`,`ascii`),M=`aes-256-gcm`,Dt=`scrypt`,Ot={N:131072,r:8,p:1};async function kt(e,t,n){let r=le(16),i=le(12),a={version:1,cipher:M,kdf:{name:Dt,salt:r.toString(`base64`),...Ot,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=jt(o.byteLength),u=x.concat([s,o]),d=await Mt(n,r,Ot);try{let n=await ge(t,`w`,384);try{await n.write(u)}finally{await n.close()}await S(c(e),Nt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await de(t,384)}catch(e){throw await b(t,{force:!0}),new Et(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function At(e,t,n){let r;try{let i=(await be(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await ge(e,`r`),o,s,u;try{if(o=await It(a,13,0),!o.subarray(0,j.byteLength).equals(j))throw Error(`The export file signature is invalid`);if(o.readUInt8(j.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(j.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await It(a,e,13),u=await It(a,16,i-16)}finally{await a.close()}let d=Ft(JSON.parse(s.toString(`utf8`)));r=await Mt(n,d.salt,d.header.kdf);let f=x.concat([o,s]);await S(c(e,{start:13+s.byteLength,end:i-16-1}),Pt(r,d.nonce,f,u),l(t,{mode:384})),await de(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Et?e:new Et(Rt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Rt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function jt(e){let t=x.alloc(13);return j.copy(t,0),t.writeUInt8(1,j.byteLength),t.writeUInt32BE(e,j.byteLength+1),t}function Mt(e,t,n){return new Promise((r,i)=>{ue(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Nt(e,t,n){let r=oe(M,e,t,{authTagLength:16});return r.setAAD(n),new Ee({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,x.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Pt(e,t,n,r){let i=se(M,e,t,{authTagLength:16});return i.setAAD(n),new Ee({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 Ft(e){if(!Lt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==M||!Lt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Dt||typeof t.salt!=`string`||t.N!==Ot.N||t.r!==Ot.r||t.p!==Ot.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=x.from(t.salt,`base64`),r=x.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:M,kdf:{name:Dt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function It(e,t,n){let r=x.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Lt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function zt(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function Bt(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function N(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function Vt(e,t){Ht(e,`${JSON.stringify(t,null,2)}\n`)}function Ht(e,t){Bt(r.dirname(e));let n=`${e}.${y()}.tmp`;try{let i=p(n,`wx`,384);try{ne(i,t),d(i)}finally{s(i)}ee(n,e),N(r.dirname(e))}finally{g(n,{force:!0})}}const Ut=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var P=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Wt=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}},Gt=class extends Error{agentIds;code=`INSTRUCTION_IN_USE`;constructor(e){super(`Instruction is assigned to: ${e.join(`, `)}`),this.agentIds=e,this.name=`InstructionInUseError`}};function Kt(e){if(!qt(e))throw new P(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new P(`name is required`);let t=e.name.trim();if(!t)throw new P(`name is required`);if(t.length>200)throw new P(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new P(`content is required`);if(e.content.length>1e6)throw new P(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Jt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Yt(e,t){let n=Date.now(),r={id:y(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=cn(t,r.id),a=en(r);return t.transaction(()=>{Ht(i,a)}),r}function Xt(e){let t=sn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(ln(e))return[];throw e}return n.map(e=>nn(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)}function Zt(e,t){if(!Ut.test(e))return;let n=`${e}.md`;try{return nn(r.join(sn(t),n),n)}catch(e){if(ln(e))return;throw e}}function Qt(e,t,n){let r=Zt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.transaction(()=>{Ht(cn(n,i.id),en(i))}),i}function $t(e,t){if(!Ut.test(e))return`missing`;let n=sn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>{try{return g(i),N(n),`removed`}catch(e){if(ln(e))return`missing`;throw e}})}function en(e){return`---\n${Oe({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function tn(e,t){let n=Jt.exec(e);if(!n)throw F(t);let r=rn(n[1]);if(`${r.id}.md`!==t)throw F(t);let i=e.slice(n[0].length);return i.startsWith(`\r
3
+ `)?i=i.slice(2):i.startsWith(`
4
+ `)&&(i=i.slice(1)),{...r,content:i}}function nn(e,t){return tn(m(e,`utf8`),t)}function rn(e){let t;try{t=De(e)}catch{throw F(`frontmatter`)}if(!un(t))throw F(`frontmatter`);let n=an(t.id),r=an(t.name);if(!r||r.length>200||!Ut.test(n))throw F(`frontmatter`);return{id:n,name:r,createdAt:on(t.createdAt),updatedAt:on(t.updatedAt)}}function an(e){return typeof e==`string`?e:``}function on(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw F(`frontmatter`);return e}function sn(e){return r.join(e.path,`instructions`)}function cn(e,t){if(!Ut.test(t))throw Error(`Invalid instruction ID`);return r.join(sn(e),`${t}.md`)}function F(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function ln(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dn(e){return e.transaction(()=>{let t=new Set(Ve);return{settings:e.readSettings(),instructions:Xt(e),agents:e.all(`agents`).filter(({id:e})=>t.has(e)).toSorted((e,t)=>e.id.localeCompare(t.id))}})}var fn=class{storage;constructor(e){this.storage=e}async createExport(e){let t=dn(this.storage),n=await he(r.join(ae(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=JSON.stringify(t,null,2),o=r.join(n,`foundry.json`),s=r.join(n,`manifest.json`),c=r.join(n,`foundry.zip`),l=r.join(n,`foundry.foundry-backup`),u={format:`foundry.data`,archiveVersion:2,appVersion:Le,createdAt:i,data:{path:Ze,bytes:x.byteLength(a,`utf8`),sha256:ce(`sha256`).update(a).digest(`hex`)}};return await xe(o,a,{mode:384}),await xe(s,JSON.stringify(u,null,2),{mode:384}),await St([{entryPath:`manifest.json`,filePath:s},{entryPath:Ze,filePath:o}],c),await kt(c,l,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await _e(l)}}finally{await zt(n)}}},I=class extends Error{code;constructor(e,t){super(t),this.code=e}};function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pn(e){if(!L(e)||e.format!==`foundry.data`||e.archiveVersion!==2||!L(e.data)||e.data.path!==`data/foundry.json`||typeof e.data.bytes!=`number`||!Number.isSafeInteger(e.data.bytes)||e.data.bytes<=0||typeof e.data.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.data.sha256))throw new I(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:Ze,bytes:e.data.bytes,sha256:e.data.sha256}}}function mn(e){if(!L(e)||!L(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw R(`Backup data must contain settings, instructions, and agents`);let t=hn(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:tt(e.settings),instructions:t,agents:gn(e.agents,n)}}function hn(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!L(e))throw R(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!Ut.test(r)||t.has(r))throw R(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw R(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw R(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:_n(e.createdAt,n),updatedAt:_n(e.updatedAt,n)};return t.add(r),a})}function gn(e,t){let n=new Set(Ve),r=/* @__PURE__ */ new Set;return e.map((e,i)=>{if(!L(e)||!L(e.instructions))throw R(`Invalid agent at index ${i}`);let a=e.id;if(typeof a!=`string`||!n.has(a)||r.has(a))throw R(`Invalid agent at index ${i}`);let o=e.instructions,s=o.instructionIds;if(!Array.isArray(s))throw R(`Invalid instruction assignment for agent ${a}`);let c=s.map(e=>{if(typeof e!=`string`)throw R(`Invalid instruction assignment for agent ${a}`);return e});if(new Set(c).size!==c.length||c.some(e=>!t.has(e)))throw R(`Invalid instruction assignment for agent ${a}`);if(typeof o.enabled!=`boolean`)throw R(`Invalid enabled state for agent ${a}`);if(o.enabled&&c.length===0)throw R(`Enabled agent ${a} has no instructions`);let l={id:a,instructions:{instructionIds:c,enabled:o.enabled,createdAt:_n(o.createdAt,i),updatedAt:_n(o.updatedAt,i)}};return r.add(a),l})}function _n(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw R(`Invalid timestamp at index ${t}`);return e}function R(e){return new I(`INVALID_BACKUP`,e)}function vn(e,t){e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of Xt(e))n.has(t.id)||e.removeTextFile(yn(t.id));for(let n of t.instructions)e.putTextFile(yn(n.id),en(n));let r=new Set(t.agents.map(({id:e})=>e));for(let t of e.all(`agents`))r.has(t.id)||e.remove(`agents`,t.id);for(let n of t.agents)e.put(`agents`,n);e.setSettings(t.settings)})}function yn(e){return r.join(`instructions`,`${e}.md`)}var bn=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await he(r.join(ae(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await At(e,i,t);let a=await Ct(i,r.join(n,`extracted`)),o=pn(JSON.parse(await _e(a[`manifest.json`],`utf8`))),s=await _e(a[Ze]);if(s.byteLength!==o.data.bytes||ce(`sha256`).update(s).digest(`hex`)!==o.data.sha256)throw new I(`INVALID_BACKUP`,`Backup checksum does not match`);let c=mn(JSON.parse(s.toString(`utf8`)));try{vn(this.storage,c)}catch{throw new I(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof I?e:e instanceof Et?e.code===`INVALID_PASSPHRASE`?new I(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new I(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new I(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await zt(n)}}};function xn(e){return e.all(`agents`)}function Sn(e,t){return e.get(`agents`,t)}function Cn(e,t){return xn(e).filter(({instructions:e})=>e.instructionIds.includes(t)).map(({id:e})=>e)}function wn(e,t){return e.put(`agents`,t),t}var Tn=class{storage;constructor(e){this.storage=e}list(){return Xt(this.storage)}get(e){let t=Zt(e,this.storage);if(!t)throw new Wt(e);return t}create(e){return Yt(e,this.storage)}update(e,t){let n=Qt(e,t,this.storage);if(!n)throw new Wt(e);return n}delete(e){return this.storage.transaction(()=>{let t=Zt(e,this.storage);if(!t)throw new Wt(e);let n=Cn(this.storage,e);if(n.length>0)throw new Gt(n);if($t(e,this.storage)===`missing`)throw new Wt(e);return t})}};const En=`<!-- foundry:instructions:start -->`,Dn=`<!-- foundry:instructions:end -->`;function On(e,t){let n=kn(e),r=jn(t);return`${n}${An(n)}${r}\n`}function kn(e){let t=``,n=0;for(let r of Mn(e)){let e=Nn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function An(e){return!e||e.endsWith(`
5
+ `)?``:`
6
+ `}function jn(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
7
+
8
+ `);return t?`${En}\n\n${t}\n\n${Dn}`:`${En}\n${Dn}`}function Mn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function Nn(e){let t=e.replace(/\r?\n$/u,``).trim();return/^<!--\s*foundry\b/iu.test(t)?/\bstart\b/iu.test(t)?`start`:/\bend\b/iu.test(t)?`end`:`other`:null}var Pn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Tn(e),n=re.homedir(),r=Ue){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=He(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new w(`AGENT_NOT_FOUND`,`Unknown agent: ${e}`,404);return t}readAssignedInstructions(e){let t=new Map(this.instructionsService.list().map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e);if(!n)throw new w(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}writeAgentDocument(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?kn(i):On(i,t);Ln(e.filePath,a)}list(){let e=new Map(xn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>Fn(t,(e.get(t.id)??In(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e),r=this.readAssignedInstructions(t);return this.storage.transaction(()=>{let i=Sn(this.storage,e)??In(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&this.writeAgentDocument(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=wn(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return Fn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Sn(this.storage,e)??In(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new w(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);this.writeAgentDocument(n,e.map(({content:e})=>e),!1)}else this.writeAgentDocument(n,[],!0);let a=Date.now();return Fn(n,wn(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Sn(this.storage,e)??In(e),r=n.instructions;if(!r.enabled)throw new w(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);this.writeAgentDocument(t,i.map(({content:e})=>e),!1);let a=Date.now();return Fn(t,wn(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}openInstructionFile(e){let t=this.requireDefinition(e);if(!u(t.filePath))throw new w(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function Fn(e,t){return{id:e.id,name:e.name,icon:e.icon,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}function In(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}function Ln(e,t){let n=r.dirname(e);f(n,{recursive:!0,mode:448});let a=u(e)?v(e).mode&511:384,c=`${e}.${y()}.tmp`;try{let r=p(c,`wx`,a);try{i.platform!==`win32`&&o(c,a),ne(r,t),d(r)}finally{s(r)}ee(c,e),N(n)}finally{g(c,{force:!0})}}const Rn=[`agents`,`providers`,`captures`,`fetchJobs`];function zn(e){try{let t=JSON.parse(m(r.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return i.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-v(e).mtimeMs>3e4}}var Bn=class{path;changes=null;textChanges=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Bt(e);for(let e of Rn)e!==`providers`&&Bt(this.collectionPath(e))}collectionPath(e){return r.join(this.path,e===`fetchJobs`?`fetch-jobs`:e)}recordPath(e,t){if(!t||t.length>200)throw Error(`Invalid storage record ID`);return r.relative(this.path,r.join(this.collectionPath(e),`${ce(`sha256`).update(t).digest(`hex`)}.json`))}instructionFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!/^instructions[/\\][^/\\]+\.md$/u.test(t))throw Error(`Invalid instruction filename`);return t}locked(e){if(this.closed)throw Error(`Foundry storage is closed`);if(this.lockDepth>0)return e();let t=r.join(this.path,`.lock`),n=Date.now();for(;;)try{f(t,{mode:448});try{ne(r.join(t,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384})}catch(e){throw g(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,g(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=v(e);if(!zn(e))return;let n=r.join(e,`recovering`);try{f(n)}catch(e){if(e.code===`EEXIST`){let e=v(n);zn(n)&&v(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ne(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),v(e).ino!==t.ino||!zn(e)){g(n,{recursive:!0,force:!0});return}g(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!u(e))return;let t=JSON.parse(m(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!u(e)){let e=u(t)?h(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};Vt(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(_(t),N(this.path))}readProviders(){let e=this.changes?.has(`providers.json`)?this.changes.get(`providers.json`):JSON.parse(m(r.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=r.resolve(this.path,t.file),n=r.relative(this.path,e);if(n.startsWith(`..`)||r.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|(?:agents|providers|captures|fetch-jobs)[/\\][^/\\]+\.json|instructions[/\\][^/\\]+\.md)$/u.test(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(t.value===null)g(e,{force:!0}),N(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);Ht(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else Vt(e,t.value)}g(r.join(this.path,`.transaction.json`),{force:!0}),N(this.path)}readRecord(e,t){let n;if(this.changes?.has(t)){if(n=this.changes.get(t),n===null)return}else{let e=r.join(this.path,t);if(!u(e))return;n=JSON.parse(m(e,`utf8`))}let i=n;if(this.recordPath(e,i.id)!==t)throw Error(`Invalid Foundry record`);return structuredClone(i)}all(e){return this.locked(()=>{if(e===`providers`)return this.readProviders();let t=this.collectionPath(e),n=new Set(h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(e=>r.relative(this.path,r.join(t,e.name))));if(this.changes){let e=r.relative(this.path,t);for(let t of this.changes.keys())r.dirname(t)===e&&n.add(t)}let i=[];for(let t of n){let n=this.readRecord(e,t);n&&i.push(n)}return i})}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 tt(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?tt(JSON.parse(m(e,`utf8`))):structuredClone(et)})}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))}remove(e,t){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(this.recordPath(e,t),null)}putTextFile(e,t){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.instructionFilename(e),t)}removeTextFile(e){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.instructionFilename(e),null)}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,tt(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map,this.textChanges=/* @__PURE__ */ new Map;let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);let i=[...[...this.changes].map(([e,t])=>({file:e,value:t})),...[...this.textChanges].map(([e,t])=>t===null?{file:e,value:t}:{file:e,text:t})];if(i.length>0){let e={changes:i};Vt(r.join(this.path,`.transaction.json`),e),t={value:n},this.applyJournal(e)}return n}catch(e){if(t)return this.recover(),t.value;throw e}finally{this.changes=null,this.textChanges=null}})}close(){this.closed=!0}};function Vn(e=We()){let t=new Bn(e);try{return t.transaction(()=>{let n=t.readSettings();u(r.join(e,`settings.json`))||t.setSettings(n)}),t}catch(e){throw t.close(),e}}function Hn(){return Ge(),Vn()}async function z(e){let t;try{let n=Hn(),r=new Tn(n);t={storage:n,agentsService:new Pn(n,r),settingsService:new ht(n),settingsSkillCopyService:new _t,dataExportService:new fn(n),dataImportService:new bn(n),instructionsService:r},Wn(await e(t))}catch(e){let t=Gn(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function Un(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new B(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Wn(e){console.log(JSON.stringify(e,null,2))}function Gn(e){return e instanceof Error?{code:Kn(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Kn(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const qn=Ve.join(`, `),V={type:`positional`,description:`Agent ID: ${qn}`,required:!0},Jn=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return z(({agentsService:e})=>e.list())}}),Yn=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...V,description:`Optional agent ID: ${qn}`,required:!1}},run({args:e}){return z(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new B(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${qn}`);let i=new Map(n.list().map(e=>[e.id,e.name]));return r.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({id:e.id,name:e.name,instructionFile:e.instructionFile,enabled:e.enabled,instructions:e.instructionIds.map(e=>({id:e,name:i.get(e)??null}))}))})}}),Xn=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:V,instructions:{type:`string`,description:`Comma-separated instruction IDs in block order; pass an empty string to clear`,valueHint:`id1,id2`,required:!0}},run({args:e}){return z(({agentsService:t})=>{let n=Re({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Zn=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),Qn=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),$n=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.reapply(e.agent))}}),er=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.openInstructionFile(e.agent))}}),tr=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions for supported agents`},subCommands:{list:Jn,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:Yn,assign:Xn,enable:Zn,disable:Qn,reapply:$n,open:er}})}}),nr=e({meta:{name:`new`,description:`Create an instruction from a name and Markdown content`},args:{name:{type:`string`,description:`Instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.create(Kt({name:e.name,content:e.content})))}}),rr=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return z(({instructionsService:e})=>e.list())}}),ir=e({meta:{name:`get`,description:`Read one instruction by ID as JSON`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.get(e.id))}}),ar=e({meta:{name:`edit`,description:`Replace an instruction name and Markdown content`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0},name:{type:`string`,description:`New instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`New Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.update(e.id,Kt({name:e.name,content:e.content})))}}),or=e({meta:{name:`delete`,description:`Delete an unused instruction by ID`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.delete(e.id))}}),sr=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:nr,list:rr,get:ir,edit:ar,delete:or}});function cr(e){if(!ur(e)||!Array.isArray(e.targets))throw new lr(`targets must be an array`);if(e.targets.length===0)throw new lr(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!$e.includes(e))throw new lr(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var lr=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function ur(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const dr=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({dataExportService:t})=>{let n=await t.createExport(Un(e.passphrase)),r=pr(e.output);return await mr(n.contents,r,e.force),{filePath:r}})}}),fr=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},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({dataImportService:t})=>(await t.importData(r.resolve(e.file),Un(e.passphrase)),{status:`imported`}))}});function pr(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(`:`,`-`),n=e??`foundry-${t}.foundry-backup`,i=r.resolve(n);return i.toLowerCase().endsWith(`.foundry-backup`)?i:`${i}.foundry-backup`}async function mr(e,t,n){await me(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${y()}.tmp`);try{if(await xe(a,e,{mode:384}),i.platform!==`win32`&&await de(a,384),n){await ye(a,t);return}if(u(t))throw hr(t);try{await pe(a,t)}catch(e){throw gr(e)?hr(t):e}}finally{await b(a,{force:!0})}}function hr(e){return new B(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function gr(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const H={"color-theme":{field:`theme`,values:Ke},language:{field:`language`,values:qe},"time-zone":{field:`timezone`,values:Ye},"time-format":{field:`timeFormat`,values:Je}},_r=[...Object.keys(H),`config-folder`],vr=Object.entries(H).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
9
+ `);function yr(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const br=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${_r.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return z(({settingsService:t})=>{let n=yr(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${_r.join(`, `)}`);return n[e.key]})}}),xr=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(H).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${vr}`,required:!0}},run({args:e}){return z(({settingsService:t})=>{if(e.key===`config-folder`)throw new B(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(H,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(H).join(`, `)}`);let n=H[e.key];if(!n.values.includes(e.value))throw new B(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=yr(t.update(nt({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Sr=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return z(({settingsService:e})=>e.openConfigFolder())}}),Cr=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(({settingsSkillCopyService:t})=>{let n=cr({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),wr=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:br,set:xr,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Sr}}),export:dr,import:fr,"download-skill":Cr}});function Tr(e){let t=new C;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Re(await Er(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Dr(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=ze(await Er(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Dr(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Dr(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Dr(t,e)}}),t}async function Er(e){try{return await e.req.json()}catch{throw new w(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Dr(e,t){if(t instanceof w)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Or(e){if(!Mr(e)||typeof e.url!=`string`)throw new jr(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function kr(e){return e===`no-successful`?`no-successful`:`all`}function Ar(e){if(!Mr(e)||typeof e.userNote!=`string`)throw new jr(`userNote must be a string`);return e.userNote}var jr=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Mr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var U=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function Nr(e,t=()=>{}){let n=new C;return n.get(`/`,t=>{let n=kr(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=Or(await Pr(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return W(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return W(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 W(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 W(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Ar(await Pr(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return W(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return W(t,e)}}),n}async function Pr(e){try{return await e.req.json()}catch{throw new jr(`Request body must be valid JSON`)}}function W(e,t){if(t instanceof jr)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}},Fr(t.code));throw t}function Fr(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 Ir(e){let t=new C;return t.get(`/`,t=>t.json(e.list())),t.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return Rr(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(Kt(await Lr(t)));return t.json(n,201)}catch(e){return Rr(t,e)}}),t.put(`/:id`,async t=>{try{let n=Kt(await Lr(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Rr(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Rr(t,e)}}),t}async function Lr(e){try{return await e.req.json()}catch{throw new P(`Request body must be valid JSON`)}}function Rr(e,t){if(t instanceof P)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Wt)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Gt)return e.json({error:{code:t.code,message:t.message}},409);throw t}const zr=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Br=[`active`,`disabled`,`deleted`];var G=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},Vr=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function Hr(e){if(!Yr(e))throw new G(`Provider input must be an object`);let t=K(e.name,`name`),n=qr(e.protocol),r=Jr(e.baseURL),i=e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Kr(e.customModels);return{...e.avatar!==void 0&&{avatar:Ur(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Ur(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 G(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Wr(e){if(!Yr(e))throw new G(`Provider connection must be an object`);return{protocol:qr(e.protocol),baseURL:Jr(e.baseURL),apiKey:e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Gr(e){if(typeof e!=`string`||!Br.includes(e))throw new G(`Invalid provider status`);return e}function Kr(e){if(e===void 0)return[];if(!Array.isArray(e))throw new G(`customModels must be an array`);return e.map(e=>{if(!Yr(e))throw new G(`Each custom model must be an object`);return{id:K(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:K(e.displayName,`customModels.displayName`)}})}function qr(e){if(typeof e!=`string`||!zr.includes(e))throw new G(`Invalid provider protocol`);return e}function Jr(e){let t=K(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new G(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function K(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new G(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new G(`${t} is required`);return r}function Yr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var q=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Xr(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(Zr(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new q(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new q(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new q(`Provider returned invalid JSON`)}return Qr(i)}function Zr(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Qr(e){if(!ei(e)||!Array.isArray(e.data))throw new q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!ei(e)||typeof e.id!=`string`||e.id.length===0)throw new q(`Provider returned an invalid model entry`);let t=$r(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function $r(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function ei(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ti=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},ni=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-e.updatedAt).map(t=>({...ri(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?ri(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 ti;let r=Date.now(),i={id:t??y(),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),ri(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new Vr;let r=this.storage.get(`providers`,e);if(!r)throw new ti;let i=Date.now(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),ri(a)})}};function ri(e){return{...e,avatar:e.avatar??null,status:e.status}}function ii(e,t=()=>{}){let n=new C;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 J(t,e)}}),n.post(`/models`,async t=>{try{let n=Wr(await ai(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return J(t,e)}}),n.post(`/`,async n=>{try{let r=Hr(await ai(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return J(n,e)}}),n.put(`/:id`,async n=>{try{let r=Hr(await ai(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return J(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await ai(n),i=Gr(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 J(n,e)}}),n}async function ai(e){try{return await e.req.json()}catch{throw new G(`Request body must be valid JSON`)}}function J(e,t){if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof ti)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Vr)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},502);throw t}function oi(e){let t=O(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))si(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function si(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ci=class{storage;repository;constructor(e){this.storage=e,this.repository=new ni(e)}list(){return this.repository.list(oi(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new ti;return Xr(t)}fetchModelsForConnection(e){return Xr(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,oi(this.storage)))}};function li(e,t=()=>{},n=new _t){let r=new C;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=nt(await ui(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return di(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=cr(await ui(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return di(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function ui(e){try{return await e.req.json()}catch{throw new T(`Request body must be valid JSON`)}}function di(e,t){if(t instanceof T||t instanceof lr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof A)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}var fi=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function pi(e){let t=new C;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return mi(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return mi(t,e)}}),t}function mi(e,t){if(t instanceof fi)switch(t.code){case`CODEX_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CODEX_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500);case`CLAUDE_DATA_NOT_FOUND`:return e.json({error:{code:t.code,message:t.message}},404);case`CLAUDE_READ_FAILED`:return e.json({error:{code:t.code,message:t.message}},500)}throw t}function hi(){let e=i.env.CLAUDE_CONFIG_DIR?.trim();return e?r.resolve(e):r.join(re.homedir(),`.claude`)}const gi=1048576;async function _i(e){let t;try{t=await ve(e,{withFileTypes:!0})}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`ENOENT`;return{files:[],unreadable:+!t,found:!t}}let n={files:[],unreadable:0,found:!0};for(let i of t){let t=r.join(e,i.name);if(i.isDirectory()){let e=await _i(t);n.files.push(...e.files),n.unreadable+=e.unreadable}else i.isFile()&&/\.jsonl(?:\.zst)?$/u.test(i.name)&&n.files.push(t)}let i=new Set(n.files);return n.files=n.files.filter(e=>!e.endsWith(`.zst`)||!i.has(e.slice(0,-4))).toSorted((e,t)=>e.localeCompare(t)),n}async function vi(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Y(r)?t(r):n=!0},i=async e=>{let t=new je(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
4
10
  `,e);for(;a!==-1;)r(n.slice(e,a)),e=a+1,a=n.indexOf(`
5
- `,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await C(s(e,{highWaterMark:Jn}),ke({chunkSize:Jn}),i):await C(s(e,{highWaterMark:Jn}),i),{hasMalformedLines:n}}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e){return typeof e==`string`?e:``}function Zn(e){let t=Date.parse(X(e));return Number.isFinite(t)?t:null}function Qn(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function $n(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Y).filter(e=>[`text`,`input_text`,`output_text`].includes(X(e.type))).map(e=>X(e.text)).join(`
6
- `):``}function er(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function tr(e){let t=await Yn(v.join(e,`projects`));if(!t.found)throw new Wn(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n=t.unreadable,r=/* @__PURE__ */ new Map;for(let e of t.files)try{let t=await nr(e);if((t.hasMalformedLines||!t.thread)&&(n+=1),t.thread){let e=r.get(t.thread.id);(!e||e.updatedAt<t.thread.updatedAt)&&r.set(t.thread.id,t.thread)}}catch{n+=1}return{threads:r.values().toArray(),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function nr(e){let t=await ye(e),n=``,r=``,i=null,a=``,o=``,s=``,c=null,l=1/0,u=0,d=e.split(v.sep).includes(`subagents`),f=d?v.basename(v.dirname(v.dirname(e))):null,p=d,m=/* @__PURE__ */ new Map,ee=0,{hasMalformedLines:h}=await Xn(e,e=>{d?f=X(e.sessionId)||f:n||=X(e.sessionId),r=X(e.cwd)||r,i=X(e.gitBranch)||i,p||=e.isSidechain===!0;let t=Zn(e.timestamp);t!==null&&(l=Math.min(l,t),u=Math.max(u,t)),e.type===`custom-title`?o=X(e.customTitle)||o:e.type===`last-prompt`&&(s=X(e.lastPrompt)||s);let h=Y(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&h.role===`user`&&(a||=$n(h.content).trim()),e.type!==`assistant`||h.role!==`assistant`)return;let te=X(h.model);te&&te!==`<synthetic>`&&(c=te);let g=Y(h.usage)?h.usage:{},ne=[g.input_tokens,g.output_tokens,g.cache_creation_input_tokens,g.cache_read_input_tokens].reduce((e,t)=>e+Qn(t),0),_=X(h.id)||X(e.uuid);_?m.set(_,Math.max(m.get(_)??0,ne)):ee+=ne});return n||=v.basename(e).replace(/\.jsonl(?:\.zst)?$/u,``),Number.isFinite(l)?{thread:{id:n,title:er(o||a||s,n),cwd:r,gitBranch:i,model:c,archived:!1,subagent:p,parentThreadId:f,createdAt:new Date(l).toISOString(),updatedAt:new Date(u).toISOString(),sizeBytes:t.size,segmentCount:1,tokensUsed:m.values().reduce((e,t)=>e+t,ee)},hasMalformedLines:h}:{thread:null,hasMalformedLines:!0}}function rr(){let e=r.env.CODEX_HOME?.trim();return e?v.resolve(e):v.join(re.homedir(),`.codex`)}async function ir(e){let t=await Promise.all([Yn(v.join(e,`sessions`)),Yn(v.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new Wn(`CODEX_DATA_NOT_FOUND`,`Codex session directories were not found`);let n=t.reduce((e,t)=>e+t.unreadable,0),r=/* @__PURE__ */ new Map;for(let[e,i]of t.entries())for(let t of i.files)try{let i=await ar(t,e===1);if((i.hasMalformedLines||!i.segment)&&(n+=1),i.segment){let e=r.get(i.segment.id)??[];e.push(i.segment),r.set(i.segment.id,e)}}catch{n+=1}return{threads:Array.from(r.values(),or),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function ar(e,t){let n={id:``,title:``,cwd:``,model:null,gitBranch:null,subagent:!1,parentThreadId:null,archived:t,createdAt:1/0,updatedAt:0,sizeBytes:(await ye(e)).size,tokensUsed:0},r=``,{hasMalformedLines:i}=await Xn(e,e=>{let t=Zn(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let i=Y(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=X(i.id),n.cwd||=X(i.cwd),n.model??=X(i.model_provider)||null;let e=Y(i.git)?i.git:{};n.gitBranch??=X(e.branch)||null;let t=Y(i.source)?i.source:{},r=Y(i.thread_source)?i.thread_source:{},a=Y(t.subagent)?t.subagent:{},o=Y(r.subagent)?r.subagent:{};n.parentThreadId??=X(i.parent_thread_id)||X(a.parent_thread_id)||X(o.parent_thread_id)||null,n.subagent||=!!i.parent_thread_id||Y(i.source)&&`subagent`in i.source||Y(i.thread_source)&&`subagent`in i.thread_source}else if(e.type===`turn_context`)n.cwd=X(i.cwd)||n.cwd,n.model=X(i.model)||n.model;else if(e.type===`response_item`&&i.type===`message`&&i.role===`user`){let e=$n(i.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(r||=e)}else if(e.type===`token_usage_record`){let e=Y(i.thread_token_usage)?i.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,Qn(e.total_tokens))}else if(e.type===`event_msg`&&i.type===`token_count`){let e=Y(i.info)?i.info:{},t=Y(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,Qn(t.total_tokens))}});return n.title=r,n.id||=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/u.exec(v.basename(e))?.[1]??``,Number.isFinite(n.createdAt)?{segment:n.id?n:null,hasMalformedLines:i}:{segment:null,hasMalformedLines:!0}}function or(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:er(e.find(e=>e.title)?.title??``,t.id),cwd:e.findLast(e=>e.cwd)?.cwd??``,model:e.findLast(e=>e.model)?.model??null,gitBranch:e.findLast(e=>e.gitBranch)?.gitBranch??null,archived:e.every(e=>e.archived),subagent:e.some(e=>e.subagent),parentThreadId:e.findLast(e=>e.parentThreadId)?.parentThreadId??null,createdAt:new Date(Math.min(...e.map(e=>e.createdAt))).toISOString(),updatedAt:new Date(Math.max(...e.map(e=>e.updatedAt))).toISOString(),sizeBytes:e.reduce((e,t)=>e+t.sizeBytes,0),segmentCount:e.length,tokensUsed:Math.max(...e.map(e=>e.tokensUsed))}}var sr=class{codexHome;claudeHome;constructor(e=rr(),t=qn()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return cr(`codex`,await ir(this.codexHome))}async getClaudeSnapshot(){return cr(`claude`,await tr(this.claudeHome))}};function cr(e,t){return{source:e,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),threads:t.threads.toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)),warnings:t.warnings}}function lr(e){let t=new w;return t.get(`/`,t=>Ae(t,async n=>{await ur(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||dr(n,e)}),c=setInterval(()=>{r||fr(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 ur(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function dr(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function fr(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var pr=class extends Error{code=`INVALID_EXPORT_INPUT`};function mr(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new pr(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function hr(e){let t=new w;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new pr(`Request body must be valid JSON`)}let{passphrase:r}=mr(n),i=await e.createExport(r);return t.body(i.contents,200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${i.fileName}"`,"cache-control":`no-store`})}catch(e){return e instanceof pr?t.json({error:{code:e.code,message:e.message}},400):t.json({error:{code:`DATA_EXPORT_FAILED`,message:`Unable to export data`}},500)}}),t}function gr(e,t){let n=new w;return n.post(`/`,async n=>{let r;try{if(n.req.header(`content-type`)?.split(`;`,1)[0].trim()!==`application/octet-stream`||!n.req.raw.body)throw new L(`INVALID_BACKUP`,`A backup file is required`);let i;try{i=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new L(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!i)throw new L(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);r=await he(v.join(ae(),`foundry-import-upload-`));let a=v.join(r,`backup.foundry-backup`);await C(we.fromWeb(n.req.raw.body),c(a,{mode:384})),await e.importData(a,i);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json({status:`imported`})}catch(e){return e instanceof L?n.json({error:{code:e.code,message:e.message}},e.code===`IMPORT_FAILED`?500:400):n.json({error:{code:`IMPORT_FAILED`,message:`Unable to import data`}},500)}finally{r&&await At(r)}}),n}function _r(e){return e===`/api`||e.startsWith(`/api/`)}function vr(e,t={}){let n=new w,r=t.providerService??new Bn(e),i=t.settingsService??new st(e),a=t.settingsSkillCopyService??new lt,o=t.sessionService??new sr;return n.get(`/api/health`,t=>t.json({status:`ok`,version:Pe,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,lr(t.eventHub)),n.route(`/api/data-import`,gr(t.dataImportService??new Lt(e),()=>{t.onSettingsChanged?.(),t.eventHub?.publish(Be,{fields:[`theme`,`language`,`timeFormat`,`timezone`,`captures`]})})),n.route(`/api/data-export`,hr(t.dataExportService??new Mt(e))),n.route(`/api/providers`,In(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Vn(i,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(Be,e)},a)),n.route(`/api/sessions`,Gn(o)),t.captureService&&n.route(`/api/captures`,mn(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),n.notFound(e=>_r(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),_r(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function yr(e,t,n){let r=vr(t,n),i=De({root:e});r.use(`*`,(e,t)=>_r(e.req.path)?t():i(e,t));let a=De({root:e,path:`/index.html`});return r.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!_r(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&v.posix.extname(e.req.path)===``?a(e,t):t()),r}var br=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:y(),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=>xr(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:xr(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 U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=(/* @__PURE__ */ new Date()).toISOString(),i={id:y(),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:xr(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 U(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Sr(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 U(`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),xr(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=>Sr(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Sr(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 xr(e){let{deletedAt:t,...n}=e;return n}function Sr(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}}var Z=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function Cr(e){if(e instanceof Z)return e;let t=wr(e);return t===null?Dr(e)?new Z(`timeout`,`The configured fetcher timed out`):Or(e)?new Z(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new Z(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new Z(`http_${t}`,Tr(e)??`The configured fetcher returned ${t}`,t)}function wr(e){if(!Q(e))return null;let t=kr(e.status);return t===null?Q(e.response)?kr(e.response.status):null:t}function Tr(e){if(!Q(e))return null;if(Q(e.response)){let t=Er(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:Er(e.details)}function Er(e){return Q(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function Dr(e){if(!(e instanceof Error))return!1;let t=Ar(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function Or(e){if(e instanceof TypeError)return!0;if(!Q(e))return!1;let t=Ar(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!Q(e.response)}function kr(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function Ar(e){let t=e.code;return typeof t==`string`?t:null}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var jr=class extends je{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function Mr(e,t,n={}){let r=new jr({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 Nr(e,t,n=1,r=Mr(t,n)){try{let t=Pr(e),n=await r.search(Fr(t));if(!$(n))throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new Z(`fetcher_error`,Zr(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);let i=Xr(n);if(i===null)throw new Z(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=Ur(e,Hr(n));return{title:a?Jr(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw Cr(e)}}function Pr(e){return{query:Ir(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 Fr(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function Ir(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=Lr(t.pathname),i=Vr(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function Lr(e){let t=e.split(`/`).map(e=>Rr(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||Br(n))continue;let r=zr(n);if(r)return r}return null}function Rr(e){try{return decodeURIComponent(e)}catch{return e}}function zr(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function Br(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 Vr(e){return Me(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function Hr(e){return!$(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!$(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:$(e.metadata)?e.metadata:{}}])}function Ur(e,t){let n=Gr(e);if(n){let e=t.find(e=>Wr(e).some(e=>Gr(e)===n));if(e)return e}let r=Kr(e),i=r===null?[]:t.filter(e=>Wr(e).some(e=>Kr(e)===r));return i.find(e=>qr(e))??(i.length>0?i[0]:null)}function Wr(e){return[e.url,Yr(e,`sourceURL`),Yr(e,`url`)].filter(e=>!!e)}function Gr(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 Kr(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function qr(e){return Wr(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function Jr(e){return e.title?.trim()||Yr(e,`ogTitle`)?.trim()||Yr(e,`title`)?.trim()||null}function Yr(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function Xr(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function Zr(e){return $(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qr(e,t){return Nr(e,t.apiKey,t.maxAttempts)}var $r=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;constructor(e,t,n=()=>{},r=Qr){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){let e=j(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=ei(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=Cr(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()}};function ei(e){let t=e;if(!ti(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 ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ni=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=j(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 U(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=ri(e.url);if(!t)throw new U(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new U(`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 U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new U(`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 U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new U(`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 ri(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function ii(e,t,n){let r=new br(e),i=new $r(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new ni(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}function ai(e,t){let n,r=ne(e,{persistent:!1},(e,r)=>{(r===null||r===`settings.json`)&&(clearTimeout(n),n=setTimeout(t,30),n.unref())});return r.on(`error`,()=>{console.error(`Unable to watch Foundry settings`)}),()=>{clearTimeout(n),r.close()}}var oi=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:y(),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 si(e){let t=new oi,n=ii(e,t),r=new Mt(e),i=new Lt(e),a=new Bn(e),o=new st(e),s=new lt,c=new sr,l={captureRuntime:n,dataExportService:r,dataImportService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c},u;return{services:l,apiOptions:{captureService:n.service,dataExportService:r,dataImportService:i,providerService:a,settingsService:o,settingsSkillCopyService:s,sessionService:c,eventHub:t,onSettingsChanged:n.notifySettingsChanged},start(){u??=ai(e.path,()=>{n.notifySettingsChanged(),t.publish(Be,{fields:[]})}),n.start()},stop(){u?.(),u=void 0}}}const{dirname:ci,join:li,resolve:ui}=v,di=ci(xe(import.meta.url));function fi(){let e=[ui(di,`web`),ui(r.cwd(),`dist/web`)].find(e=>l(li(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function pi({storage:e,webRoot:t=fi(),onListening:n}){let i=si(e),a=yr(t,e,i.apiOptions);i.start();let o=Ee({fetch:a.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return o.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),r.exitCode=1}),o.on(`close`,i.stop),o}function mi(e,t){return new Promise((n,r)=>{let i=Ne();i.once(`error`,r),i.listen(t,e,()=>{i.close(e=>{e?r(e):n()})})})}function hi(e){let t=`xdg-open`,n=[e];r.platform===`darwin`?t=`open`:r.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let a=i(t,n,{detached:!0,stdio:`ignore`});a.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),a.unref()}const gi=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 mi(`127.0.0.1`,11111)}catch(e){_i(e);return}pi({storage:Wt(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&hi(t)}})}});function _i(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),r.exitCode=1}function vi(){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:Pe,description:`Manage Foundry settings or start the Web UI`},default:`help`,subCommands:{help:r,web:gi,settings:ln}}),t}t(vi());export{};
11
+ `,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await S(c(e,{highWaterMark:gi}),Me({chunkSize:gi}),i):await S(c(e,{highWaterMark:gi}),i),{hasMalformedLines:n}}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e){return typeof e==`string`?e:``}function yi(e){let t=Date.parse(X(e));return Number.isFinite(t)?t:null}function bi(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function xi(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Y).filter(e=>[`text`,`input_text`,`output_text`].includes(X(e.type))).map(e=>X(e.text)).join(`
12
+ `):``}function Si(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function Ci(e){let t=await _i(r.join(e,`projects`));if(!t.found)throw new fi(`CLAUDE_DATA_NOT_FOUND`,`Claude Code sessions directory was not found`);let n=t.unreadable,i=/* @__PURE__ */ new Map;for(let e of t.files)try{let t=await wi(e);if((t.hasMalformedLines||!t.thread)&&(n+=1),t.thread){let e=i.get(t.thread.id);(!e||e.updatedAt<t.thread.updatedAt)&&i.set(t.thread.id,t.thread)}}catch{n+=1}return{threads:i.values().toArray(),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function wi(e){let t=await be(e),n=``,i=``,a=null,o=``,s=``,c=``,l=null,u=1/0,d=0,f=e.split(r.sep).includes(`subagents`),p=f?r.basename(r.dirname(r.dirname(e))):null,m=f,h=/* @__PURE__ */ new Map,ee=0,{hasMalformedLines:g}=await vi(e,e=>{f?p=X(e.sessionId)||p:n||=X(e.sessionId),i=X(e.cwd)||i,a=X(e.gitBranch)||a,m||=e.isSidechain===!0;let t=yi(e.timestamp);t!==null&&(u=Math.min(u,t),d=Math.max(d,t)),e.type===`custom-title`?s=X(e.customTitle)||s:e.type===`last-prompt`&&(c=X(e.lastPrompt)||c);let r=Y(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&r.role===`user`&&(o||=xi(r.content).trim()),e.type!==`assistant`||r.role!==`assistant`)return;let g=X(r.model);g&&g!==`<synthetic>`&&(l=g);let _=Y(r.usage)?r.usage:{},v=[_.input_tokens,_.output_tokens,_.cache_creation_input_tokens,_.cache_read_input_tokens].reduce((e,t)=>e+bi(t),0),te=X(r.id)||X(e.uuid);te?h.set(te,Math.max(h.get(te)??0,v)):ee+=v});return n||=r.basename(e).replace(/\.jsonl(?:\.zst)?$/u,``),Number.isFinite(u)?{thread:{id:n,title:Si(s||o||c,n),cwd:i,gitBranch:a,model:l,archived:!1,subagent:m,parentThreadId:p,createdAt:new Date(u).toISOString(),updatedAt:new Date(d).toISOString(),sizeBytes:t.size,segmentCount:1,tokensUsed:h.values().reduce((e,t)=>e+t,ee)},hasMalformedLines:g}:{thread:null,hasMalformedLines:!0}}function Ti(){let e=i.env.CODEX_HOME?.trim();return e?r.resolve(e):r.join(re.homedir(),`.codex`)}async function Ei(e){let t=await Promise.all([_i(r.join(e,`sessions`)),_i(r.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new fi(`CODEX_DATA_NOT_FOUND`,`Codex session directories were not found`);let n=t.reduce((e,t)=>e+t.unreadable,0),i=/* @__PURE__ */ new Map;for(let[e,r]of t.entries())for(let t of r.files)try{let r=await Di(t,e===1);if((r.hasMalformedLines||!r.segment)&&(n+=1),r.segment){let e=i.get(r.segment.id)??[];e.push(r.segment),i.set(r.segment.id,e)}}catch{n+=1}return{threads:Array.from(i.values(),Oi),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function Di(e,t){let n={id:``,title:``,cwd:``,model:null,gitBranch:null,subagent:!1,parentThreadId:null,archived:t,createdAt:1/0,updatedAt:0,sizeBytes:(await be(e)).size,tokensUsed:0},i=``,{hasMalformedLines:a}=await vi(e,e=>{let t=yi(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let r=Y(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=X(r.id),n.cwd||=X(r.cwd),n.model??=X(r.model_provider)||null;let e=Y(r.git)?r.git:{};n.gitBranch??=X(e.branch)||null;let t=Y(r.source)?r.source:{},i=Y(r.thread_source)?r.thread_source:{},a=Y(t.subagent)?t.subagent:{},o=Y(i.subagent)?i.subagent:{};n.parentThreadId??=X(r.parent_thread_id)||X(a.parent_thread_id)||X(o.parent_thread_id)||null,n.subagent||=!!r.parent_thread_id||Y(r.source)&&`subagent`in r.source||Y(r.thread_source)&&`subagent`in r.thread_source}else if(e.type===`turn_context`)n.cwd=X(r.cwd)||n.cwd,n.model=X(r.model)||n.model;else if(e.type===`response_item`&&r.type===`message`&&r.role===`user`){let e=xi(r.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(i||=e)}else if(e.type===`token_usage_record`){let e=Y(r.thread_token_usage)?r.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,bi(e.total_tokens))}else if(e.type===`event_msg`&&r.type===`token_count`){let e=Y(r.info)?r.info:{},t=Y(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,bi(t.total_tokens))}});return n.title=i,n.id||=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/u.exec(r.basename(e))?.[1]??``,Number.isFinite(n.createdAt)?{segment:n.id?n:null,hasMalformedLines:a}:{segment:null,hasMalformedLines:!0}}function Oi(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:Si(e.find(e=>e.title)?.title??``,t.id),cwd:e.findLast(e=>e.cwd)?.cwd??``,model:e.findLast(e=>e.model)?.model??null,gitBranch:e.findLast(e=>e.gitBranch)?.gitBranch??null,archived:e.every(e=>e.archived),subagent:e.some(e=>e.subagent),parentThreadId:e.findLast(e=>e.parentThreadId)?.parentThreadId??null,createdAt:new Date(Math.min(...e.map(e=>e.createdAt))).toISOString(),updatedAt:new Date(Math.max(...e.map(e=>e.updatedAt))).toISOString(),sizeBytes:e.reduce((e,t)=>e+t.sizeBytes,0),segmentCount:e.length,tokensUsed:Math.max(...e.map(e=>e.tokensUsed))}}var ki=class{codexHome;claudeHome;constructor(e=Ti(),t=hi()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return Ai(`codex`,await Ei(this.codexHome))}async getClaudeSnapshot(){return Ai(`claude`,await Ci(this.claudeHome))}};function Ai(e,t){return{source:e,capturedAt:(/* @__PURE__ */ new Date()).toISOString(),threads:t.threads.toSorted((e,t)=>t.updatedAt.localeCompare(e.updatedAt)),warnings:t.warnings}}function ji(e){let t=new C;return t.get(`/`,t=>Ne(t,async n=>{await Mi(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Ni(n,e)}),c=setInterval(()=>{r||Pi(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 Mi(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Ni(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Pi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Fi=class extends Error{code=`INVALID_EXPORT_INPUT`};function Ii(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Fi(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Li(e){let t=new C;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Fi(`Request body must be valid JSON`)}let{passphrase:r}=Ii(n),i=await e.createExport(r);return t.body(i.contents,200,{"content-type":`application/octet-stream`,"content-disposition":`attachment; filename="${i.fileName}"`,"cache-control":`no-store`})}catch(e){return e instanceof Fi?t.json({error:{code:e.code,message:e.message}},400):t.json({error:{code:`DATA_EXPORT_FAILED`,message:`Unable to export data`}},500)}}),t}function Ri(e,t){let n=new C;return n.post(`/`,async n=>{let i;try{if(n.req.header(`content-type`)?.split(`;`,1)[0].trim()!==`application/octet-stream`||!n.req.raw.body)throw new I(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new I(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new I(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await he(r.join(ae(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await S(Te.fromWeb(n.req.raw.body),l(o,{mode:384})),await e.importData(o,a);try{t()}catch{console.error(`Data was imported, but notifying settings consumers failed`)}return n.json({status:`imported`})}catch(e){return e instanceof I?n.json({error:{code:e.code,message:e.message}},e.code===`IMPORT_FAILED`?500:400):n.json({error:{code:`IMPORT_FAILED`,message:`Unable to import data`}},500)}finally{i&&await zt(i)}}),n}function zi(e){return e===`/api`||e.startsWith(`/api/`)}function Bi(e,t={}){let n=new C,r=t.providerService??new ci(e),i=t.settingsService??new ht(e),a=t.settingsSkillCopyService??new _t,o=t.sessionService??new ki,s=t.instructionsService??new Tn(e),c=t.agentsService??new Pn(e,s);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Le,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,ji(t.eventHub)),n.route(`/api/data-import`,Ri(t.dataImportService??new bn(e),()=>{t.onSettingsChanged?.(),t.eventHub?.publish(Qe,{fields:[`theme`,`language`,`timeFormat`,`timezone`,`captures`]})})),n.route(`/api/data-export`,Li(t.dataExportService??new fn(e))),n.route(`/api/agents`,Tr(c)),n.route(`/api/instructions`,Ir(s)),n.route(`/api/providers`,ii(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,li(i,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(Qe,e)},a)),n.route(`/api/sessions`,pi(o)),t.captureService&&n.route(`/api/captures`,Nr(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),n.notFound(e=>zi(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),zi(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Vi(e,t,n){let i=Bi(t,n),a=Ae({root:e});i.use(`*`,(e,t)=>zi(e.req.path)?t():a(e,t));let o=Ae({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!zi(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}var Hi=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=Date.now();return{id:y(),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-e.createdAt).map(e=>Ui(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:Ui(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 U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=Date.now(),i={id:y(),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:Ui(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 U(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Wi(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 U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=Date.now();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:Date.now()};return this.storage.put(`captures`,r),Ui(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt-e.createdAt).map(e=>Wi(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Wi(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:Date.now()})})}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=Date.now();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:Date.now()})})}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-t.createdAt).map(e=>e.id)}};function Ui(e){let{deletedAt:t,...n}=e;return n}function Wi(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}}var Z=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function Gi(e){if(e instanceof Z)return e;let t=Ki(e);return t===null?Yi(e)?new Z(`timeout`,`The configured fetcher timed out`):Xi(e)?new Z(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new Z(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new Z(`http_${t}`,qi(e)??`The configured fetcher returned ${t}`,t)}function Ki(e){if(!Q(e))return null;let t=Zi(e.status);return t===null?Q(e.response)?Zi(e.response.status):null:t}function qi(e){if(!Q(e))return null;if(Q(e.response)){let t=Ji(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:Ji(e.details)}function Ji(e){return Q(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function Yi(e){if(!(e instanceof Error))return!1;let t=Qi(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function Xi(e){if(e instanceof TypeError)return!0;if(!Q(e))return!1;let t=Qi(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!Q(e.response)}function Zi(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function Qi(e){let t=e.code;return typeof t==`string`?t:null}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $i=class extends Pe{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function ea(e,t,n={}){let r=new $i({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 ta(e,t,n=1,r=ea(t,n)){try{let t=na(e),n=await r.search(ra(t));if(!$(n))throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new Z(`fetcher_error`,ya(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);let i=va(n);if(i===null)throw new Z(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=da(e,ua(n));return{title:a?ga(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw Gi(e)}}function na(e){return{query:ia(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 ra(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function ia(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=aa(t.pathname),i=la(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function aa(e){let t=e.split(`/`).map(e=>oa(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||ca(n))continue;let r=sa(n);if(r)return r}return null}function oa(e){try{return decodeURIComponent(e)}catch{return e}}function sa(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function ca(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 la(e){return Fe(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function ua(e){return!$(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!$(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:$(e.metadata)?e.metadata:{}}])}function da(e,t){let n=pa(e);if(n){let e=t.find(e=>fa(e).some(e=>pa(e)===n));if(e)return e}let r=ma(e),i=r===null?[]:t.filter(e=>fa(e).some(e=>ma(e)===r));return i.find(e=>ha(e))??(i.length>0?i[0]:null)}function fa(e){return[e.url,_a(e,`sourceURL`),_a(e,`url`)].filter(e=>!!e)}function pa(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 ma(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function ha(e){return fa(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function ga(e){return e.title?.trim()||_a(e,`ogTitle`)?.trim()||_a(e,`title`)?.trim()||null}function _a(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function va(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function ya(e){return $(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ba(e,t){return ta(e,t.apiKey,t.maxAttempts)}var xa=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;constructor(e,t,n=()=>{},r=ba){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){let e=O(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=Sa(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=Gi(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()}};function Sa(e){let t=e;if(!Ca(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 Ca(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var wa=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=O(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 U(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Ta(e.url);if(!t)throw new U(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new U(`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 U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new U(`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 U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new U(`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 Ta(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Ea(e,t,n){let r=new Hi(e),i=new xa(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new wa(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}function Da(e,t){let n,r=te(e,{persistent:!1},(e,r)=>{(r===null||r===`settings.json`)&&(clearTimeout(n),n=setTimeout(t,30),n.unref())});return r.on(`error`,()=>{console.error(`Unable to watch Foundry settings`)}),()=>{clearTimeout(n),r.close()}}var Oa=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:y(),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 ka(e){let t=new Oa,n=Ea(e,t),r=new fn(e),i=new bn(e),a=new Tn(e),o=new Pn(e,a),s=new ci(e),c=new ht(e),l=new _t,u=new ki,d={agentsService:o,captureRuntime:n,dataExportService:r,dataImportService:i,instructionsService:a,providerService:s,settingsService:c,settingsSkillCopyService:l,sessionService:u},f;return{services:d,apiOptions:{agentsService:o,captureService:n.service,dataExportService:r,dataImportService:i,instructionsService:a,providerService:s,settingsService:c,settingsSkillCopyService:l,sessionService:u,eventHub:t,onSettingsChanged:n.notifySettingsChanged},start(){f??=Da(e.path,()=>{n.notifySettingsChanged(),t.publish(Qe,{fields:[]})}),n.start()},stop(){f?.(),f=void 0}}}const{dirname:Aa,join:ja,resolve:Ma}=r,Na=Aa(Se(import.meta.url));function Pa(){let e=[Ma(Na,`web`),Ma(i.cwd(),`dist/web`)].find(e=>u(ja(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Fa({storage:e,webRoot:t=Pa(),onListening:n}){let r=ka(e),a=Vi(t,e,r.apiOptions);r.start();let o=ke({fetch:a.fetch,hostname:`127.0.0.1`,port:11111},()=>{n?.({url:`http://localhost:11111`,webRoot:t})});return o.on(`error`,e=>{console.error(`Unable to start Foundry: ${e.message}`),i.exitCode=1}),o.on(`close`,r.stop),o}function Ia(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 La(e){let t=`xdg-open`,n=[e];i.platform===`darwin`?t=`open`:i.platform===`win32`&&(t=`cmd`,n=[`/c`,`start`,`""`,e]);let r=a(t,n,{detached:!0,stdio:`ignore`});r.on(`error`,e=>{console.error(`Unable to open the browser: ${e.message}`)}),r.unref()}const Ra=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await Ia(`127.0.0.1`,11111)}catch(e){za(e);return}Fa({storage:Hn(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&La(t)}})}});function za(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function Ba(){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 Foundry settings and instructions or start the Web UI`},default:`help`,subCommands:{help:r,web:Ra,settings:wr,instructions:sr,agents:tr}}),t}t(Ba());export{};