@dhzh/foundry 7.3.2 → 7.4.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 +17 -12
- package/dist/index.mjs +7 -7
- package/dist/skills/foundry/SKILL.md +8 -3
- package/dist/skills/foundry/references/backups.md +6 -6
- package/dist/skills/foundry/references/settings.md +3 -3
- package/dist/skills/foundry/references/skills.md +62 -0
- package/dist/web/assets/index-BCwzZP_O.css +1 -0
- package/dist/web/assets/index-huTxUjD-.js +155 -0
- package/dist/web/assets/{markdown-editor-BUDoC1Cq.js → markdown-editor-nKIMVkN5.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -3
- package/dist/web/assets/index-DBRqOV2p.css +0 -1
- package/dist/web/assets/index-DDnGtSmA.js +0 -135
package/README.md
CHANGED
|
@@ -6,8 +6,8 @@ import encrypted backups, and install the bundled Foundry Skill.
|
|
|
6
6
|
|
|
7
7
|
## Current scope
|
|
8
8
|
|
|
9
|
-
The current Web UI implements Instructions and Settings. The CLI exposes
|
|
10
|
-
`instructions`, `agents`, and `settings` business command groups. Instructions
|
|
9
|
+
The current Web UI implements Instructions, Skills, and Settings. The CLI exposes
|
|
10
|
+
`instructions`, `agents`, `skills`, and `settings` business command groups. Instructions
|
|
11
11
|
supports creating, editing, deleting, and listing Markdown instruction files
|
|
12
12
|
from the Web UI or CLI, and the Web page and CLI assign them to ChatGPT and
|
|
13
13
|
Claude Code.
|
|
@@ -16,7 +16,13 @@ encrypted backups and bundled Skill installation. The main layout and sidebar
|
|
|
16
16
|
remain available, with placeholder routes for features not implemented yet. The
|
|
17
17
|
root route opens Dashboard; opening Settings without a category shows Appearance.
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
Skills supports manual creation from a name and description, followed by a
|
|
20
|
+
read-only detail page. The equivalent CLI action is
|
|
21
|
+
`foundry skills create manual --name hello --description "Use when greeting users."`.
|
|
22
|
+
Each skill lives at `<home>/.foundry/skill/<name>/SKILL.md`. See the
|
|
23
|
+
[Skills reference](skills/foundry/references/skills.md) for metadata rules and scope.
|
|
24
|
+
|
|
25
|
+
Provider and session backend services and APIs are retained.
|
|
20
26
|
Their presence does not imply a corresponding page or CLI command in the current
|
|
21
27
|
product. `app/web/legacy-src` holds remaining reference code; its Settings
|
|
22
28
|
implementation has been removed. Keeping the current scope focused on
|
|
@@ -126,16 +132,16 @@ foundry instructions edit <id> \
|
|
|
126
132
|
and advances `updatedAt`. It changes the instruction record only; reapply any
|
|
127
133
|
enabled agent that uses it to rewrite the managed block.
|
|
128
134
|
|
|
129
|
-
Delete an
|
|
135
|
+
Delete an instruction:
|
|
130
136
|
|
|
131
137
|
```bash
|
|
132
138
|
foundry instructions delete <id>
|
|
133
139
|
```
|
|
134
140
|
|
|
135
|
-
Deletion removes the Markdown file
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
141
|
+
Deletion removes the Markdown file and detaches it from every agent. Enabled
|
|
142
|
+
agent files are updated immediately; removing an agent's final assignment
|
|
143
|
+
disables it and removes its managed block. The command prints the deleted record
|
|
144
|
+
as JSON.
|
|
139
145
|
|
|
140
146
|
Instructions are stored as individual Markdown files at
|
|
141
147
|
`<home>/.foundry/instructions/<id>.md`. Each file has YAML frontmatter for the
|
|
@@ -200,9 +206,9 @@ foundry settings download-skill --target .agents,.claude
|
|
|
200
206
|
Backup passphrases use `FOUNDRY_PASSPHRASE` or `--passphrase`. Export rejects an
|
|
201
207
|
existing destination unless `--force` is supplied. Import normalizes backup data
|
|
202
208
|
and replaces the supported data completely. The backup payload contains
|
|
203
|
-
settings, instructions, and agent assignments. Providers
|
|
204
|
-
|
|
205
|
-
|
|
209
|
+
settings, instructions, and agent assignments. Providers and the external
|
|
210
|
+
`AGENTS.md`/`CLAUDE.md` files are outside this payload; reapply enabled agents
|
|
211
|
+
after import to rewrite their managed blocks. Web import reloads
|
|
206
212
|
the page without the hash route and enters the normal root route. See
|
|
207
213
|
[backup behavior and format](docs/data-export.md).
|
|
208
214
|
|
|
@@ -251,7 +257,6 @@ Runtime data lives in `<home>/.foundry`, outside the repository and `dist`:
|
|
|
251
257
|
|
|
252
258
|
- `settings.json`: normalized application settings
|
|
253
259
|
- `providers.json`: retained provider records
|
|
254
|
-
- `captures/` and `fetch-jobs/`: one JSON file per retained record
|
|
255
260
|
- `instructions/`: one Markdown instruction file per record
|
|
256
261
|
- `agents/`: one JSON agent profile per record, including the `instructions`
|
|
257
262
|
capability state
|
package/dist/index.mjs
CHANGED
|
@@ -1,12 +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: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 te,statSync as _,watch as ne,writeFileSync as re}from"node:fs";import ie,{homedir as ae,tmpdir as oe}from"node:os";import{createCipheriv as se,createDecipheriv as ce,createHash as le,randomBytes as ue,randomUUID as v,scrypt as de}from"node:crypto";import{chmod as fe,cp as pe,link as me,mkdir as he,mkdtemp as ge,open as _e,readFile as ve,readdir as ye,rename as be,rm as y,stat as xe,writeFile as Se}from"node:fs/promises";import{fileURLToPath as Ce}from"node:url";import{Buffer as b}from"node:buffer";import{pipeline as x}from"node:stream/promises";import we from"yauzl";import Te from"yazl";import{Readable as Ee,Transform as De}from"node:stream";import{parse as Oe,stringify as ke}from"yaml";import{serve as Ae}from"@hono/node-server";import{serveStatic as je}from"@hono/node-server/serve-static";import{Hono as S}from"hono";import{StringDecoder as Me}from"node:string_decoder";import{createZstdDecompress as Ne}from"node:zlib";import{streamSSE as Pe}from"hono/streaming";import{FirecrawlClient as Fe}from"firecrawl";import{parse as Ie}from"tldts";import{createServer as Le}from"node:net";var Re=`7.3.2`,C=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function ze(e){if(!Ve(e)||!Array.isArray(e.instructionIds))throw new C(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new C(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new C(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function Be(e){if(!Ve(e)||typeof e.enabled!=`boolean`)throw new C(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Ve(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const He=[`chatgpt`,`claude-code`];function Ue(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 We(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 Ge(){return r.join(ie.homedir(),`.foundry`)}function Ke(){let e=Ge();return f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const qe=[`system`,`light`,`dark`],Je=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ye=[`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`],Xe=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Ze=[`firecrawl`],w=`data/foundry.json`,Qe=`settings.changed`,$e=[`agents`,`claude`],T={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 et(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{},a=O(t.features)?t.features:{},o=O(a.library)?a.library:{},s=O(o.captures)?o.captures:{},c=O(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":st(r[`color-theme`],qe,T.workspace.appearance[`color-theme`])},"language-region":{language:st(i.language,Je,T.workspace[`language-region`].language),"time-format":st(i[`time-format`],Ye,T.workspace[`language-region`][`time-format`]),"time-zone":st(i[`time-zone`],Xe,T.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:at(s.fetcher),maxAttempts:ct(s.maxAttempts,10,1),fetchConcurrency:ct(s.fetchConcurrency,5,2),firecrawl:{apiKey:dt(c.apiKey)}}}}}}function tt(e){if(!O(e))throw new E(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=D(e.theme,qe,`theme`)),`language`in e&&(t.language=D(e.language,Je,`language`)),`timeFormat`in e&&(t.timeFormat=D(e.timeFormat,Ye,`timeFormat`)),`timezone`in e&&(t.timezone=D(e.timezone,Xe,`timezone`)),`captures`in e&&(t.captures=it(e.captures)),t}function nt(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 rt(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 E=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function it(e){if(!O(e))throw new E(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:D(e.fetcher,Ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=lt(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=lt(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=ut(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function at(e){return ot(e,Ze)}function ot(e,t){return typeof e==`string`&&t.includes(e)?e:null}function st(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function D(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new E(`Invalid ${n}`);return e}function ct(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function lt(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new E(`${n} must be an integer from 1 to ${t}`);return e}function ut(e,t){if(typeof e!=`string`)throw new E(`${t} must be a string`);return e.trim()}function dt(e){return typeof e==`string`?e:``}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ft(e){return e.readSettings()}function pt(e){return rt(ft(e))}function mt(e,t){return t.transaction(()=>{let n=nt(ft(t),e);return t.setSettings(n),rt(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=Ge(),n=We){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(Ce(import.meta.url)),k=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ae()}={}){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}-${v()}.tmp`),o=r.join(n,`.${k}-${v()}.backup`);try{return await he(n,{recursive:!0}),await pe(t,a,{recursive:!0,errorOnExist:!0}),await yt(a,i,o),{target:e,destination:i}}catch(e){throw await y(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 be(t,n);try{await be(e,t),r&&await y(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await be(n,t),e}}const bt=`manifest.json`,xt=/* @__PURE__ */ new Set([bt,w]);async function St(e,t){let n=new Te.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await x(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 he(r.dirname(a),{recursive:!0,mode:448}),await x(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 y(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(bt)||!i.has(`data/foundry.json`))throw await y(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function wt(e){return new Promise((t,n)=>{we.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=b.from(`FOUNDRYX`,`ascii`),M=`aes-256-gcm`,Dt=`scrypt`,N={N:131072,r:8,p:1};async function Ot(e,t,n){let r=ue(16),i=ue(12),a={version:1,cipher:M,kdf:{name:Dt,salt:r.toString(`base64`),...N,keyLength:32},nonce:i.toString(`base64`)},o=b.from(JSON.stringify(a),`utf8`),s=At(o.byteLength),u=b.concat([s,o]),d=await jt(n,r,N);try{let n=await _e(t,`w`,384);try{await n.write(u)}finally{await n.close()}await x(c(e),Mt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),new Et(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function kt(e,t,n){let r;try{let i=(await xe(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await _e(e,`r`),o,s,u;try{if(o=await Ft(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 Ft(a,e,13),u=await Ft(a,16,i-16)}finally{await a.close()}let d=Pt(JSON.parse(s.toString(`utf8`)));r=await jt(n,d.salt,d.header.kdf);let f=b.concat([o,s]);await x(c(e,{start:13+s.byteLength,end:i-16-1}),Nt(r,d.nonce,f,u),l(t,{mode:384})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),e instanceof Et?e:new Et(Lt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Lt(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 At(e){let t=b.alloc(13);return j.copy(t,0),t.writeUInt8(1,j.byteLength),t.writeUInt32BE(e,j.byteLength+1),t}function jt(e,t,n){return new Promise((r,i)=>{de(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Mt(e,t,n){let r=se(M,e,t,{authTagLength:16});return r.setAAD(n),new De({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,b.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Nt(e,t,n,r){let i=ce(M,e,t,{authTagLength:16});return i.setAAD(n),new De({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 Pt(e){if(!It(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==M||!It(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Dt||typeof t.salt!=`string`||t.N!==N.N||t.r!==N.r||t.p!==N.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=b.from(t.salt,`base64`),r=b.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 Ft(e,t,n){let r=b.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Rt(e){try{await y(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function zt(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function P(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function Bt(e,t){Vt(e,`${JSON.stringify(t,null,2)}\n`)}function Vt(e,t){zt(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=p(n,`wx`,384);try{re(i,t),d(i)}finally{s(i)}ee(n,e),P(r.dirname(e))}finally{g(n,{force:!0})}}const F=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var I=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Ht=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Ut(e){if(!Wt(e))throw new I(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new I(`name is required`);let t=e.name.trim();if(!t)throw new I(`name is required`);if(t.length>200)throw new I(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new I(`content is required`);if(e.content.length>1e6)throw new I(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Kt(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=an(t,r.id),a=Zt(r);return t.transaction(()=>{Vt(i,a)}),r}function qt(e){let t=rn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(on(e))return[];throw e}return n.map(e=>$t(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)}function Jt(e,t){if(!F.test(e))return;let n=`${e}.md`;try{return $t(r.join(rn(t),n),n)}catch(e){if(on(e))return;throw e}}function Yt(e,t,n){let r=Jt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.transaction(()=>{Vt(an(n,i.id),Zt(i))}),i}function Xt(e,t){if(!F.test(e))return`missing`;let n=rn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>{try{return g(i),P(n),`removed`}catch(e){if(on(e))return`missing`;throw e}})}function Zt(e){return`---\n${ke({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function Qt(e,t){let n=Gt.exec(e);if(!n)throw L(t);let r=en(n[1]);if(`${r.id}.md`!==t)throw L(t);let i=e.slice(n[0].length);return i.startsWith(`\r
|
|
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 y,{homedir as re,tmpdir as ie}from"node:os";import{createCipheriv as ae,createDecipheriv as oe,createHash as se,randomBytes as ce,randomUUID as b,scrypt as le}from"node:crypto";import{chmod as ue,cp as de,link as fe,mkdir as pe,mkdtemp as me,open as he,readFile as ge,readdir as _e,rename as ve,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{parse as Ee,stringify as De}from"yaml";import{serve as Oe}from"@hono/node-server";import{serveStatic as ke}from"@hono/node-server/serve-static";import{Hono as w}from"hono";import{StringDecoder as Ae}from"node:string_decoder";import{createZstdDecompress as je}from"node:zlib";import{streamSSE as Me}from"hono/streaming";import{createServer as Ne}from"node:net";var Pe=`7.4.1`,T=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function Fe(e){if(!Le(e)||!Array.isArray(e.instructionIds))throw new T(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new T(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new T(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function Ie(e){if(!Le(e)||typeof e.enabled!=`boolean`)throw new T(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Re=new class{adapters;constructor(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(n.id)||t.has(n.id))throw Error(`Invalid or duplicate agent ID: ${n.id}`);t.add(n.id);let{instructions:e,skills:r}=n.capabilities;if(!Object.hasOwn(n.capabilities,`instructions`))throw Error(`Missing instruction configuration for agent: ${n.id}`);for(let t of[e.file,r?.directory])if(t&&(t.length===0||t.some(e=>!e||e===`.`||e===`..`||/[/\\:\0]/u.test(e))))throw Error(`Invalid home-relative path for agent: ${n.id}`)}this.adapters=structuredClone(e)}list(){return this.adapters}get(e){return this.adapters.find(t=>t.id===e)}supporting(e){return this.adapters.filter(t=>t.capabilities[e]!==void 0)}}([{id:`chatgpt`,name:`ChatGPT`,icon:{name:`openai`,invertInDark:!0},capabilities:{instructions:{file:[`.codex`,`AGENTS.md`]},skills:{directory:[`.agents`,`skills`]}}},{id:`claude-code`,name:`Claude Code`,icon:{name:`claudecode`,asset:`claudecode-color`},capabilities:{instructions:{file:[`.claude`,`CLAUDE.md`]},skills:{directory:[`.claude`,`skills`]}}}]);function ze(e){return`~/${e.join(`/`)}`}function Be(e,t){return r.join(e,...t)}function Ve(e){let{instructions:t,skills:n}=e.capabilities;return{instructions:{file:ze(t.file)},...n&&{skills:{directory:ze(n.directory)}}}}function He(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 Ue(){return r.join(y.homedir(),`.foundry`)}function We(){let e=Ue();return f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const Ge=[`system`,`light`,`dark`],Ke=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],qe=[`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`],Je=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],E=`data/foundry.json`,Ye=`settings.changed`,Xe=[`agents`,`claude`],Ze=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function Qe(e){return e.trim().normalize(`NFKC`)}function $e(e){let t=Qe(e);return[...t].length<=64&&t===t.toLowerCase()&&Ze.test(t)}const D={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}}};function et(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":at(r[`color-theme`],Ge,D.workspace.appearance[`color-theme`])},"language-region":{language:at(i.language,Ke,D.workspace[`language-region`].language),"time-format":at(i[`time-format`],qe,D.workspace[`language-region`][`time-format`]),"time-zone":at(i[`time-zone`],Je,D.workspace[`language-region`][`time-zone`])}}}}function tt(e){if(!O(e))throw new it(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=ot(e.theme,Ge,`theme`)),`language`in e&&(t.language=ot(e.language,Ke,`language`)),`timeFormat`in e&&(t.timeFormat=ot(e.timeFormat,qe,`timeFormat`)),`timezone`in e&&(t.timezone=ot(e.timezone,Je,`timezone`)),t}function nt(e,t){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`]}}}}function rt(e){return{workspace:e.workspace}}var it=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function at(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function ot(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new it(`Invalid ${n}`);return e}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function st(e){return e.readSettings()}function ct(e){return rt(st(e))}function lt(e,t){return t.transaction(()=>{let n=nt(st(t),e);return t.setSettings(n),rt(n)})}var ut=class{storage;configFolder;openFolder;constructor(e,t=Ue(),n=He){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...ct(this.storage),configFolder:this.configFolder}}update(e){return{...lt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const dt=r.dirname(xe(import.meta.url)),k=`foundry`;var ft=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=re()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??pt();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}-${b()}.tmp`),o=r.join(n,`.${k}-${b()}.backup`);try{return await pe(n,{recursive:!0}),await de(t,a,{recursive:!0,errorOnExist:!0}),await mt(a,i,o),{target:e,destination:i}}catch(e){throw await x(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 pt(){let e=[r.resolve(dt,`skills`,k),r.resolve(dt,`..`,`..`,`..`,`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 mt(e,t,n){let r=u(t);r&&await ve(t,n);try{await ve(e,t),r&&await x(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await ve(n,t),e}}const ht=`manifest.json`,gt=/* @__PURE__ */ new Set([ht,E]);async function _t(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,l(t,{mode:384}))}async function vt(e,t){let n=await yt(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(!gt.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 pe(r.dirname(a),{recursive:!0,mode:448}),await C(await bt(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 x(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(ht)||!i.has(`data/foundry.json`))throw await x(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function yt(e){return new Promise((t,n)=>{Se.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function bt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var xt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const j=S.from(`FOUNDRYX`,`ascii`),M=`aes-256-gcm`,St=`scrypt`,N={N:131072,r:8,p:1};async function Ct(e,t,n){let r=ce(16),i=ce(12),a={version:1,cipher:M,kdf:{name:St,salt:r.toString(`base64`),...N,keyLength:32},nonce:i.toString(`base64`)},o=S.from(JSON.stringify(a),`utf8`),s=Tt(o.byteLength),u=S.concat([s,o]),d=await Et(n,r,N);try{let n=await he(t,`w`,384);try{await n.write(u)}finally{await n.close()}await C(c(e),Dt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await ue(t,384)}catch(e){throw await x(t,{force:!0}),new xt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function wt(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 he(e,`r`),o,s,u;try{if(o=await At(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 At(a,e,13),u=await At(a,16,i-16)}finally{await a.close()}let d=kt(JSON.parse(s.toString(`utf8`)));r=await Et(n,d.salt,d.header.kdf);let f=S.concat([o,s]);await C(c(e,{start:13+s.byteLength,end:i-16-1}),Ot(r,d.nonce,f,u),l(t,{mode:384})),await ue(t,384)}catch(e){throw await x(t,{force:!0}),e instanceof xt?e:new xt(Mt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Mt(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 Tt(e){let t=S.alloc(13);return j.copy(t,0),t.writeUInt8(1,j.byteLength),t.writeUInt32BE(e,j.byteLength+1),t}function Et(e,t,n){return new Promise((r,i)=>{le(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Dt(e,t,n){let r=ae(M,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 Ot(e,t,n,r){let i=oe(M,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 kt(e){if(!jt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==M||!jt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==St||typeof t.salt!=`string`||t.N!==N.N||t.r!==N.r||t.p!==N.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:M,kdf:{name:St,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function At(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 jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Nt(e){try{await x(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}const P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var F=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Pt=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Ft(e){if(!It(e))throw new F(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new F(`name is required`);let t=e.name.trim();if(!t)throw new F(`name is required`);if(t.length>200)throw new F(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new F(`content is required`);if(e.content.length>1e6)throw new F(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Lt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Rt(e,t){let n=Date.now(),r={id:b(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=Xt(t,r.id),a=Ut(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function zt(e){return e.transaction(()=>{let t=Yt(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(Zt(e))return[];throw e}return n.map(e=>Gt(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function Bt(e,t){return t.transaction(()=>{if(!P.test(e))return;let n=`${e}.md`;try{return Gt(r.join(Yt(t),n),n)}catch(e){if(Zt(e))return;throw e}})}function Vt(e,t,n){return n.transaction(()=>{let r=Bt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(Xt(n,i.id),Ut(i)),i})}function Ht(e,t){if(!P.test(e))return`missing`;let n=Yt(t),i=r.join(n,`${e}.md`);return t.transaction(()=>u(i)?(t.removeTextFile(i),`removed`):`missing`)}function Ut(e){return`---\n${De({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function Wt(e,t){let n=Lt.exec(e);if(!n)throw I(t);let r=Kt(n[1]);if(`${r.id}.md`!==t)throw I(t);let i=e.slice(n[0].length);return i.startsWith(`\r
|
|
3
3
|
`)?i=i.slice(2):i.startsWith(`
|
|
4
|
-
`)&&(i=i.slice(1)),{...r,content:i}}function
|
|
4
|
+
`)&&(i=i.slice(1)),{...r,content:i}}function Gt(e,t){return Wt(m(e,`utf8`),t)}function Kt(e){let t;try{t=Ee(e)}catch{throw I(`frontmatter`)}if(!Qt(t))throw I(`frontmatter`);let n=qt(t.id),r=qt(t.name);if(!r||r.length>200||!P.test(n))throw I(`frontmatter`);return{id:n,name:r,createdAt:Jt(t.createdAt),updatedAt:Jt(t.updatedAt)}}function qt(e){return typeof e==`string`?e:``}function Jt(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw I(`frontmatter`);return e}function Yt(e){return r.join(e.path,`instructions`)}function Xt(e,t){if(!P.test(t))throw Error(`Invalid instruction ID`);return r.join(Yt(e),`${t}.md`)}function I(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function Zt(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function Qt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e){return e.transaction(()=>{let t=new Set(Re.list().map(({id:e})=>e));return{settings:e.readSettings(),instructions:zt(e),agents:e.all(`agents`).filter(({id:e})=>t.has(e)).toSorted((e,t)=>e.id.localeCompare(t.id))}})}var en=class{storage;constructor(e){this.storage=e}async createExport(e){let t=$t(this.storage),n=await me(r.join(ie(),`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:Pe,createdAt:i,data:{path:E,bytes:S.byteLength(a,`utf8`),sha256:se(`sha256`).update(a).digest(`hex`)}};return await be(o,a,{mode:384}),await be(s,JSON.stringify(u,null,2),{mode:384}),await _t([{entryPath:`manifest.json`,filePath:s},{entryPath:E,filePath:o}],c),await Ct(c,l,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await ge(l)}}finally{await Nt(n)}}},L=class extends Error{code;constructor(e,t){super(t),this.code=e}};function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tn(e){if(!R(e)||e.format!==`foundry.data`||e.archiveVersion!==2||!R(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:E,bytes:e.data.bytes,sha256:e.data.sha256}}}function nn(e){if(!R(e)||!R(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw z(`Backup data must contain settings, instructions, and agents`);let t=rn(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:et(e.settings),instructions:t,agents:an(e.agents,n)}}function rn(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!R(e))throw z(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!P.test(r)||t.has(r))throw z(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw z(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw z(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:on(e.createdAt,n),updatedAt:on(e.updatedAt,n)};return t.add(r),a})}function an(e,t){let n=new Set(Re.list().map(({id:e})=>e)),r=/* @__PURE__ */ new Set;return e.map((e,i)=>{if(!R(e)||!R(e.instructions))throw z(`Invalid agent at index ${i}`);let a=e.id;if(typeof a!=`string`||!n.has(a)||r.has(a))throw z(`Invalid agent at index ${i}`);let o=e.instructions,s=o.instructionIds;if(!Array.isArray(s))throw z(`Invalid instruction assignment for agent ${a}`);let c=s.map(e=>{if(typeof e!=`string`)throw z(`Invalid instruction assignment for agent ${a}`);return e});if(new Set(c).size!==c.length||c.some(e=>!t.has(e)))throw z(`Invalid instruction assignment for agent ${a}`);if(typeof o.enabled!=`boolean`)throw z(`Invalid enabled state for agent ${a}`);if(o.enabled&&c.length===0)throw z(`Enabled agent ${a} has no instructions`);let l={id:a,instructions:{instructionIds:c,enabled:o.enabled,createdAt:on(o.createdAt,i),updatedAt:on(o.updatedAt,i)}};return r.add(a),l})}function on(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw z(`Invalid timestamp at index ${t}`);return e}function z(e){return new L(`INVALID_BACKUP`,e)}function sn(e,t){e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of zt(e))n.has(t.id)||e.removeTextFile(cn(t.id));for(let n of t.instructions)e.putTextFile(cn(n.id),Ut(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 cn(e){return r.join(`instructions`,`${e}.md`)}var ln=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await me(r.join(ie(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await wt(e,i,t);let a=await vt(i,r.join(n,`extracted`)),o=tn(JSON.parse(await ge(a[`manifest.json`],`utf8`))),s=await ge(a[E]);if(s.byteLength!==o.data.bytes||se(`sha256`).update(s).digest(`hex`)!==o.data.sha256)throw new L(`INVALID_BACKUP`,`Backup checksum does not match`);let c=nn(JSON.parse(s.toString(`utf8`)));try{sn(this.storage,c)}catch{throw new L(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof L?e:e instanceof xt?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 Nt(n)}}};function un(e,t=Re){return t.list().map(t=>({id:t.id,name:t.name,icon:t.icon.name,instructionFile:ze(t.capabilities.instructions.file),filePath:Be(e,t.capabilities.instructions.file),capabilities:Ve(t)}))}function dn(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function B(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function fn(e,t){pn(e,`${JSON.stringify(t,null,2)}\n`)}function pn(e,t){dn(r.dirname(e));let n=`${e}.${b()}.tmp`;try{let i=p(n,`wx`,384);try{ne(i,t),d(i)}finally{s(i)}ee(n,e),B(r.dirname(e))}finally{g(n,{force:!0})}}const mn=`<!-- foundry:instructions:start -->`,hn=`<!-- foundry:instructions:end -->`;function gn(e,t){let n=_n(e),r=yn(t);return`${n}${vn(n)}${r}\n`}function _n(e){let t=``,n=0;for(let r of bn(e)){let e=xn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function vn(e){return!e||e.endsWith(`
|
|
5
5
|
`)?``:`
|
|
6
|
-
`}function
|
|
6
|
+
`}function yn(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
|
|
7
7
|
|
|
8
|
-
`);return t?`${vn}\n\n${t}\n\n${yn}`:`${vn}\n${yn}`}function wn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function Tn(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}function En(e,t){let n=r.dirname(e);f(n,{recursive:!0,mode:448});let a=u(e)?_(e).mode&511:384,c=`${e}.${v()}.tmp`;try{let r=p(c,`wx`,a);try{i.platform!==`win32`&&o(c,a),re(r,t),d(r)}finally{s(r)}ee(c,e),P(n)}finally{g(c,{force:!0})}}function Dn(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?xn(i):bn(i,t);En(e.filePath,a)}function On(e){return e.all(`agents`)}function kn(e,t){return e.get(`agents`,t)}function An(e,t){return e.put(`agents`,t),t}function jn(e,t,n){let r=On(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(Ue(n).map(e=>[e.id,e])),a=new Map(qt(e).map(e=>[e.id,e])),o=Date.now();for(let n of r){let r=n.instructions,s=r.instructionIds.filter(e=>e!==t),c=i.get(n.id);c&&r.enabled&&Dn(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),An(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Mn=class{storage;homeDirectory;constructor(e,t=ie.homedir()){this.storage=e,this.homeDirectory=t}list(){return qt(this.storage)}get(e){let t=Jt(e,this.storage);if(!t)throw new Ht(e);return t}create(e){return Kt(e,this.storage)}update(e,t){let n=Yt(e,t,this.storage);if(!n)throw new Ht(e);return n}delete(e){return this.storage.transaction(()=>{let t=Jt(e,this.storage);if(!t||(jn(this.storage,e,this.homeDirectory),Xt(e,this.storage)===`missing`))throw new Ht(e);return t})}},Nn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Mn(e),n=ie.homedir(),r=We){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=Ue(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new C(`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 C(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}list(){let e=new Map(On(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>Pn(t,(e.get(t.id)??Fn(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e),r=this.readAssignedInstructions(t);return this.storage.transaction(()=>{let i=kn(this.storage,e)??Fn(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&Dn(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=An(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return Pn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=kn(this.storage,e)??Fn(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new C(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);Dn(n,e.map(({content:e})=>e),!1)}else Dn(n,[],!0);let a=Date.now();return Pn(n,An(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=kn(this.storage,e)??Fn(e),r=n.instructions;if(!r.enabled)throw new C(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);Dn(t,i.map(({content:e})=>e),!1);let a=Date.now();return Pn(t,An(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}openInstructionFile(e){let t=this.requireDefinition(e);if(!u(t.filePath))throw new C(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function Pn(e,t){return{id:e.id,name:e.name,icon:e.icon,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}function Fn(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}const In=[`agents`,`providers`,`captures`,`fetchJobs`];function Ln(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()-_(e).mtimeMs>3e4}}var Rn=class{path;changes=null;textChanges=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,zt(e);for(let e of In)e!==`providers`&&zt(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),`${le(`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{re(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=_(e);if(!Ln(e))return;let n=r.join(e,`recovering`);try{f(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);Ln(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(re(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!Ln(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}))]};Bt(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(te(t),P(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}),P(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);Vt(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else Bt(e,t.value)}g(r.join(this.path,`.transaction.json`),{force:!0}),P(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 et(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?et(JSON.parse(m(e,`utf8`))):structuredClone(T)})}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`,et(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};Bt(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 zn(e=Ge()){let t=new Rn(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 Bn(){return Ke(),zn()}async function V(e){let t;try{let n=Bn(),r=new Mn(n);t={storage:n,agentsService:new Nn(n,r),settingsService:new ht(n),settingsSkillCopyService:new _t,dataExportService:new ln(n),dataImportService:new _n(n),instructionsService:r},Hn(await e(t))}catch(e){let t=Un(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function Vn(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new H(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var H=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Hn(e){console.log(JSON.stringify(e,null,2))}function Un(e){return e instanceof Error?{code:Wn(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function Wn(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Gn=He.join(`, `),U={type:`positional`,description:`Agent ID: ${Gn}`,required:!0},Kn=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return V(({agentsService:e})=>e.list())}}),qn=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...U,description:`Optional agent ID: ${Gn}`,required:!1}},run({args:e}){return V(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new H(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${Gn}`);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}))}))})}}),Jn=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:U,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 V(({agentsService:t})=>{let n=ze({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Yn=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:U},run({args:e}){return V(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),Xn=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:U},run({args:e}){return V(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),Zn=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:U},run({args:e}){return V(({agentsService:t})=>t.reapply(e.agent))}}),Qn=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:U},run({args:e}){return V(({agentsService:t})=>t.openInstructionFile(e.agent))}}),$n=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions for supported agents`},subCommands:{list:Kn,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:qn,assign:Jn,enable:Yn,disable:Xn,reapply:Zn,open:Qn}})}}),er=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 V(({instructionsService:t})=>t.create(Ut({name:e.name,content:e.content})))}}),tr=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return V(({instructionsService:e})=>e.list())}}),nr=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 V(({instructionsService:t})=>t.get(e.id))}}),rr=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 V(({instructionsService:t})=>t.update(e.id,Ut({name:e.name,content:e.content})))}}),ir=e({meta:{name:`delete`,description:`Delete an instruction and remove it from every agent`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return V(({instructionsService:t})=>t.delete(e.id))}}),ar=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:er,list:tr,get:nr,edit:rr,delete:ir}});function or(e){if(!cr(e)||!Array.isArray(e.targets))throw new sr(`targets must be an array`);if(e.targets.length===0)throw new sr(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!$e.includes(e))throw new sr(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var sr=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function cr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const lr=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 V(async({dataExportService:t})=>{let n=await t.createExport(Vn(e.passphrase)),r=dr(e.output);return await fr(n.contents,r,e.force),{filePath:r}})}}),ur=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 V(async({dataImportService:t})=>(await t.importData(r.resolve(e.file),Vn(e.passphrase)),{status:`imported`}))}});function dr(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 fr(e,t,n){await he(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${v()}.tmp`);try{if(await Se(a,e,{mode:384}),i.platform!==`win32`&&await fe(a,384),n){await be(a,t);return}if(u(t))throw pr(t);try{await me(a,t)}catch(e){throw mr(e)?pr(t):e}}finally{await y(a,{force:!0})}}function pr(e){return new H(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function mr(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const W={"color-theme":{field:`theme`,values:qe},language:{field:`language`,values:Je},"time-zone":{field:`timezone`,values:Xe},"time-format":{field:`timeFormat`,values:Ye}},hr=[...Object.keys(W),`config-folder`],gr=Object.entries(W).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
9
|
-
`);function _r(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const vr=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${hr.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return V(({settingsService:t})=>{let n=_r(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new H(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${hr.join(`, `)}`);return n[e.key]})}}),yr=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(W).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${gr}`,required:!0}},run({args:e}){return V(({settingsService:t})=>{if(e.key===`config-folder`)throw new H(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(W,e.key))throw new H(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(W).join(`, `)}`);let n=W[e.key];if(!n.values.includes(e.value))throw new H(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=_r(t.update(tt({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),br=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return V(({settingsService:e})=>e.openConfigFolder())}}),xr=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 V(({settingsSkillCopyService:t})=>{let n=or({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Sr=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:vr,set:yr,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:br}}),export:lr,import:ur,"download-skill":xr}});function Cr(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=ze(await wr(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Tr(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=Be(await wr(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Tr(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Tr(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Tr(t,e)}}),t}async function wr(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Tr(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Er(e){if(!Ar(e)||typeof e.url!=`string`)throw new kr(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Dr(e){return e===`no-successful`?`no-successful`:`all`}function Or(e){if(!Ar(e)||typeof e.userNote!=`string`)throw new kr(`userNote must be a string`);return e.userNote}var kr=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Ar(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var G=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function jr(e,t=()=>{}){let n=new S;return n.get(`/`,t=>{let n=Dr(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=Er(await Mr(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return K(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return K(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 K(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 K(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Or(await Mr(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return K(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return K(t,e)}}),n}async function Mr(e){try{return await e.req.json()}catch{throw new kr(`Request body must be valid JSON`)}}function K(e,t){if(t instanceof kr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},Nr(t.code));throw t}function Nr(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 Pr(e){let t=new S;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 Ir(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(Ut(await Fr(t)));return t.json(n,201)}catch(e){return Ir(t,e)}}),t.put(`/:id`,async t=>{try{let n=Ut(await Fr(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Ir(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Ir(t,e)}}),t}async function Fr(e){try{return await e.req.json()}catch{throw new I(`Request body must be valid JSON`)}}function Ir(e,t){if(t instanceof I)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Ht)return e.json({error:{code:t.code,message:t.message}},404);throw t}const Lr=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Rr=[`active`,`disabled`,`deleted`];var q=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},zr=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function Br(e){if(!qr(e))throw new q(`Provider input must be an object`);let t=J(e.name,`name`),n=Gr(e.protocol),r=Kr(e.baseURL),i=e.apiKey===void 0?``:J(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Wr(e.customModels);return{...e.avatar!==void 0&&{avatar:Vr(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Vr(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 q(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Hr(e){if(!qr(e))throw new q(`Provider connection must be an object`);return{protocol:Gr(e.protocol),baseURL:Kr(e.baseURL),apiKey:e.apiKey===void 0?``:J(e.apiKey,`apiKey`,{allowEmpty:!0})}}function Ur(e){if(typeof e!=`string`||!Rr.includes(e))throw new q(`Invalid provider status`);return e}function Wr(e){if(e===void 0)return[];if(!Array.isArray(e))throw new q(`customModels must be an array`);return e.map(e=>{if(!qr(e))throw new q(`Each custom model must be an object`);return{id:J(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:J(e.displayName,`customModels.displayName`)}})}function Gr(e){if(typeof e!=`string`||!Lr.includes(e))throw new q(`Invalid provider protocol`);return e}function Kr(e){let t=J(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new q(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function J(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new q(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new q(`${t} is required`);return r}function qr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Y=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Jr(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(Yr(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new Y(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new Y(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new Y(`Provider returned invalid JSON`)}return Xr(i)}function Yr(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function Xr(e){if(!Qr(e)||!Array.isArray(e.data))throw new Y(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Qr(e)||typeof e.id!=`string`||e.id.length===0)throw new Y(`Provider returned an invalid model entry`);let t=Zr(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function Zr(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Qr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $r=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},ei=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=>({...ti(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?ti(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 $r;let r=Date.now(),i={id:t??v(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),ti(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new zr;let r=this.storage.get(`providers`,e);if(!r)throw new $r;let i=Date.now(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),ti(a)})}};function ti(e){return{...e,avatar:e.avatar??null,status:e.status}}function ni(e,t=()=>{}){let n=new S;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return ii(t,e)}}),n.post(`/models`,async t=>{try{let n=Hr(await ri(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return ii(t,e)}}),n.post(`/`,async n=>{try{let r=Br(await ri(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return ii(n,e)}}),n.put(`/:id`,async n=>{try{let r=Br(await ri(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return ii(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await ri(n),i=Ur(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return ii(n,e)}}),n}async function ri(e){try{return await e.req.json()}catch{throw new q(`Request body must be valid JSON`)}}function ii(e,t){if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof $r)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof zr)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof Y)return e.json({error:{code:t.code,message:t.message}},502);throw t}function ai(e){let t=ft(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))oi(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function oi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var si=class{storage;repository;constructor(e){this.storage=e,this.repository=new ei(e)}list(){return this.repository.list(ai(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new $r;return Jr(t)}fetchModelsForConnection(e){return Jr(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,ai(this.storage)))}};function ci(e,t=()=>{},n=new _t){let r=new S;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=tt(await li(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return ui(n,e)}}),r.post(`/config-folder/open`,t=>{let n=e.openConfigFolder();return t.json({configFolder:n.configFolder},202)}),r.post(`/skill-copy`,async e=>{try{let t=or(await li(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return ui(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function li(e){try{return await e.req.json()}catch{throw new E(`Request body must be valid JSON`)}}function ui(e,t){if(t instanceof E||t instanceof sr)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 di=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function fi(e){let t=new S;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return pi(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return pi(t,e)}}),t}function pi(e,t){if(t instanceof di)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 mi(){let e=i.env.CLAUDE_CONFIG_DIR?.trim();return e?r.resolve(e):r.join(ie.homedir(),`.claude`)}const hi=1048576;async function gi(e){let t;try{t=await ye(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 gi(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 _i(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}X(r)?t(r):n=!0},i=async e=>{let t=new Me(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
8
|
+
`);return t?`${mn}\n\n${t}\n\n${hn}`:`${mn}\n${hn}`}function bn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function xn(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}function Sn(e,t){let n=r.dirname(e);f(n,{recursive:!0,mode:448});let a=u(e)?v(e).mode&511:384,c=`${e}.${b()}.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),B(n)}finally{g(c,{force:!0})}}function V(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?_n(i):gn(i,t);Sn(e.filePath,a)}function Cn(e){return e.all(`agents`)}function wn(e,t){return e.get(`agents`,t)}function Tn(e,t){return e.put(`agents`,t),t}function En(e,t,n){let r=Cn(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(un(n).map(e=>[e.id,e])),a=new Map(zt(e).map(e=>[e.id,e])),o=Date.now();for(let n of r){let r=n.instructions,s=r.instructionIds.filter(e=>e!==t),c=i.get(n.id);c&&r.enabled&&V(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),Tn(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Dn=class{storage;homeDirectory;constructor(e,t=y.homedir()){this.storage=e,this.homeDirectory=t}list(){return zt(this.storage)}get(e){let t=Bt(e,this.storage);if(!t)throw new Pt(e);return t}create(e){return Rt(e,this.storage)}update(e,t){let n=Vt(e,t,this.storage);if(!n)throw new Pt(e);return n}delete(e){return this.storage.transaction(()=>{let t=Bt(e,this.storage);if(!t||(En(this.storage,e,this.homeDirectory),Ht(e,this.storage)===`missing`))throw new Pt(e);return t})}},On=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Dn(e),n=y.homedir(),r=He){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=un(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new T(`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 T(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}list(){let e=new Map(Cn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>kn(t,(e.get(t.id)??An(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=wn(this.storage,e)??An(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&V(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=Tn(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return kn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=wn(this.storage,e)??An(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new T(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);V(n,e.map(({content:e})=>e),!1)}else V(n,[],!0);let a=Date.now();return kn(n,Tn(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=wn(this.storage,e)??An(e),r=n.instructions;if(!r.enabled)throw new T(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);V(t,i.map(({content:e})=>e),!1);let a=Date.now();return kn(t,Tn(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}openInstructionFile(e){let t=this.requireDefinition(e);if(!u(t.filePath))throw new T(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function kn(e,t){return{id:e.id,name:e.name,icon:e.icon,capabilities:e.capabilities,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}function An(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}var H=class extends Error{code=`INVALID_SKILL_INPUT`},jn=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},Mn=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function Nn(e){return e===e.trim()&&$e(e)}function Pn(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new H(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new H(`name is required`);let t=Qe(e.name);if(!Nn(t))throw new H(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new H(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new H(`description must be 1–1024 characters`);return{name:t,description:n}}const Fn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var In=class{storage;constructor(e){this.storage=e}directory(e){if(!Nn(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,`skill`,e)}create(e){return this.storage.transaction(()=>{let t=this.directory(e.name);if(u(t))throw new Mn(e.name);return this.storage.putTextFile(r.join(t,`SKILL.md`),`---\n${De(e).trimEnd()}\n---\n`),{...e,content:``}})}get(e){if(Nn(e))return this.storage.transaction(()=>{try{let t=m(r.join(this.directory(e),`SKILL.md`),`utf8`),n=Fn.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=Pn(Ee(n[1]));if(i.name!==Qe(e))throw Error(`Skill name does not match directory: ${e}`);return{...i,content:t.slice(n[0].length)}}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}})}list(){return this.storage.transaction(()=>{let e;try{e=h(r.join(this.storage.path,`skill`),{withFileTypes:!0}).filter(e=>e.isDirectory()&&Nn(e.name)).map(e=>e.name)}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return[];throw e}return e.toSorted((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=this.get(e);return t?[t]:[]})})}},Ln=class{repository;constructor(e){this.repository=new In(e)}create(e){return this.repository.create(Pn(e))}get(e){let t=this.repository.get(e);if(!t)throw new jn(e);return t}list(){return this.repository.list()}};const Rn=[`agents`,`providers`];function zn(e){if(/^instructions[/\\][^/\\]+\.md$/u.test(e))return!0;let t=/^skill[/\\]([^/\\]+)[/\\]SKILL\.md$/u.exec(e);return!!(t&&t[1]===t[1].trim()&&$e(t[1]))}function Bn(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 Vn=class{path;changes=null;textChanges=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,dn(e);for(let e of Rn)e!==`providers`&&dn(this.collectionPath(e))}collectionPath(e){return r.join(this.path,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),`${se(`sha256`).update(t).digest(`hex`)}.json`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!zn(t))throw Error(`Invalid storage text 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(!Bn(e))return;let n=r.join(e,`recovering`);try{f(n)}catch(e){if(e.code===`EEXIST`){let e=v(n);Bn(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||!Bn(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}))]};fn(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(_(t),B(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|[a-z][a-z-]*[/\\][a-f0-9]{64}\.json)$/u.test(n)&&!zn(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(t.value===null)g(e,{force:!0}),B(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);pn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else fn(e,t.value)}g(r.join(this.path,`.transaction.json`),{force:!0}),B(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 et(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?et(JSON.parse(m(e,`utf8`))):structuredClone(D)})}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.textFilename(e),t)}removeTextFile(e){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),null)}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,et(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};fn(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 Hn(e=Ue()){let t=new Vn(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 Un(){return We(),Hn()}async function U(e){let t;try{let n=Un(),r=new Dn(n);t={storage:n,agentsService:new On(n,r),settingsService:new ut(n),settingsSkillCopyService:new ft,dataExportService:new en(n),dataImportService:new ln(n),instructionsService:r,skillsService:new Ln(n)},Gn(await e(t))}catch(e){let t=Kn(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function Wn(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new W(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var W=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function Gn(e){console.log(JSON.stringify(e,null,2))}function Kn(e){return e instanceof Error?{code:qn(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function qn(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const Jn=Re.list().map(({id:e})=>e).join(`, `),G={type:`positional`,description:`Agent ID: ${Jn}`,required:!0},Yn=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return U(({agentsService:e})=>e.list())}}),Xn=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...G,description:`Optional agent ID: ${Jn}`,required:!1}},run({args:e}){return U(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new W(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${Jn}`);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}))}))})}}),Zn=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:G,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 U(({agentsService:t})=>{let n=Fe({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),Qn=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:G},run({args:e}){return U(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),$n=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:G},run({args:e}){return U(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),er=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:G},run({args:e}){return U(({agentsService:t})=>t.reapply(e.agent))}}),tr=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:G},run({args:e}){return U(({agentsService:t})=>t.openInstructionFile(e.agent))}}),nr=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions for supported agents`},subCommands:{list:Yn,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:Xn,assign:Zn,enable:Qn,disable:$n,reapply:er,open:tr}})}}),rr=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 U(({instructionsService:t})=>t.create(Ft({name:e.name,content:e.content})))}}),ir=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return U(({instructionsService:e})=>e.list())}}),ar=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 U(({instructionsService:t})=>t.get(e.id))}}),or=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 U(({instructionsService:t})=>t.update(e.id,Ft({name:e.name,content:e.content})))}}),sr=e({meta:{name:`delete`,description:`Delete an instruction and remove it from every agent`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return U(({instructionsService:t})=>t.delete(e.id))}}),cr=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:rr,list:ir,get:ar,edit:or,delete:sr}});function lr(e){if(!dr(e)||!Array.isArray(e.targets))throw new ur(`targets must be an array`);if(e.targets.length===0)throw new ur(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!Xe.includes(e))throw new ur(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var ur=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function dr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const fr=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 U(async({dataExportService:t})=>{let n=await t.createExport(Wn(e.passphrase)),r=mr(e.output);return await hr(n.contents,r,e.force),{filePath:r}})}}),pr=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 U(async({dataImportService:t})=>(await t.importData(r.resolve(e.file),Wn(e.passphrase)),{status:`imported`}))}});function mr(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 hr(e,t,n){await pe(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${b()}.tmp`);try{if(await be(a,e,{mode:384}),i.platform!==`win32`&&await ue(a,384),n){await ve(a,t);return}if(u(t))throw gr(t);try{await fe(a,t)}catch(e){throw _r(e)?gr(t):e}}finally{await x(a,{force:!0})}}function gr(e){return new W(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function _r(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const K={"color-theme":{field:`theme`,values:Ge},language:{field:`language`,values:Ke},"time-zone":{field:`timezone`,values:Je},"time-format":{field:`timeFormat`,values:qe}},vr=[...Object.keys(K),`config-folder`],yr=Object.entries(K).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
9
|
+
`);function br(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const xr=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${vr.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return U(({settingsService:t})=>{let n=br(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new W(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${vr.join(`, `)}`);return n[e.key]})}}),Sr=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(K).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${yr}`,required:!0}},run({args:e}){return U(({settingsService:t})=>{if(e.key===`config-folder`)throw new W(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(K,e.key))throw new W(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(K).join(`, `)}`);let n=K[e.key];if(!n.values.includes(e.value))throw new W(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=br(t.update(tt({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Cr=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return U(({settingsService:e})=>e.openConfigFolder())}}),wr=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 U(({settingsSkillCopyService:t})=>{let n=lr({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Tr=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:xr,set:Sr,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Cr}}),export:fr,import:pr,"download-skill":wr}}),Er=e({meta:{name:`manual`,description:`Create skill metadata with an empty Markdown body in ~/.foundry/skill/<name>/SKILL.md`},args:{name:{type:`string`,description:`Unique name: 1–64 Unicode letters or digits, lowercase where applicable, with single hyphens between words`,valueHint:`hello`,required:!0},description:{type:`string`,description:`When an agent should use this skill (1–1024 characters)`,valueHint:`text`,required:!0}},run({args:e}){return U(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),Dr=e({meta:{name:`skills`,description:`Manage skills in the Foundry library`},subCommands:{create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:Er}})}});function Or(e){let t=new w;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=Fe(await kr(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Ar(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=Ie(await kr(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Ar(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Ar(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Ar(t,e)}}),t}async function kr(e){try{return await e.req.json()}catch{throw new T(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Ar(e,t){if(t instanceof T)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function jr(e){let t=new w;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 Nr(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(Ft(await Mr(t)));return t.json(n,201)}catch(e){return Nr(t,e)}}),t.put(`/:id`,async t=>{try{let n=Ft(await Mr(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Nr(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Nr(t,e)}}),t}async function Mr(e){try{return await e.req.json()}catch{throw new F(`Request body must be valid JSON`)}}function Nr(e,t){if(t instanceof F)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Pt)return e.json({error:{code:t.code,message:t.message}},404);throw t}const Pr=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],Fr=[`active`,`disabled`,`deleted`];var q=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function Ir(e){if(!Ur(e))throw new q(`Provider input must be an object`);let t=J(e.name,`name`),n=Vr(e.protocol),r=Hr(e.baseURL),i=e.apiKey===void 0?``:J(e.apiKey,`apiKey`,{allowEmpty:!0}),a=Br(e.customModels);return{...e.avatar!==void 0&&{avatar:Lr(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function Lr(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 q(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function Rr(e){if(!Ur(e))throw new q(`Provider connection must be an object`);return{protocol:Vr(e.protocol),baseURL:Hr(e.baseURL),apiKey:e.apiKey===void 0?``:J(e.apiKey,`apiKey`,{allowEmpty:!0})}}function zr(e){if(typeof e!=`string`||!Fr.includes(e))throw new q(`Invalid provider status`);return e}function Br(e){if(e===void 0)return[];if(!Array.isArray(e))throw new q(`customModels must be an array`);return e.map(e=>{if(!Ur(e))throw new q(`Each custom model must be an object`);return{id:J(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:J(e.displayName,`customModels.displayName`)}})}function Vr(e){if(typeof e!=`string`||!Pr.includes(e))throw new q(`Invalid provider protocol`);return e}function Hr(e){let t=J(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new q(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function J(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new q(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new q(`${t} is required`);return r}function Ur(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Y=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function Wr(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(Gr(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new Y(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new Y(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new Y(`Provider returned invalid JSON`)}return Kr(i)}function Gr(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function Kr(e){if(!Jr(e)||!Array.isArray(e.data))throw new Y(`Provider response does not contain a model list`);return e.data.map(e=>{if(!Jr(e)||typeof e.id!=`string`||e.id.length===0)throw new Y(`Provider returned an invalid model entry`);let t=qr(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function qr(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function Jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var X=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},Yr=class{storage;constructor(e){this.storage=e}list(){return this.storage.all(`providers`).filter(e=>e.status!==`deleted`).toSorted((e,t)=>t.updatedAt-e.updatedAt).map(e=>Xr(e))}get(e){let t=this.storage.get(`providers`,e);return t?Xr(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 X;let r=Date.now(),i={id:t??b(),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),Xr(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new X;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),Xr(i)})}};function Xr(e){return{...e,avatar:e.avatar??null,status:e.status}}function Zr(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 Z(t,e)}}),n.post(`/models`,async t=>{try{let n=Rr(await Qr(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return Z(t,e)}}),n.post(`/`,async n=>{try{let r=Ir(await Qr(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return Z(n,e)}}),n.put(`/:id`,async n=>{try{let r=Ir(await Qr(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return Z(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await Qr(n),i=zr(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 Z(n,e)}}),n}async function Qr(e){try{return await e.req.json()}catch{throw new q(`Request body must be valid JSON`)}}function Z(e,t){if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof X)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Y)return e.json({error:{code:t.code,message:t.message}},502);throw t}var $r=class{repository;constructor(e){this.repository=new Yr(e)}list(){return this.repository.list()}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new X;return Wr(t)}fetchModelsForConnection(e){return Wr(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function ei(e,t=()=>{},n=new ft){let r=new w;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=tt(await ti(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return ni(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=lr(await ti(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return ni(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function ti(e){try{return await e.req.json()}catch{throw new it(`Request body must be valid JSON`)}}function ni(e,t){if(t instanceof it||t instanceof ur)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 ri=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function ii(e){let t=new w;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return ai(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return ai(t,e)}}),t}function ai(e,t){if(t instanceof ri)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 oi(e){let t=new w;return t.get(`/`,t=>t.json(e.list())),t.get(`/:name`,t=>{try{return t.json(e.get(t.req.param(`name`)))}catch(e){return si(t,e)}}),t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new H(`Request body must be valid JSON`)}return t.json(e.create(Pn(n)),201)}catch(e){return si(t,e)}}),t}function si(e,t){if(t instanceof H)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Mn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof jn)return e.json({error:{code:t.code,message:t.message}},404);throw t}function ci(){let e=i.env.CLAUDE_CONFIG_DIR?.trim();return e?r.resolve(e):r.join(y.homedir(),`.claude`)}const li=1048576;async function ui(e){let t;try{t=await _e(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 ui(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 di(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Q(r)?t(r):n=!0},i=async e=>{let t=new Ae(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
10
10
|
`,e);for(;a!==-1;)r(n.slice(e,a)),e=a+1,a=n.indexOf(`
|
|
11
|
-
`,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await
|
|
12
|
-
`):``}function xi(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function Si(e){let t=await gi(r.join(e,`projects`));if(!t.found)throw new di(`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 Ci(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 Ci(e){let t=await xe(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 _i(e,e=>{f?p=Z(e.sessionId)||p:n||=Z(e.sessionId),i=Z(e.cwd)||i,a=Z(e.gitBranch)||a,m||=e.isSidechain===!0;let t=vi(e.timestamp);t!==null&&(u=Math.min(u,t),d=Math.max(d,t)),e.type===`custom-title`?s=Z(e.customTitle)||s:e.type===`last-prompt`&&(c=Z(e.lastPrompt)||c);let r=X(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&r.role===`user`&&(o||=bi(r.content).trim()),e.type!==`assistant`||r.role!==`assistant`)return;let g=Z(r.model);g&&g!==`<synthetic>`&&(l=g);let te=X(r.usage)?r.usage:{},_=[te.input_tokens,te.output_tokens,te.cache_creation_input_tokens,te.cache_read_input_tokens].reduce((e,t)=>e+yi(t),0),ne=Z(r.id)||Z(e.uuid);ne?h.set(ne,Math.max(h.get(ne)??0,_)):ee+=_});return n||=r.basename(e).replace(/\.jsonl(?:\.zst)?$/u,``),Number.isFinite(u)?{thread:{id:n,title:xi(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 wi(){let e=i.env.CODEX_HOME?.trim();return e?r.resolve(e):r.join(ie.homedir(),`.codex`)}async function Ti(e){let t=await Promise.all([gi(r.join(e,`sessions`)),gi(r.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new di(`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 Ei(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(),Di),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function Ei(e,t){let n={id:``,title:``,cwd:``,model:null,gitBranch:null,subagent:!1,parentThreadId:null,archived:t,createdAt:1/0,updatedAt:0,sizeBytes:(await xe(e)).size,tokensUsed:0},i=``,{hasMalformedLines:a}=await _i(e,e=>{let t=vi(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let r=X(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=Z(r.id),n.cwd||=Z(r.cwd),n.model??=Z(r.model_provider)||null;let e=X(r.git)?r.git:{};n.gitBranch??=Z(e.branch)||null;let t=X(r.source)?r.source:{},i=X(r.thread_source)?r.thread_source:{},a=X(t.subagent)?t.subagent:{},o=X(i.subagent)?i.subagent:{};n.parentThreadId??=Z(r.parent_thread_id)||Z(a.parent_thread_id)||Z(o.parent_thread_id)||null,n.subagent||=!!r.parent_thread_id||X(r.source)&&`subagent`in r.source||X(r.thread_source)&&`subagent`in r.thread_source}else if(e.type===`turn_context`)n.cwd=Z(r.cwd)||n.cwd,n.model=Z(r.model)||n.model;else if(e.type===`response_item`&&r.type===`message`&&r.role===`user`){let e=bi(r.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(i||=e)}else if(e.type===`token_usage_record`){let e=X(r.thread_token_usage)?r.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,yi(e.total_tokens))}else if(e.type===`event_msg`&&r.type===`token_count`){let e=X(r.info)?r.info:{},t=X(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,yi(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 Di(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:xi(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 Oi=class{codexHome;claudeHome;constructor(e=wi(),t=mi()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return ki(`codex`,await Ti(this.codexHome))}async getClaudeSnapshot(){return ki(`claude`,await Si(this.claudeHome))}};function ki(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 Ai(e){let t=new S;return t.get(`/`,t=>Pe(t,async n=>{await ji(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Mi(n,e)}),c=setInterval(()=>{r||Ni(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 ji(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Mi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Ni(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Pi=class extends Error{code=`INVALID_EXPORT_INPUT`};function Fi(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Pi(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Ii(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Pi(`Request body must be valid JSON`)}let{passphrase:r}=Fi(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 Pi?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 Li(e,t){let n=new S;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 R(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new R(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new R(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await ge(r.join(oe(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await x(Ee.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 R?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 Rt(i)}}),n}function Ri(e){return e===`/api`||e.startsWith(`/api/`)}function zi(e,t={}){let n=new S,r=t.providerService??new si(e),i=t.settingsService??new ht(e),a=t.settingsSkillCopyService??new _t,o=t.sessionService??new Oi,s=t.instructionsService??new Mn(e),c=t.agentsService??new Nn(e,s);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Re,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,Ai(t.eventHub)),n.route(`/api/data-import`,Li(t.dataImportService??new _n(e),()=>{t.onSettingsChanged?.(),t.eventHub?.publish(Qe,{fields:[`theme`,`language`,`timeFormat`,`timezone`,`captures`]})})),n.route(`/api/data-export`,Ii(t.dataExportService??new ln(e))),n.route(`/api/agents`,Cr(c)),n.route(`/api/instructions`,Pr(s)),n.route(`/api/providers`,ni(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,ci(i,e=>{t.onSettingsChanged?.(),t.eventHub?.publish(Qe,e)},a)),n.route(`/api/sessions`,fi(o)),t.captureService&&n.route(`/api/captures`,jr(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),n.notFound(e=>Ri(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),Ri(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Bi(e,t,n){let i=zi(t,n),a=je({root:e});i.use(`*`,(e,t)=>Ri(e.req.path)?t():a(e,t));let o=je({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!Ri(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}var Vi=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:v(),captureId:e,fetcher:t.fetcher,configSnapshot:t,rawResponse:null,creditsUsed:null,status:`pending`,errorCode:null,errorMessage:null,createdAt:n,updatedAt:n,deletedAt:null}}list(e){return this.storage.all(`captures`).filter(t=>!t.deletedAt&&(e!==`no-successful`||!t.latestSuccessfulJobId)).toSorted((e,t)=>t.createdAt-e.createdAt).map(e=>Hi(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:Hi(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 G(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=Date.now(),i={id:v(),url:e,title:null,userNote:t,latestSuccessfulJobId:null,createdAt:r,updatedAt:r,deletedAt:null},a=this.newJob(i.id,n);return this.storage.put(`captures`,i),this.storage.put(`fetchJobs`,a),{capture:Hi(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 G(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new G(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:Ui(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 G(`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),Hi(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt-e.createdAt).map(e=>Ui(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?Ui(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 Hi(e){let{deletedAt:t,...n}=e;return n}function Ui(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 Q=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function Wi(e){if(e instanceof Q)return e;let t=Gi(e);return t===null?Ji(e)?new Q(`timeout`,`The configured fetcher timed out`):Yi(e)?new Q(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new Q(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new Q(`http_${t}`,Ki(e)??`The configured fetcher returned ${t}`,t)}function Gi(e){if(!$(e))return null;let t=Xi(e.status);return t===null?$(e.response)?Xi(e.response.status):null:t}function Ki(e){if(!$(e))return null;if($(e.response)){let t=qi(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:qi(e.details)}function qi(e){return $(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function Ji(e){if(!(e instanceof Error))return!1;let t=Zi(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function Yi(e){if(e instanceof TypeError)return!0;if(!$(e))return!1;let t=Zi(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!$(e.response)}function Xi(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function Zi(e){let t=e.code;return typeof t==`string`?t:null}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Qi=class extends Fe{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function $i(e,t,n={}){let r=new Qi({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 ea(e,t,n=1,r=$i(t,n)){try{let t=ta(e),n=await r.search(na(t));if(!ya(n))throw new Q(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new Q(`fetcher_error`,va(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new Q(`invalid_response`,`The configured fetcher returned an invalid response`);let i=_a(n);if(i===null)throw new Q(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=ua(e,la(n));return{title:a?ha(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw Wi(e)}}function ta(e){return{query:ra(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 na(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function ra(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=ia(t.pathname),i=ca(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function ia(e){let t=e.split(`/`).map(e=>aa(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||sa(n))continue;let r=oa(n);if(r)return r}return null}function aa(e){try{return decodeURIComponent(e)}catch{return e}}function oa(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function sa(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 ca(e){return Ie(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function la(e){return!ya(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!ya(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:ya(e.metadata)?e.metadata:{}}])}function ua(e,t){let n=fa(e);if(n){let e=t.find(e=>da(e).some(e=>fa(e)===n));if(e)return e}let r=pa(e),i=r===null?[]:t.filter(e=>da(e).some(e=>pa(e)===r));return i.find(e=>ma(e))??(i.length>0?i[0]:null)}function da(e){return[e.url,ga(e,`sourceURL`),ga(e,`url`)].filter(e=>!!e)}function fa(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 pa(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function ma(e){return da(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function ha(e){return e.title?.trim()||ga(e,`ogTitle`)?.trim()||ga(e,`title`)?.trim()||null}function ga(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function _a(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function va(e){return ya(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function ya(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ba(e,t){return ea(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=ft(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=Wi(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=ft(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 G(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Ta(e.url);if(!t)throw new G(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new G(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new G(`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 G(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new G(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new G(`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 G(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new G(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new G(`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 Vi(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=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 Oa=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:v(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function ka(e){let t=new Oa,n=Ea(e,t),r=new ln(e),i=new _n(e),a=new Mn(e),o=new Nn(e,a),s=new si(e),c=new ht(e),l=new _t,u=new Oi,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(Ce(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=Bi(t,e,r.apiOptions);r.start();let o=Ae({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=Le();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:Bn(),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:Re,description:`Manage Foundry settings and instructions or start the Web UI`},default:`help`,subCommands:{help:r,web:Ra,settings:Sr,instructions:ar,agents:$n}}),t}t(Ba());export{};
|
|
11
|
+
`,e);n=n.slice(e)}n+=t.end(),r(n)};return e.endsWith(`.zst`)?await C(c(e,{highWaterMark:li}),je({chunkSize:li}),i):await C(c(e,{highWaterMark:li}),i),{hasMalformedLines:n}}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e){return typeof e==`string`?e:``}function fi(e){let t=Date.parse($(e));return Number.isFinite(t)?t:null}function pi(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function mi(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Q).filter(e=>[`text`,`input_text`,`output_text`].includes($(e.type))).map(e=>$(e.text)).join(`
|
|
12
|
+
`):``}function hi(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function gi(e){let t=await ui(r.join(e,`projects`));if(!t.found)throw new ri(`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 _i(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 _i(e){let t=await ye(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 di(e,e=>{f?p=$(e.sessionId)||p:n||=$(e.sessionId),i=$(e.cwd)||i,a=$(e.gitBranch)||a,m||=e.isSidechain===!0;let t=fi(e.timestamp);t!==null&&(u=Math.min(u,t),d=Math.max(d,t)),e.type===`custom-title`?s=$(e.customTitle)||s:e.type===`last-prompt`&&(c=$(e.lastPrompt)||c);let r=Q(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&r.role===`user`&&(o||=mi(r.content).trim()),e.type!==`assistant`||r.role!==`assistant`)return;let g=$(r.model);g&&g!==`<synthetic>`&&(l=g);let _=Q(r.usage)?r.usage:{},v=[_.input_tokens,_.output_tokens,_.cache_creation_input_tokens,_.cache_read_input_tokens].reduce((e,t)=>e+pi(t),0),te=$(r.id)||$(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:hi(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 vi(){let e=i.env.CODEX_HOME?.trim();return e?r.resolve(e):r.join(y.homedir(),`.codex`)}async function yi(e){let t=await Promise.all([ui(r.join(e,`sessions`)),ui(r.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new ri(`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 bi(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(),xi),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function bi(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},i=``,{hasMalformedLines:a}=await di(e,e=>{let t=fi(e.timestamp);t!==null&&(n.createdAt=Math.min(n.createdAt,t),n.updatedAt=Math.max(n.updatedAt,t));let r=Q(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=$(r.id),n.cwd||=$(r.cwd),n.model??=$(r.model_provider)||null;let e=Q(r.git)?r.git:{};n.gitBranch??=$(e.branch)||null;let t=Q(r.source)?r.source:{},i=Q(r.thread_source)?r.thread_source:{},a=Q(t.subagent)?t.subagent:{},o=Q(i.subagent)?i.subagent:{};n.parentThreadId??=$(r.parent_thread_id)||$(a.parent_thread_id)||$(o.parent_thread_id)||null,n.subagent||=!!r.parent_thread_id||Q(r.source)&&`subagent`in r.source||Q(r.thread_source)&&`subagent`in r.thread_source}else if(e.type===`turn_context`)n.cwd=$(r.cwd)||n.cwd,n.model=$(r.model)||n.model;else if(e.type===`response_item`&&r.type===`message`&&r.role===`user`){let e=mi(r.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(i||=e)}else if(e.type===`token_usage_record`){let e=Q(r.thread_token_usage)?r.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,pi(e.total_tokens))}else if(e.type===`event_msg`&&r.type===`token_count`){let e=Q(r.info)?r.info:{},t=Q(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,pi(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 xi(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:hi(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 Si=class{codexHome;claudeHome;constructor(e=vi(),t=ci()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return Ci(`codex`,await yi(this.codexHome))}async getClaudeSnapshot(){return Ci(`claude`,await gi(this.claudeHome))}};function Ci(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 wi(e){let t=new w;return t.get(`/`,t=>Me(t,async n=>{await Ti(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||Ei(n,e)}),c=setInterval(()=>{r||Di(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 Ti(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function Ei(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Di(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Oi=class extends Error{code=`INVALID_EXPORT_INPUT`};function ki(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Oi(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Ai(e){let t=new w;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Oi(`Request body must be valid JSON`)}let{passphrase:r}=ki(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 Oi?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 ji(e,t){let n=new w;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 L(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new L(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new L(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await me(r.join(ie(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await C(we.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 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{i&&await Nt(i)}}),n}function Mi(e){return e===`/api`||e.startsWith(`/api/`)}function Ni(e,t={}){let n=new w,r=t.providerService??new $r(e),i=t.settingsService??new ut(e),a=t.settingsSkillCopyService??new ft,o=t.sessionService??new Si,s=t.instructionsService??new Dn(e),c=t.agentsService??new On(e,s);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Pe,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,wi(t.eventHub)),n.route(`/api/data-import`,ji(t.dataImportService??new ln(e),()=>{t.eventHub?.publish(Ye,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Ai(t.dataExportService??new en(e))),n.route(`/api/agents`,Or(c)),n.route(`/api/skills`,oi(t.skillsService??new Ln(e))),n.route(`/api/instructions`,jr(s)),n.route(`/api/providers`,Zr(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,ei(i,e=>{t.eventHub?.publish(Ye,e)},a)),n.route(`/api/sessions`,ii(o)),n.notFound(e=>Mi(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),Mi(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Pi(e,t,n){let i=Ni(t,n),a=ke({root:e});i.use(`*`,(e,t)=>Mi(e.req.path)?t():a(e,t));let o=ke({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!Mi(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function Fi(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 Ii=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:b(),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 Li(e){let t=new Ii,n=new en(e),r=new ln(e),i=new Dn(e),a=new On(e,i),o=new $r(e),s=new ut(e),c=new ft,l=new Si,u=new Ln(e),d={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,sessionService:l,skillsService:u},f;return{services:d,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,sessionService:l,skillsService:u,eventHub:t},start(){f??=Fi(e.path,()=>{t.publish(Ye,{fields:[]})})},stop(){f?.(),f=void 0}}}const{dirname:Ri,join:zi,resolve:Bi}=r,Vi=Ri(xe(import.meta.url));function Hi(){let e=[Bi(Vi,`web`),Bi(i.cwd(),`dist/web`)].find(e=>u(zi(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ui({storage:e,webRoot:t=Hi(),onListening:n}){let r=Li(e),a=Pi(t,e,r.apiOptions);r.start();let o=Oe({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 Wi(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 Gi(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 Ki=e({meta:{name:`web`,description:`Start the Foundry local Web UI`},args:{open:{type:`boolean`,description:`Open the Web UI in the default browser`,negativeDescription:`Do not open the browser`,default:!0}},async run({args:e}){try{await Wi(`127.0.0.1`,11111)}catch(e){qi(e);return}Ui({storage:Un(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Gi(t)}})}});function qi(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function Ji(){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, instructions, and skills or start the Web UI`},default:`help`,subCommands:{help:r,web:Ki,settings:Tr,instructions:cr,agents:nr,skills:Dr}}),t}t(Ji());export{};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: foundry
|
|
3
|
-
description: Operate the local Foundry workbench through its installed CLI. Use when a task asks to create, read, edit, delete, list, assign, enable, disable, or reapply Foundry instructions for ChatGPT or Claude Code, read or change Foundry settings, open its configuration folder, export or import encrypted Foundry data, install or inspect the Foundry Skill, or start its Web UI.
|
|
3
|
+
description: Operate the local Foundry workbench through its installed CLI. Use when a task asks to create a skill in the Foundry library, create, read, edit, delete, list, assign, enable, disable, or reapply Foundry instructions for ChatGPT or Claude Code, read or change Foundry settings, open its configuration folder, export or import encrypted Foundry data, install or inspect the Foundry Skill, or start its Web UI.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Foundry
|
|
@@ -13,6 +13,7 @@ JSON.
|
|
|
13
13
|
Use this Skill when the user wants to:
|
|
14
14
|
|
|
15
15
|
- Save, read, edit, delete, or inspect reusable Markdown instructions.
|
|
16
|
+
- Create a skill from its name and description in the Foundry library.
|
|
16
17
|
- Make ChatGPT or Claude Code follow selected instructions.
|
|
17
18
|
- Reorder, enable, disable, or reapply an agent's instruction set.
|
|
18
19
|
- Read or change appearance, language, time zone, or time format.
|
|
@@ -31,6 +32,7 @@ the command details, output shapes, failure modes, and end-to-end examples.
|
|
|
31
32
|
| Need | CLI entry point | Reference |
|
|
32
33
|
| --- | --- | --- |
|
|
33
34
|
| Create, read, edit, delete, or list reusable Markdown instructions | `foundry instructions` | [Instructions](references/instructions.md) |
|
|
35
|
+
| Create skill metadata with an empty Markdown body | `foundry skills create manual` | [Skills](references/skills.md) |
|
|
34
36
|
| Inspect, assign, enable, disable, or reapply instructions for an agent | `foundry agents instructions` | [Agents](references/agents.md) |
|
|
35
37
|
| Inspect supported agents and raw assignment state | `foundry agents list` | [Agents](references/agents.md) |
|
|
36
38
|
| Read or change application preferences | `foundry settings get/set` | [Settings](references/settings.md) |
|
|
@@ -183,6 +185,7 @@ foundry settings set language zh-CN
|
|
|
183
185
|
| --- | --- |
|
|
184
186
|
| `<home>/.foundry/settings.json` | Normalized application settings |
|
|
185
187
|
| `<home>/.foundry/instructions/<id>.md` | One Markdown instruction per file |
|
|
188
|
+
| `<home>/.foundry/skill/<name>/SKILL.md` | One skill directory with YAML metadata and a Markdown body |
|
|
186
189
|
| `<home>/.foundry/agents/<sha256(agent-id)>.json` | Assignment order and enabled state per agent |
|
|
187
190
|
| `~/.codex/AGENTS.md` | ChatGPT instruction file managed by Foundry |
|
|
188
191
|
| `~/.claude/CLAUDE.md` | Claude Code instruction file managed by Foundry |
|
|
@@ -201,8 +204,10 @@ foundry web
|
|
|
201
204
|
```
|
|
202
205
|
|
|
203
206
|
Use `--no-open` to start the same local server without opening a browser. It
|
|
204
|
-
prints the URL and serves the UI on port `11111`. Instructions and
|
|
205
|
-
the implemented Web features.
|
|
207
|
+
prints the URL and serves the UI on port `11111`. Instructions, Skills, and
|
|
208
|
+
Settings are the implemented Web features. Skills supports manual creation and
|
|
209
|
+
read-only details at `#/library/skills`; see [Skills](references/skills.md).
|
|
210
|
+
The Instructions page is at
|
|
206
211
|
`#/library/instructions` and supports creation, direct source editing, and
|
|
207
212
|
agent assignment. Each instruction row exposes Edit and Delete through its
|
|
208
213
|
actions menu or a right-click. Delete removes the instruction from every agent
|
|
@@ -11,11 +11,11 @@ assignment profiles. It is not a snapshot of all Foundry runtime files.
|
|
|
11
11
|
|
|
12
12
|
| Data | Included in backup |
|
|
13
13
|
| --- | --- |
|
|
14
|
-
| Normalized
|
|
14
|
+
| Normalized workspace settings | Yes |
|
|
15
15
|
| Instructions, including Markdown content and timestamps | Yes |
|
|
16
16
|
| Agent assignments, order, and enabled state | Yes |
|
|
17
17
|
| External `~/.codex/AGENTS.md` and `~/.claude/CLAUDE.md` files | No |
|
|
18
|
-
| Provider
|
|
18
|
+
| Provider records | No |
|
|
19
19
|
|
|
20
20
|
## When to use
|
|
21
21
|
|
|
@@ -26,8 +26,8 @@ Use export/import when the user wants to:
|
|
|
26
26
|
- Preserve settings before a risky change.
|
|
27
27
|
- Replace current settings, instructions, and assignments with a snapshot.
|
|
28
28
|
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
External agent files and provider records require a separate, explicitly chosen
|
|
30
|
+
backup process.
|
|
31
31
|
|
|
32
32
|
Import updates Foundry's own agent profiles but never rewrites external agent
|
|
33
33
|
instruction files. If an imported agent is enabled, run
|
|
@@ -85,8 +85,8 @@ Import:
|
|
|
85
85
|
1. Reads and decrypts the archive.
|
|
86
86
|
2. Validates the manifest version, checksum, archive structure, settings,
|
|
87
87
|
instruction records, agent profiles, and instruction references.
|
|
88
|
-
3. Normalizes
|
|
89
|
-
|
|
88
|
+
3. Normalizes workspace preferences with Foundry's regular enum defaults and
|
|
89
|
+
omits unsupported fields.
|
|
90
90
|
4. Replaces settings, instructions, and agent profiles completely.
|
|
91
91
|
5. Returns `{ "status": "imported" }`.
|
|
92
92
|
|
|
@@ -14,9 +14,9 @@ editable preference keys plus a read-only configuration-folder key:
|
|
|
14
14
|
| `time-format` | Date/time display pattern |
|
|
15
15
|
| `config-folder` | Read-only absolute path to Foundry's data folder |
|
|
16
16
|
|
|
17
|
-
The CLI view is not a raw dump of `settings.json`. The file
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
The CLI view is not a raw dump of `settings.json`. The file stores these
|
|
18
|
+
preferences under `workspace`; the CLI presents the four editable keys as a flat
|
|
19
|
+
view and adds the read-only configuration-folder path.
|
|
20
20
|
|
|
21
21
|
Use this reference for preference changes, opening the data folder, and
|
|
22
22
|
installing the Foundry Skill. Use [Encrypted backups](backups.md) for export and
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Skills
|
|
2
|
+
|
|
3
|
+
Use this reference to create a skill in the Foundry library from its metadata.
|
|
4
|
+
This creates a new local skill; installing the bundled Foundry usage manual
|
|
5
|
+
into another agent uses [Settings](settings.md#install-this-skill).
|
|
6
|
+
|
|
7
|
+
## Create manually
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
foundry skills create manual \
|
|
11
|
+
--name hello \
|
|
12
|
+
--description "Use when greeting users."
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Both options are required:
|
|
16
|
+
|
|
17
|
+
- `name`: 1–64 Unicode letters or digits, lowercase where applicable, with
|
|
18
|
+
single hyphens between words. Leading, trailing, and consecutive hyphens are
|
|
19
|
+
invalid. Names are normalized with NFKC before validation and storage, and
|
|
20
|
+
must be unique in the Foundry skill library. These rules follow the
|
|
21
|
+
[Agent Skills reference validator](https://github.com/agentskills/agentskills/blob/main/skills-ref/src/skills_ref/validator.py).
|
|
22
|
+
- `description`: 1–1024 characters describing when an agent should use the
|
|
23
|
+
skill. Leading and trailing whitespace is removed from both fields.
|
|
24
|
+
|
|
25
|
+
Success prints JSON:
|
|
26
|
+
|
|
27
|
+
```json
|
|
28
|
+
{"name":"hello","description":"Use when greeting users.","content":""}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The file is `<home>/.foundry/skill/hello/SKILL.md`:
|
|
32
|
+
|
|
33
|
+
```markdown
|
|
34
|
+
---
|
|
35
|
+
name: hello
|
|
36
|
+
description: Use when greeting users.
|
|
37
|
+
---
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Each skill has its own directory. YAML frontmatter holds the metadata, and the
|
|
41
|
+
Markdown body starts empty. The name matches the directory. Writes use Foundry
|
|
42
|
+
storage transactions and interrupted writes are recovered. POSIX directories
|
|
43
|
+
and files use `0700` and `0600` permissions.
|
|
44
|
+
|
|
45
|
+
## Errors and scope
|
|
46
|
+
|
|
47
|
+
- `INVALID_SKILL_INPUT`: fix the name or description and retry.
|
|
48
|
+
- `SKILL_NAME_CONFLICT`: choose another name. Existing directories, including
|
|
49
|
+
incomplete skill directories, are preserved.
|
|
50
|
+
- Missing required flags produce CLI argument errors.
|
|
51
|
+
|
|
52
|
+
`manual` is currently the only implemented creation source. Local and URL
|
|
53
|
+
import menu entries are UI placeholders. Creation does not assign or install
|
|
54
|
+
the skill into an agent. Skills are currently outside encrypted backup payloads.
|
|
55
|
+
|
|
56
|
+
## Web UI
|
|
57
|
+
|
|
58
|
+
At `#/library/skills`, select **New skill → Create manually**, enter the same
|
|
59
|
+
metadata, and submit. Success opens `#/library/skills/<name>`. The page displays
|
|
60
|
+
the name, description, and `SKILL.md` body; a new skill shows an empty-content
|
|
61
|
+
state. The library list can reopen an existing skill. History, content editing,
|
|
62
|
+
and supporting-file management are not implemented yet.
|