@dhzh/foundry 7.4.0 → 7.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -18
- package/dist/index.mjs +7 -8
- package/dist/skills/foundry/SKILL.md +7 -6
- package/dist/skills/foundry/references/agents.md +8 -1
- package/dist/skills/foundry/references/backups.md +13 -10
- package/dist/skills/foundry/references/settings.md +3 -3
- package/dist/skills/foundry/references/skills.md +198 -8
- package/dist/web/assets/abap-DLDM7-KI.js +1 -0
- package/dist/web/assets/apex-DNDY2TF8.js +1 -0
- package/dist/web/assets/azcli-Y6nb8tq_.js +1 -0
- package/dist/web/assets/bat-BwHxbl9M.js +1 -0
- package/dist/web/assets/bicep-CFznDFnq.js +2 -0
- package/dist/web/assets/cameligo-Bf6VGUru.js +1 -0
- package/dist/web/assets/clojure-Dnu-v4kV.js +1 -0
- package/dist/web/assets/code-editor-D9YqPRu9.js +1123 -0
- package/dist/web/assets/codicon-MIjLT6Vj.ttf +0 -0
- package/dist/web/assets/coffee-Bd8akH9Z.js +1 -0
- package/dist/web/assets/cpp-BbWJElDN.js +1 -0
- package/dist/web/assets/csharp-Co3qMtFm.js +1 -0
- package/dist/web/assets/csp-D-4FJmMZ.js +1 -0
- package/dist/web/assets/css-DdJfP1eB.js +3 -0
- package/dist/web/assets/cypher-cTPe9QuQ.js +1 -0
- package/dist/web/assets/dart-BOtBlQCF.js +1 -0
- package/dist/web/assets/dockerfile-BG73LgW2.js +1 -0
- package/dist/web/assets/ecl-BEgZUVRK.js +1 -0
- package/dist/web/assets/elixir-B99a8Jiy.js +1 -0
- package/dist/web/assets/flow9-BeJ5waoc.js +1 -0
- package/dist/web/assets/freemarker2-Cqc6DC0X.js +3 -0
- package/dist/web/assets/fsharp-PahG7c26.js +1 -0
- package/dist/web/assets/go-acbASCJo.js +1 -0
- package/dist/web/assets/graphql-BxJiqAUM.js +1 -0
- package/dist/web/assets/handlebars-vhUCOYp2.js +1 -0
- package/dist/web/assets/hcl-DtV1sZF8.js +1 -0
- package/dist/web/assets/html-B9OWsMTw.js +1 -0
- package/dist/web/assets/index-BLI6_UFc.css +1 -0
- package/dist/web/assets/index-ZHZEjBKE.js +198 -0
- package/dist/web/assets/ini-CWGZJIwx.js +1 -0
- package/dist/web/assets/java-CXBNlu9o.js +1 -0
- package/dist/web/assets/javascript-VVG9ORob.js +1 -0
- package/dist/web/assets/json.worker-DjMR4gyh.js +77 -0
- package/dist/web/assets/jsonMode-83eKggsx.js +56 -0
- package/dist/web/assets/jsonMode-Dnk_vNU4.css +1 -0
- package/dist/web/assets/julia-cl7-CwDS.js +1 -0
- package/dist/web/assets/kotlin-s7OhZKlX.js +1 -0
- package/dist/web/assets/less-9HpZscsL.js +2 -0
- package/dist/web/assets/lexon-OrD6JF1K.js +1 -0
- package/dist/web/assets/liquid-iK6GMLcM.js +1 -0
- package/dist/web/assets/lua-Cyyb5UIc.js +1 -0
- package/dist/web/assets/m3-B8OfTtLu.js +1 -0
- package/dist/web/assets/mdx-C9wUAJkS.js +1 -0
- package/dist/web/assets/mips-CiqrrVzr.js +1 -0
- package/dist/web/assets/msdax-DmeGPVcC.js +1 -0
- package/dist/web/assets/mysql-C_tMU-Nz.js +1 -0
- package/dist/web/assets/objective-c-BDtDVThU.js +1 -0
- package/dist/web/assets/pascal-vHIfCaH5.js +1 -0
- package/dist/web/assets/pascaligo-DtZ0uQbO.js +1 -0
- package/dist/web/assets/perl-Ub6l9XKa.js +1 -0
- package/dist/web/assets/pgsql-BlNEE0v7.js +1 -0
- package/dist/web/assets/php-BBUBE1dy.js +1 -0
- package/dist/web/assets/pla-DSh2-awV.js +1 -0
- package/dist/web/assets/postiats-CocnycG-.js +1 -0
- package/dist/web/assets/powerquery-tScXyioY.js +1 -0
- package/dist/web/assets/powershell-COWaemsV.js +1 -0
- package/dist/web/assets/protobuf-Brw8urJB.js +2 -0
- package/dist/web/assets/pug-8SOpv6rk.js +1 -0
- package/dist/web/assets/python-C12wwW7S.js +1 -0
- package/dist/web/assets/qsharp-Bw9ernYp.js +1 -0
- package/dist/web/assets/r-j7ic8hl3.js +1 -0
- package/dist/web/assets/razor-BRAlXnRe.js +1 -0
- package/dist/web/assets/redis-Bu5POkcn.js +1 -0
- package/dist/web/assets/redshift-Bs9aos_-.js +1 -0
- package/dist/web/assets/restructuredtext-CqXO7rUv.js +1 -0
- package/dist/web/assets/ruby-zBfavPgS.js +1 -0
- package/dist/web/assets/rust-BzKRNQWT.js +1 -0
- package/dist/web/assets/sb-BBc9UKZt.js +1 -0
- package/dist/web/assets/scala-D9hQfWCl.js +1 -0
- package/dist/web/assets/scheme-BPhDTwHR.js +1 -0
- package/dist/web/assets/scss-CBJaRo0y.js +3 -0
- package/dist/web/assets/shell-DiJ1NA_G.js +1 -0
- package/dist/web/assets/solidity-Db0IVjzk.js +1 -0
- package/dist/web/assets/sophia-CnS9iZB_.js +1 -0
- package/dist/web/assets/sparql-CJmd_6j2.js +1 -0
- package/dist/web/assets/sql-ClhHkBeG.js +1 -0
- package/dist/web/assets/st-CHwy0fLd.js +1 -0
- package/dist/web/assets/swift-CnmFD0ga.js +1 -0
- package/dist/web/assets/systemverilog-Bs9z6M-B.js +1 -0
- package/dist/web/assets/tcl-Dm6ycUr_.js +1 -0
- package/dist/web/assets/twig-Csy3S7wG.js +1 -0
- package/dist/web/assets/typescript-Bx_6s3Vf.js +1 -0
- package/dist/web/assets/typespec-Btyra-wh.js +1 -0
- package/dist/web/assets/vb-Db0cS2oM.js +1 -0
- package/dist/web/assets/wgsl-BTesnYfV.js +298 -0
- package/dist/web/assets/xml-CA6ArVkO.js +1 -0
- package/dist/web/assets/yaml-BfVk-7Da.js +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -3
- package/dist/web/assets/index-BB11hmXJ.css +0 -1
- package/dist/web/assets/index-BmnFtxk4.js +0 -155
- package/dist/web/assets/markdown-editor-BOmYrZEd.js +0 -1120
- /package/dist/web/assets/{markdown-editor-DMeNDIaI.css → code-editor-DMeNDIaI.css} +0 -0
package/README.md
CHANGED
|
@@ -16,13 +16,28 @@ 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
|
-
Skills supports manual creation
|
|
20
|
-
|
|
19
|
+
Skills supports manual creation, metadata editing, and deletion from the list,
|
|
20
|
+
with file navigation and a Monaco editor for Skill files on its detail page. The creation CLI action is
|
|
21
21
|
`foundry skills create manual --name hello --description "Use when greeting users."`.
|
|
22
22
|
Each skill lives at `<home>/.foundry/skill/<name>/SKILL.md`. See the
|
|
23
23
|
[Skills reference](skills/foundry/references/skills.md) for metadata rules and scope.
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
Use `foundry skills edit <skill> --name ... --description ...` to update metadata
|
|
25
|
+
and `foundry skills delete <skill>` to remove the entire source folder. Edits create or refresh symlinks only in assigned agents’ Skill directories;
|
|
26
|
+
renames remove the previous matching links, and deletion explicitly unlinks
|
|
27
|
+
matching entries. Unrelated files, folders, and links are preserved.
|
|
28
|
+
|
|
29
|
+
Use `foundry skills list` for summaries and `foundry skills get <skill>` for
|
|
30
|
+
metadata and the complete nested file tree. Save file additions, edits, and
|
|
31
|
+
deletions with `foundry skills save <skill> --file <json-path|->`; `-` reads
|
|
32
|
+
stdin without an intermediate JSON file and is preferred for agent workflows.
|
|
33
|
+
Saving applies the complete tree, deleting omitted entries and preserving
|
|
34
|
+
metadata. The full `get` output can be edited and submitted directly.
|
|
35
|
+
Use `foundry agents skills list [agent]` to inspect saved assignments,
|
|
36
|
+
`foundry agents skills assign <agent> --skill <name>` to create or repair a
|
|
37
|
+
link, and `foundry agents skills unassign <agent> --skill <name>` to remove it.
|
|
38
|
+
These commands share the Web UI's services, validation, and storage transactions.
|
|
39
|
+
|
|
40
|
+
Provider backend services and APIs are retained.
|
|
26
41
|
Their presence does not imply a corresponding page or CLI command in the current
|
|
27
42
|
product. `app/web/legacy-src` holds remaining reference code; its Settings
|
|
28
43
|
implementation has been removed. Keeping the current scope focused on
|
|
@@ -132,16 +147,16 @@ foundry instructions edit <id> \
|
|
|
132
147
|
and advances `updatedAt`. It changes the instruction record only; reapply any
|
|
133
148
|
enabled agent that uses it to rewrite the managed block.
|
|
134
149
|
|
|
135
|
-
Delete an
|
|
150
|
+
Delete an instruction:
|
|
136
151
|
|
|
137
152
|
```bash
|
|
138
153
|
foundry instructions delete <id>
|
|
139
154
|
```
|
|
140
155
|
|
|
141
|
-
Deletion removes the Markdown file
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
156
|
+
Deletion removes the Markdown file and detaches it from every agent. Enabled
|
|
157
|
+
agent files are updated immediately; removing an agent's final assignment
|
|
158
|
+
disables it and removes its managed block. The command prints the deleted record
|
|
159
|
+
as JSON.
|
|
145
160
|
|
|
146
161
|
Instructions are stored as individual Markdown files at
|
|
147
162
|
`<home>/.foundry/instructions/<id>.md`. Each file has YAML frontmatter for the
|
|
@@ -206,9 +221,9 @@ foundry settings download-skill --target .agents,.claude
|
|
|
206
221
|
Backup passphrases use `FOUNDRY_PASSPHRASE` or `--passphrase`. Export rejects an
|
|
207
222
|
existing destination unless `--force` is supplied. Import normalizes backup data
|
|
208
223
|
and replaces the supported data completely. The backup payload contains
|
|
209
|
-
settings, instructions, and agent assignments. Providers
|
|
210
|
-
|
|
211
|
-
|
|
224
|
+
settings, instructions, and agent assignments. Providers and the external
|
|
225
|
+
`AGENTS.md`/`CLAUDE.md` files are outside this payload; reapply enabled agents
|
|
226
|
+
after import to rewrite their managed blocks. Web import reloads
|
|
212
227
|
the page without the hash route and enters the normal root route. See
|
|
213
228
|
[backup behavior and format](docs/data-export.md).
|
|
214
229
|
|
|
@@ -257,16 +272,14 @@ Runtime data lives in `<home>/.foundry`, outside the repository and `dist`:
|
|
|
257
272
|
|
|
258
273
|
- `settings.json`: normalized application settings
|
|
259
274
|
- `providers.json`: retained provider records
|
|
260
|
-
- `captures/` and `fetch-jobs/`: one JSON file per retained record
|
|
261
275
|
- `instructions/`: one Markdown instruction file per record
|
|
262
|
-
- `agents
|
|
263
|
-
capability state
|
|
276
|
+
- `agents/<agent-id>.json`: one JSON profile per agent, including `instructions`
|
|
277
|
+
and persisted `skills.skillNames` capability state
|
|
264
278
|
|
|
265
279
|
Foundry uses process locking, atomic replacement, and a redo journal for storage
|
|
266
280
|
transactions. Reads load files directly. Startup recovers committed interrupted
|
|
267
281
|
writes; a new installation uses default settings and empty collections. Foundry
|
|
268
|
-
does not import old SQLite databases.
|
|
269
|
-
Codex and Claude Code JSONL transcripts, including `.jsonl.zst` files, read-only.
|
|
282
|
+
does not import old SQLite databases.
|
|
270
283
|
On POSIX, Foundry runtime directories use `0700` and data files use `0600`.
|
|
271
284
|
|
|
272
285
|
`pnpm build` bundles the CLI with tsdown, copies the Skill into `dist/skills`,
|
|
@@ -292,7 +305,6 @@ exposes only `./package.json`. Verify with `pnpm pack --dry-run`.
|
|
|
292
305
|
- [Settings implementation](docs/settings.md): routing, synchronization, and API boundaries
|
|
293
306
|
- [Data export and import](docs/data-export.md): normalization, replacement, and format
|
|
294
307
|
- [Foundry Skill](skills/foundry/SKILL.md): installed CLI usage for agents
|
|
295
|
-
- [Sessions vocabulary](GLOSSARY.md): retained backend domain terms
|
|
296
308
|
- [ADRs](docs/adr/): decisions with current backend and historical UI scope identified
|
|
297
309
|
- [Chatbot research](docs/research/chatbot-api-and-persistence.md): historical proposal
|
|
298
310
|
|
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
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.4.0`,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`],Qe=`data/foundry.json`,$e=`settings.changed`,et=[`agents`,`claude`],tt=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function nt(e){return e.trim().normalize(`NFKC`)}function rt(e){let t=nt(e);return[...t].length<=64&&t===t.toLowerCase()&&tt.test(t)}const w={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function it(e){let t=E(e)?e:{},n=E(t.workspace)?t.workspace:{},r=E(n.appearance)?n.appearance:{},i=E(n[`language-region`])?n[`language-region`]:{},a=E(t.features)?t.features:{},o=E(a.library)?a.library:{},s=E(o.captures)?o.captures:{},c=E(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":dt(r[`color-theme`],qe,w.workspace.appearance[`color-theme`])},"language-region":{language:dt(i.language,Je,w.workspace[`language-region`].language),"time-format":dt(i[`time-format`],Ye,w.workspace[`language-region`][`time-format`]),"time-zone":dt(i[`time-zone`],Xe,w.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:lt(s.fetcher),maxAttempts:pt(s.maxAttempts,10,1),fetchConcurrency:pt(s.fetchConcurrency,5,2),firecrawl:{apiKey:gt(c.apiKey)}}}}}}function at(e){if(!E(e))throw new T(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=ft(e.theme,qe,`theme`)),`language`in e&&(t.language=ft(e.language,Je,`language`)),`timeFormat`in e&&(t.timeFormat=ft(e.timeFormat,Ye,`timeFormat`)),`timezone`in e&&(t.timezone=ft(e.timezone,Xe,`timezone`)),`captures`in e&&(t.captures=ct(e.captures)),t}function ot(e,t){let n=e.features.library.captures,r=t.captures;return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function st(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var T=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function ct(e){if(!E(e))throw new T(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:ft(e.fetcher,Ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=mt(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=mt(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=ht(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function lt(e){return ut(e,Ze)}function ut(e,t){return typeof e==`string`&&t.includes(e)?e:null}function dt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function ft(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new T(`Invalid ${n}`);return e}function pt(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function mt(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new T(`${n} must be an integer from 1 to ${t}`);return e}function ht(e,t){if(typeof e!=`string`)throw new T(`${t} must be a string`);return e.trim()}function gt(e){return typeof e==`string`?e:``}function E(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _t(e){return e.readSettings()}function vt(e){return st(_t(e))}function yt(e,t){return t.transaction(()=>{let n=ot(_t(t),e);return t.setSettings(n),st(n)})}var bt=class{storage;configFolder;openFolder;constructor(e,t=Ge(),n=We){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...vt(this.storage),configFolder:this.configFolder}}update(e){return{...yt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const xt=r.dirname(Ce(import.meta.url)),D=`foundry`;var St=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ae()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??Ct();if(!u(r.join(t,`SKILL.md`)))throw new O(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,D),a=r.join(n,`.${D}-${v()}.tmp`),o=r.join(n,`.${D}-${v()}.backup`);try{return await he(n,{recursive:!0}),await pe(t,a,{recursive:!0,errorOnExist:!0}),await wt(a,i,o),{target:e,destination:i}}catch(e){throw await y(a,{recursive:!0,force:!0}),e instanceof O?e:new O(`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),D)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},O=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function Ct(){let e=[r.resolve(xt,`skills`,D),r.resolve(xt,`..`,`..`,`..`,`skills`,D),r.resolve(i.cwd(),`skills`,D)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new O(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function wt(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 Tt=`manifest.json`,Et=/* @__PURE__ */ new Set([Tt,Qe]);async function Dt(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 Ot(e,t){let n=await kt(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(!Et.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 At(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(Tt)||!i.has(`data/foundry.json`))throw await y(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function kt(e){return new Promise((t,n)=>{we.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function At(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var jt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=b.from(`FOUNDRYX`,`ascii`),A=`aes-256-gcm`,Mt=`scrypt`,j={N:131072,r:8,p:1};async function Nt(e,t,n){let r=ue(16),i=ue(12),a={version:1,cipher:A,kdf:{name:Mt,salt:r.toString(`base64`),...j,keyLength:32},nonce:i.toString(`base64`)},o=b.from(JSON.stringify(a),`utf8`),s=Ft(o.byteLength),u=b.concat([s,o]),d=await It(n,r,j);try{let n=await _e(t,`w`,384);try{await n.write(u)}finally{await n.close()}await x(c(e),Lt(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 jt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function Pt(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 Bt(a,13,0),!o.subarray(0,k.byteLength).equals(k))throw Error(`The export file signature is invalid`);if(o.readUInt8(k.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(k.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 Bt(a,e,13),u=await Bt(a,16,i-16)}finally{await a.close()}let d=zt(JSON.parse(s.toString(`utf8`)));r=await It(n,d.salt,d.header.kdf);let f=b.concat([o,s]);await x(c(e,{start:13+s.byteLength,end:i-16-1}),Rt(r,d.nonce,f,u),l(t,{mode:384})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),e instanceof jt?e:new jt(Ht(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Ht(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 Ft(e){let t=b.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function It(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 Lt(e,t,n){let r=se(A,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 Rt(e,t,n,r){let i=ce(A,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 zt(e){if(!Vt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==A||!Vt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Mt||typeof t.salt!=`string`||t.N!==j.N||t.r!==j.r||t.p!==j.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:A,kdf:{name:Mt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Bt(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 Vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ht(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Ut(e){try{await y(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function Wt(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function M(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function Gt(e,t){Kt(e,`${JSON.stringify(t,null,2)}\n`)}function Kt(e,t){Wt(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),M(r.dirname(e))}finally{g(n,{force:!0})}}const qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var N=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Jt=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Yt(e){if(!Xt(e))throw new N(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new N(`name is required`);let t=e.name.trim();if(!t)throw new N(`name is required`);if(t.length>200)throw new N(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new N(`content is required`);if(e.content.length>1e6)throw new N(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Zt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Qt(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=dn(t,r.id),a=rn(r);return t.transaction(()=>{Kt(i,a)}),r}function $t(e){let t=un(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(fn(e))return[];throw e}return n.map(e=>on(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)}function en(e,t){if(!qt.test(e))return;let n=`${e}.md`;try{return on(r.join(un(t),n),n)}catch(e){if(fn(e))return;throw e}}function tn(e,t,n){let r=en(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.transaction(()=>{Kt(dn(n,i.id),rn(i))}),i}function nn(e,t){if(!qt.test(e))return`missing`;let n=un(t),i=r.join(n,`${e}.md`);return t.transaction(()=>{try{return g(i),M(n),`removed`}catch(e){if(fn(e))return`missing`;throw e}})}function rn(e){return`---\n${ke({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function an(e,t){let n=Zt.exec(e);if(!n)throw P(t);let r=sn(n[1]);if(`${r.id}.md`!==t)throw P(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,lstatSync as f,mkdirSync as p,openSync as ee,readFileSync as m,readdirSync as h,readlinkSync as te,realpathSync as ne,renameSync as re,rmSync as g,rmdirSync as ie,statSync as _,symlinkSync as ae,unlinkSync as oe,watch as se,writeFileSync as ce}from"node:fs";import le,{homedir as ue,tmpdir as de}from"node:os";import{createCipheriv as fe,createDecipheriv as pe,createHash as v,randomBytes as me,randomUUID as y,scrypt as he}from"node:crypto";import{chmod as ge,cp as _e,link as ve,mkdir as ye,mkdtemp as be,open as xe,readFile as Se,rename as Ce,rm as b,stat as we,writeFile as Te}from"node:fs/promises";import{fileURLToPath as Ee}from"node:url";import{Buffer as x}from"node:buffer";import{pipeline as S}from"node:stream/promises";import De from"yauzl";import Oe from"yazl";import{Readable as ke,Transform as Ae}from"node:stream";import{parse as je,parseDocument as Me,stringify as Ne}from"yaml";import{serve as Pe}from"@hono/node-server";import{serveStatic as Fe}from"@hono/node-server/serve-static";import{Hono as C}from"hono";import{streamSSE as Ie}from"hono/streaming";import{createServer as Le}from"node:net";var Re=`7.5.0`,w=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 w(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new w(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new w(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function Be(e){if(!Ve(e)||typeof e.enabled!=`boolean`)throw new w(`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 T=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 He(e){return`~/${e.join(`/`)}`}function Ue(e,t){return r.join(e,...t)}function We(e){let{instructions:t,skills:n}=e.capabilities;return{instructions:{file:He(t.file)},...n&&{skills:{directory:He(n.directory)}}}}function Ge(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 Ke(){return r.join(le.homedir(),`.foundry`)}function qe(){let e=Ke();return p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const Je=[`system`,`light`,`dark`],Ye=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Xe=[`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`],Ze=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],E=`data/foundry.json`,Qe=`settings.changed`,$e=[`agents`,`claude`],et=/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u;function tt(e){return e.trim().normalize(`NFKC`)}function nt(e){let t=tt(e);return[...t].length<=64&&t===t.toLowerCase()&&et.test(t)}function rt(e){return e.length>0&&e.length<=1024&&e.split(`/`).every(e=>e.length>0&&e.length<=255&&e!==`.`&&e!==`..`&&!/[\\<>:"|?*]/u.test(e)&&!/\p{Cc}/u.test(e)&&!/[. ]$/u.test(e)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(e))}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 it(e){let t=dt(e)?e:{},n=dt(t.workspace)?t.workspace:{},r=dt(n.appearance)?n.appearance:{},i=dt(n[`language-region`])?n[`language-region`]:{};return{workspace:{appearance:{"color-theme":lt(r[`color-theme`],Je,D.workspace.appearance[`color-theme`])},"language-region":{language:lt(i.language,Ye,D.workspace[`language-region`].language),"time-format":lt(i[`time-format`],Xe,D.workspace[`language-region`][`time-format`]),"time-zone":lt(i[`time-zone`],Ze,D.workspace[`language-region`][`time-zone`])}}}}function at(e){if(!dt(e))throw new ct(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=ut(e.theme,Je,`theme`)),`language`in e&&(t.language=ut(e.language,Ye,`language`)),`timeFormat`in e&&(t.timeFormat=ut(e.timeFormat,Xe,`timeFormat`)),`timezone`in e&&(t.timezone=ut(e.timezone,Ze,`timezone`)),t}function ot(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 st(e){return{workspace:e.workspace}}var ct=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function lt(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function ut(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new ct(`Invalid ${n}`);return e}function dt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ft(e){return e.readSettings()}function pt(e){return st(ft(e))}function mt(e,t){return t.transaction(()=>{let n=ot(ft(t),e);return t.setSettings(n),st(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=Ke(),n=Ge){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(Ee(import.meta.url)),O=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ue()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??yt();if(!u(r.join(t,`SKILL.md`)))throw new vt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,O),a=r.join(n,`.${O}-${y()}.tmp`),o=r.join(n,`.${O}-${y()}.backup`);try{return await ye(n,{recursive:!0}),await _e(t,a,{recursive:!0,errorOnExist:!0}),await bt(a,i,o),{target:e,destination:i}}catch(e){throw await b(a,{recursive:!0,force:!0}),e instanceof vt?e:new vt(`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),O)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},vt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function yt(){let e=[r.resolve(gt,`skills`,O),r.resolve(gt,`..`,`..`,`..`,`skills`,O),r.resolve(i.cwd(),`skills`,O)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new vt(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function bt(e,t,n){let r=u(t);r&&await Ce(t,n);try{await Ce(e,t),r&&await b(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await Ce(n,t),e}}const xt=`manifest.json`,St=/* @__PURE__ */ new Set([xt,E]);async function Ct(e,t){let n=new Oe.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await S(n.outputStream,l(t,{mode:384}))}async function wt(e,t){let n=await Tt(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(!St.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 ye(r.dirname(a),{recursive:!0,mode:448}),await S(await Et(n,e),l(a,{mode:384})),i.set(e.fileName,a),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await b(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(xt)||!i.has(`data/foundry.json`))throw await b(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function Tt(e){return new Promise((t,n)=>{De.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Et(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Dt=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const k=x.from(`FOUNDRYX`,`ascii`),A=`aes-256-gcm`,Ot=`scrypt`,j={N:131072,r:8,p:1};async function kt(e,t,n){let r=me(16),i=me(12),a={version:1,cipher:A,kdf:{name:Ot,salt:r.toString(`base64`),...j,keyLength:32},nonce:i.toString(`base64`)},o=x.from(JSON.stringify(a),`utf8`),s=jt(o.byteLength),u=x.concat([s,o]),d=await Mt(n,r,j);try{let n=await xe(t,`w`,384);try{await n.write(u)}finally{await n.close()}await S(c(e),Nt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await ge(t,384)}catch(e){throw await b(t,{force:!0}),new Dt(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function At(e,t,n){let r;try{let i=(await we(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await xe(e,`r`),o,s,u;try{if(o=await It(a,13,0),!o.subarray(0,k.byteLength).equals(k))throw Error(`The export file signature is invalid`);if(o.readUInt8(k.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(k.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await It(a,e,13),u=await It(a,16,i-16)}finally{await a.close()}let d=Ft(JSON.parse(s.toString(`utf8`)));r=await Mt(n,d.salt,d.header.kdf);let f=x.concat([o,s]);await S(c(e,{start:13+s.byteLength,end:i-16-1}),Pt(r,d.nonce,f,u),l(t,{mode:384})),await ge(t,384)}catch(e){throw await b(t,{force:!0}),e instanceof Dt?e:new Dt(Rt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Rt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function jt(e){let t=x.alloc(13);return k.copy(t,0),t.writeUInt8(1,k.byteLength),t.writeUInt32BE(e,k.byteLength+1),t}function Mt(e,t,n){return new Promise((r,i)=>{he(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Nt(e,t,n){let r=fe(A,e,t,{authTagLength:16});return r.setAAD(n),new Ae({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,x.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Pt(e,t,n,r){let i=pe(A,e,t,{authTagLength:16});return i.setAAD(n),new Ae({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Ft(e){if(!Lt(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==A||!Lt(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Ot||typeof t.salt!=`string`||t.N!==j.N||t.r!==j.r||t.p!==j.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=x.from(t.salt,`base64`),r=x.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:A,kdf:{name:Ot,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function It(e,t,n){let r=x.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function Lt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function zt(e){try{await b(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}const M=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var N=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Bt=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Vt(e){if(!Ht(e))throw new N(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new N(`name is required`);let t=e.name.trim();if(!t)throw new N(`name is required`);if(t.length>200)throw new N(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new N(`content is required`);if(e.content.length>1e6)throw new N(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ut=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Wt(e,t){let n=Date.now(),r={id:y(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=nn(t,r.id),a=Yt(r);return t.transaction(()=>{t.putTextFile(i,a)}),r}function Gt(e){return e.transaction(()=>{let t=tn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(rn(e))return[];throw e}return n.map(e=>Zt(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)})}function Kt(e,t){return t.transaction(()=>{if(!M.test(e))return;let n=`${e}.md`;try{return Zt(r.join(tn(t),n),n)}catch(e){if(rn(e))return;throw e}})}function qt(e,t,n){return n.transaction(()=>{let r=Kt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.putTextFile(nn(n,i.id),Yt(i)),i})}function Jt(e,t){if(!M.test(e))return`missing`;let n=tn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>u(i)?(t.removeTextFile(i),`removed`):`missing`)}function Yt(e){return`---\n${Ne({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function Xt(e,t){let n=Ut.exec(e);if(!n)throw P(t);let r=Qt(n[1]);if(`${r.id}.md`!==t)throw P(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 Zt(e,t){return Xt(m(e,`utf8`),t)}function Qt(e){let t;try{t=je(e)}catch{throw P(`frontmatter`)}if(!an(t))throw P(`frontmatter`);let n=$t(t.id),r=$t(t.name);if(!r||r.length>200||!M.test(n))throw P(`frontmatter`);return{id:n,name:r,createdAt:en(t.createdAt),updatedAt:en(t.updatedAt)}}function $t(e){return typeof e==`string`?e:``}function en(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw P(`frontmatter`);return e}function tn(e){return r.join(e.path,`instructions`)}function nn(e,t){if(!M.test(t))throw Error(`Invalid instruction ID`);return r.join(tn(e),`${t}.md`)}function P(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function rn(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function an(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function on(e){return e.transaction(()=>{let t=new Set(T.list().map(({id:e})=>e));return{settings:e.readSettings(),instructions:Gt(e),agents:e.all(`agents`).filter(({id:e})=>t.has(e)).map(({id:e,instructions:t})=>({id:e,instructions:t})).toSorted((e,t)=>e.id.localeCompare(t.id))}})}var sn=class{storage;constructor(e){this.storage=e}async createExport(e){let t=on(this.storage),n=await be(r.join(de(),`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:Re,createdAt:i,data:{path:E,bytes:x.byteLength(a,`utf8`),sha256:v(`sha256`).update(a).digest(`hex`)}};return await Te(o,a,{mode:384}),await Te(s,JSON.stringify(u,null,2),{mode:384}),await Ct([{entryPath:`manifest.json`,filePath:s},{entryPath:E,filePath:o}],c),await kt(c,l,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await Se(l)}}finally{await zt(n)}}},F=class extends Error{code;constructor(e,t){super(t),this.code=e}};function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cn(e){if(!I(e)||e.format!==`foundry.data`||e.archiveVersion!==2||!I(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 F(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:E,bytes:e.data.bytes,sha256:e.data.sha256}}}function ln(e){if(!I(e)||!I(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw L(`Backup data must contain settings, instructions, and agents`);let t=un(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:it(e.settings),instructions:t,agents:dn(e.agents,n)}}function un(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!I(e))throw L(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!M.test(r)||t.has(r))throw L(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw L(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw L(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:fn(e.createdAt,n),updatedAt:fn(e.updatedAt,n)};return t.add(r),a})}function dn(e,t){let n=new Set(T.list().map(({id:e})=>e)),r=/* @__PURE__ */ new Set;return e.map((e,i)=>{if(!I(e)||!I(e.instructions))throw L(`Invalid agent at index ${i}`);let a=e.id;if(typeof a!=`string`||!n.has(a)||r.has(a))throw L(`Invalid agent at index ${i}`);let o=e.instructions,s=o.instructionIds;if(!Array.isArray(s))throw L(`Invalid instruction assignment for agent ${a}`);let c=s.map(e=>{if(typeof e!=`string`)throw L(`Invalid instruction assignment for agent ${a}`);return e});if(new Set(c).size!==c.length||c.some(e=>!t.has(e)))throw L(`Invalid instruction assignment for agent ${a}`);if(typeof o.enabled!=`boolean`)throw L(`Invalid enabled state for agent ${a}`);if(o.enabled&&c.length===0)throw L(`Enabled agent ${a} has no instructions`);let l={id:a,instructions:{instructionIds:c,enabled:o.enabled,createdAt:fn(o.createdAt,i),updatedAt:fn(o.updatedAt,i)}};return r.add(a),l})}function fn(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw L(`Invalid timestamp at index ${t}`);return e}function L(e){return new F(`INVALID_BACKUP`,e)}function R(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}function pn(e){return e.all(`agents`)}function mn(e,t){return e.get(`agents`,t)}function hn(e,t){return e.put(`agents`,t),t}function gn(e,t){e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of Gt(e))n.has(t.id)||e.removeTextFile(_n(t.id));for(let n of t.instructions)e.putTextFile(_n(n.id),Yt(n));let r=new Set(t.agents.map(({id:e})=>e)),i=new Map(e.all(`agents`).map(e=>[e.id,e]));for(let t of i.values())r.has(t.id)||(t.skills?e.put(`agents`,{...R(t.id),skills:t.skills}):e.remove(`agents`,t.id));for(let n of t.agents){let t=i.get(n.id)?.skills;e.put(`agents`,{...n,...t&&{skills:t}})}e.setSettings(t.settings)})}function _n(e){return r.join(`instructions`,`${e}.md`)}var vn=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await be(r.join(de(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await At(e,i,t);let a=await wt(i,r.join(n,`extracted`)),o=cn(JSON.parse(await Se(a[`manifest.json`],`utf8`))),s=await Se(a[E]);if(s.byteLength!==o.data.bytes||v(`sha256`).update(s).digest(`hex`)!==o.data.sha256)throw new F(`INVALID_BACKUP`,`Backup checksum does not match`);let c=ln(JSON.parse(s.toString(`utf8`)));try{gn(this.storage,c)}catch{throw new F(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof F?e:e instanceof Dt?e.code===`INVALID_PASSPHRASE`?new F(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new F(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new F(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await zt(n)}}};function yn(e,t=T){return t.list().map(t=>({id:t.id,name:t.name,icon:t.icon.name,instructionFile:He(t.capabilities.instructions.file),filePath:Ue(e,t.capabilities.instructions.file),capabilities:We(t)}))}function bn(e){p(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function z(e){if(i.platform===`win32`)return;let t=ee(e,`r`);try{d(t)}finally{s(t)}}function xn(e,t){Sn(e,`${JSON.stringify(t,null,2)}\n`)}function Sn(e,t){bn(r.dirname(e));let n=`${e}.${y()}.tmp`;try{let i=ee(n,`wx`,384);try{ce(i,t),d(i)}finally{s(i)}re(n,e),z(r.dirname(e))}finally{g(n,{force:!0})}}const Cn=`<!-- foundry:instructions:start -->`,wn=`<!-- foundry:instructions:end -->`;function Tn(e,t){let n=En(e),r=On(t);return`${n}${Dn(n)}${r}\n`}function En(e){let t=``,n=0;for(let r of kn(e)){let e=An(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function Dn(e){return!e||e.endsWith(`
|
|
5
5
|
`)?``:`
|
|
6
|
-
`}function
|
|
6
|
+
`}function On(e){let t=e.map(e=>e.trimEnd()).filter(Boolean).join(`
|
|
7
7
|
|
|
8
|
-
`);return t?`${wn}\n\n${t}\n\n${Tn}`:`${wn}\n${Tn}`}function An(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function jn(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 Mn(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),M(n)}finally{g(c,{force:!0})}}function Nn(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?Dn(i):En(i,t);Mn(e.filePath,a)}function Pn(e){return e.all(`agents`)}function Fn(e,t){return e.get(`agents`,t)}function In(e,t){return e.put(`agents`,t),t}function Ln(e,t,n){let r=Pn(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($t(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&&Nn(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),In(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Rn=class{storage;homeDirectory;constructor(e,t=ie.homedir()){this.storage=e,this.homeDirectory=t}list(){return $t(this.storage)}get(e){let t=en(e,this.storage);if(!t)throw new Jt(e);return t}create(e){return Qt(e,this.storage)}update(e,t){let n=tn(e,t,this.storage);if(!n)throw new Jt(e);return n}delete(e){return this.storage.transaction(()=>{let t=en(e,this.storage);if(!t||(Ln(this.storage,e,this.homeDirectory),nn(e,this.storage)===`missing`))throw new Jt(e);return t})}},zn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Rn(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(Pn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>Bn(t,(e.get(t.id)??Vn(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e),r=this.readAssignedInstructions(t);return this.storage.transaction(()=>{let i=Fn(this.storage,e)??Vn(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&Nn(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=In(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return Bn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=Fn(this.storage,e)??Vn(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);Nn(n,e.map(({content:e})=>e),!1)}else Nn(n,[],!0);let a=Date.now();return Bn(n,In(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=Fn(this.storage,e)??Vn(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);Nn(t,i.map(({content:e})=>e),!1);let a=Date.now();return Bn(t,In(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 Bn(e,t){return{id:e.id,name:e.name,icon:e.icon,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}function Vn(e){let t=Date.now();return{id:e,instructions:{instructionIds:[],enabled:!1,createdAt:t,updatedAt:t}}}var R=class extends Error{code=`INVALID_SKILL_INPUT`},Hn=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},Un=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function Wn(e){return e===e.trim()&&rt(e)}function Gn(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new R(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new R(`name is required`);let t=nt(e.name);if(!Wn(t))throw new R(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new R(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new R(`description must be 1–1024 characters`);return{name:t,description:n}}const Kn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var qn=class{storage;constructor(e){this.storage=e}directory(e){if(!Wn(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 Un(e.name);return this.storage.putTextFile(r.join(t,`SKILL.md`),`---\n${ke(e).trimEnd()}\n---\n`),{...e,content:``}})}get(e){if(Wn(e))return this.storage.transaction(()=>{try{let t=m(r.join(this.directory(e),`SKILL.md`),`utf8`),n=Kn.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=Gn(Oe(n[1]));if(i.name!==nt(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()&&Wn(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]:[]})})}},Jn=class{repository;constructor(e){this.repository=new qn(e)}create(e){return this.repository.create(Gn(e))}get(e){let t=this.repository.get(e);if(!t)throw new Hn(e);return t}list(){return this.repository.list()}};const Yn=[`agents`,`providers`,`captures`,`fetchJobs`];function Xn(e){if(/^instructions[/\\][^/\\]+\.md$/u.test(e))return!0;let t=/^skill[/\\]([^/\\]+)[/\\]SKILL\.md$/u.exec(e);return!!(t&&t[1]===t[1].trim()&&rt(t[1]))}function Zn(e){try{let t=JSON.parse(m(r.join(e,`owner.json`),`utf8`));if(typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0)throw Error(`Invalid lock owner`);try{return i.kill(t.pid,0),!1}catch(e){return e.code===`ESRCH`}}catch{return Date.now()-_(e).mtimeMs>3e4}}var Qn=class{path;changes=null;textChanges=null;closed=!1;lockDepth=0;formatVersion=1;constructor(e){this.path=e,Wt(e);for(let e of Yn)e!==`providers`&&Wt(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`))}textFilename(e){let t=r.relative(this.path,r.resolve(this.path,e));if(t.startsWith(`..`)||r.isAbsolute(t)||!Xn(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{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(!Zn(e))return;let n=r.join(e,`recovering`);try{f(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);Zn(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||!Zn(e)){g(n,{recursive:!0,force:!0});return}g(e,{recursive:!0,force:!0})}catch{}}recover(){let e=r.join(this.path,`.transaction.json`);if(!u(e))return;let t=JSON.parse(m(e,`utf8`));this.applyJournal(t)}initializeProviders(){let e=r.join(this.path,`providers.json`),t=this.collectionPath(`providers`);if(!u(e)){let e=u(t)?h(t).filter(e=>e.endsWith(`.json`)):[],n={changes:[{file:`providers.json`,value:e.map(e=>this.readRecord(`providers`,r.join(`providers`,e)))},...e.map(e=>({file:r.join(`providers`,e),value:null}))]};Gt(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(te(t),M(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)$/u.test(n)&&!Xn(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(t.value===null)g(e,{force:!0}),M(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);Kt(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else Gt(e,t.value)}g(r.join(this.path,`.transaction.json`),{force:!0}),M(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 it(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?it(JSON.parse(m(e,`utf8`))):structuredClone(w)})}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`,it(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};Gt(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 $n(e=Ge()){let t=new Qn(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 er(){return Ke(),$n()}async function z(e){let t;try{let n=er(),r=new Rn(n);t={storage:n,agentsService:new zn(n,r),settingsService:new bt(n),settingsSkillCopyService:new St,dataExportService:new hn(n),dataImportService:new Cn(n),instructionsService:r,skillsService:new Jn(n)},nr(await e(t))}catch(e){let t=rr(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function tr(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new B(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function nr(e){console.log(JSON.stringify(e,null,2))}function rr(e){return e instanceof Error?{code:ir(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function ir(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const ar=He.join(`, `),V={type:`positional`,description:`Agent ID: ${ar}`,required:!0},or=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return z(({agentsService:e})=>e.list())}}),sr=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...V,description:`Optional agent ID: ${ar}`,required:!1}},run({args:e}){return z(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new B(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${ar}`);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}))}))})}}),cr=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:V,instructions:{type:`string`,description:`Comma-separated instruction IDs in block order; pass an empty string to clear`,valueHint:`id1,id2`,required:!0}},run({args:e}){return z(({agentsService:t})=>{let n=ze({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),lr=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),ur=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),dr=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.reapply(e.agent))}}),fr=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:V},run({args:e}){return z(({agentsService:t})=>t.openInstructionFile(e.agent))}}),pr=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions for supported agents`},subCommands:{list:or,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:sr,assign:cr,enable:lr,disable:ur,reapply:dr,open:fr}})}}),mr=e({meta:{name:`new`,description:`Create an instruction from a name and Markdown content`},args:{name:{type:`string`,description:`Instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.create(Yt({name:e.name,content:e.content})))}}),hr=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return z(({instructionsService:e})=>e.list())}}),gr=e({meta:{name:`get`,description:`Read one instruction by ID as JSON`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.get(e.id))}}),_r=e({meta:{name:`edit`,description:`Replace an instruction name and Markdown content`},args:{id:{type:`positional`,description:`Instruction ID from the list command`,required:!0},name:{type:`string`,description:`New instruction name`,valueHint:`text`,required:!0},content:{type:`string`,description:`New Markdown content; quote values containing spaces or newlines`,valueHint:`markdown`,required:!0}},run({args:e}){return z(({instructionsService:t})=>t.update(e.id,Yt({name:e.name,content:e.content})))}}),vr=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 z(({instructionsService:t})=>t.delete(e.id))}}),yr=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:mr,list:hr,get:gr,edit:_r,delete:vr}});function br(e){if(!Sr(e)||!Array.isArray(e.targets))throw new xr(`targets must be an array`);if(e.targets.length===0)throw new xr(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!et.includes(e))throw new xr(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var xr=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function Sr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Cr=e({meta:{name:`export`,description:`Write an encrypted Foundry backup`},args:{passphrase:{type:`string`,description:`Encryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`},output:{type:`string`,description:`Destination .foundry-backup path`,valueHint:`path`,alias:[`o`]},force:{type:`boolean`,description:`Overwrite an existing destination file`,default:!1}},run({args:e}){return z(async({dataExportService:t})=>{let n=await t.createExport(tr(e.passphrase)),r=Tr(e.output);return await Er(n.contents,r,e.force),{filePath:r}})}}),wr=e({meta:{name:`import`,description:`Replace local Foundry data from an encrypted backup`},args:{file:{type:`positional`,description:`Path to a .foundry-backup file`,required:!0},passphrase:{type:`string`,description:`Decryption passphrase; defaults to FOUNDRY_PASSPHRASE`,valueHint:`text`}},run({args:e}){return z(async({dataImportService:t})=>(await t.importData(r.resolve(e.file),tr(e.passphrase)),{status:`imported`}))}});function Tr(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 Er(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 Dr(t);try{await me(a,t)}catch(e){throw Or(e)?Dr(t):e}}finally{await y(a,{force:!0})}}function Dr(e){return new B(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Or(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const H={"color-theme":{field:`theme`,values:qe},language:{field:`language`,values:Je},"time-zone":{field:`timezone`,values:Xe},"time-format":{field:`timeFormat`,values:Ye}},kr=[...Object.keys(H),`config-folder`],Ar=Object.entries(H).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
9
|
-
`);function jr(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const Mr=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${kr.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return z(({settingsService:t})=>{let n=jr(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${kr.join(`, `)}`);return n[e.key]})}}),Nr=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(H).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${Ar}`,required:!0}},run({args:e}){return z(({settingsService:t})=>{if(e.key===`config-folder`)throw new B(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(H,e.key))throw new B(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(H).join(`, `)}`);let n=H[e.key];if(!n.values.includes(e.value))throw new B(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=jr(t.update(at({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Pr=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return z(({settingsService:e})=>e.openConfigFolder())}}),Fr=e({meta:{name:`download-skill`,description:`Copy the bundled Foundry skill into user-level skill targets`},args:{target:{type:`string`,description:`Comma-separated targets: .agents, .claude`,valueHint:`.agents,.claude`,required:!0}},run({args:e}){return z(({settingsSkillCopyService:t})=>{let n=br({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Ir=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:Mr,set:Nr,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Pr}}),export:Cr,import:wr,"download-skill":Fr}}),Lr=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 z(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),Rr=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:Lr}})}});function zr(e){let t=new S;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=ze(await Br(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Vr(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=Be(await Br(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Vr(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Vr(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Vr(t,e)}}),t}async function Br(e){try{return await e.req.json()}catch{throw new C(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Vr(e,t){if(t instanceof C)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Hr(e){if(!Kr(e)||typeof e.url!=`string`)throw new Gr(`A URL is required`);return{url:e.url,userNote:typeof e.userNote==`string`?e.userNote:void 0}}function Ur(e){return e===`no-successful`?`no-successful`:`all`}function Wr(e){if(!Kr(e)||typeof e.userNote!=`string`)throw new Gr(`userNote must be a string`);return e.userNote}var Gr=class extends Error{code=`INVALID_CAPTURE_INPUT`;constructor(e){super(e),this.name=`CaptureInputError`}};function Kr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var U=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CaptureError`}};function qr(e,t=()=>{}){let n=new S;return n.get(`/`,t=>{let n=Ur(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=Hr(await Jr(n)),i=e.create(r);return t({captureId:i.id,action:`created`}),n.json(i,201)}catch(e){return W(n,e)}}),n.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return W(t,e)}}),n.post(`/:id/recapture`,n=>{try{let r=n.req.param(`id`),i=e.recapture(r);return t({captureId:r,action:`recaptured`}),n.json(i,202)}catch(e){return W(n,e)}}),n.delete(`/:id`,n=>{try{let r=n.req.param(`id`);return e.delete(r),t({captureId:r,action:`deleted`}),n.body(null,204)}catch(e){return W(n,e)}}),n.patch(`/:id/note`,async n=>{try{let r=Wr(await Jr(n)),i=n.req.param(`id`),a=e.updateNote(i,r);return t({captureId:i,action:`updated`}),n.json(a)}catch(e){return W(n,e)}}),n.get(`/:id/jobs`,t=>{try{return t.json(e.listJobs(t.req.param(`id`)))}catch(e){return W(t,e)}}),n}async function Jr(e){try{return await e.req.json()}catch{throw new Gr(`Request body must be valid JSON`)}}function W(e,t){if(t instanceof Gr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof U)return e.json({error:{code:t.code,message:t.message}},Yr(t.code));throw t}function Yr(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 Xr(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 Qr(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(Yt(await Zr(t)));return t.json(n,201)}catch(e){return Qr(t,e)}}),t.put(`/:id`,async t=>{try{let n=Yt(await Zr(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Qr(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Qr(t,e)}}),t}async function Zr(e){try{return await e.req.json()}catch{throw new N(`Request body must be valid JSON`)}}function Qr(e,t){if(t instanceof N)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Jt)return e.json({error:{code:t.code,message:t.message}},404);throw t}const $r=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],ei=[`active`,`disabled`,`deleted`];var G=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}},ti=class extends Error{code=`PROVIDER_IN_USE`;constructor(){super(`Provider is currently in use`),this.name=`ProviderInUseError`}};function ni(e){if(!li(e))throw new G(`Provider input must be an object`);let t=K(e.name,`name`),n=si(e.protocol),r=ci(e.baseURL),i=e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0}),a=oi(e.customModels);return{...e.avatar!==void 0&&{avatar:ri(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function ri(e){if(e===null)return null;if(typeof e==`string`&&e.length<=2796236){let t=/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,/u.exec(e);if(t){let n=e.slice(t[0].length),r=n.endsWith(`==`)?2:+!!n.endsWith(`=`);if(n.length>0&&n.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(n)&&n.length/4*3-r<=2097152)return e}}throw new G(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function ii(e){if(!li(e))throw new G(`Provider connection must be an object`);return{protocol:si(e.protocol),baseURL:ci(e.baseURL),apiKey:e.apiKey===void 0?``:K(e.apiKey,`apiKey`,{allowEmpty:!0})}}function ai(e){if(typeof e!=`string`||!ei.includes(e))throw new G(`Invalid provider status`);return e}function oi(e){if(e===void 0)return[];if(!Array.isArray(e))throw new G(`customModels must be an array`);return e.map(e=>{if(!li(e))throw new G(`Each custom model must be an object`);return{id:K(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:K(e.displayName,`customModels.displayName`)}})}function si(e){if(typeof e!=`string`||!$r.includes(e))throw new G(`Invalid provider protocol`);return e}function ci(e){let t=K(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new G(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function K(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new G(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new G(`${t} is required`);return r}function li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var q=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function ui(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(di(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new q(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new q(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new q(`Provider returned invalid JSON`)}return fi(i)}function di(e){return new URL(`models${e.endsWith(`/`)?``:`/`}`,e).href}function fi(e){if(!mi(e)||!Array.isArray(e.data))throw new q(`Provider response does not contain a model list`);return e.data.map(e=>{if(!mi(e)||typeof e.id!=`string`||e.id.length===0)throw new q(`Provider returned an invalid model entry`);let t=pi(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function pi(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function mi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var hi=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},gi=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=>({..._i(t),isInUse:e.has(t.id)}))}get(e){let t=this.storage.get(`providers`,e);return t?_i(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 hi;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),_i(i)})}setStatus(e,t,n=/* @__PURE__ */ new Set){return this.storage.transaction(()=>{if(n.has(e)&&(t===`disabled`||t===`deleted`))throw new ti;let r=this.storage.get(`providers`,e);if(!r)throw new hi;let i=Date.now(),a={...r,status:t,deletedAt:t===`deleted`?i:null,updatedAt:i};return this.storage.put(`providers`,a),_i(a)})}};function _i(e){return{...e,avatar:e.avatar??null,status:e.status}}function vi(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 J(t,e)}}),n.post(`/models`,async t=>{try{let n=ii(await yi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return J(t,e)}}),n.post(`/`,async n=>{try{let r=ni(await yi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return J(n,e)}}),n.put(`/:id`,async n=>{try{let r=ni(await yi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return J(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await yi(n),i=ai(typeof r==`object`&&r&&`status`in r?r.status:void 0),a=e.setStatus(n.req.param(`id`),i);return t(),n.json(a)}catch(e){return J(n,e)}}),n}async function yi(e){try{return await e.req.json()}catch{throw new G(`Request body must be valid JSON`)}}function J(e,t){if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof hi)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof ti)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof q)return e.json({error:{code:t.code,message:t.message}},502);throw t}function bi(e){let t=_t(e),n=/* @__PURE__ */ new Set;for(let e of Object.values(t.features))xi(e)&&typeof e.provider==`string`&&e.provider.trim().length>0&&n.add(e.provider);return n}function xi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Si=class{storage;repository;constructor(e){this.storage=e,this.repository=new gi(e)}list(){return this.repository.list(bi(this.storage))}get(e){return this.repository.get(e)}fetchModels(e){let t=this.repository.getConnection(e);if(!t)throw new hi;return ui(t)}fetchModelsForConnection(e){return ui(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.storage.transaction(()=>this.repository.setStatus(e,t,bi(this.storage)))}};function Ci(e,t=()=>{},n=new St){let r=new S;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=at(await wi(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Ti(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=br(await wi(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Ti(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function wi(e){try{return await e.req.json()}catch{throw new T(`Request body must be valid JSON`)}}function Ti(e,t){if(t instanceof T||t instanceof xr)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof O)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}var Ei=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`SessionSourceError`}};function Di(e){let t=new S;return t.get(`/codex`,async t=>{try{return t.json(await e.getCodexSnapshot())}catch(e){return Oi(t,e)}}),t.get(`/claude`,async t=>{try{return t.json(await e.getClaudeSnapshot())}catch(e){return Oi(t,e)}}),t}function Oi(e,t){if(t instanceof Ei)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 ki(e){let t=new S;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 Ai(t,e)}}),t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new R(`Request body must be valid JSON`)}return t.json(e.create(Gn(n)),201)}catch(e){return Ai(t,e)}}),t}function Ai(e,t){if(t instanceof R)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Un)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof Hn)return e.json({error:{code:t.code,message:t.message}},404);throw t}function ji(){let e=i.env.CLAUDE_CONFIG_DIR?.trim();return e?r.resolve(e):r.join(ie.homedir(),`.claude`)}const Mi=1048576;async function Ni(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 Ni(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 Pi(e,t){let n=!1,r=e=>{if(!e.trim())return;let r;try{r=JSON.parse(e)}catch{n=!0;return}Y(r)?t(r):n=!0},i=async e=>{let t=new Me(`utf8`),n=``;for await(let i of e){n+=t.write(i);let e=0,a=n.indexOf(`
|
|
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 x(c(e,{highWaterMark:Mi}),Ne({chunkSize:Mi}),i):await x(c(e,{highWaterMark:Mi}),i),{hasMalformedLines:n}}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e){return typeof e==`string`?e:``}function Fi(e){let t=Date.parse(X(e));return Number.isFinite(t)?t:null}function Ii(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):0}function Li(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(Y).filter(e=>[`text`,`input_text`,`output_text`].includes(X(e.type))).map(e=>X(e.text)).join(`
|
|
12
|
-
`):``}function Ri(e,t){return e.replaceAll(/\s+/gu,` `).trim().slice(0,240)||t.slice(0,8)}async function zi(e){let t=await Ni(r.join(e,`projects`));if(!t.found)throw new Ei(`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 Bi(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 Bi(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 Pi(e,e=>{f?p=X(e.sessionId)||p:n||=X(e.sessionId),i=X(e.cwd)||i,a=X(e.gitBranch)||a,m||=e.isSidechain===!0;let t=Fi(e.timestamp);t!==null&&(u=Math.min(u,t),d=Math.max(d,t)),e.type===`custom-title`?s=X(e.customTitle)||s:e.type===`last-prompt`&&(c=X(e.lastPrompt)||c);let r=Y(e.message)?e.message:{};if(e.type===`user`&&e.isMeta!==!0&&r.role===`user`&&(o||=Li(r.content).trim()),e.type!==`assistant`||r.role!==`assistant`)return;let g=X(r.model);g&&g!==`<synthetic>`&&(l=g);let te=Y(r.usage)?r.usage:{},_=[te.input_tokens,te.output_tokens,te.cache_creation_input_tokens,te.cache_read_input_tokens].reduce((e,t)=>e+Ii(t),0),ne=X(r.id)||X(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:Ri(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(ie.homedir(),`.codex`)}async function Hi(e){let t=await Promise.all([Ni(r.join(e,`sessions`)),Ni(r.join(e,`archived_sessions`))]);if(t.every(e=>!e.found))throw new Ei(`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 Ui(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(),Wi),warnings:n>0?[{code:`TRANSCRIPT_FILES_UNREADABLE`,count:n}]:[]}}async function Ui(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 Pi(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=Y(e.payload)?e.payload:{};if(e.type===`session_meta`){n.id||=X(r.id),n.cwd||=X(r.cwd),n.model??=X(r.model_provider)||null;let e=Y(r.git)?r.git:{};n.gitBranch??=X(e.branch)||null;let t=Y(r.source)?r.source:{},i=Y(r.thread_source)?r.thread_source:{},a=Y(t.subagent)?t.subagent:{},o=Y(i.subagent)?i.subagent:{};n.parentThreadId??=X(r.parent_thread_id)||X(a.parent_thread_id)||X(o.parent_thread_id)||null,n.subagent||=!!r.parent_thread_id||Y(r.source)&&`subagent`in r.source||Y(r.thread_source)&&`subagent`in r.thread_source}else if(e.type===`turn_context`)n.cwd=X(r.cwd)||n.cwd,n.model=X(r.model)||n.model;else if(e.type===`response_item`&&r.type===`message`&&r.role===`user`){let e=Li(r.content).trim();e&&!e.startsWith(`<environment_context>`)&&!e.startsWith(`# AGENTS.md instructions`)&&(i||=e)}else if(e.type===`token_usage_record`){let e=Y(r.thread_token_usage)?r.thread_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,Ii(e.total_tokens))}else if(e.type===`event_msg`&&r.type===`token_count`){let e=Y(r.info)?r.info:{},t=Y(e.total_token_usage)?e.total_token_usage:{};n.tokensUsed=Math.max(n.tokensUsed,Ii(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 Wi(e){e.sort((e,t)=>e.updatedAt-t.updatedAt);let t=e[0];return{id:t.id,title:Ri(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 Gi=class{codexHome;claudeHome;constructor(e=Vi(),t=ji()){this.codexHome=e,this.claudeHome=t}async getCodexSnapshot(){return Ki(`codex`,await Hi(this.codexHome))}async getClaudeSnapshot(){return Ki(`claude`,await zi(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 qi(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||Yi(n,e)}),c=setInterval(()=>{r||Xi(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 Yi(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Xi(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var Zi=class extends Error{code=`INVALID_EXPORT_INPUT`};function Qi(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new Zi(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function $i(e){let t=new S;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new Zi(`Request body must be valid JSON`)}let{passphrase:r}=Qi(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 Zi?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 ea(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 F(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new F(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new F(`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 F?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 Ut(i)}}),n}function ta(e){return e===`/api`||e.startsWith(`/api/`)}function na(e,t={}){let n=new S,r=t.providerService??new Si(e),i=t.settingsService??new bt(e),a=t.settingsSkillCopyService??new St,o=t.sessionService??new Gi,s=t.instructionsService??new Rn(e),c=t.agentsService??new zn(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`,qi(t.eventHub)),n.route(`/api/data-import`,ea(t.dataImportService??new Cn(e),()=>{t.onSettingsChanged?.(),t.eventHub?.publish($e,{fields:[`theme`,`language`,`timeFormat`,`timezone`,`captures`]})})),n.route(`/api/data-export`,$i(t.dataExportService??new hn(e))),n.route(`/api/agents`,zr(c)),n.route(`/api/skills`,ki(t.skillsService??new Jn(e))),n.route(`/api/instructions`,Xr(s)),n.route(`/api/providers`,vi(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,Ci(i,e=>{t.onSettingsChanged?.(),t.eventHub?.publish($e,e)},a)),n.route(`/api/sessions`,Di(o)),t.captureService&&n.route(`/api/captures`,qr(t.captureService,e=>{t.eventHub?.publish(`captures.changed`,e)})),n.notFound(e=>ta(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),ta(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function ra(e,t,n){let i=na(t,n),a=je({root:e});i.use(`*`,(e,t)=>ta(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`)&&!ta(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}var ia=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=>aa(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:aa(t),rawResponse:n?.captureId===e&&!n.deletedAt?n.rawResponse:null}})}findActiveByURL(e){return this.storage.all(`captures`).find(t=>t.url===e&&!t.deletedAt)??null}createWithJob(e,t,n){return this.storage.transaction(()=>{if(this.findActiveByURL(e))throw new U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let r=Date.now(),i={id: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:aa(i),jobId:a.id}})}hasActiveJob(e){return this.storage.all(`fetchJobs`).some(t=>t.captureId===e&&!t.deletedAt&&[`pending`,`running`].includes(t.status))}createJob(e,t){return this.storage.transaction(()=>{if(!this.findCapture(e))throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`);if(this.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=this.newJob(e,t);return this.storage.put(`fetchJobs`,n),{job:oa(n),jobId:n.id}})}delete(e){return this.storage.transaction(()=>{let t=this.findCapture(e);if(!t)return!1;if(this.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let n=Date.now();this.storage.put(`captures`,{...t,deletedAt:n,updatedAt:n});for(let t of this.storage.all(`fetchJobs`))t.captureId===e&&!t.deletedAt&&this.storage.put(`fetchJobs`,{...t,deletedAt:n,updatedAt:n});return!0})}updateNote(e,t){return this.storage.transaction(()=>{let n=this.findCapture(e);if(!n)return null;let r={...n,userNote:t.trim()||null,updatedAt:Date.now()};return this.storage.put(`captures`,r),aa(r)})}listJobs(e){return this.storage.all(`fetchJobs`).filter(t=>t.captureId===e&&!t.deletedAt).toSorted((e,t)=>t.createdAt-e.createdAt).map(e=>oa(e))}getJob(e,t){let n=this.getJobContext(t);return n?.capture.id===e?oa(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 aa(e){let{deletedAt:t,...n}=e;return n}function oa(e){return{id:e.id,captureId:e.captureId,status:e.status,fetcher:e.fetcher,creditsUsed:e.creditsUsed,errorCode:e.errorCode,errorMessage:e.errorMessage,createdAt:e.createdAt,updatedAt:e.updatedAt}}var Z=class extends Error{code;statusCode;constructor(e,t,n){super(t),this.code=e,this.statusCode=n,this.name=`FetcherError`}};function sa(e){if(e instanceof Z)return e;let t=ca(e);return t===null?da(e)?new Z(`timeout`,`The configured fetcher timed out`):fa(e)?new Z(`network_error`,e instanceof Error?e.message:`The configured fetcher could not be reached`):new Z(`fetch_failed`,e instanceof Error?e.message:`The capture fetch failed`):new Z(`http_${t}`,la(e)??`The configured fetcher returned ${t}`,t)}function ca(e){if(!Q(e))return null;let t=pa(e.status);return t===null?Q(e.response)?pa(e.response.status):null:t}function la(e){if(!Q(e))return null;if(Q(e.response)){let t=ua(e.response.data);if(t)return t}return typeof e.message==`string`&&e.message?e.message:ua(e.details)}function ua(e){return Q(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function da(e){if(!(e instanceof Error))return!1;let t=ma(e);return e.name===`TimeoutError`||t===`ECONNABORTED`||t===`ETIMEDOUT`||/timeout/i.test(e.message)}function fa(e){if(e instanceof TypeError)return!0;if(!Q(e))return!1;let t=ma(e);return t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ENOTFOUND`||t===`ERR_NETWORK`||e.name===`AxiosError`&&!Q(e.response)}function pa(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function ma(e){let t=e.code;return typeof t==`string`?t:null}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ha=class extends Fe{async searchEnvelope(e){return(await this.http.post(`/v2/search`,{...e},{timeoutMs:e.timeout+5e3})).data}};function ga(e,t,n={}){let r=new ha({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 _a(e,t,n=1,r=ga(t,n)){try{let t=va(e),n=await r.search(ya(t));if(!$(n))throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);if(n.success===!1)throw new Z(`fetcher_error`,Fa(n)??`The configured fetcher reported an error`);if(n.success!==!0)throw new Z(`invalid_response`,`The configured fetcher returned an invalid response`);let i=Pa(n);if(i===null)throw new Z(`missing_credits_used`,`The configured fetcher response did not report credit usage`);let a=Da(e,Ea(n));return{title:a?Ma(a):null,rawResponse:n,creditsUsed:i}}catch(e){throw sa(e)}}function va(e){return{query:ba(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 ya(e){return{query:e.query,limit:e.limit,sources:e.sources,highlights:e.highlights,ignoreInvalidURLs:e.ignoreInvalidURLs,timeout:e.timeout,scrapeOptions:e.pageOptions}}function ba(e){let t=new URL(e),n=t.hostname.toLowerCase(),r=xa(t.pathname),i=Ta(n);return`site:${n} ${(r??i??n.split(`.`,1)[0]).replaceAll(/\s+/g,` `).trim().slice(0,200)}`}function xa(e){let t=e.split(`/`).map(e=>Sa(e)).filter(Boolean);for(let e=t.length-1;e>=0;--e){let n=t[e]?.trim()??``;if(!n||wa(n))continue;let r=Ca(n);if(r)return r}return null}function Sa(e){try{return decodeURIComponent(e)}catch{return e}}function Ca(e){return e.replace(/\.(?:html?|php|aspx?|jsp)$/i,``).replaceAll(/[-_]+/g,` `).trim()}function wa(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 Ta(e){return Ie(e,{allowPrivateDomains:!0}).domainWithoutSuffix?.trim()||null}function Ea(e){return!$(e.data)||!Array.isArray(e.data.web)?[]:e.data.web.flatMap(e=>!$(e)||typeof e.url!=`string`||!e.url?[]:[{url:e.url,title:typeof e.title==`string`?e.title:null,metadata:$(e.metadata)?e.metadata:{}}])}function Da(e,t){let n=ka(e);if(n){let e=t.find(e=>Oa(e).some(e=>ka(e)===n));if(e)return e}let r=Aa(e),i=r===null?[]:t.filter(e=>Oa(e).some(e=>Aa(e)===r));return i.find(e=>ja(e))??(i.length>0?i[0]:null)}function Oa(e){return[e.url,Na(e,`sourceURL`),Na(e,`url`)].filter(e=>!!e)}function ka(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 Aa(e){try{return new URL(e).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}function ja(e){return Oa(e).some(e=>{try{return new URL(e).pathname===`/`}catch{return!1}})}function Ma(e){return e.title?.trim()||Na(e,`ogTitle`)?.trim()||Na(e,`title`)?.trim()||null}function Na(e,t){let n=e.metadata[t];return typeof n==`string`&&n?n:null}function Pa(e){return typeof e.creditsUsed==`number`&&Number.isSafeInteger(e.creditsUsed)&&e.creditsUsed>=0?e.creditsUsed:null}function Fa(e){return $(e)?typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:null:null}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ia(e,t){return _a(e,t.apiKey,t.maxAttempts)}var La=class{repository;storage;onChanged;fetchCaptureImplementation;queue=[];knownJobIDs=/* @__PURE__ */ new Set;runningCount=0;constructor(e,t,n=()=>{},r=Ia){this.repository=e,this.storage=t,this.onChanged=n,this.fetchCaptureImplementation=r}schedule(){let e=_t(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=Ra(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=sa(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 Ra(e){let t=e;if(!za(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 za(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ba=class{repository;storage;runner;constructor(e,t,n){this.repository=e,this.storage=t,this.runner=n}executionConfig(){let e=_t(this.storage).features.library.captures;if(!e.fetcher)return null;let t=e[e.fetcher].apiKey.trim();return t?{fetcher:e.fetcher,apiKey:t,maxAttempts:e.maxAttempts}:null}list(e){return this.repository.list(e)}counts(){return this.repository.counts()}get(e){let t=this.repository.get(e);if(!t)throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`);return t}create(e){let t=Va(e.url);if(!t)throw new U(`INVALID_URL`,`Enter a valid HTTP or HTTPS URL`);if(this.repository.findActiveByURL(t))throw new U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`);let n=this.executionConfig();if(!n)throw new U(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before adding a capture`);try{let r=this.repository.createWithJob(t,e.userNote?.trim()||null,n);return this.runner.enqueue(r.jobId),r.capture}catch(e){throw this.repository.findActiveByURL(t)?new U(`CAPTURE_ALREADY_EXISTS`,`This link is already captured`):e}}recapture(e){if(this.get(e),this.repository.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);let t=this.executionConfig();if(!t)throw new U(`FETCHER_NOT_CONFIGURED`,`Configure a capture service before re-capturing`);let n=this.repository.createJob(e,t);return this.runner.enqueue(n.jobId),n.job}delete(e){if(this.get(e),this.repository.hasActiveJob(e))throw new U(`ACTIVE_JOB_EXISTS`,`This capture already has an active fetch job`);if(!this.repository.delete(e))throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`)}updateNote(e,t){let n=this.repository.updateNote(e,t);if(!n)throw new U(`CAPTURE_NOT_FOUND`,`Capture not found`);return n}listJobs(e){return this.get(e),this.repository.listJobs(e)}getJob(e,t){return this.get(e),this.repository.getJob(e,t)}};function Va(e){let t=e.trim();try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?t:null}catch{return null}}function Ha(e,t,n){let r=new ia(e),i=new La(r,e,e=>t?.publish(`capture.job.changed`,e),n);return{service:new Ba(r,e,i),runner:i,start:()=>{i.start()},notifySettingsChanged:()=>{i.notifySettingsChanged()}}}function Ua(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 Wa=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 Ga(e){let t=new Wa,n=Ha(e,t),r=new hn(e),i=new Cn(e),a=new Rn(e),o=new zn(e,a),s=new Si(e),c=new bt(e),l=new St,u=new Gi,d=new Jn(e),f={agentsService:o,captureRuntime:n,dataExportService:r,dataImportService:i,instructionsService:a,providerService:s,settingsService:c,settingsSkillCopyService:l,sessionService:u,skillsService:d},p;return{services:f,apiOptions:{agentsService:o,captureService:n.service,dataExportService:r,dataImportService:i,instructionsService:a,providerService:s,settingsService:c,settingsSkillCopyService:l,sessionService:u,skillsService:d,eventHub:t,onSettingsChanged:n.notifySettingsChanged},start(){p??=Ua(e.path,()=>{n.notifySettingsChanged(),t.publish($e,{fields:[]})}),n.start()},stop(){p?.(),p=void 0}}}const{dirname:Ka,join:qa,resolve:Ja}=r,Ya=Ka(Ce(import.meta.url));function Xa(){let e=[Ja(Ya,`web`),Ja(i.cwd(),`dist/web`)].find(e=>u(qa(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Za({storage:e,webRoot:t=Xa(),onListening:n}){let r=Ga(e),a=ra(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 Qa(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 $a(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 eo=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 Qa(`127.0.0.1`,11111)}catch(e){to(e);return}Za({storage:er(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&$a(t)}})}});function to(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function no(){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, instructions, and skills or start the Web UI`},default:`help`,subCommands:{help:r,web:eo,settings:Ir,instructions:yr,agents:pr,skills:Rr}}),t}t(no());export{};
|
|
8
|
+
`);return t?`${Cn}\n\n${t}\n\n${wn}`:`${Cn}\n${wn}`}function kn(e){return e.match(/[^\n]*\n|[^\n]+$/gu)??[]}function An(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 jn(e,t){let n=r.dirname(e);p(n,{recursive:!0,mode:448});let a=u(e)?_(e).mode&511:384,c=`${e}.${y()}.tmp`;try{let r=ee(c,`wx`,a);try{i.platform!==`win32`&&o(c,a),ce(r,t),d(r)}finally{s(r)}re(c,e),z(n)}finally{g(c,{force:!0})}}function B(e,t,n){let r=u(e.filePath);if(n&&!r)return;let i=r?m(e.filePath,`utf8`):``,a=n?En(i):Tn(i,t);jn(e.filePath,a)}function Mn(e,t,n){let r=pn(e).filter(({instructions:e})=>e.instructionIds.includes(t));if(r.length===0)return;let i=new Map(yn(n).map(e=>[e.id,e])),a=new Map(Gt(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&&B(c,s.map(e=>a.get(e)?.content).filter(e=>e!==void 0),s.length===0),hn(e,{...n,instructions:{...r,instructionIds:s,enabled:s.length>0&&r.enabled,updatedAt:o}})}}var Nn=class{storage;homeDirectory;constructor(e,t=le.homedir()){this.storage=e,this.homeDirectory=t}list(){return Gt(this.storage)}get(e){let t=Kt(e,this.storage);if(!t)throw new Bt(e);return t}create(e){return Wt(e,this.storage)}update(e,t){let n=qt(e,t,this.storage);if(!n)throw new Bt(e);return n}delete(e){return this.storage.transaction(()=>{let t=Kt(e,this.storage);if(!t||(Mn(this.storage,e,this.homeDirectory),Jt(e,this.storage)===`missing`))throw new Bt(e);return t})}},Pn=class{storage;instructionsService;openFile;definitions;constructor(e,t=new Nn(e),n=le.homedir(),r=Ge){this.storage=e,this.instructionsService=t,this.openFile=r,this.definitions=yn(n)}requireDefinition(e){let t=this.definitions.find(({id:t})=>t===e);if(!t)throw new w(`AGENT_NOT_FOUND`,`Unknown agent: ${e}`,404);return t}readAssignedInstructions(e){let t=new Map(this.instructionsService.list().map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e);if(!n)throw new w(`UNKNOWN_INSTRUCTION`,`Unknown instruction: ${e}`,400);return n})}list(){let e=new Map(pn(this.storage).map(e=>[e.id,e]));return this.definitions.map(t=>Fn(t,(e.get(t.id)??R(t.id)).instructions))}updateInstructions(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=this.readAssignedInstructions(t),i=mn(this.storage,e)??R(e),a=i.instructions,o=t.length>0&&a.enabled;a.enabled&&B(n,r.map(({content:e})=>e),t.length===0);let s=Date.now(),c=hn(this.storage,{...i,instructions:{...a,instructionIds:t,enabled:o,updatedAt:s}});return Fn(n,c.instructions)})}setEnabled(e,t){let n=this.requireDefinition(e);return this.storage.transaction(()=>{let r=mn(this.storage,e)??R(e),i=r.instructions;if(t){if(i.instructionIds.length===0)throw new w(`AGENT_HAS_NO_INSTRUCTIONS`,`Add at least one instruction before enabling this agent`,400);let e=this.readAssignedInstructions(i.instructionIds);B(n,e.map(({content:e})=>e),!1)}else B(n,[],!0);let a=Date.now();return Fn(n,hn(this.storage,{...r,instructions:{...i,enabled:t,updatedAt:a}}).instructions)})}reapply(e){let t=this.requireDefinition(e);return this.storage.transaction(()=>{let n=mn(this.storage,e)??R(e),r=n.instructions;if(!r.enabled)throw new w(`AGENT_DISABLED`,`Enable this agent before reapplying its instructions`,409);let i=this.readAssignedInstructions(r.instructionIds);B(t,i.map(({content:e})=>e),!1);let a=Date.now();return Fn(t,hn(this.storage,{...n,instructions:{...r,updatedAt:a}}).instructions)})}openInstructionFile(e){let t=this.requireDefinition(e);if(!u(t.filePath))throw new w(`AGENT_FILE_NOT_FOUND`,`Instruction file does not exist: ${t.instructionFile}`,404);return this.openFile(t.filePath),{path:t.instructionFile}}};function Fn(e,t){return{id:e.id,name:e.name,icon:e.icon,capabilities:e.capabilities,instructionFile:e.instructionFile,enabled:t.enabled,instructionIds:t.instructionIds}}var In=class extends Error{code=`SKILL_AGENT_NOT_FOUND`;constructor(e){super(`Agent does not support skills: ${e}`)}},Ln=class extends Error{code=`SKILL_LINK_CONFLICT`;constructor(e){super(`An unrelated entry already exists at the agent skill destination: ${e}`)}},Rn=class{libraryRoot;homeDirectory;registry;constructor(e,t,n=T){this.libraryRoot=e,this.homeDirectory=t,this.registry=n}source(e){if(e!==e.trim()||!nt(e))throw Error(`Invalid agent skill link name`);return r.resolve(this.libraryRoot,`skill`,e)}destinations(e){let t=this.source(e.previousName),n=e.name===null?null:this.source(e.name),i=this.registry.supporting(`skills`),a=e.agentIds??[];for(let e of a)if(i.every(t=>t.id!==e))throw new In(e);return[...new Set(i.filter(t=>!e.agentIds||e.agentIds.includes(t.id)).map(e=>Ue(this.homeDirectory,e.capabilities.skills.directory)))].map(i=>({directory:i,previous:r.join(i,e.previousName),destination:e.name===null?null:r.join(i,e.name),previousSource:t,source:n}))}targets(){return this.registry.supporting(`skills`).map(e=>({id:e.id,name:e.name,icon:e.icon.name,directory:He(e.capabilities.skills.directory)}))}assignedAgentIds(e){let t=this.source(e);return this.registry.supporting(`skills`).filter(n=>H(r.join(Ue(this.homeDirectory,n.capabilities.skills.directory),e),t)).map(e=>e.id)}validate(e){for(let{destination:t,source:n,previousSource:r}of this.destinations(e))if(t&&n&&V(t)&&!H(t,n)&&!H(t,r))throw new Ln(t)}apply(e){this.validate(e);for(let{directory:t,previous:n,destination:i,source:a,previousSource:o}of this.destinations(e)){if(i&&a){p(t,{recursive:!0,mode:448});let e=v(`sha256`).update(`${i}\0${a}`).digest(`hex`),n=r.join(t,`.foundry-${e}.tmp`);try{if(V(n)&&!H(n,a))throw new Ln(n);if(V(n)||ae(a,n,`dir`),V(i)&&!H(i,a)&&!H(i,o))throw new Ln(i);re(n,i),z(t)}finally{H(n,a)&&oe(n)}}n!==i&&H(n,o)&&(oe(n),z(t))}}};function V(e){try{return f(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function H(e,t){return V(e)&&f(e).isSymbolicLink()&&zn(r.resolve(r.dirname(e),te(e)))===zn(t)}function zn(e){try{return r.join(ne(r.dirname(e)),r.basename(e))}catch(t){if(t.code===`ENOENT`)return e;throw t}}var U=class extends Error{code=`INVALID_SKILL_INPUT`},W=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n}};function Bn(e){if(typeof e!=`string`||!rt(e))throw new W(`INVALID_SKILL_FILE_PATH`,`Use a relative path within this skill`,400);return e}function Vn(e){if(!e||typeof e!=`object`||!(`files`in e)||!Array.isArray(e.files))throw new U(`files must be an array`);let t=/* @__PURE__ */ new Set,n=0,r=(e,i,a)=>{if(a>32)throw new U(`File tree is too deep`);return e.map(e=>{if(!e||typeof e!=`object`||!(`path`in e))throw new U(`Invalid file entry`);let o=Bn(e.path);if(t.has(o)||o.split(`/`).slice(0,-1).join(`/`)!==i||t.size>=5e3)throw new U(`Invalid, duplicate, or misplaced file path`);if(t.add(o),`children`in e){if(!Array.isArray(e.children)||`content`in e)throw new U(`Invalid directory entry`);return{path:o,children:r(e.children,o,a+1)}}if(!(`content`in e)||typeof e.content!=`string`&&e.content!==null)throw new U(`File content must be text or null for an uneditable existing file`);if(e.content!==null&&(Hn(e.content),n+=x.byteLength(e.content,`utf8`),n>16777216))throw new U(`Skill text exceeds 16 MiB`);return{path:o,content:e.content}})},i=r(e.files,``,0);if(i.every(e=>e.path!==`SKILL.md`||typeof e.content!=`string`))throw new W(`SKILL_ENTRY_REQUIRED`,`SKILL.md is required`,409);return{files:i}}function Hn(e){if(x.byteLength(e,`utf8`)>2097152)throw new W(`SKILL_FILE_TOO_LARGE`,`Text files must be at most 2 MiB`,413);if(e.includes(`\0`))throw new W(`SKILL_FILE_NOT_TEXT`,`Binary files cannot be edited as text`,415)}function Un(e){if(!e||typeof e!=`object`||Array.isArray(e)||!(`assigned`in e)||typeof e.assigned!=`boolean`)throw new U(`assigned must be a boolean`);return{assigned:e.assigned}}var G=class extends Error{code=`SKILL_NOT_FOUND`;constructor(e){super(`Skill not found: ${e}`)}},Wn=class extends Error{code=`SKILL_NAME_CONFLICT`;constructor(e){super(`A skill directory named ${e} already exists`)}};function Gn(e){return e===e.trim()&&nt(e)}function K(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new U(`Skill input must be an object`);if(!(`name`in e)||typeof e.name!=`string`)throw new U(`name is required`);let t=tt(e.name);if(!Gn(t))throw new U(`name must be 1–64 lowercase letters, digits, or single hyphens between words`);if(!(`description`in e)||typeof e.description!=`string`)throw new U(`description is required`);let n=e.description.trim();if(!n||n.length>1024)throw new U(`description must be 1–1024 characters`);return{name:t,description:n}}const Kn=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;var qn=class{storage;constructor(e){this.storage=e}directory(e){if(!Gn(e))throw Error(`Invalid skill directory name`);return r.join(this.storage.path,`skill`,e)}assertSourceDirectory(e){try{let t=f(this.directory(e));if(!t.isDirectory()||t.isSymbolicLink())throw new U(`Skill source must be a directory in the Foundry library`)}catch(t){throw t instanceof Error&&Reflect.get(t,`code`)===`ENOENT`?new G(e):t}}assertAvailable(e){try{f(this.directory(e))}catch(e){if(e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`)return;throw e}throw new Wn(e)}create(e){return this.storage.transaction(()=>{let t=this.directory(e.name);return this.assertAvailable(e.name),this.storage.putTextFile(r.join(t,`SKILL.md`),`---\n${Ne(e).trimEnd()}\n---\n`),{...e,content:``}})}update(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new G(e);this.assertSourceDirectory(e);let i=this.directory(e),a=m(r.join(i,`SKILL.md`),`utf8`),o=Kn.exec(a);if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=Me(o[1]);s.set(`name`,t.name),s.set(`description`,t.description);let c=this.directory(t.name);return e!==t.name&&(this.assertAvailable(t.name),this.storage.moveSkillDirectory(i,c)),this.storage.putTextFile(r.join(c,`SKILL.md`),`---\n${s.toString().trimEnd()}\n---\n${n.content}`),{...t,content:n.content}})}delete(e){return this.storage.transaction(()=>{let t=this.get(e);if(!t)throw new G(e);return this.assertSourceDirectory(e),this.storage.removeSkillDirectory(this.directory(e)),t})}updateContent(e,t){return this.storage.transaction(()=>{let n=this.get(e);if(!n)throw new G(e);this.assertSourceDirectory(e);let i=r.join(this.directory(e),`SKILL.md`);if(f(i).isSymbolicLink())throw new U(`Skill source file must not be a symbolic link`);let a=m(i,`utf8`),o=Kn.exec(a)?.[0];if(!o)throw Error(`Invalid skill file: ${e}/SKILL.md`);let s=t===``||o.endsWith(`
|
|
9
|
+
`)?``:`
|
|
10
|
+
`;return this.storage.putTextFile(i,`${o}${s}${t}`),{...n,content:t}})}get(e){if(Gn(e))return this.storage.transaction(()=>{try{let t=m(r.join(this.directory(e),`SKILL.md`),`utf8`),n=Kn.exec(t);if(!n)throw Error(`Invalid skill file: ${e}/SKILL.md`);let i=K(je(n[1]));if(i.name!==tt(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()&&Gn(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]:[]})})}};function Jn(e){return e.flatMap(e=>e.children?[e,...Jn(e.children)]:[e])}var Yn=class{storage;skills;constructor(e,t){this.storage=e,this.skills=t}root(e){if(!this.skills.get(e))throw new G(e);let t=r.join(this.storage.path,`skill`,e);if(!f(t).isDirectory()||f(t).isSymbolicLink()||f(r.dirname(t)).isSymbolicLink())throw new W(`INVALID_SKILL_FILE_PATH`,`Skill source must be a local directory`,400);return t}assertLocal(e,t){let n=e;for(let e of t.split(`/`)){n=r.join(n,e);try{if(f(n).isSymbolicLink())throw new W(`INVALID_SKILL_FILE_PATH`,`Symbolic links cannot be changed through the editor`,400)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;return}}}read(e){let t=this.root(e),n=(t,i)=>h(t,{withFileTypes:!0}).toSorted((e,t)=>e.name.localeCompare(t.name)).flatMap(a=>{let o=i?`${i}/${a.name}`:a.name;if(!rt(o)||a.isSymbolicLink())return[];let s=r.join(t,a.name);if(a.isDirectory())return[{path:o,children:n(s,o)}];if(!a.isFile())return[];if(o===`SKILL.md`)return[{path:o,content:this.skills.get(e).content}];let c=null;if(f(s).size<=2097152)try{let e=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(m(s));c=e.includes(`\0`)?null:e}catch{}return[{path:o,content:c}]});return n(t,``)}replace(e,t){let n=this.root(e),i=new Map(Jn(this.read(e)).map(e=>[e.path,e])),a=new Map(Jn(t).map(e=>[e.path,e]));for(let e of a.values())if(this.assertLocal(n,e.path),e.content===null&&i.get(e.path)?.content!==null)throw new W(`SKILL_FILE_NOT_TEXT`,`Uneditable files must refer to existing unchanged files`,415);let o=[];for(let e of i.values()){let t=a.get(e.path);t&&!!e.children==!!t.children||o.some(t=>e.path.startsWith(`${t}/`))||(this.storage.removeSkillEntry(r.join(n,e.path)),o.push(e.path))}for(let t of a.values()){let a=i.get(t.path),o=r.join(n,t.path);t.children?a?.children||this.storage.createSkillFolder(o):t.content!==null&&t.content!==a?.content&&(t.path===`SKILL.md`?this.skills.updateContent(e,t.content):this.storage.putTextFile(o,t.content))}}},Xn=class{storage;repository;files;constructor(e){this.storage=e,this.repository=new qn(e),this.files=new Yn(e,this.repository)}assignmentRecords(){let e=new Map(this.storage.all(`agents`).map(e=>[e.id,e])),t=this.storage.listSkillAgents().filter(({id:t})=>!e.get(t)?.skills);if(t.length>0){let n=this.list().map(({name:e})=>({name:e,agentIds:this.storage.discoverLinkedSkillAgents(e)})),r=Date.now();for(let{id:i}of t){let t=e.get(i)??R(i);t.skills={skillNames:n.filter(({agentIds:e})=>e.includes(i)).map(({name:e})=>e),createdAt:r,updatedAt:r},this.storage.put(`agents`,t),e.set(i,t)}}return e.values().toArray()}assignedIds(e,t){return this.storage.listSkillAgents().filter(({id:n})=>t.some(t=>t.id===n&&t.skills?.skillNames.includes(e))).map(({id:e})=>e)}create(e){return this.repository.create(K(e))}get(e){let t=this.repository.get(e);if(!t)throw new G(e);return t}list(){return this.repository.list()}assignments(){return this.storage.transaction(()=>{let e=this.assignmentRecords();return{agents:this.storage.listSkillAgents(),skills:this.list().map(({name:t})=>({name:t,agentIds:this.assignedIds(t,e)}))}})}setAssignment(e,t,n){return this.storage.transaction(()=>{this.get(e);let r=this.assignmentRecords().find(({id:e})=>e===t);if(!r?.skills||this.storage.listSkillAgents().every(({id:e})=>e!==t))throw new In(t);let i=r.skills.skillNames.filter(t=>t!==e);n&&i.push(e),this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:i,updatedAt:Date.now()}}),this.storage.syncAgentSkillLinks({previousName:e,name:n?e:null,agentIds:[t]})}),{name:e,agentIds:this.assignedIds(e,this.storage.all(`agents`))}}update(e,t){let n=K(t);return this.storage.transaction(()=>{let t=this.assignmentRecords(),r=this.assignedIds(e,t),i=this.repository.update(e,n);if(e!==n.name)for(let r of t)r.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...r,skills:{...r.skills,skillNames:r.skills.skillNames.map(t=>t===e?n.name:t),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:n.name,agentIds:r}),i})}detail(e){return this.storage.transaction(()=>({...this.get(e),files:this.files.read(e)}))}saveFiles(e,t){let n=Vn({files:t});return this.storage.transaction(()=>this.files.replace(e,n.files)),this.detail(e)}delete(e){return this.storage.transaction(()=>{let t=this.assignmentRecords(),n=this.repository.delete(e);for(let n of t)n.skills?.skillNames.includes(e)&&this.storage.put(`agents`,{...n,skills:{...n.skills,skillNames:n.skills.skillNames.filter(t=>t!==e),updatedAt:Date.now()}});return this.storage.syncAgentSkillLinks({previousName:e,name:null}),n})}};const Zn=[`agents`,`providers`];function Qn(e){let t=/^skill[/\\]([^/\\]+)$/u.exec(e);return!!(t&&t[1]===t[1].trim()&&nt(t[1]))}function $n(e){return/^instructions[/\\][^/\\]+\.md$/u.test(e)||er(e)}function er(e){let t=e.split(r.sep);return t[0]===`skill`&&t.length>2&&t[1]===t[1].trim()&&nt(t[1])&&rt(t.slice(2).join(`/`))}function tr(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 nr=class{path;changes=null;textChanges=null;directoryChanges=null;skillLinkChange;skillLinks;closed=!1;lockDepth=0;formatVersion=1;constructor(e,t=le.homedir()){this.path=e,this.skillLinks=new Rn(e,t),bn(e);for(let e of Zn)e!==`providers`&&bn(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`);if(e===`agents`){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t))throw Error(`Invalid agent record ID`);return r.join(`agents`,`${t}.json`)}return r.relative(this.path,r.join(this.collectionPath(e),`${v(`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)||!$n(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{p(t,{mode:448});try{ce(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(),this.initializeAgents(),e()}finally{this.lockDepth=0,g(t,{recursive:!0,force:!0})}}recoverLock(e){try{let t=_(e);if(!tr(e))return;let n=r.join(e,`recovering`);try{p(n)}catch(e){if(e.code===`EEXIST`){let e=_(n);tr(n)&&_(n).ino===e.ino&&g(n,{recursive:!0,force:!0})}return}if(ce(r.join(n,`owner.json`),JSON.stringify({pid:i.pid}),{mode:384,flag:`wx`}),_(e).ino!==t.ino||!tr(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}))]};xn(r.join(this.path,`.transaction.json`),n),this.applyJournal(n)}u(t)&&h(t).length===0&&(ie(t),z(this.path))}initializeAgents(){let e=[],t=this.collectionPath(`agents`),n=h(t,{withFileTypes:!0});for(let t of n){if(!t.isFile()||!/^[a-f0-9]{64}\.json$/u.test(t.name))continue;let n=r.join(`agents`,t.name),i=JSON.parse(m(r.join(this.path,n),`utf8`)),a=this.recordPath(`agents`,i.id);if(t.name!==`${v(`sha256`).update(i.id).digest(`hex`)}.json`){if(n===a)continue;throw Error(`Invalid legacy agent record`)}if(u(r.join(this.path,a))){let e=JSON.parse(m(r.join(this.path,a),`utf8`));if(JSON.stringify(e)!==JSON.stringify(i))throw Error(`Conflicting legacy agent record: ${i.id}`)}else e.push({file:a,value:i});e.push({file:n,value:null})}if(e.length===0)return;let i={changes:e};xn(r.join(this.path,`.transaction.json`),i),this.applyJournal(i)}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)}assertLocalSkillPath(e){let t=r.relative(this.path,e);if(!er(t))throw Error(`Invalid skill entry path`);let n=this.path;for(let e of t.split(r.sep)){n=r.join(n,e);try{if(f(n).isSymbolicLink())throw Error(`Cannot write through symbolic links in skill storage`)}catch(e){if(Reflect.get(new Object(e),`code`)!==`ENOENT`)throw e;break}}}applyJournal(e){for(let t of e.changes){let e=r.resolve(this.path,t.file),n=r.relative(this.path,e);if(t.createDirectory||t.removeEntry){if(!er(n)||t.value!==void 0||t.text!==void 0||t.moveTo!==void 0||t.removeDirectory||t.createDirectory&&t.removeEntry)throw Error(`Invalid skill entry journal`);this.assertLocalSkillPath(e),t.createDirectory?bn(e):(g(e,{recursive:!0,force:!0}),z(r.dirname(e)))}else if(t.moveTo!==void 0||t.removeDirectory!==void 0)this.applyDirectoryChange(t,n);else{if(n.startsWith(`..`)||r.isAbsolute(n)||!/^(?:(?:settings|providers)\.json|[a-z][a-z-]*[/\\][a-f0-9]{64}\.json|agents[/\\][a-z0-9]+(?:-[a-z0-9]+)*\.json)$/u.test(n)&&!$n(n)||t.text!==void 0&&t.value!==void 0)throw Error(`Invalid storage recovery journal`);if(er(n)&&this.assertLocalSkillPath(e),t.value===null)g(e,{force:!0}),z(r.dirname(e));else if(t.text!==void 0){if(typeof t.text!=`string`)throw TypeError(`Invalid storage recovery journal`);Sn(e,t.text)}else if(t.value===void 0)throw Error(`Invalid storage recovery journal`);else xn(e,t.value)}}e.skillLinks&&this.skillLinks.apply(e.skillLinks),g(r.join(this.path,`.transaction.json`),{force:!0}),z(this.path)}skillDirectory(e){let t=r.relative(this.path,r.resolve(this.path,e));if(!Qn(t))throw Error(`Invalid storage skill directory`);return t}applyDirectoryChange(e,t){if(!Qn(t)||e.value!==void 0||e.text!==void 0||e.moveTo!==void 0&&e.removeDirectory!==void 0)throw Error(`Invalid storage directory journal`);let n=r.join(this.path,t);if(e.moveTo!==void 0){let t=r.join(this.path,this.skillDirectory(e.moveTo));if(u(n)){if(!f(n).isDirectory()||f(n).isSymbolicLink()||u(t))throw Error(`Invalid storage directory move`);re(n,t)}else if(!u(t)||!f(t).isDirectory()||f(t).isSymbolicLink())throw Error(`Missing storage directory move`)}else if(e.removeDirectory===!0)g(n,{recursive:!0,force:!0});else throw Error(`Invalid storage directory journal`);z(r.dirname(n))}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 it(this.changes.get(`settings.json`));let e=r.join(this.path,`settings.json`);return u(e)?it(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)}createSkillFolder(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),createDirectory:!0})}removeSkillEntry(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.assertLocalSkillPath(e),this.directoryChanges.push({file:r.relative(this.path,e),removeEntry:!0})}removeTextFile(e){if(!this.changes||!this.textChanges)throw Error(`Storage writes require a transaction`);this.textChanges.set(this.textFilename(e),null)}moveSkillDirectory(e,t){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),moveTo:this.skillDirectory(t)})}removeSkillDirectory(e){if(!this.directoryChanges)throw Error(`Storage writes require a transaction`);this.directoryChanges.push({file:this.skillDirectory(e),removeDirectory:!0})}syncAgentSkillLinks(e){if(!this.changes)throw Error(`Storage writes require a transaction`);if(this.skillLinkChange)throw Error(`Only one skill link synchronization is allowed per transaction`);this.skillLinks.validate(e),this.skillLinkChange=e}listSkillAgents(){return this.skillLinks.targets()}discoverLinkedSkillAgents(e){return this.locked(()=>this.skillLinks.assignedAgentIds(e))}setSettings(e){if(!this.changes)throw Error(`Storage writes require a transaction`);this.changes.set(`settings.json`,it(structuredClone(e)))}transaction(e){return this.locked(()=>{if(this.changes)return e(this);this.changes=/* @__PURE__ */ new Map,this.textChanges=/* @__PURE__ */ new Map,this.directoryChanges=[];let t;try{let n=e(this);if(n instanceof Promise)throw TypeError(`Storage transactions must be synchronous`);let i=[...this.directoryChanges,...[...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||this.skillLinkChange){let e={changes:i,...this.skillLinkChange&&{skillLinks:this.skillLinkChange}};xn(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,this.directoryChanges=null,this.skillLinkChange=void 0}})}close(){this.closed=!0}};function rr(e=Ke(),t){let n=new nr(e,t);try{return n.transaction(()=>{let t=n.readSettings();u(r.join(e,`settings.json`))||n.setSettings(t)}),n}catch(e){throw n.close(),e}}function ir(){return qe(),rr()}async function q(e){let t;try{let n=ir(),r=new Nn(n);t={storage:n,agentsService:new Pn(n,r),settingsService:new ht(n),settingsSkillCopyService:new _t,dataExportService:new sn(n),dataImportService:new vn(n),instructionsService:r,skillsService:new Xn(n)},or(await e(t))}catch(e){let t=sr(e);console.error(JSON.stringify({error:t},null,2)),i.exitCode=1}finally{t?.storage.close()}}function ar(e){let t=e??i.env.FOUNDRY_PASSPHRASE;if(!t)throw new J(`PASSPHRASE_REQUIRED`,`Provide --passphrase or set FOUNDRY_PASSPHRASE`);return t}var J=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`CliInputError`}};function or(e){console.log(JSON.stringify(e,null,2))}function sr(e){return e instanceof Error?{code:cr(e)??`CLI_ERROR`,message:e.message}:{code:`CLI_ERROR`,message:String(e)}}function cr(e){let t=Reflect.get(e,`code`);return typeof t==`string`?t:void 0}const lr={type:`positional`,description:`Agent ID with Skills support: ${T.supporting(`skills`).map(({id:e})=>e).join(`, `)}`,required:!0};function ur(t){return e({meta:{name:t?`assign`:`unassign`,description:t?`Assign one skill and create or repair its agent symlink; preserve other assignments`:`Unassign one skill and unlink its matching agent entry; preserve other assignments`},args:{agent:lr,skill:{type:`string`,description:`Existing skill name`,required:!0}},run({args:e}){return q(({skillsService:n})=>n.setAssignment(e.skill,e.agent,t))}})}const dr=e({meta:{name:`skills`,description:`Inspect, assign, or unassign skills through registered agent symlinks`},subCommands:{list:e({meta:{name:`list`,description:`List agents, skill directories, and saved skill names as JSON`},args:{agent:{...lr,required:!1}},run({args:e}){return q(({skillsService:t})=>{let n=t.assignments();if(e.agent!==void 0&&n.agents.every(({id:t})=>t!==e.agent))throw new In(e.agent);return n.agents.filter(({id:t})=>e.agent===void 0||t===e.agent).map(e=>({...e,skillNames:n.skills.filter(({agentIds:t})=>t.includes(e.id)).map(({name:e})=>e)}))})}}),assign:ur(!0),unassign:ur(!1)}}),fr=T.list().map(({id:e})=>e).join(`, `),Y={type:`positional`,description:`Agent ID: ${fr}`,required:!0},pr=e({meta:{name:`list`,description:`List supported agents and their raw assignment state as JSON`},run(){return q(({agentsService:e})=>e.list())}}),mr=e({meta:{name:`list`,description:`List ordered instruction assignments with instruction names as JSON`},args:{agent:{...Y,description:`Optional agent ID: ${fr}`,required:!1}},run({args:e}){return q(({agentsService:t,instructionsService:n})=>{let r=t.list();if(e.agent!==void 0&&r.every(({id:t})=>t!==e.agent))throw new J(`AGENT_NOT_FOUND`,`Unknown agent: ${e.agent}. Available agents: ${fr}`);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}))}))})}}),hr=e({meta:{name:`assign`,description:`Replace an agent instruction assignment in composed order`},args:{agent:Y,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 q(({agentsService:t})=>{let n=ze({instructionIds:e.instructions.split(`,`).map(e=>e.trim()).filter(Boolean)});return t.updateInstructions(e.agent,n.instructionIds)})}}),gr=e({meta:{name:`enable`,description:`Write the managed instruction block to the agent file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.setEnabled(e.agent,!0))}}),_r=e({meta:{name:`disable`,description:`Remove the managed instruction block from the agent file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.setEnabled(e.agent,!1))}}),vr=e({meta:{name:`reapply`,description:`Rewrite the managed instruction block for an enabled agent`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.reapply(e.agent))}}),yr=e({meta:{name:`open`,description:`Open the existing agent instruction file`},args:{agent:Y},run({args:e}){return q(({agentsService:t})=>t.openInstructionFile(e.agent))}}),br=e({meta:{name:`agents`,description:`Orchestrate Foundry instructions and skills for supported agents`},subCommands:{list:pr,skills:dr,instructions:e({meta:{name:`instructions`,description:`Manage the instruction assignment for an agent`},subCommands:{list:mr,assign:hr,enable:gr,disable:_r,reapply:vr,open:yr}})}}),xr=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 q(({instructionsService:t})=>t.create(Vt({name:e.name,content:e.content})))}}),Sr=e({meta:{name:`list`,description:`List instructions, newest first, as JSON`},run(){return q(({instructionsService:e})=>e.list())}}),Cr=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 q(({instructionsService:t})=>t.get(e.id))}}),wr=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 q(({instructionsService:t})=>t.update(e.id,Vt({name:e.name,content:e.content})))}}),Tr=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 q(({instructionsService:t})=>t.delete(e.id))}}),Er=e({meta:{name:`instructions`,description:`Create, read, edit, delete, and list Foundry instructions`},subCommands:{new:xr,list:Sr,get:Cr,edit:wr,delete:Tr}});function Dr(e){if(!kr(e)||!Array.isArray(e.targets))throw new Or(`targets must be an array`);if(e.targets.length===0)throw new Or(`Choose at least one target`);let t=e.targets.map(e=>{if(typeof e!=`string`||!$e.includes(e))throw new Or(`Invalid skill target`);return e});return{targets:t.filter((e,n)=>t.indexOf(e)===n)}}var Or=class extends Error{code=`INVALID_SKILL_INPUT`;constructor(e){super(e),this.name=`BundledSkillInputError`}};function kr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ar=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 q(async({dataExportService:t})=>{let n=await t.createExport(ar(e.passphrase)),r=Mr(e.output);return await Nr(n.contents,r,e.force),{filePath:r}})}}),jr=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 q(async({dataImportService:t})=>(await t.importData(r.resolve(e.file),ar(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 Nr(e,t,n){await ye(r.dirname(t),{recursive:!0,mode:448});let a=r.join(r.dirname(t),`.${r.basename(t)}.${y()}.tmp`);try{if(await Te(a,e,{mode:384}),i.platform!==`win32`&&await ge(a,384),n){await Ce(a,t);return}if(u(t))throw Pr(t);try{await ve(a,t)}catch(e){throw Fr(e)?Pr(t):e}}finally{await b(a,{force:!0})}}function Pr(e){return new J(`OUTPUT_EXISTS`,`Destination already exists: ${e}`)}function Fr(e){return e instanceof Error&&Reflect.get(e,`code`)===`EEXIST`}const X={"color-theme":{field:`theme`,values:Je},language:{field:`language`,values:Ye},"time-zone":{field:`timezone`,values:Ze},"time-format":{field:`timeFormat`,values:Xe}},Ir=[...Object.keys(X),`config-folder`],Lr=Object.entries(X).map(([e,{values:t}])=>`${e}: ${t.join(` | `)}`).join(`
|
|
11
|
+
`);function Rr(e){return{"color-theme":e.workspace.appearance[`color-theme`],...e.workspace[`language-region`],"config-folder":e.configFolder}}const zr=e({meta:{name:`get`,description:`Read all current settings, or one setting, as JSON`},args:{key:{type:`positional`,description:`Optional key: ${Ir.join(`, `)} (config-folder is read-only)`,required:!1}},run({args:e}){return q(({settingsService:t})=>{let n=Rr(t.read());if(e.key===void 0)return n;if(!Object.hasOwn(n,e.key))throw new J(`UNKNOWN_SETTING`,`Unknown setting. Available keys: ${Ir.join(`, `)}`);return n[e.key]})}}),Br=e({meta:{name:`set`,description:`Set one setting; --help lists allowed values`},args:{key:{type:`positional`,description:`Setting key: ${Object.keys(X).join(`, `)}`,required:!0},value:{type:`positional`,description:`Allowed values (quote values containing spaces):\n${Lr}`,required:!0}},run({args:e}){return q(({settingsService:t})=>{if(e.key===`config-folder`)throw new J(`READ_ONLY_SETTING`,`config-folder is read-only`);if(!Object.hasOwn(X,e.key))throw new J(`UNKNOWN_SETTING`,`Unknown setting. Editable keys: ${Object.keys(X).join(`, `)}`);let n=X[e.key];if(!n.values.includes(e.value))throw new J(`INVALID_SETTINGS_INPUT`,`Invalid ${e.key}. Allowed values: ${n.values.join(` | `)}`);let r=Rr(t.update(at({[n.field]:e.value})));return{key:e.key,value:r[e.key]}})}}),Vr=e({meta:{name:`open`,description:`Open the Foundry configuration folder`},run(){return q(({settingsService:e})=>e.openConfigFolder())}}),Hr=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 q(({settingsSkillCopyService:t})=>{let n=Dr({targets:e.target.split(`,`).map(e=>e.trim().replace(/^\./u,``))});return t.copyToTargets(n.targets)})}}),Ur=e({meta:{name:`settings`,description:`Manage Foundry settings; use set --help for allowed values`},subCommands:{get:zr,set:Br,"config-folder":e({meta:{name:`config-folder`,description:`Configuration folder actions`},subCommands:{open:Vr}}),export:Ar,import:jr,"download-skill":Hr}}),Wr={type:`positional`,description:`Current skill name`,required:!0},Gr=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 q(({skillsService:t})=>t.create({name:e.name,description:e.description}))}}),Kr=e({meta:{name:`skills`,description:`Manage skills in the Foundry library`},subCommands:{list:e({meta:{name:`list`,description:`List all skill names and descriptions as JSON`},run(){return q(({skillsService:e})=>e.list().map(({name:e,description:t})=>({name:e,description:t})))}}),get:e({meta:{name:`get`,description:`Read skill metadata and the complete nested files tree as JSON`},args:{skill:Wr},run({args:e}){return q(({skillsService:t})=>t.detail(e.skill))}}),save:e({meta:{name:`save`,description:`Replace the complete skill files tree; omitted entries are deleted and metadata is preserved`},args:{skill:Wr,file:{type:`string`,description:`JSON file containing { files }, or - for stdin. Accepts get output; only files is applied. SKILL.md is required; its content excludes frontmatter. Null content preserves existing opaque files.`,valueHint:`path|-`,required:!0}},run({args:e}){return q(({skillsService:t})=>{if(e.file===`-`&&i.stdin.isTTY)throw new U(`Pipe JSON to stdin or provide a JSON file with --file`);let n=m(e.file===`-`?0:r.resolve(e.file),`utf8`),a;try{a=JSON.parse(n)}catch{throw new U(`Skill files input must be valid JSON`)}let o=Vn(a);return t.saveFiles(e.skill,o.files)})}}),edit:e({meta:{name:`edit`,description:`Update skill metadata and refresh links in assigned agent skill directories`},args:{skill:{type:`positional`,description:`Current skill name`,required:!0},name:{type:`string`,description:`New unique skill name`,required:!0},description:{type:`string`,description:`New description (1–1024 characters)`,required:!0}},run({args:e}){return q(({skillsService:t})=>t.update(e.skill,{name:e.name,description:e.description}))}}),delete:e({meta:{name:`delete`,description:`Delete a skill and its files, and unlink matching registered agent entries`},args:{skill:{type:`positional`,description:`Skill name to permanently delete`,required:!0}},run({args:e}){return q(({skillsService:t})=>t.delete(e.skill))}}),create:e({meta:{name:`create`,description:`Create a skill using the selected source`},subCommands:{manual:Gr}})}});function qr(e){let t=new C;return t.get(`/`,t=>t.json(e.list())),t.put(`/:id/instructions`,async t=>{try{let n=ze(await Jr(t));return t.json(e.updateInstructions(t.req.param(`id`),n.instructionIds))}catch(e){return Yr(t,e)}}),t.put(`/:id/enabled`,async t=>{try{let n=Be(await Jr(t));return t.json(e.setEnabled(t.req.param(`id`),n.enabled))}catch(e){return Yr(t,e)}}),t.post(`/:id/reapply`,t=>{try{return t.json(e.reapply(t.req.param(`id`)))}catch(e){return Yr(t,e)}}),t.post(`/:id/open-file`,t=>{try{return t.json(e.openInstructionFile(t.req.param(`id`)))}catch(e){return Yr(t,e)}}),t}async function Jr(e){try{return await e.req.json()}catch{throw new w(`INVALID_AGENT_INPUT`,`Request body must be valid JSON`,400)}}function Yr(e,t){if(t instanceof w)return e.json({error:{code:t.code,message:t.message}},t.status);throw t}function Xr(e){let t=new C;return t.get(`/`,t=>t.json(e.list())),t.get(`/:id`,t=>{try{return t.json(e.get(t.req.param(`id`)))}catch(e){return Qr(t,e)}}),t.post(`/`,async t=>{try{let n=e.create(Vt(await Zr(t)));return t.json(n,201)}catch(e){return Qr(t,e)}}),t.put(`/:id`,async t=>{try{let n=Vt(await Zr(t));return t.json(e.update(t.req.param(`id`),n))}catch(e){return Qr(t,e)}}),t.delete(`/:id`,t=>{try{return e.delete(t.req.param(`id`)),t.body(null,204)}catch(e){return Qr(t,e)}}),t}async function Zr(e){try{return await e.req.json()}catch{throw new N(`Request body must be valid JSON`)}}function Qr(e,t){if(t instanceof N)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Bt)return e.json({error:{code:t.code,message:t.message}},404);throw t}const $r=[`openai-responses`,`anthropic-messages`,`openai-compatible-chat-completions`],ei=[`active`,`disabled`,`deleted`];var Z=class extends Error{code=`INVALID_PROVIDER_INPUT`;constructor(e){super(e),this.name=`ProviderInputError`}};function ti(e){if(!ci(e))throw new Z(`Provider input must be an object`);let t=Q(e.name,`name`),n=oi(e.protocol),r=si(e.baseURL),i=e.apiKey===void 0?``:Q(e.apiKey,`apiKey`,{allowEmpty:!0}),a=ai(e.customModels);return{...e.avatar!==void 0&&{avatar:ni(e.avatar)},name:t,protocol:n,baseURL:r,apiKey:i,customModels:a}}function ni(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 Z(`avatar must be a base64 PNG, JPEG, GIF, WebP, or SVG data URL up to 2 MB, or null`)}function ri(e){if(!ci(e))throw new Z(`Provider connection must be an object`);return{protocol:oi(e.protocol),baseURL:si(e.baseURL),apiKey:e.apiKey===void 0?``:Q(e.apiKey,`apiKey`,{allowEmpty:!0})}}function ii(e){if(typeof e!=`string`||!ei.includes(e))throw new Z(`Invalid provider status`);return e}function ai(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Z(`customModels must be an array`);return e.map(e=>{if(!ci(e))throw new Z(`Each custom model must be an object`);return{id:Q(e.id,`customModels.id`),displayName:e.displayName===null||e.displayName===void 0?null:Q(e.displayName,`customModels.displayName`)}})}function oi(e){if(typeof e!=`string`||!$r.includes(e))throw new Z(`Invalid provider protocol`);return e}function si(e){let t=Q(e,`baseURL`);try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`Unsupported URL protocol`)}catch{throw new Z(`baseURL must be a valid HTTP or HTTPS URL`)}return t}function Q(e,t,{allowEmpty:n=!1}={}){if(typeof e!=`string`)throw new Z(`${t} must be a string`);let r=e.trim();if(!n&&r.length===0)throw new Z(`${t} is required`);return r}function ci(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $=class extends Error{code=`PROVIDER_MODELS_FAILED`;constructor(e){super(e),this.name=`ProviderModelsError`}};async function li(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(ui(e.baseURL),{headers:n,signal:AbortSignal.timeout(15e3)})}catch(e){throw new $(`Unable to reach provider: ${e instanceof Error?e.message:`Unknown network error`}`)}if(!r.ok)throw new $(`Provider returned HTTP ${r.status}`);let i;try{i=await r.json()}catch{throw new $(`Provider returned invalid JSON`)}return di(i)}function ui(e){let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/u,``)}/models`,t.href}function di(e){if(!pi(e)||!Array.isArray(e.data))throw new $(`Provider response does not contain a model list`);return e.data.map(e=>{if(!pi(e)||typeof e.id!=`string`||e.id.length===0)throw new $(`Provider returned an invalid model entry`);let t=fi(e);return t?{id:e.id,displayName:t}:{id:e.id}})}function fi(e){return typeof e.display_name==`string`?e.display_name:typeof e.name==`string`?e.name:void 0}function pi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var mi=class extends Error{code=`PROVIDER_NOT_FOUND`;constructor(){super(`Provider not found`),this.name=`ProviderNotFoundError`}},hi=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=>gi(e))}get(e){let t=this.storage.get(`providers`,e);return t?gi(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 mi;let r=Date.now(),i={id:t??y(),status:`active`,createdAt:r,deletedAt:null,...n,...e,avatar:e.avatar===void 0?n?.avatar??null:e.avatar,updatedAt:r};return this.storage.put(`providers`,i),gi(i)})}setStatus(e,t){return this.storage.transaction(()=>{let n=this.storage.get(`providers`,e);if(!n)throw new mi;let r=Date.now(),i={...n,status:t,deletedAt:t===`deleted`?r:null,updatedAt:r};return this.storage.put(`providers`,i),gi(i)})}};function gi(e){return{...e,avatar:e.avatar??null,status:e.status}}function _i(e,t=()=>{}){let n=new C;return n.get(`/`,t=>t.json(e.list())),n.get(`/:id`,t=>{let n=e.get(t.req.param(`id`));return n?t.json(n):t.json({error:{code:`PROVIDER_NOT_FOUND`,message:`Provider not found`}},404)}),n.get(`/:id/models`,async t=>{try{return t.json(await e.fetchModels(t.req.param(`id`)))}catch(e){return yi(t,e)}}),n.post(`/models`,async t=>{try{let n=ri(await vi(t));return t.json(await e.fetchModelsForConnection(n))}catch(e){return yi(t,e)}}),n.post(`/`,async n=>{try{let r=ti(await vi(n)),i=e.save(r);return t(),n.json(i,201)}catch(e){return yi(n,e)}}),n.put(`/:id`,async n=>{try{let r=ti(await vi(n)),i=e.save(r,n.req.param(`id`));return t(),n.json(i)}catch(e){return yi(n,e)}}),n.patch(`/:id/status`,async n=>{try{let r=await vi(n),i=ii(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 yi(n,e)}}),n}async function vi(e){try{return await e.req.json()}catch{throw new Z(`Request body must be valid JSON`)}}function yi(e,t){if(t instanceof Z)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof mi)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof $)return e.json({error:{code:t.code,message:t.message}},502);throw t}var bi=class{repository;constructor(e){this.repository=new hi(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 mi;return li(t)}fetchModelsForConnection(e){return li(e)}save(e,t){return this.repository.save(e,t)}setStatus(e,t){return this.repository.setStatus(e,t)}};function xi(e,t=()=>{},n=new _t){let r=new C;return r.get(`/`,t=>t.json(e.read())),r.patch(`/`,async n=>{try{let r=at(await Si(n)),i=e.update(r);return t({fields:Object.keys(r)}),n.json(i)}catch(e){return Ci(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=Dr(await Si(e));return e.json(await n.copyToTargets(t.targets))}catch(t){return Ci(e,t)}}),r.get(`/skill-copy`,e=>e.json(n.getTargets())),r}async function Si(e){try{return await e.req.json()}catch{throw new ct(`Request body must be valid JSON`)}}function Ci(e,t){if(t instanceof ct||t instanceof Or)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof vt)return e.json({error:{code:t.code,message:t.message}},t.code===`SKILL_NOT_FOUND`?404:500);throw t}function wi(e){let t=new C;return t.get(`/agents/assignments`,t=>t.json(e.assignments())),t.put(`/:name/agents/:id`,async t=>{try{let n=Un(await Ti(t));return t.json(e.setAssignment(t.req.param(`name`),t.req.param(`id`),n.assigned))}catch(e){return Ei(t,e)}}),t.get(`/`,t=>t.json(e.list())),t.get(`/:name`,t=>{try{return t.json(e.detail(t.req.param(`name`)))}catch(e){return Ei(t,e)}}),t.post(`/`,async t=>{try{let n=await Ti(t);return t.json(e.create(K(n)),201)}catch(e){return Ei(t,e)}}),t.put(`/:name`,async t=>{try{let n=await Ti(t);if(n&&typeof n==`object`&&`files`in n){let r=Vn(n);return t.json(e.saveFiles(t.req.param(`name`),r.files))}return t.json(e.update(t.req.param(`name`),K(n)))}catch(e){return Ei(t,e)}}),t.delete(`/:name`,t=>{try{return e.delete(t.req.param(`name`)),t.body(null,204)}catch(e){return Ei(t,e)}}),t}async function Ti(e){try{return await e.req.json()}catch{throw new U(`Request body must be valid JSON`)}}function Ei(e,t){if(t instanceof W)return e.json({error:{code:t.code,message:t.message}},t.status);if(t instanceof In)return e.json({error:{code:t.code,message:t.message}},404);if(t instanceof Ln)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof U)return e.json({error:{code:t.code,message:t.message}},400);if(t instanceof Wn)return e.json({error:{code:t.code,message:t.message}},409);if(t instanceof G)return e.json({error:{code:t.code,message:t.message}},404);throw t}function Di(e){let t=new C;return t.get(`/`,t=>Ie(t,async n=>{await Oi(n);let r=!1,{promise:i,resolve:a}=Promise.withResolvers(),o=()=>{r||(r=!0,a(void 0))},s=e.subscribe(e=>{r||ki(n,e)}),c=setInterval(()=>{r||Ai(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 Oi(e){return e.writeSSE({event:`ready`,data:JSON.stringify({version:1})})}function ki(e,t){return e.writeSSE({id:t.id,event:`foundry`,data:JSON.stringify(t)})}function Ai(e){return e.writeSSE({event:`heartbeat`,data:String(Date.now())})}var ji=class extends Error{code=`INVALID_EXPORT_INPUT`};function Mi(e){if(typeof e!=`object`||!e||!(`passphrase`in e)||typeof e.passphrase!=`string`||!e.passphrase)throw new ji(`A non-empty export passphrase is required`);return{passphrase:e.passphrase}}function Ni(e){let t=new C;return t.post(`/`,async t=>{try{let n;try{n=await t.req.json()}catch{throw new ji(`Request body must be valid JSON`)}let{passphrase:r}=Mi(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 ji?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 Pi(e,t){let n=new C;return n.post(`/`,async n=>{let i;try{if(n.req.header(`content-type`)?.split(`;`,1)[0].trim()!==`application/octet-stream`||!n.req.raw.body)throw new F(`INVALID_BACKUP`,`A backup file is required`);let a;try{a=decodeURIComponent(n.req.header(`x-foundry-passphrase`)??``)}catch{throw new F(`INVALID_PASSPHRASE`,`Invalid backup passphrase`)}if(!a)throw new F(`INVALID_PASSPHRASE`,`Enter the backup passphrase`);i=await be(r.join(de(),`foundry-import-upload-`));let o=r.join(i,`backup.foundry-backup`);await S(ke.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 F?n.json({error:{code:e.code,message:e.message}},e.code===`IMPORT_FAILED`?500:400):n.json({error:{code:`IMPORT_FAILED`,message:`Unable to import data`}},500)}finally{i&&await zt(i)}}),n}function Fi(e){return e===`/api`||e.startsWith(`/api/`)}function Ii(e,t={}){let n=new C,r=t.providerService??new bi(e),i=t.settingsService??new ht(e),a=t.settingsSkillCopyService??new _t,o=t.instructionsService??new Nn(e),s=t.agentsService??new Pn(e,o);return n.get(`/api/health`,t=>t.json({status:`ok`,version:Re,storage:{format:`json`,formatVersion:e.formatVersion}})),t.eventHub&&n.route(`/api/events`,Di(t.eventHub)),n.route(`/api/data-import`,Pi(t.dataImportService??new vn(e),()=>{t.eventHub?.publish(Qe,{fields:[`theme`,`language`,`timeFormat`,`timezone`]})})),n.route(`/api/data-export`,Ni(t.dataExportService??new sn(e))),n.route(`/api/agents`,qr(s)),n.route(`/api/skills`,wi(t.skillsService??new Xn(e))),n.route(`/api/instructions`,Xr(o)),n.route(`/api/providers`,_i(r,()=>{t.eventHub?.publish(`providers.changed`,{})})),n.route(`/api/settings`,xi(i,e=>{t.eventHub?.publish(Qe,e)},a)),n.notFound(e=>Fi(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),Fi(t.req.path)?t.json({error:{code:`INTERNAL_SERVER_ERROR`,message:`Internal server error`}},500):t.text(`Internal Server Error`,500))),n}function Li(e,t,n){let i=Ii(t,n),a=Fe({root:e});i.use(`*`,(e,t)=>Fi(e.req.path)?t():a(e,t));let o=Fe({root:e,path:`/index.html`});return i.get(`*`,(e,t)=>(e.req.header(`accept`)?.toLowerCase()??``).includes(`text/html`)&&!Fi(e.req.path)&&!e.req.path.startsWith(`/assets/`)&&r.posix.extname(e.req.path)===``?o(e,t):t()),i}function Ri(e,t){let n,r=se(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 zi=class{listeners=/* @__PURE__ */ new Set;publish(e,t){let n={version:1,id:y(),type:e,occurredAt:(/* @__PURE__ */ new Date()).toISOString(),data:t};for(let e of this.listeners)e(n);return n}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function Bi(e){let t=new zi,n=new sn(e),r=new vn(e),i=new Nn(e),a=new Pn(e,i),o=new bi(e),s=new ht(e),c=new _t,l=new Xn(e),u={agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l},d;return{services:u,apiOptions:{agentsService:a,dataExportService:n,dataImportService:r,instructionsService:i,providerService:o,settingsService:s,settingsSkillCopyService:c,skillsService:l,eventHub:t},start(){d??=Ri(e.path,()=>{t.publish(Qe,{fields:[]})})},stop(){d?.(),d=void 0}}}const{dirname:Vi,join:Hi,resolve:Ui}=r,Wi=Vi(Ee(import.meta.url));function Gi(){let e=[Ui(Wi,`web`),Ui(i.cwd(),`dist/web`)].find(e=>u(Hi(e,`index.html`)));if(!e)throw Error("Web UI assets not found in dist/web. Run `pnpm build` before starting Foundry.");return e}function Ki({storage:e,webRoot:t=Gi(),onListening:n}){let r=Bi(e),a=Li(t,e,r.apiOptions);r.start();let o=Pe({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 qi(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 Ji(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 Yi=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 qi(`127.0.0.1`,11111)}catch(e){Xi(e);return}Ki({storage:ir(),onListening({url:t}){console.info(`Foundry is running at ${t}`),e.open&&Ji(t)}})}});function Xi(e){console.error(JSON.stringify({error:{code:`WEB_START_FAILED`,message:e instanceof Error?e.message:String(e)}},null,2)),i.exitCode=1}function Zi(){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, instructions, and skills or start the Web UI`},default:`help`,subCommands:{help:r,web:Yi,settings:Ur,instructions:Er,agents:br,skills:Kr}}),t}t(Zi());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 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.
|
|
3
|
+
description: Operate the local Foundry workbench through its installed CLI. Use when a task asks to list, read, create, edit, delete, or assign 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,7 +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
|
-
-
|
|
16
|
+
- List, read, create, edit Skill metadata and files, delete, or assign Skills.
|
|
17
17
|
- Make ChatGPT or Claude Code follow selected instructions.
|
|
18
18
|
- Reorder, enable, disable, or reapply an agent's instruction set.
|
|
19
19
|
- Read or change appearance, language, time zone, or time format.
|
|
@@ -32,7 +32,8 @@ the command details, output shapes, failure modes, and end-to-end examples.
|
|
|
32
32
|
| Need | CLI entry point | Reference |
|
|
33
33
|
| --- | --- | --- |
|
|
34
34
|
| Create, read, edit, delete, or list reusable Markdown instructions | `foundry instructions` | [Instructions](references/instructions.md) |
|
|
35
|
-
|
|
|
35
|
+
| List, read, create, edit metadata or files, or delete a Skill | `foundry skills` | [Skills](references/skills.md) |
|
|
36
|
+
| Inspect, assign, or unassign an agent's Skills | `foundry agents skills` | [Skill assignments](references/skills.md#external-symbolic-links) |
|
|
36
37
|
| Inspect, assign, enable, disable, or reapply instructions for an agent | `foundry agents instructions` | [Agents](references/agents.md) |
|
|
37
38
|
| Inspect supported agents and raw assignment state | `foundry agents list` | [Agents](references/agents.md) |
|
|
38
39
|
| Read or change application preferences | `foundry settings get/set` | [Settings](references/settings.md) |
|
|
@@ -49,7 +50,7 @@ Instructions, agent assignments, and agent files are three separate layers:
|
|
|
49
50
|
|
|
|
50
51
|
| assign: choose IDs and order
|
|
51
52
|
v
|
|
52
|
-
<home>/.foundry/agents/<
|
|
53
|
+
<home>/.foundry/agents/<agent-id>.json
|
|
53
54
|
|
|
|
54
55
|
| enable: write the managed block
|
|
55
56
|
v
|
|
@@ -186,7 +187,7 @@ foundry settings set language zh-CN
|
|
|
186
187
|
| `<home>/.foundry/settings.json` | Normalized application settings |
|
|
187
188
|
| `<home>/.foundry/instructions/<id>.md` | One Markdown instruction per file |
|
|
188
189
|
| `<home>/.foundry/skill/<name>/SKILL.md` | One skill directory with YAML metadata and a Markdown body |
|
|
189
|
-
| `<home>/.foundry/agents/<
|
|
190
|
+
| `<home>/.foundry/agents/<agent-id>.json` | Assignment order and enabled state per agent |
|
|
190
191
|
| `~/.codex/AGENTS.md` | ChatGPT instruction file managed by Foundry |
|
|
191
192
|
| `~/.claude/CLAUDE.md` | Claude Code instruction file managed by Foundry |
|
|
192
193
|
| `<home>/.agents/skills/foundry` | Installed Skill for `.agents` targets |
|
|
@@ -206,7 +207,7 @@ foundry web
|
|
|
206
207
|
Use `--no-open` to start the same local server without opening a browser. It
|
|
207
208
|
prints the URL and serves the UI on port `11111`. Instructions, Skills, and
|
|
208
209
|
Settings are the implemented Web features. Skills supports manual creation and
|
|
209
|
-
|
|
210
|
+
body editing at `#/library/skills`; see [Skills](references/skills.md).
|
|
210
211
|
The Instructions page is at
|
|
211
212
|
`#/library/instructions` and supports creation, direct source editing, and
|
|
212
213
|
agent assignment. Each instruction row exposes Edit and Delete through its
|
|
@@ -20,6 +20,9 @@ Use this reference when the task is to inspect agent state, assign or reorder
|
|
|
20
20
|
instructions, turn instruction writing on or off, recover a managed block, or
|
|
21
21
|
open an agent's instruction file. Read [Instructions](instructions.md) first
|
|
22
22
|
when the needed instruction does not exist yet.
|
|
23
|
+
For Skill distribution, use `foundry agents skills list/assign/unassign`;
|
|
24
|
+
see [Skill assignments](skills.md#external-symbolic-links) for command arguments,
|
|
25
|
+
persisted state, and symlink behavior.
|
|
23
26
|
|
|
24
27
|
## Supported agents
|
|
25
28
|
|
|
@@ -237,7 +240,7 @@ the Markdown body.
|
|
|
237
240
|
Each agent has one JSON profile:
|
|
238
241
|
|
|
239
242
|
```text
|
|
240
|
-
<home>/.foundry/agents/<
|
|
243
|
+
<home>/.foundry/agents/<agent-id>.json
|
|
241
244
|
```
|
|
242
245
|
|
|
243
246
|
The profile keeps the stable agent ID at the top level and instruction state in
|
|
@@ -255,6 +258,10 @@ an `instructions` namespace:
|
|
|
255
258
|
}
|
|
256
259
|
```
|
|
257
260
|
|
|
261
|
+
The `skills` sibling namespace stores `skillNames` and its own timestamps;
|
|
262
|
+
see [Skill assignments](skills.md#external-symbolic-links). Legacy hashed
|
|
263
|
+
profile filenames migrate transactionally to `<agent-id>.json`.
|
|
264
|
+
|
|
258
265
|
Read it through `foundry agents list` or
|
|
259
266
|
`foundry agents instructions list`; use the CLI for writes. Timestamps are Unix
|
|
260
267
|
epoch milliseconds, not ISO strings.
|