@dhzh/foundry 1.4.0 → 1.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 +32 -10
- package/dist/app/index.html +1 -1
- package/dist/app/static/css/index.f4c40968ed.css +2 -0
- package/dist/app/static/js/110.f18ecb6e71.js +2 -0
- package/dist/app/static/js/index.c5443edcce.js +1 -0
- package/dist/app/static/js/{lib-router.c327fb621e.js → lib-router.440ec6193a.js} +3 -3
- package/dist/cli.mjs +10 -10
- package/dist/index.mjs +1 -1
- package/dist/migrations/0004_neat_vulcan.sql +18 -0
- package/dist/migrations/meta/0004_snapshot.json +402 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/package-DS5RZ0CH.mjs +2 -0
- package/package.json +1 -1
- package/dist/app/static/css/index.608f829ba2.css +0 -2
- package/dist/app/static/js/293.20c8fa0618.js +0 -2
- package/dist/app/static/js/index.37bf97044c.js +0 -1
- package/dist/package-BRv6jbgV.mjs +0 -2
- /package/dist/app/static/js/{293.20c8fa0618.js.LICENSE.txt → 110.f18ecb6e71.js.LICENSE.txt} +0 -0
- /package/dist/app/static/js/{lib-router.c327fb621e.js.LICENSE.txt → lib-router.440ec6193a.js.LICENSE.txt} +0 -0
package/dist/cli.mjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"./package-BRv6jbgV.mjs";import{defineCommand as t,renderUsage as n,runMain as r}from"citty";import i from"node:process";import a from"open";import{serve as o}from"@hono/node-server";import{serveStatic as s}from"@hono/node-server/serve-static";import{zValidator as c}from"@hono/zod-validator";import{constants as l,existsSync as u}from"node:fs";import d from"node:path";import{Hono as f}from"hono";import{z as p}from"zod";import{Uint8ArrayReader as m,Uint8ArrayWriter as h,ZipReader as ee,ZipWriter as te}from"@zip.js/zip.js";import{createHash as g,randomUUID as ne,randomUUIDv7 as re}from"node:crypto";import{bodyLimit as ie}from"hono/body-limit";import{TextDecoder as ae,promisify as oe}from"node:util";import{Buffer as se}from"node:buffer";import ce from"better-sqlite3";import{drizzle as le}from"drizzle-orm/better-sqlite3";import{access as ue,chmod as de,lstat as fe,mkdir as _,readFile as pe,readdir as me,realpath as he,rename as ge,rm as v,stat as _e,writeFile as ve}from"node:fs/promises";import{readMigrationFiles as ye}from"drizzle-orm/migrator";import be from"env-paths";import{homedir as xe}from"node:os";import{and as y,desc as Se,eq as b,isNull as x,sql as S}from"drizzle-orm";import{blob as Ce,check as C,index as we,integer as w,sqliteTable as T,text as E,uniqueIndex as Te}from"drizzle-orm/sqlite-core";import{parse as Ee,patch as De,stringify as Oe}from"@decimalturn/toml-patch";import{execFile as ke}from"node:child_process";var Ae=Object.defineProperty,je=(e,t)=>{let n={};for(var r in e)Ae(n,r,{get:e[r],enumerable:!0});return t||Ae(n,Symbol.toStringTag,{value:`Module`}),n};const D={providerConnectionFailed:`PROVIDER_CONNECTION_FAILED`,providerInUse:`PROVIDER_IN_USE`,providerNotFound:`PROVIDER_NOT_FOUND`,runtimeApplyFailed:`RUNTIME_APPLY_FAILED`,runtimeConfigurationChanged:`RUNTIME_CONFIGURATION_CHANGED`,runtimeConfigurationInvalid:`RUNTIME_CONFIGURATION_INVALID`,runtimeNotDetected:`RUNTIME_NOT_DETECTED`,success:`SUCCESS`},O=[`system`,`light`,`dark`],Me=`foundry-export-v1`,Ne=[`settings`,`providers`],k=[`codex`,`claude-code`],Pe=[`image/png`,`image/jpeg`,`image/webp`,`image/svg+xml`],Fe=[`authorization`,`x-api-key`],Ie=[`effort`,`xhigh_effort`,`max_effort`,`thinking`,`adaptive_thinking`,`interleaved_thinking`],Le=p.strictObject({});function Re(e,t){e.get(`/api/data/export`,c(`query`,Le),async()=>{let e=await t.createExport();return new Response(e.content,{headers:{"cache-control":`no-store`,"content-disposition":`attachment; filename="${e.filename}"`,"content-length":String(e.content.byteLength),"content-type":`application/octet-stream`,"x-content-type-options":`nosniff`}})})}const ze=new TextEncoder;function A(e){return String(e).padStart(2,`0`)}function Be(e){let t={avatar:e.avatar,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark};return e.runtime,{...t,configuration:e.configuration,runtime:e.runtime}}function Ve(e,t,n,r){let i=ze.encode(JSON.stringify(r));return{content:i,manifest:{id:e,mediaType:`application/json`,overwrite:n,path:t,sha256:g(`sha256`).update(i).digest(`hex`),size:i.byteLength}}}function He(e){return`foundry-export-${[e.getFullYear(),`-`,A(e.getMonth()+1),`-`,A(e.getDate()),`T`,A(e.getHours()),A(e.getMinutes()),A(e.getSeconds())].join(``)}.foundry`}var Ue=class{providerStore;settingsStore;now;foundryVersion;constructor(t,n,r=()=>new Date,i=e){this.providerStore=t,this.settingsStore=n,this.now=r,this.foundryVersion=i}async createExport(){let e=this.now(),t=this.settingsStore.getApplicationSettings(),n=k.flatMap(e=>this.providerStore.listProviders(e).map(e=>Be(e))),r=[Ve(`settings`,`modules/settings.json`,!0,t),Ve(`providers`,`modules/providers.json`,!1,n)],i={createdAt:e.toISOString(),format:Me,foundryVersion:this.foundryVersion,modules:r.map(e=>e.manifest)},a=new te(new h),o=JSON.stringify(i),s=ze.encode(o);await a.add(`manifest.json`,new m(s));for(let e of r)await a.add(e.manifest.path,new m(e.content));return{content:await a.close(),filename:He(e),manifest:i}}};const We=/^[A-Za-z0-9+/]+={0,2}$/u;function Ge(e,t){for(let n of e){let e=n.codePointAt(0)??0,r=t&&[9,10,13].includes(e);if(e===127||!r&&e<32)return!0}return!1}function j(e){return p.string().trim().max(e).refine(e=>!Ge(e,!0),{message:`Control characters are not allowed.`})}function M(e){return j(e).nullable().transform(e=>e===``?null:e)}function Ke(e,t){try{let n=new URL(e);return[`http:`,`https:`].includes(n.protocol)&&n.username===``&&n.password===``&&(t||n.search===``&&n.hash===``)}catch{return!1}}const qe=j(2048).min(1).refine(e=>Ke(e,!1),{message:`Provide an HTTP or HTTPS URL without credentials, a query, or a fragment.`}),Je=M(2048).refine(e=>e===null||Ke(e,!0),{message:`Provide an HTTP or HTTPS URL without credentials.`}),Ye=j(100).min(1),Xe=M(100),Ze=M(2e3),N=j(200).min(1),Qe=M(200),$e=M(2e3),et=p.string().min(1).max(16384).refine(e=>!Ge(e,!1),{message:`Control characters are not allowed.`}),tt=p.union([et,p.literal(``),p.null()]).transform(e=>e===``?null:e);function nt(e,t){if(e===`image/png`)return[137,80,78,71,13,10,26,10].every((e,n)=>t[n]===e);if(e===`image/jpeg`)return t[0]===255&&t[1]===216&&t[2]===255;if(e===`image/svg+xml`)try{let e=new ae(`utf-8`,{fatal:!0}).decode(t);return/^\s*(?:(?:<\?xml[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[\s\S]*?>)\s*)*<svg(?:\s|>)/u.test(e)}catch{return!1}return t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80}const rt=p.strictObject({data:p.string().min(1).max(2796204),mimeType:p.enum(Pe)}).superRefine((e,t)=>{if(!We.test(e.data)){t.addIssue({code:`custom`,message:`Avatar data must be valid Base64.`});return}let n=se.from(e.data,`base64`);(n.byteLength===0||n.byteLength>2097152||n.toString(`base64`)!==e.data||!nt(e.mimeType,n))&&t.addIssue({code:`custom`,message:`Avatar data must be a valid PNG, JPEG, WebP, or SVG image no larger than 2 MB.`})}),it=p.array(p.enum(Ie)).max(Ie.length).refine(e=>new Set(e).size===e.length,{message:`Model capabilities must be unique.`}),P=p.strictObject({description:Ze,displayName:Xe,model:N,supportedCapabilities:it}),at=p.union([N,P.transform(e=>e.model)]),ot=p.strictObject({apiKey:tt,baseUrl:qe,defaultModel:N,protocol:p.literal(`responses`),reviewModel:Qe}),st=p.strictObject({apiKey:et,apiKeyHeader:p.enum(Fe),baseUrl:qe,fableModel:P.nullable(),haikuModel:P.nullable(),opusModel:P.nullable(),defaultModel:at,protocol:p.literal(`messages`),sonnetModel:P.nullable(),subagentModel:Qe,subagentModelForce:p.boolean().default(!1),hideAiAttribution:p.boolean().default(!1),teammatesMode:p.boolean().default(!1),enableToolSearch:p.boolean().default(!1),maxEffortThinking:p.boolean().default(!1),disableAutoUpdater:p.boolean().default(!1)}),ct={avatar:rt.nullable(),name:Ye,officialWebsite:Je,remark:$e},F=p.discriminatedUnion(`runtime`,[p.strictObject({...ct,configuration:ot,runtime:p.literal(`codex`)}),p.strictObject({...ct,configuration:st,runtime:p.literal(`claude-code`)})]),I=p.strictObject({providerId:p.string().min(1)}),lt=p.strictObject({runtime:p.enum(k)});function L(e){return F.parse(e)}function ut(e){return ot.parse(e)}function dt(e){return st.parse(e)}function ft(e){return e===null?null:se.from(rt.parse(e).data,`base64`)}const pt=new ae(`utf-8`,{fatal:!0}),mt=p.string().regex(/^[a-f0-9]{64}$/u),ht=p.strictObject({id:p.string().min(1).max(100).regex(/^[a-z][a-z0-9-]*$/u),mediaType:p.string().min(1).max(100),overwrite:p.boolean(),path:p.string().min(1).max(512),sha256:mt,size:p.number().int().nonnegative().max(2**53-1)}),gt=p.strictObject({createdAt:p.string().min(1).max(64).refine(e=>!Number.isNaN(Date.parse(e))),format:p.literal(Me),foundryVersion:p.string().min(1).max(100),modules:p.array(ht).max(256)}).superRefine((e,t)=>{let n=new Set,r=new Set;for(let[i,a]of e.modules.entries())n.has(a.id)&&t.addIssue({code:`custom`,message:`Export Module identifiers must be unique.`,path:[`modules`,i,`id`]}),r.has(a.path)&&t.addIssue({code:`custom`,message:`Export Module paths must be unique.`,path:[`modules`,i,`path`]}),n.add(a.id),r.add(a.path)}),_t=p.strictObject({colorMode:p.enum(O)}),vt=p.array(F);var R=class extends Error{constructor(e){super(`The selected file is not a valid Foundry Export.`,{cause:e}),this.name=`FoundryImportFileError`}};function yt(e){return Ne.includes(e)}function bt(e,t){let n=e.find(e=>e.filename===t);if(!n||n.directory||n.encrypted||n.symlink)throw Error(`The Export Module entry is unavailable.`);return n}async function xt(e,t){if(e.uncompressedSize>t)throw Error(`The archive entry is too large.`);let n=await e.getData(new h);if(n.byteLength>t)throw Error(`The archive entry is too large.`);return JSON.parse(pt.decode(n))}async function St(e){try{let t=gt.parse(await xt(bt(e,`manifest.json`),1048576)),n=new Set([`manifest.json`,...t.modules.map(e=>e.path)]),r=e.some(e=>!e.directory&&!n.has(e.filename)),i=new Set(t.modules.map(e=>e.id));if(r||Ne.some(e=>!i.has(e)))throw Error(`The Foundry Export package is incomplete.`);return t}catch(e){throw new R(e)}}async function Ct(e,t){if(e.mediaType!==`application/json`||e.size>268435456)throw Error(`The Export Module metadata is invalid.`);let n=bt(t,e.path);if(n.uncompressedSize!==e.size)throw Error(`The Export Module size does not match its manifest.`);let r=await n.getData(new h),i=g(`sha256`).update(r).digest(`hex`);if(r.byteLength!==e.size||i!==e.sha256)throw Error(`The Export Module does not match its manifest.`);return JSON.parse(pt.decode(r))}function wt(e){return{id:e,importedItems:0,message:`${e===`settings`?`Application Settings`:`Providers`} could not be imported.`,status:`failed`}}var Tt=class{providerStore;settingsStore;constructor(e,t){this.providerStore=e,this.settingsStore=t}async importData(e){if(e.byteLength===0)throw new R;let t=new ee(new m(e),{checkCrc32:!0,filenameValidation:`strict`,maxAppendedDataSize:0,strictness:`strict`});try{let e;try{e=await t.getEntries()}catch(e){throw new R(e)}if(e.length>256)throw new R;let n=await St(e),r=[];for(let t of n.modules){if(!yt(t.id)){r.push({id:t.id,importedItems:0,message:`This Export Module is not supported by this Foundry version.`,status:`unsupported`});continue}try{let n=await Ct(t,e);if(t.id===`settings`){if(!t.overwrite)throw Error(`Application Settings must use overwrite import behavior.`);this.settingsStore.updateApplicationSettings(_t.parse(n)),r.push({id:t.id,importedItems:1,status:`imported`})}else{if(t.overwrite)throw Error(`Providers must use append import behavior.`);let e=vt.parse(n);this.providerStore.createProviders(e),r.push({id:t.id,importedItems:e.length,status:`imported`})}}catch{r.push(wt(t.id))}}return{modules:r}}finally{await t.close()}}};const Et=p.strictObject({});function Dt(e,t){e.post(`/api/data/import`,c(`query`,Et),ie({maxSize:268435456}),async e=>{try{let n=await t.importData(new Uint8Array(await e.req.arrayBuffer()));return e.json({status:D.success,data:n})}catch(t){if(t instanceof R)return e.json({message:t.message},400);throw t}})}function z(e){return{avatar:e.avatar,baseUrl:e.configuration.baseUrl,id:e.id,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark,runtime:e.runtime}}function Ot(e,t,n){e.get(`/api/providers`,c(`query`,lt),e=>e.json({status:D.success,data:t.listProviders(e.req.valid(`query`).runtime).map(e=>z(e))})),e.delete(`/api/providers/:providerId`,c(`param`,I),e=>{let n=t.deleteProvider(e.req.valid(`param`).providerId);return n===`in-use`?e.json({status:D.providerInUse,data:!1,message:`A Provider in use cannot be deleted.`}):n===`not-found`?e.json({status:D.providerNotFound,data:!1,message:`The selected Provider is unavailable.`}):e.json({status:D.success,data:!0})}),e.post(`/api/providers/:providerId/test-connection`,c(`param`,I),async e=>{let r=t.getProvider(e.req.valid(`param`).providerId);if(r===null)return e.json({status:D.providerNotFound,data:!1,message:`The selected Provider is unavailable.`});let i=await n.testProvider(r);return i.successful?e.json({status:D.success,data:!0}):e.json({status:D.providerConnectionFailed,data:!1,message:i.message})}),e.post(`/api/providers`,c(`json`,F),e=>{let n=e.req.valid(`json`),r=z(t.createProvider(n));return e.json({status:D.success,data:r},201)}),e.get(`/api/providers/:providerId`,c(`param`,I),e=>{let n=t.getProvider(e.req.valid(`param`).providerId);return n===null?e.json({status:D.providerNotFound,data:null,message:`The selected Provider is unavailable.`}):e.json({status:D.success,data:n})}),e.post(`/api/providers/:providerId/copy`,c(`param`,I),c(`json`,F),e=>{let n=e.req.valid(`param`).providerId,r=t.getProvider(n);if(r===null)return e.json({status:D.providerNotFound,data:null,message:`The selected Provider is unavailable.`});let i=e.req.valid(`json`);if(i.runtime!==r.runtime)return e.json({message:`A Provider Runtime cannot be changed.`},400);let a=t.copyProvider(n,i);return a===null?e.json({status:D.providerNotFound,data:null,message:`The selected Provider is unavailable.`}):e.json({status:D.success,data:z(a)},201)}),e.put(`/api/providers/:providerId`,c(`param`,I),c(`json`,F),e=>{let n=e.req.valid(`param`).providerId,r=t.getProvider(n);if(r===null)return e.json({status:D.providerNotFound,data:null,message:`The selected Provider is unavailable.`});let i=e.req.valid(`json`);if(i.runtime!==r.runtime)return e.json({message:`A Provider Runtime cannot be changed.`},400);let a=t.updateProvider(n,i);return e.json({status:D.success,data:a===null?null:z(a)})})}var B=class extends Error{status;constructor(e,t){super(t),this.status=e}};const kt=p.discriminatedUnion(`kind`,[p.strictObject({kind:p.literal(`official-default`)}),p.strictObject({kind:p.literal(`provider`),providerId:p.string().min(1)})]),At=p.strictObject({runtime:p.enum(k)}),jt=p.strictObject({}),Mt=p.strictObject({providerKey:p.string().min(1).max(200).optional(),target:kt}),Nt=p.strictObject({expectedFileHash:p.string().regex(/^[0-9a-f]{64}$/),providerKey:p.string().min(1).max(200).optional(),target:kt});function Pt(e,t){e.get(`/api/runtimes`,c(`query`,jt),async e=>e.json({status:D.success,data:await t.listRuntimes()})),e.post(`/api/runtimes/:runtime/preview`,c(`param`,At),c(`json`,Mt),async e=>{try{return e.json({status:D.success,data:await t.previewConfiguration(e.req.valid(`param`).runtime,e.req.valid(`json`))})}catch(t){if(t instanceof B)return e.json({status:t.status,data:null,message:t.message});throw t}}),e.post(`/api/runtimes/:runtime/apply`,c(`param`,At),c(`json`,Nt),async e=>{try{return e.json({status:D.success,data:await t.applyConfiguration(e.req.valid(`param`).runtime,e.req.valid(`json`))})}catch(t){if(t instanceof B)return e.json({status:t.status,data:null,message:t.message});throw t}})}const Ft=p.strictObject({}),It=p.strictObject({colorMode:p.enum(O)});function Lt(e,t){e.get(`/api/settings`,c(`query`,Ft),e=>e.json({status:D.success,data:t.getApplicationSettings()})),e.patch(`/api/settings`,c(`json`,It),e=>e.json({status:D.success,data:t.updateApplicationSettings(e.req.valid(`json`))}))}const Rt=p.strictObject({});function zt(){return[d.resolve(import.meta.dirname,`app`),d.resolve(import.meta.dirname,`../../dist/app`)].find(e=>u(e))}function Bt(e){let t=new f;t.get(`/api/health`,c(`query`,Rt),e=>e.json({status:D.success,data:!0,message:`Service is healthy.`})),Re(t,new Ue(e.providerStore,e.settingsStore)),Dt(t,new Tt(e.providerStore,e.settingsStore)),Lt(t,e.settingsStore),Ot(t,e.providerStore,e.providerConnectionTester),Pt(t,e.runtimeService);let n=e.webRoot??zt();return n&&t.use(`*`,s({root:n})),t}const V=`__drizzle_migrations`;function Vt(e){return!!e.prepare(`
|
|
2
|
+
import{t as e}from"./package-DS5RZ0CH.mjs";import{defineCommand as t,renderUsage as n,runMain as r}from"citty";import i from"node:process";import a from"open";import{serve as o}from"@hono/node-server";import{serveStatic as s}from"@hono/node-server/serve-static";import{zValidator as c}from"@hono/zod-validator";import{constants as l,existsSync as u}from"node:fs";import d from"node:path";import{Hono as f}from"hono";import{z as p}from"zod";import{Uint8ArrayReader as m,Uint8ArrayWriter as h,ZipReader as ee,ZipWriter as te}from"@zip.js/zip.js";import{createHash as g,randomUUID as ne,randomUUIDv7 as _}from"node:crypto";import{bodyLimit as re}from"hono/body-limit";import{TextDecoder as ie,promisify as ae}from"node:util";import{Buffer as oe}from"node:buffer";import{and as v,desc as se,eq as y,isNull as b,sql as x}from"drizzle-orm";import{blob as ce,check as S,index as le,integer as C,sqliteTable as w,text as T,uniqueIndex as ue}from"drizzle-orm/sqlite-core";import de from"better-sqlite3";import{drizzle as fe}from"drizzle-orm/better-sqlite3";import{access as pe,chmod as me,lstat as he,mkdir as E,readFile as ge,readdir as _e,realpath as ve,rename as ye,rm as D,stat as be,writeFile as xe}from"node:fs/promises";import{readMigrationFiles as Se}from"drizzle-orm/migrator";import Ce from"env-paths";import{homedir as we}from"node:os";import{parse as Te,patch as Ee,stringify as De}from"@decimalturn/toml-patch";import{execFile as Oe}from"node:child_process";var ke=Object.defineProperty,Ae=(e,t)=>{let n={};for(var r in e)ke(n,r,{get:e[r],enumerable:!0});return t||ke(n,Symbol.toStringTag,{value:`Module`}),n};const O={promptNotFound:`PROMPT_NOT_FOUND`,providerConnectionFailed:`PROVIDER_CONNECTION_FAILED`,providerInUse:`PROVIDER_IN_USE`,providerNotFound:`PROVIDER_NOT_FOUND`,runtimeApplyFailed:`RUNTIME_APPLY_FAILED`,runtimeConfigurationChanged:`RUNTIME_CONFIGURATION_CHANGED`,runtimeConfigurationInvalid:`RUNTIME_CONFIGURATION_INVALID`,runtimeNotDetected:`RUNTIME_NOT_DETECTED`,success:`SUCCESS`},k=[`system`,`light`,`dark`],je=`foundry-export-v1`,Me=[`settings`,`providers`,`prompts`],A=[`codex`,`claude-code`],Ne=[`image/png`,`image/jpeg`,`image/webp`,`image/svg+xml`],Pe=[`authorization`,`x-api-key`],Fe=[`effort`,`xhigh_effort`,`max_effort`,`thinking`,`adaptive_thinking`,`interleaved_thinking`],Ie=p.strictObject({});function Le(e,t){e.get(`/api/data/export`,c(`query`,Ie),async()=>{let e=await t.createExport();return new Response(e.content,{headers:{"cache-control":`no-store`,"content-disposition":`attachment; filename="${e.filename}"`,"content-length":String(e.content.byteLength),"content-type":`application/octet-stream`,"x-content-type-options":`nosniff`}})})}const Re=new TextEncoder;function j(e){return String(e).padStart(2,`0`)}function ze(e){let t={avatar:e.avatar,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark};return e.runtime,{...t,configuration:e.configuration,runtime:e.runtime}}function M(e,t,n,r){let i=Re.encode(JSON.stringify(r));return{content:i,manifest:{id:e,mediaType:`application/json`,overwrite:n,path:t,sha256:g(`sha256`).update(i).digest(`hex`),size:i.byteLength}}}function Be(e){return`foundry-export-${[e.getFullYear(),`-`,j(e.getMonth()+1),`-`,j(e.getDate()),`T`,j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(``)}.foundry`}var Ve=class{promptStore;providerStore;settingsStore;now;foundryVersion;constructor(t,n,r,i=()=>new Date,a=e){this.promptStore=t,this.providerStore=n,this.settingsStore=r,this.now=i,this.foundryVersion=a}async createExport(){let e=this.now(),t=this.settingsStore.getApplicationSettings(),n=A.flatMap(e=>this.providerStore.listProviders(e).map(e=>ze(e))),r=this.promptStore.listAllPrompts().map(e=>({content:e.content,description:e.description,title:e.title})),i=[M(`settings`,`modules/settings.json`,!0,t),M(`providers`,`modules/providers.json`,!1,n),M(`prompts`,`modules/prompts.json`,!1,r)],a={createdAt:e.toISOString(),format:je,foundryVersion:this.foundryVersion,modules:i.map(e=>e.manifest)},o=new te(new h),s=JSON.stringify(a),c=Re.encode(s);await o.add(`manifest.json`,new m(c));for(let e of i)await o.add(e.manifest.path,new m(e.content));return{content:await o.close(),filename:Be(e),manifest:a}}};const He=/^[A-Za-z0-9+/]+={0,2}$/u;function Ue(e,t){for(let n of e){let e=n.codePointAt(0)??0,r=t&&[9,10,13].includes(e);if(e===127||!r&&e<32)return!0}return!1}function N(e){return p.string().trim().max(e).refine(e=>!Ue(e,!0),{message:`Control characters are not allowed.`})}function P(e){return N(e).nullable().transform(e=>e===``?null:e)}function We(e,t){try{let n=new URL(e);return[`http:`,`https:`].includes(n.protocol)&&n.username===``&&n.password===``&&(t||n.search===``&&n.hash===``)}catch{return!1}}const Ge=N(2048).min(1).refine(e=>We(e,!1),{message:`Provide an HTTP or HTTPS URL without credentials, a query, or a fragment.`}),Ke=P(2048).refine(e=>e===null||We(e,!0),{message:`Provide an HTTP or HTTPS URL without credentials.`}),qe=N(100).min(1),Je=P(100),Ye=P(2e3),F=N(200).min(1),Xe=P(200),Ze=P(2e3),Qe=p.string().min(1).max(16384).refine(e=>!Ue(e,!1),{message:`Control characters are not allowed.`}),$e=p.union([Qe,p.literal(``),p.null()]).transform(e=>e===``?null:e);function et(e,t){if(e===`image/png`)return[137,80,78,71,13,10,26,10].every((e,n)=>t[n]===e);if(e===`image/jpeg`)return t[0]===255&&t[1]===216&&t[2]===255;if(e===`image/svg+xml`)try{let e=new ie(`utf-8`,{fatal:!0}).decode(t);return/^\s*(?:(?:<\?xml[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[\s\S]*?>)\s*)*<svg(?:\s|>)/u.test(e)}catch{return!1}return t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80}const tt=p.strictObject({data:p.string().min(1).max(2796204),mimeType:p.enum(Ne)}).superRefine((e,t)=>{if(!He.test(e.data)){t.addIssue({code:`custom`,message:`Avatar data must be valid Base64.`});return}let n=oe.from(e.data,`base64`);(n.byteLength===0||n.byteLength>2097152||n.toString(`base64`)!==e.data||!et(e.mimeType,n))&&t.addIssue({code:`custom`,message:`Avatar data must be a valid PNG, JPEG, WebP, or SVG image no larger than 2 MB.`})}),nt=p.array(p.enum(Fe)).max(Fe.length).refine(e=>new Set(e).size===e.length,{message:`Model capabilities must be unique.`}),I=p.strictObject({description:Ye,displayName:Je,model:F,supportedCapabilities:nt}),rt=p.union([F,I.transform(e=>e.model)]),it=p.strictObject({apiKey:$e,baseUrl:Ge,defaultModel:F,protocol:p.literal(`responses`),reviewModel:Xe}),at=p.strictObject({apiKey:Qe,apiKeyHeader:p.enum(Pe),baseUrl:Ge,fableModel:I.nullable(),haikuModel:I.nullable(),opusModel:I.nullable(),defaultModel:rt,protocol:p.literal(`messages`),sonnetModel:I.nullable(),subagentModel:Xe,subagentModelForce:p.boolean().default(!1),hideAiAttribution:p.boolean().default(!1),teammatesMode:p.boolean().default(!1),enableToolSearch:p.boolean().default(!1),maxEffortThinking:p.boolean().default(!1),disableAutoUpdater:p.boolean().default(!1)}),ot={avatar:tt.nullable(),name:qe,officialWebsite:Ke,remark:Ze},L=p.discriminatedUnion(`runtime`,[p.strictObject({...ot,configuration:it,runtime:p.literal(`codex`)}),p.strictObject({...ot,configuration:at,runtime:p.literal(`claude-code`)})]),R=p.strictObject({providerId:p.string().min(1)}),st=p.strictObject({runtime:p.enum(A)});function ct(e){return L.parse(e)}function lt(e){return it.parse(e)}function ut(e){return at.parse(e)}function dt(e){return e===null?null:oe.from(tt.parse(e).data,`base64`)}const ft=new TextEncoder,pt=p.string().trim().min(1).max(100),mt=p.string().trim().max(2e3).nullable().transform(e=>e===``?null:e),ht=p.string().refine(e=>e.trim().length>0,{message:`Prompt content is required.`}).refine(e=>ft.encode(e).byteLength<=1048576,{message:`Prompt content must be no larger than 1 MiB.`}),z=p.strictObject({content:ht,description:mt,title:pt}),B=p.strictObject({promptId:p.string().min(1)}),gt=p.strictObject({query:p.string().trim().max(500).optional().default(``)});function _t(e){return e.normalize(`NFKC`).toLocaleLowerCase(`en-US`)}function vt(e){return z.parse(e)}const yt=new ie(`utf-8`,{fatal:!0}),bt=p.string().regex(/^[a-f0-9]{64}$/u),xt=p.strictObject({id:p.string().min(1).max(100).regex(/^[a-z][a-z0-9-]*$/u),mediaType:p.string().min(1).max(100),overwrite:p.boolean(),path:p.string().min(1).max(512),sha256:bt,size:p.number().int().nonnegative().max(2**53-1)}),St=p.strictObject({createdAt:p.string().min(1).max(64).refine(e=>!Number.isNaN(Date.parse(e))),format:p.literal(je),foundryVersion:p.string().min(1).max(100),modules:p.array(xt).max(256)}).superRefine((e,t)=>{let n=new Set,r=new Set;for(let[i,a]of e.modules.entries())n.has(a.id)&&t.addIssue({code:`custom`,message:`Export Module identifiers must be unique.`,path:[`modules`,i,`id`]}),r.has(a.path)&&t.addIssue({code:`custom`,message:`Export Module paths must be unique.`,path:[`modules`,i,`path`]}),n.add(a.id),r.add(a.path)}),Ct=p.strictObject({colorMode:p.enum(k)}),wt=p.array(L),Tt=z.extend({tags:p.array(p.string()).optional()}).transform(e=>({content:e.content,description:e.description,title:e.title})),Et=p.array(Tt),Dt=[`settings`,`providers`];var V=class extends Error{constructor(e){super(`The selected file is not a valid Foundry Export.`,{cause:e}),this.name=`FoundryImportFileError`}};function Ot(e){return Me.includes(e)}function kt(e,t){let n=e.find(e=>e.filename===t);if(!n||n.directory||n.encrypted||n.symlink)throw Error(`The Export Module entry is unavailable.`);return n}async function At(e,t){if(e.uncompressedSize>t)throw Error(`The archive entry is too large.`);let n=await e.getData(new h);if(n.byteLength>t)throw Error(`The archive entry is too large.`);return JSON.parse(yt.decode(n))}async function jt(e){try{let t=St.parse(await At(kt(e,`manifest.json`),1048576)),n=new Set([`manifest.json`,...t.modules.map(e=>e.path)]),r=e.some(e=>!e.directory&&!n.has(e.filename)),i=new Set(t.modules.map(e=>e.id));if(r||Dt.some(e=>!i.has(e)))throw Error(`The Foundry Export package is incomplete.`);return t}catch(e){throw new V(e)}}async function Mt(e,t){if(e.mediaType!==`application/json`||e.size>268435456)throw Error(`The Export Module metadata is invalid.`);let n=kt(t,e.path);if(n.uncompressedSize!==e.size)throw Error(`The Export Module size does not match its manifest.`);let r=await n.getData(new h),i=g(`sha256`).update(r).digest(`hex`);if(r.byteLength!==e.size||i!==e.sha256)throw Error(`The Export Module does not match its manifest.`);return JSON.parse(yt.decode(r))}async function Nt(e,t,n){let r=await Mt(t,n);if(e===`settings`){if(!t.overwrite)throw Error(`Application Settings must use overwrite import behavior.`);return{data:Ct.parse(r),id:e,itemCount:1}}if(e===`providers`){if(t.overwrite)throw Error(`Providers must use append import behavior.`);let n=wt.parse(r);return{data:n,id:e,itemCount:n.length}}if(t.overwrite)throw Error(`Prompts must use append import behavior.`);let i=Et.parse(r);return{data:i,id:e,itemCount:i.length}}function Pt(e){return{id:e.id,itemCount:null,message:`This Export Module is not supported by this Foundry version.`,overwrite:e.overwrite,status:`unsupported`}}function Ft(e){return{id:e.id,itemCount:null,message:`This Export Module is invalid and cannot be imported.`,overwrite:e.overwrite,status:`invalid`}}function It(e){return{id:e,importedItems:0,message:`${{prompts:`Prompts`,providers:`Providers`,settings:`Application Settings`}[e]??e} could not be imported.`,status:`failed`}}async function Lt(e,t){if(e.byteLength===0)throw new V;let n=new ee(new m(e),{checkCrc32:!0,filenameValidation:`strict`,maxAppendedDataSize:0,strictness:`strict`});try{let e;try{e=await n.getEntries()}catch(e){throw new V(e)}if(e.length>256)throw new V;return await t(await jt(e),e)}finally{await n.close()}}var Rt=class{promptStore;providerStore;settingsStore;constructor(e,t,n){this.promptStore=e,this.providerStore=t,this.settingsStore=n}async inspectData(e){return Lt(e,async(e,t)=>{let n=[];for(let r of e.modules){if(!Ot(r.id)){n.push(Pt(r));continue}try{let e=await Nt(r.id,r,t);n.push({id:r.id,itemCount:e.itemCount,overwrite:r.overwrite,status:`available`})}catch{n.push(Ft(r))}}return{createdAt:e.createdAt,foundryVersion:e.foundryVersion,modules:n}})}async importData(e,t){return Lt(e,async(e,n)=>{let r=new Set(t),i=new Set(e.modules.map(e=>e.id));if(r.size===0||[...r].some(e=>!i.has(e)))throw new V;let a=[];for(let t of e.modules)if(!(!Ot(t.id)||!r.has(t.id)))try{let e=await Nt(t.id,t,n);e.id===`settings`?this.settingsStore.updateApplicationSettings(e.data):e.id===`providers`?this.providerStore.createProviders(e.data):this.promptStore.createPrompts(e.data),a.push({id:e.id,importedItems:e.itemCount,status:`imported`})}catch{a.push(It(t.id))}return{modules:a}})}};const zt=268435456,Bt=p.strictObject({}),Vt=p.preprocess(e=>typeof e==`string`?e.split(`,`):e,p.array(p.enum(Me)).min(1).refine(e=>new Set(e).size===e.length)),Ht=p.strictObject({modules:Vt});function Ut(e,t){e.post(`/api/data/import/inspect`,c(`query`,Bt),re({maxSize:zt}),async e=>{try{let n=await t.inspectData(new Uint8Array(await e.req.arrayBuffer()));return e.json({status:O.success,data:n})}catch(t){if(t instanceof V)return e.json({message:t.message},400);throw t}}),e.post(`/api/data/import`,c(`query`,Ht),re({maxSize:zt}),async e=>{try{let n=await t.importData(new Uint8Array(await e.req.arrayBuffer()),e.req.valid(`query`).modules);return e.json({status:O.success,data:n})}catch(t){if(t instanceof V)return e.json({message:t.message},400);throw t}})}var Wt=Ae({prompts:()=>W,providers:()=>U,runtimes:()=>G,settings:()=>H});const H=w(`settings`,{id:T(`id`).primaryKey(),key:T(`key`).notNull(),value:T(`value`,{mode:`json`}).$type().notNull(),createdAt:C(`created_at`).notNull(),updatedAt:C(`updated_at`).notNull(),deletedAt:C(`deleted_at`)},e=>[ue(`settings_key_unique`).on(e.key),S(`settings_id_not_empty`,x`length(${e.id}) > 0`),S(`settings_key_not_empty`,x`length(trim(${e.key})) > 0`),S(`settings_value_json`,x`json_valid(${e.value})`),S(`settings_created_at_nonnegative`,x`${e.createdAt} >= 0`),S(`settings_updated_at_valid`,x`${e.updatedAt} >= ${e.createdAt}`),S(`settings_deleted_at_valid`,x`${e.deletedAt} IS NULL OR ${e.deletedAt} >= ${e.createdAt}`)]),U=w(`providers`,{id:T(`id`).primaryKey(),runtime:T(`runtime`,{enum:[`codex`,`claude-code`]}).notNull(),name:T(`name`).notNull(),officialWebsite:T(`official_website`),remark:T(`remark`),avatarMimeType:T(`avatar_mime_type`,{enum:[`image/png`,`image/jpeg`,`image/webp`,`image/svg+xml`]}),avatarData:ce(`avatar_data`,{mode:`buffer`}),configuration:T(`configuration`,{mode:`json`}).$type().notNull(),createdAt:C(`created_at`).notNull(),updatedAt:C(`updated_at`).notNull(),deletedAt:C(`deleted_at`)},e=>[le(`providers_runtime_created_at_index`).on(e.runtime,e.createdAt),S(`providers_id_not_empty`,x`length(${e.id}) > 0`),S(`providers_runtime_valid`,x`${e.runtime} IN ('codex', 'claude-code')`),S(`providers_name_valid`,x`length(trim(${e.name})) BETWEEN 1 AND 100`),S(`providers_official_website_valid`,x`${e.officialWebsite} IS NULL OR length(${e.officialWebsite}) <= 2048`),S(`providers_remark_valid`,x`${e.remark} IS NULL OR length(${e.remark}) <= 2000`),S(`providers_avatar_valid`,x`(${e.avatarMimeType} IS NULL AND ${e.avatarData} IS NULL) OR (${e.avatarMimeType} IN ('image/png', 'image/jpeg', 'image/webp', 'image/svg+xml') AND ${e.avatarData} IS NOT NULL AND length(${e.avatarData}) BETWEEN 1 AND 2097152)`),S(`providers_configuration_json`,x`json_valid(${e.configuration})`),S(`providers_created_at_nonnegative`,x`${e.createdAt} >= 0`),S(`providers_updated_at_valid`,x`${e.updatedAt} >= ${e.createdAt}`),S(`providers_deleted_at_valid`,x`${e.deletedAt} IS NULL OR ${e.deletedAt} >= ${e.createdAt}`)]),W=w(`prompts`,{id:T(`id`).primaryKey(),title:T(`title`).notNull(),description:T(`description`),content:T(`content`).notNull(),createdAt:C(`created_at`).notNull(),updatedAt:C(`updated_at`).notNull(),deletedAt:C(`deleted_at`)},e=>[le(`prompts_updated_at_index`).on(e.updatedAt),S(`prompts_id_not_empty`,x`length(${e.id}) > 0`),S(`prompts_title_valid`,x`length(trim(${e.title})) BETWEEN 1 AND 100`),S(`prompts_description_valid`,x`${e.description} IS NULL OR length(${e.description}) <= 2000`),S(`prompts_content_valid`,x`length(trim(${e.content})) > 0 AND length(CAST(${e.content} AS BLOB)) <= 1048576`),S(`prompts_created_at_nonnegative`,x`${e.createdAt} >= 0`),S(`prompts_updated_at_valid`,x`${e.updatedAt} >= ${e.createdAt}`),S(`prompts_deleted_at_valid`,x`${e.deletedAt} IS NULL OR ${e.deletedAt} >= ${e.createdAt}`)]),G=w(`runtimes`,{runtime:T(`runtime`,{enum:[`codex`,`claude-code`]}).primaryKey(),managed:C(`managed`,{mode:`boolean`}).notNull().default(!1),providerId:T(`provider_id`).references(()=>U.id,{onDelete:`restrict`}),appliedAt:C(`applied_at`)},e=>[S(`runtimes_runtime_valid`,x`${e.runtime} IN ('codex', 'claude-code')`),S(`runtimes_state_valid`,x`(${e.managed} = 0 AND ${e.providerId} IS NULL AND ${e.appliedAt} IS NULL) OR (${e.managed} = 1 AND ${e.appliedAt} IS NOT NULL)`),S(`runtimes_applied_at_nonnegative`,x`${e.appliedAt} IS NULL OR ${e.appliedAt} >= 0`)]);function Gt(e){return{content:e.content,createdAt:e.createdAt,description:e.description,id:e.id,title:e.title,updatedAt:e.updatedAt}}function K(e){return{createdAt:e.createdAt,description:e.description,excerpt:e.content.replaceAll(/\s+/gu,` `).trim().slice(0,240),id:e.id,title:e.title,updatedAt:e.updatedAt}}function Kt(e,t){let n=_t(t);return n===``||[e.title,e.description??``,e.content].some(e=>_t(e).includes(n))}var qt=class{database;now;createId;constructor(e,t=Date.now,n=_){this.database=e,this.now=t,this.createId=n}createPrompt(e){let t=vt(e),n=this.now(),r=this.createId();return this.database.insert(W).values({...t,createdAt:n,deletedAt:null,id:r,updatedAt:n}).run(),{...t,createdAt:n,id:r,updatedAt:n}}createPrompts(e){return this.database.transaction(()=>e.map(e=>this.createPrompt(e)))}deletePrompt(e){return this.database.update(W).set({deletedAt:this.now()}).where(v(y(W.id,e),b(W.deletedAt))).run().changes>0}getPrompt(e){let t=this.database.select().from(W).where(v(y(W.id,e),b(W.deletedAt))).get();return t?Gt(t):null}listAllPrompts(){return this.database.select().from(W).where(b(W.deletedAt)).all().map(e=>Gt(e))}listPrompts(e){return{items:this.listAllPrompts().filter(t=>Kt(t,e.query)).toSorted((e,t)=>t.updatedAt-e.updatedAt||t.id.localeCompare(e.id)).map(e=>K(e))}}updatePrompt(e,t){if(this.getPrompt(e)===null)return null;let n=vt(t);return this.database.update(W).set({...n,updatedAt:this.now()}).where(v(y(W.id,e),b(W.deletedAt))).run(),this.getPrompt(e)}};function Jt(e,t){e.get(`/api/prompts`,c(`query`,gt),e=>e.json({data:t.listPrompts(e.req.valid(`query`)),status:O.success})),e.post(`/api/prompts`,c(`json`,z),e=>{let n=t.createPrompt(e.req.valid(`json`));return e.json({data:K(n),status:O.success},201)}),e.delete(`/api/prompts/:promptId`,c(`param`,B),e=>t.deletePrompt(e.req.valid(`param`).promptId)?e.json({data:!0,status:O.success}):e.json({data:!1,message:`The selected Prompt is unavailable.`,status:O.promptNotFound})),e.get(`/api/prompts/:promptId`,c(`param`,B),e=>{let n=t.getPrompt(e.req.valid(`param`).promptId);return n===null?e.json({data:null,message:`The selected Prompt is unavailable.`,status:O.promptNotFound}):e.json({data:n,status:O.success})}),e.put(`/api/prompts/:promptId`,c(`param`,B),c(`json`,z),e=>{let n=t.updatePrompt(e.req.valid(`param`).promptId,e.req.valid(`json`));return n===null?e.json({data:null,message:`The selected Prompt is unavailable.`,status:O.promptNotFound}):e.json({data:K(n),status:O.success})})}function q(e){return{avatar:e.avatar,baseUrl:e.configuration.baseUrl,id:e.id,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark,runtime:e.runtime}}function Yt(e,t,n){e.get(`/api/providers`,c(`query`,st),e=>e.json({status:O.success,data:t.listProviders(e.req.valid(`query`).runtime).map(e=>q(e))})),e.delete(`/api/providers/:providerId`,c(`param`,R),e=>{let n=t.deleteProvider(e.req.valid(`param`).providerId);return n===`in-use`?e.json({status:O.providerInUse,data:!1,message:`A Provider in use cannot be deleted.`}):n===`not-found`?e.json({status:O.providerNotFound,data:!1,message:`The selected Provider is unavailable.`}):e.json({status:O.success,data:!0})}),e.post(`/api/providers/:providerId/test-connection`,c(`param`,R),async e=>{let r=t.getProvider(e.req.valid(`param`).providerId);if(r===null)return e.json({status:O.providerNotFound,data:!1,message:`The selected Provider is unavailable.`});let i=await n.testProvider(r);return i.successful?e.json({status:O.success,data:!0}):e.json({status:O.providerConnectionFailed,data:!1,message:i.message})}),e.post(`/api/providers`,c(`json`,L),e=>{let n=e.req.valid(`json`),r=q(t.createProvider(n));return e.json({status:O.success,data:r},201)}),e.get(`/api/providers/:providerId`,c(`param`,R),e=>{let n=t.getProvider(e.req.valid(`param`).providerId);return n===null?e.json({status:O.providerNotFound,data:null,message:`The selected Provider is unavailable.`}):e.json({status:O.success,data:n})}),e.post(`/api/providers/:providerId/copy`,c(`param`,R),c(`json`,L),e=>{let n=e.req.valid(`param`).providerId,r=t.getProvider(n);if(r===null)return e.json({status:O.providerNotFound,data:null,message:`The selected Provider is unavailable.`});let i=e.req.valid(`json`);if(i.runtime!==r.runtime)return e.json({message:`A Provider Runtime cannot be changed.`},400);let a=t.copyProvider(n,i);return a===null?e.json({status:O.providerNotFound,data:null,message:`The selected Provider is unavailable.`}):e.json({status:O.success,data:q(a)},201)}),e.put(`/api/providers/:providerId`,c(`param`,R),c(`json`,L),e=>{let n=e.req.valid(`param`).providerId,r=t.getProvider(n);if(r===null)return e.json({status:O.providerNotFound,data:null,message:`The selected Provider is unavailable.`});let i=e.req.valid(`json`);if(i.runtime!==r.runtime)return e.json({message:`A Provider Runtime cannot be changed.`},400);let a=t.updateProvider(n,i);return e.json({status:O.success,data:a===null?null:q(a)})})}var J=class extends Error{status;constructor(e,t){super(t),this.status=e}};const Xt=p.discriminatedUnion(`kind`,[p.strictObject({kind:p.literal(`official-default`)}),p.strictObject({kind:p.literal(`provider`),providerId:p.string().min(1)})]),Zt=p.strictObject({runtime:p.enum(A)}),Qt=p.strictObject({}),$t=p.strictObject({providerKey:p.string().min(1).max(200).optional(),target:Xt}),en=p.strictObject({expectedFileHash:p.string().regex(/^[0-9a-f]{64}$/),providerKey:p.string().min(1).max(200).optional(),target:Xt});function tn(e,t){e.get(`/api/runtimes`,c(`query`,Qt),async e=>e.json({status:O.success,data:await t.listRuntimes()})),e.post(`/api/runtimes/:runtime/preview`,c(`param`,Zt),c(`json`,$t),async e=>{try{return e.json({status:O.success,data:await t.previewConfiguration(e.req.valid(`param`).runtime,e.req.valid(`json`))})}catch(t){if(t instanceof J)return e.json({status:t.status,data:null,message:t.message});throw t}}),e.post(`/api/runtimes/:runtime/apply`,c(`param`,Zt),c(`json`,en),async e=>{try{return e.json({status:O.success,data:await t.applyConfiguration(e.req.valid(`param`).runtime,e.req.valid(`json`))})}catch(t){if(t instanceof J)return e.json({status:t.status,data:null,message:t.message});throw t}})}const nn=p.strictObject({}),rn=p.strictObject({colorMode:p.enum(k)});function an(e,t){e.get(`/api/settings`,c(`query`,nn),e=>e.json({status:O.success,data:t.getApplicationSettings()})),e.patch(`/api/settings`,c(`json`,rn),e=>e.json({status:O.success,data:t.updateApplicationSettings(e.req.valid(`json`))}))}const on=p.strictObject({});function sn(){return[d.resolve(import.meta.dirname,`app`),d.resolve(import.meta.dirname,`../../dist/app`)].find(e=>u(e))}function cn(e){let t=new f;t.get(`/api/health`,c(`query`,on),e=>e.json({status:O.success,data:!0,message:`Service is healthy.`})),Le(t,new Ve(e.promptStore,e.providerStore,e.settingsStore)),Ut(t,new Rt(e.promptStore,e.providerStore,e.settingsStore)),an(t,e.settingsStore),Jt(t,e.promptStore),Yt(t,e.providerStore,e.providerConnectionTester),tn(t,e.runtimeService);let n=e.webRoot??sn();return n&&t.use(`*`,s({root:n})),t}const Y=`__drizzle_migrations`;function ln(e){return!!e.prepare(`
|
|
3
3
|
SELECT 1
|
|
4
4
|
FROM sqlite_master
|
|
5
5
|
WHERE type = 'table' AND name = ?
|
|
6
|
-
`).pluck().get(
|
|
6
|
+
`).pluck().get(Y)}function un(e){return ln(e)?e.prepare(`
|
|
7
7
|
SELECT hash, created_at
|
|
8
|
-
FROM ${
|
|
8
|
+
FROM ${Y}
|
|
9
9
|
ORDER BY created_at ASC
|
|
10
|
-
`).all():[]}function
|
|
11
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
10
|
+
`).all():[]}function dn(e,t){if(e.length>t.length)throw Error(`The Foundry database was migrated by a newer CLI version.`);for(let[n,r]of e.entries()){let e=t[n];if(r.hash!==e.hash||r.created_at!==e.folderMillis)throw Error(`The Foundry database migration history is incompatible.`)}}async function fn(e){let t=(await _e(e)).filter(e=>e.startsWith(`foundry-before-`)&&e.endsWith(`.sqlite`)).toSorted((e,t)=>e.localeCompare(t)).slice(0,-1);await Promise.all(t.map(t=>D(d.join(e,t),{force:!0})))}async function pn(e,t,n){let r=d.join(d.dirname(t),`backups`);await E(r,{recursive:!0});let a=new Date(n()).toISOString().replaceAll(`:`,`-`),o=d.join(r,`foundry-before-${a}-${i.pid}.sqlite`);await e.backup(o),await fn(r)}function mn(e,t){e.exec(`BEGIN IMMEDIATE`);try{e.exec(`
|
|
11
|
+
CREATE TABLE IF NOT EXISTS ${Y} (
|
|
12
12
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
13
13
|
hash TEXT NOT NULL,
|
|
14
14
|
created_at INTEGER NOT NULL
|
|
15
15
|
)
|
|
16
|
-
`);let n=
|
|
17
|
-
INSERT INTO ${
|
|
16
|
+
`);let n=un(e);dn(n,t);let r=e.prepare(`
|
|
17
|
+
INSERT INTO ${Y} (hash, created_at)
|
|
18
18
|
VALUES (?, ?)
|
|
19
|
-
`);for(let i of t.slice(n.length)){for(let t of i.sql)e.exec(t);r.run(i.hash,i.folderMillis)}e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}}async function qt(e,t){let n=ye({migrationsFolder:t.migrationsFolder}),r=Ht(e);Ut(r,n),r.length!==n.length&&(t.isExistingDatabase&&await Gt(e,t.databasePath,t.now??Date.now),Kt(e,n))}function Jt(){return i.platform!==`darwin`&&i.platform!==`win32`&&i.env.XDG_DATA_HOME&&!d.isAbsolute(i.env.XDG_DATA_HOME)?d.join(xe(),`.local`,`share`,`foundry`):be(`foundry`,{suffix:``}).data}function Yt(){return d.join(Jt(),`foundry.sqlite`)}var Xt=je({providers:()=>U,runtimes:()=>W,settings:()=>H});const H=T(`settings`,{id:E(`id`).primaryKey(),key:E(`key`).notNull(),value:E(`value`,{mode:`json`}).$type().notNull(),createdAt:w(`created_at`).notNull(),updatedAt:w(`updated_at`).notNull(),deletedAt:w(`deleted_at`)},e=>[Te(`settings_key_unique`).on(e.key),C(`settings_id_not_empty`,S`length(${e.id}) > 0`),C(`settings_key_not_empty`,S`length(trim(${e.key})) > 0`),C(`settings_value_json`,S`json_valid(${e.value})`),C(`settings_created_at_nonnegative`,S`${e.createdAt} >= 0`),C(`settings_updated_at_valid`,S`${e.updatedAt} >= ${e.createdAt}`),C(`settings_deleted_at_valid`,S`${e.deletedAt} IS NULL OR ${e.deletedAt} >= ${e.createdAt}`)]),U=T(`providers`,{id:E(`id`).primaryKey(),runtime:E(`runtime`,{enum:[`codex`,`claude-code`]}).notNull(),name:E(`name`).notNull(),officialWebsite:E(`official_website`),remark:E(`remark`),avatarMimeType:E(`avatar_mime_type`,{enum:[`image/png`,`image/jpeg`,`image/webp`,`image/svg+xml`]}),avatarData:Ce(`avatar_data`,{mode:`buffer`}),configuration:E(`configuration`,{mode:`json`}).$type().notNull(),createdAt:w(`created_at`).notNull(),updatedAt:w(`updated_at`).notNull(),deletedAt:w(`deleted_at`)},e=>[we(`providers_runtime_created_at_index`).on(e.runtime,e.createdAt),C(`providers_id_not_empty`,S`length(${e.id}) > 0`),C(`providers_runtime_valid`,S`${e.runtime} IN ('codex', 'claude-code')`),C(`providers_name_valid`,S`length(trim(${e.name})) BETWEEN 1 AND 100`),C(`providers_official_website_valid`,S`${e.officialWebsite} IS NULL OR length(${e.officialWebsite}) <= 2048`),C(`providers_remark_valid`,S`${e.remark} IS NULL OR length(${e.remark}) <= 2000`),C(`providers_avatar_valid`,S`(${e.avatarMimeType} IS NULL AND ${e.avatarData} IS NULL) OR (${e.avatarMimeType} IN ('image/png', 'image/jpeg', 'image/webp', 'image/svg+xml') AND ${e.avatarData} IS NOT NULL AND length(${e.avatarData}) BETWEEN 1 AND 2097152)`),C(`providers_configuration_json`,S`json_valid(${e.configuration})`),C(`providers_created_at_nonnegative`,S`${e.createdAt} >= 0`),C(`providers_updated_at_valid`,S`${e.updatedAt} >= ${e.createdAt}`),C(`providers_deleted_at_valid`,S`${e.deletedAt} IS NULL OR ${e.deletedAt} >= ${e.createdAt}`)]),W=T(`runtimes`,{runtime:E(`runtime`,{enum:[`codex`,`claude-code`]}).primaryKey(),managed:w(`managed`,{mode:`boolean`}).notNull().default(!1),providerId:E(`provider_id`).references(()=>U.id,{onDelete:`restrict`}),appliedAt:w(`applied_at`)},e=>[C(`runtimes_runtime_valid`,S`${e.runtime} IN ('codex', 'claude-code')`),C(`runtimes_state_valid`,S`(${e.managed} = 0 AND ${e.providerId} IS NULL AND ${e.appliedAt} IS NULL) OR (${e.managed} = 1 AND ${e.appliedAt} IS NOT NULL)`),C(`runtimes_applied_at_nonnegative`,S`${e.appliedAt} IS NULL OR ${e.appliedAt} >= 0`)]);function Zt(){let e=[d.resolve(import.meta.dirname,`migrations`),d.resolve(import.meta.dirname,`../../../drizzle`)].find(e=>u(e));if(!e)throw Error(`Foundry database migrations could not be found.`);return e}async function Qt(e={}){let t=e.databasePath??Yt(),n=u(t);await _(d.dirname(t),{recursive:!0});let r=new ce(t,{timeout:5e3});try{return r.pragma(`foreign_keys = ON`),r.function(`uuid_v7`,()=>re()),await qt(r,{isExistingDatabase:n,databasePath:t,migrationsFolder:e.migrationsFolder??Zt(),now:e.now}),{client:r,db:le({client:r,schema:Xt})}}catch(e){throw r.close(),e}}function $t(e){if(e.avatarMimeType===null&&e.avatarData===null)return null;if(e.avatarMimeType===null||e.avatarData===null)throw Error(`Stored Provider avatar is invalid.`);return{data:e.avatarData.toString(`base64`),mimeType:e.avatarMimeType}}function G(e){let t={avatar:$t(e),createdAt:e.createdAt,id:e.id,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark,updatedAt:e.updatedAt};return e.runtime===`codex`?{...t,configuration:ut(e.configuration),runtime:e.runtime}:{...t,configuration:dt(e.configuration),runtime:e.runtime}}var en=class{database;now;createId;constructor(e,t=Date.now,n=re){this.database=e,this.now=t,this.createId=n}createProvider(e){let t=L(e),n=ft(t.avatar),r=this.now(),i=this.createId();return this.database.insert(U).values({avatarData:n,avatarMimeType:t.avatar?.mimeType??null,configuration:t.configuration,createdAt:r,deletedAt:null,id:i,name:t.name,officialWebsite:t.officialWebsite,remark:t.remark,runtime:t.runtime,updatedAt:r}).run(),G({avatarData:n,avatarMimeType:t.avatar?.mimeType??null,configuration:t.configuration,createdAt:r,deletedAt:null,id:i,name:t.name,officialWebsite:t.officialWebsite,remark:t.remark,runtime:t.runtime,updatedAt:r})}createProviders(e){return this.database.transaction(()=>e.map(e=>this.createProvider(e)))}copyProvider(e,t){let n=this.getProvider(e);if(n===null)return null;let r=L(t);if(r.runtime!==n.runtime)throw Error(`A Provider Runtime cannot be changed.`);return this.createProvider(r)}deleteProvider(e){return this.database.transaction(()=>this.database.select({id:U.id}).from(U).where(y(b(U.id,e),x(U.deletedAt))).get()?this.database.select({providerId:W.providerId}).from(W).where(b(W.providerId,e)).get()?`in-use`:this.database.update(U).set({deletedAt:this.now()}).where(y(b(U.id,e),x(U.deletedAt))).run().changes===1?`deleted`:`not-found`:`not-found`)}getProvider(e){let t=this.database.select().from(U).where(y(b(U.id,e),x(U.deletedAt))).get();return t?G(t):null}listProviders(e){return this.database.select().from(U).where(y(b(U.runtime,e),x(U.deletedAt))).orderBy(Se(U.createdAt),Se(U.id)).all().map(e=>G(e))}updateProvider(e,t){let n=this.getProvider(e);if(n===null)return null;let r=L(t);if(r.runtime!==n.runtime)throw Error(`A Provider Runtime cannot be changed.`);let i=ft(r.avatar),a=this.now();return this.database.update(U).set({avatarData:i,avatarMimeType:r.avatar?.mimeType??null,configuration:r.configuration,name:r.name,officialWebsite:r.officialWebsite,remark:r.remark,updatedAt:a}).where(y(b(U.id,e),x(U.deletedAt))).run(),this.getProvider(e)}};const tn=new Set([404,405,501]);function nn(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/u,``)}/${t}`,n.href}function rn(e){if(e.runtime===`codex`)return nn(e.configuration.baseUrl,`models`);let t=new URL(e.configuration.baseUrl).pathname.replace(/\/+$/u,``);return nn(e.configuration.baseUrl,t.endsWith(`/v1`)?`models`:`v1/models`)}function an(e){let t=new Headers({accept:`application/json`});if(e.runtime===`codex`){let{apiKey:n}=e.configuration;return n!==null&&t.set(`authorization`,`Bearer ${n}`),t}let{apiKey:n}=e.configuration;return t.set(`anthropic-version`,`2023-06-01`),t.set(e.configuration.apiKeyHeader,e.configuration.apiKeyHeader===`authorization`?`Bearer ${n}`:n),t}function on(e){return e>=300&&e<400?`The Provider redirected the request. Check the Base URL.`:e===401||e===403?`Authentication failed. Check the API key and its permissions.`:e===402?`The Provider rejected the request because billing is unavailable.`:e===408?`The Provider timed out while handling the request.`:e===429?`The Provider is rate limited or has insufficient quota.`:e>=500?`The Provider is temporarily unavailable.`:`The Provider returned HTTP ${e}.`}async function sn(e){return await e.body?.cancel(),{message:on(e.status),successful:!1}}function cn(e){return e instanceof DOMException&&e.name===`TimeoutError`?{message:`The connection timed out.`,successful:!1}:{message:`The Provider could not be reached${e instanceof Error?`: ${e.message}`:``}.`.slice(0,500),successful:!1}}var ln=class{fetcher;timeoutMs;constructor(e=fetch,t=1e4){this.fetcher=e,this.timeoutMs=t}async request(e,t){try{return{response:await this.fetcher(e,{headers:t,method:`GET`,redirect:`manual`,signal:AbortSignal.timeout(this.timeoutMs)}),type:`response`}}catch(e){return{error:e,type:`error`}}}async testProvider(e){let t=an(e),n=await this.request(rn(e),t);if(n.type===`error`)return cn(n.error);if(n.response.ok)return await n.response.body?.cancel(),{successful:!0};if(!tn.has(n.response.status))return sn(n.response);await n.response.body?.cancel();let r=await this.request(e.configuration.baseUrl,t);return r.type===`error`?cn(r.error):(await r.response.body?.cancel(),{successful:!0})}};function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function un(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}function dn(e,t){return e===void 0?{kind:`absent`}:t?{kind:`secret`,value:un(e)}:{kind:`plain`,value:un(e)}}function q(e,t,n,r=!1){let i;return i=t===void 0&&n===void 0?`unchanged`:t===void 0?`add`:n===void 0?`remove`:t===n?`unchanged`:`update`,{current:dn(t,r),key:e,operation:i,proposed:dn(n,r)}}function J(e){return{changes:e.filter(e=>e.operation!==`unchanged`),unchanged:e.filter(e=>e.operation===`unchanged`)}}function fn(e){return g(`sha256`).update(e===null?`absent\0`:`present\0${e}`).digest(`hex`)}function pn(e,t){try{let n=e===`codex`?Ee(t):JSON.parse(t);if(!K(n))throw Error(`Configuration root must be an object.`);return n}catch{throw new B(`RUNTIME_CONFIGURATION_INVALID`,`The ${e===`codex`?`Codex`:`Claude Code`} configuration cannot be safely parsed.`)}}async function mn(e,t){try{let n=await fe(t);if(!n.isFile())throw new B(`RUNTIME_CONFIGURATION_INVALID`,`The Runtime configuration path is not a regular file.`);let r=await pe(t,`utf8`);return{content:r,exists:!0,hash:fn(r),mode:n.mode&511,values:pn(e,r)}}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)return{content:null,exists:!1,hash:fn(null),mode:384,values:{}};throw e instanceof B?e:new B(`RUNTIME_APPLY_FAILED`,`The Runtime configuration could not be read.`)}}function Y(e){return structuredClone(e)}function X(e,t,n){n===void 0?delete e[t]:e[t]=n}function hn(e,t){return e.content===null?Oe(t):De(e.content,t)}function gn(e){let t=/(?:\r\n|\n)([\t ]+)"/.exec(e)?.[1];if(t!==void 0)return t.includes(` `)?` `:t.length}function _n(e,t){if(e.content===null)return`${JSON.stringify(t,null,2)}\n`;let n=e.content.includes(`\r
|
|
19
|
+
`);for(let i of t.slice(n.length)){for(let t of i.sql)e.exec(t);r.run(i.hash,i.folderMillis)}e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}}async function hn(e,t){let n=Se({migrationsFolder:t.migrationsFolder}),r=un(e);dn(r,n),r.length!==n.length&&(t.isExistingDatabase&&await pn(e,t.databasePath,t.now??Date.now),mn(e,n))}function gn(){return i.platform!==`darwin`&&i.platform!==`win32`&&i.env.XDG_DATA_HOME&&!d.isAbsolute(i.env.XDG_DATA_HOME)?d.join(we(),`.local`,`share`,`foundry`):Ce(`foundry`,{suffix:``}).data}function _n(){return d.join(gn(),`foundry.sqlite`)}function vn(){let e=[d.resolve(import.meta.dirname,`migrations`),d.resolve(import.meta.dirname,`../../../drizzle`)].find(e=>u(e));if(!e)throw Error(`Foundry database migrations could not be found.`);return e}async function yn(e={}){let t=e.databasePath??_n(),n=u(t);await E(d.dirname(t),{recursive:!0});let r=new de(t,{timeout:5e3});try{return r.pragma(`foreign_keys = ON`),r.function(`uuid_v7`,()=>_()),await hn(r,{isExistingDatabase:n,databasePath:t,migrationsFolder:e.migrationsFolder??vn(),now:e.now}),{client:r,db:fe({client:r,schema:Wt})}}catch(e){throw r.close(),e}}function bn(e){if(e.avatarMimeType===null&&e.avatarData===null)return null;if(e.avatarMimeType===null||e.avatarData===null)throw Error(`Stored Provider avatar is invalid.`);return{data:e.avatarData.toString(`base64`),mimeType:e.avatarMimeType}}function X(e){let t={avatar:bn(e),createdAt:e.createdAt,id:e.id,name:e.name,officialWebsite:e.officialWebsite,remark:e.remark,updatedAt:e.updatedAt};return e.runtime===`codex`?{...t,configuration:lt(e.configuration),runtime:e.runtime}:{...t,configuration:ut(e.configuration),runtime:e.runtime}}var xn=class{database;now;createId;constructor(e,t=Date.now,n=_){this.database=e,this.now=t,this.createId=n}createProvider(e){let t=ct(e),n=dt(t.avatar),r=this.now(),i=this.createId();return this.database.insert(U).values({avatarData:n,avatarMimeType:t.avatar?.mimeType??null,configuration:t.configuration,createdAt:r,deletedAt:null,id:i,name:t.name,officialWebsite:t.officialWebsite,remark:t.remark,runtime:t.runtime,updatedAt:r}).run(),X({avatarData:n,avatarMimeType:t.avatar?.mimeType??null,configuration:t.configuration,createdAt:r,deletedAt:null,id:i,name:t.name,officialWebsite:t.officialWebsite,remark:t.remark,runtime:t.runtime,updatedAt:r})}createProviders(e){return this.database.transaction(()=>e.map(e=>this.createProvider(e)))}copyProvider(e,t){let n=this.getProvider(e);if(n===null)return null;let r=ct(t);if(r.runtime!==n.runtime)throw Error(`A Provider Runtime cannot be changed.`);return this.createProvider(r)}deleteProvider(e){return this.database.transaction(()=>this.database.select({id:U.id}).from(U).where(v(y(U.id,e),b(U.deletedAt))).get()?this.database.select({providerId:G.providerId}).from(G).where(y(G.providerId,e)).get()?`in-use`:this.database.update(U).set({deletedAt:this.now()}).where(v(y(U.id,e),b(U.deletedAt))).run().changes===1?`deleted`:`not-found`:`not-found`)}getProvider(e){let t=this.database.select().from(U).where(v(y(U.id,e),b(U.deletedAt))).get();return t?X(t):null}listProviders(e){return this.database.select().from(U).where(v(y(U.runtime,e),b(U.deletedAt))).orderBy(se(U.createdAt),se(U.id)).all().map(e=>X(e))}updateProvider(e,t){let n=this.getProvider(e);if(n===null)return null;let r=ct(t);if(r.runtime!==n.runtime)throw Error(`A Provider Runtime cannot be changed.`);let i=dt(r.avatar),a=this.now();return this.database.update(U).set({avatarData:i,avatarMimeType:r.avatar?.mimeType??null,configuration:r.configuration,name:r.name,officialWebsite:r.officialWebsite,remark:r.remark,updatedAt:a}).where(v(y(U.id,e),b(U.deletedAt))).run(),this.getProvider(e)}};const Sn=new Set([404,405,501]);function Cn(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/u,``)}/${t}`,n.href}function wn(e){if(e.runtime===`codex`)return Cn(e.configuration.baseUrl,`models`);let t=new URL(e.configuration.baseUrl).pathname.replace(/\/+$/u,``);return Cn(e.configuration.baseUrl,t.endsWith(`/v1`)?`models`:`v1/models`)}function Tn(e){let t=new Headers({accept:`application/json`});if(e.runtime===`codex`){let{apiKey:n}=e.configuration;return n!==null&&t.set(`authorization`,`Bearer ${n}`),t}let{apiKey:n}=e.configuration;return t.set(`anthropic-version`,`2023-06-01`),t.set(e.configuration.apiKeyHeader,e.configuration.apiKeyHeader===`authorization`?`Bearer ${n}`:n),t}function En(e){return e>=300&&e<400?`The Provider redirected the request. Check the Base URL.`:e===401||e===403?`Authentication failed. Check the API key and its permissions.`:e===402?`The Provider rejected the request because billing is unavailable.`:e===408?`The Provider timed out while handling the request.`:e===429?`The Provider is rate limited or has insufficient quota.`:e>=500?`The Provider is temporarily unavailable.`:`The Provider returned HTTP ${e}.`}async function Dn(e){return await e.body?.cancel(),{message:En(e.status),successful:!1}}function On(e){return e instanceof DOMException&&e.name===`TimeoutError`?{message:`The connection timed out.`,successful:!1}:{message:`The Provider could not be reached${e instanceof Error?`: ${e.message}`:``}.`.slice(0,500),successful:!1}}var kn=class{fetcher;timeoutMs;constructor(e=fetch,t=1e4){this.fetcher=e,this.timeoutMs=t}async request(e,t){try{return{response:await this.fetcher(e,{headers:t,method:`GET`,redirect:`manual`,signal:AbortSignal.timeout(this.timeoutMs)}),type:`response`}}catch(e){return{error:e,type:`error`}}}async testProvider(e){let t=Tn(e),n=await this.request(wn(e),t);if(n.type===`error`)return On(n.error);if(n.response.ok)return await n.response.body?.cancel(),{successful:!0};if(!Sn.has(n.response.status))return Dn(n.response);await n.response.body?.cancel();let r=await this.request(e.configuration.baseUrl,t);return r.type===`error`?On(r.error):(await r.response.body?.cancel(),{successful:!0})}};function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function An(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=JSON.stringify(e);return typeof t==`string`?t:String(e)}function jn(e,t){return e===void 0?{kind:`absent`}:t?{kind:`secret`,value:An(e)}:{kind:`plain`,value:An(e)}}function Q(e,t,n,r=!1){let i;return i=t===void 0&&n===void 0?`unchanged`:t===void 0?`add`:n===void 0?`remove`:t===n?`unchanged`:`update`,{current:jn(t,r),key:e,operation:i,proposed:jn(n,r)}}function Mn(e){return{changes:e.filter(e=>e.operation!==`unchanged`),unchanged:e.filter(e=>e.operation===`unchanged`)}}function Nn(e){return g(`sha256`).update(e===null?`absent\0`:`present\0${e}`).digest(`hex`)}function Pn(e,t){try{let n=e===`codex`?Te(t):JSON.parse(t);if(!Z(n))throw Error(`Configuration root must be an object.`);return n}catch{throw new J(`RUNTIME_CONFIGURATION_INVALID`,`The ${e===`codex`?`Codex`:`Claude Code`} configuration cannot be safely parsed.`)}}async function Fn(e,t){try{let n=await he(t);if(!n.isFile())throw new J(`RUNTIME_CONFIGURATION_INVALID`,`The Runtime configuration path is not a regular file.`);let r=await ge(t,`utf8`);return{content:r,exists:!0,hash:Nn(r),mode:n.mode&511,values:Pn(e,r)}}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)return{content:null,exists:!1,hash:Nn(null),mode:384,values:{}};throw e instanceof J?e:new J(`RUNTIME_APPLY_FAILED`,`The Runtime configuration could not be read.`)}}function In(e){return structuredClone(e)}function Ln(e,t,n){n===void 0?delete e[t]:e[t]=n}function Rn(e,t){return e.content===null?De(t):Ee(e.content,t)}function zn(e){let t=/(?:\r\n|\n)([\t ]+)"/.exec(e)?.[1];if(t!==void 0)return t.includes(` `)?` `:t.length}function Bn(e,t){if(e.content===null)return`${JSON.stringify(t,null,2)}\n`;let n=e.content.includes(`\r
|
|
20
20
|
`)?`\r
|
|
21
21
|
`:`
|
|
22
22
|
`,r=e.content.endsWith(`
|
|
23
|
-
`),i=JSON.stringify(t,null,
|
|
23
|
+
`),i=JSON.stringify(t,null,zn(e.content));return n===`\r
|
|
24
24
|
`&&(i=i.replaceAll(`
|
|
25
25
|
`,`\r
|
|
26
|
-
`)),r?`${i}${n}`:i}function vn(e,t){return d.join(d.dirname(e),`.${d.basename(e)}.foundry-${t}-${ne()}.tmp`)}async function Z(e,t,n,r){let i=vn(e,r);try{await ve(i,t,{encoding:`utf8`,flag:`wx`,mode:n}),await de(i,n),await ge(i,e)}catch(e){try{await v(i,{force:!0})}catch{}throw e}}async function yn(e,t,n,r){if(n.source.hash!==r)throw new B(`RUNTIME_CONFIGURATION_CHANGED`,`The Runtime configuration changed after Preview. Refresh and review it again.`);let{source:i}=n,a=d.dirname(t),o=`${t}.foundry-backup`;if(!(!i.exists||n.content!==i.content))return{rollback:async()=>{}};pn(e,n.content);try{await _(a,{mode:448,recursive:!0}),i.exists&&i.content!==null?await Z(o,i.content,384,`backup`):await v(o,{force:!0}),await Z(t,n.content,i.mode,`write`)}catch(e){throw e instanceof B?e:new B(`RUNTIME_APPLY_FAILED`,`The Runtime configuration could not be safely updated.`)}return{rollback:async()=>{try{i.exists&&i.content!==null?await Z(t,i.content,i.mode,`rollback`):await v(t,{force:!0})}catch{throw new B(`RUNTIME_APPLY_FAILED`,`The previous Runtime configuration could not be restored.`)}}}}const bn=[`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`],xn=[``,`_NAME`,`_DESCRIPTION`,`_SUPPORTED_CAPABILITIES`],Sn=bn.flatMap(e=>xn.map(t=>`${e}${t}`)),Cn=[`CLAUDE_CODE_SUBAGENT_MODEL`,`CLAUDE_CODE_SUBAGENT_MODEL_FORCE`],wn=[`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS`,`ENABLE_TOOL_SEARCH`,`CLAUDE_CODE_EFFORT_LEVEL`,`DISABLE_AUTOUPDATER`],Tn=[`commit`,`pr`,`sessionUrl`],En=[`ANTHROPIC_BASE_URL`,`ANTHROPIC_AUTH_TOKEN`,`ANTHROPIC_API_KEY`,`ANTHROPIC_MODEL`,...Sn,...Cn,...wn];function Dn(e){return e===null?[void 0,void 0,void 0,void 0]:[e.model,e.displayName??void 0,e.description??void 0,e.supportedCapabilities.length>0?e.supportedCapabilities.join(`,`):void 0]}function On(e){let t=Object.fromEntries(En.map(e=>[e,void 0]));if(e===null)return t;t.ANTHROPIC_BASE_URL=e.baseUrl,t.ANTHROPIC_AUTH_TOKEN=e.apiKeyHeader===`authorization`?e.apiKey:void 0,t.ANTHROPIC_API_KEY=e.apiKeyHeader===`x-api-key`?e.apiKey:void 0,t.ANTHROPIC_MODEL=e.defaultModel;let n=[e.opusModel,e.sonnetModel,e.haikuModel,e.fableModel];for(let[e,r]of bn.entries()){let i=Dn(n[e]);for(let[e,n]of xn.entries())t[`${r}${n}`]=i[e]}return t.CLAUDE_CODE_SUBAGENT_MODEL=e.subagentModel??void 0,t.CLAUDE_CODE_SUBAGENT_MODEL_FORCE=e.subagentModelForce?`1`:void 0,t.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=e.teammatesMode?`1`:void 0,t.ENABLE_TOOL_SEARCH=e.enableToolSearch?`true`:void 0,t.CLAUDE_CODE_EFFORT_LEVEL=e.maxEffortThinking?`max`:void 0,t.DISABLE_AUTOUPDATER=e.disableAutoUpdater?`1`:void 0,t}function kn(e){let t=e?.hideAiAttribution===!0;return{commit:t?``:void 0,pr:t?``:void 0,sessionUrl:!t&&void 0}}function An(e,t,n,r){let i=e.values.env;if(i!==void 0&&!K(i))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`Claude Code env must be an object.`);let a=i??{},o=On(r?.configuration??null),s=e.values.attribution;if(s!==void 0&&!K(s))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`Claude Code attribution must be an object.`);let c=s??{},l=kn(r?.configuration??null),u=[...En.map(e=>q(`env.${e}`,a[e],o[e],e===`ANTHROPIC_AUTH_TOKEN`||e===`ANTHROPIC_API_KEY`)),...Tn.map(e=>q(`attribution.${e}`,c[e],l[e]))],d=Y(e.values),f=K(d.env)?d.env:{};d.env=f;for(let e of En)X(f,e,o[e]);Object.keys(f).length===0&&delete d.env;let p=K(d.attribution)?d.attribution:{};d.attribution=p;for(let e of Tn){let t=l[e];t===void 0?delete p[e]:p[e]=t}Object.keys(p).length===0&&delete d.attribution;let m=J(u);return{content:_n(e,d),preview:{...m,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:null,runtime:`claude-code`,target:n},source:e}}const Q=[`model`,`review_model`,`model_provider`],jn=[`name`,`base_url`,`wire_api`,`experimental_bearer_token`];function Mn(e){let t=e.model_providers;if(t===void 0)return{};if(!K(t))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`Codex model_providers must be a table.`);return t}function Nn(e){return Object.entries(Mn(e)).filter(e=>K(e[1])).map(([e])=>e)}function Pn(e,t){let n=Nn(e);if(n.length===0){if(t!==void 0&&t!==`foundry`)throw new B(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:`foundry`,keys:n}}if(n.length===1){if(t!==void 0&&t!==n[0])throw new B(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:n[0],keys:n}}if(t===void 0)return{key:null,keys:n};if(!n.includes(t))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:t,keys:n}}function Fn(e,t){let n=Mn(e)[t];if(n===void 0)return{};if(!K(n))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`Codex model_providers.${t} must be a table.`);return n}function In(e){let t=K(e.model_providers)?e.model_providers:{};if(typeof e.model_provider==`string`){let n=t[e.model_provider];return{key:e.model_provider,table:K(n)?n:{}}}let n=Object.entries(t).filter(e=>K(e[1]));return n.length===1?{key:n[0][0],table:n[0][1]}:{key:`<key>`,table:{}}}function Ln(e,t,n,r,i){if(n.kind===`official-default`){let r=In(e.values),i=[...Q.map(t=>q(t,e.values[t],void 0)),...jn.map(e=>q(`[model_providers.${r.key}].${e}`,r.table[e],r.table[e],e===`experimental_bearer_token`))],a=Y(e.values);for(let e of Q)delete a[e];let o=J(i);return{content:hn(e,a),preview:{...o,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:null,runtime:`codex`,target:n},source:e}}if(r===null)throw new B(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);let a=Pn(e.values,i);if(a.key===null)return{file:{exists:e.exists,hash:e.hash,path:t},kind:`provider-key-selection`,providerKeys:a.keys,runtime:`codex`,target:n};let o=a.key,s=Fn(e.values,o),c={model:r.configuration.defaultModel,model_provider:o,review_model:r.configuration.reviewModel??void 0},l={base_url:r.configuration.baseUrl,experimental_bearer_token:r.configuration.apiKey??void 0,name:r.name,wire_api:`responses`},u=[...Q.map(t=>q(t,e.values[t],c[t])),...jn.map(e=>q(`[model_providers.${o}].${e}`,s[e],l[e],e===`experimental_bearer_token`))],d=Y(e.values);for(let e of Q)X(d,e,c[e]);let f=K(d.model_providers)?d.model_providers:{};d.model_providers=f;let p=K(f[o])?f[o]:{};f[o]=p;for(let e of jn)X(p,e,l[e]);let m=J(u);return{content:hn(e,d),preview:{...m,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:o,runtime:`codex`,target:n},source:e}}function Rn(e,t,n){if(t.kind===`official-default`)return null;if(n?.id!==t.providerId||n.runtime!==e)throw new B(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);return n}async function zn(e,t,n,r,i){let a=await mn(e,t),o=Rn(e,n,r);return e===`codex`?Ln(a,t,n,o,i):An(a,t,n,o)}function Bn(e){return`preview`in e}var Vn=class{async preview(e,t,n,r,i){let a=await zn(e,t,n,r,i);return Bn(a)?a.preview:a}async apply(e,t,n,r,i,a){let o=await zn(e,t,n,r,a);if(!Bn(o))throw new B(`RUNTIME_CONFIGURATION_INVALID`,`Select a Codex Provider key before applying changes.`);return yn(e,t,o,i)}};const Hn=oe(ke),Un={"claude-code":{command:`claude`,configurationDirectory:`.claude`,configurationDirectoryEnvironmentVariable:`CLAUDE_CONFIG_DIR`,configurationFilename:`settings.json`},codex:{command:`codex`,configurationDirectory:`.codex`,configurationDirectoryEnvironmentVariable:`CODEX_HOME`,configurationFilename:`config.toml`}};async function Wn(e){try{return await _e(e),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code!==`ENOENT`)}}async function Gn(e,t){let n=i.platform===`win32`?(i.env.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`):[``];for(let r of t.split(d.delimiter))if(r)for(let t of n){let n=d.join(r,`${e}${t}`);try{return await ue(n,i.platform===`win32`?l.F_OK:l.X_OK),await he(n)}catch{}}return null}var Kn=class{homeDirectory;environmentPath;runVersion;environment;constructor(e=xe(),t=i.env.PATH??``,n=async e=>{let t=await Hn(e,[`--version`],{timeout:3e3,windowsHide:!0});return(t.stdout||t.stderr).trim()},r=i.env){this.homeDirectory=e,this.environmentPath=t,this.runVersion=n,this.environment=r}async detect(e){let t=Un[e],n=this.environment[t.configurationDirectoryEnvironmentVariable]?.trim(),r=n?d.resolve(n):d.join(this.homeDirectory,t.configurationDirectory),i=d.join(r,t.configurationFilename),a=await Wn(i),o=await Gn(t.command,this.environmentPath);if(!o)return{configurationExists:a,configurationPath:i,executablePath:null,message:`${t.command} was not found in PATH.`,status:`not-detected`,version:null};try{return{configurationExists:a,configurationPath:i,executablePath:o,message:null,status:`detected`,version:await this.runVersion(o)}}catch{return{configurationExists:a,configurationPath:i,executablePath:o,message:`${t.command} --version could not be completed.`,status:`failed`,version:null}}}},qn=class{runtimeStore;providerStore;detector;configurationManager;inFlightRuntimes=new Set;constructor(e,t,n,r){this.runtimeStore=e,this.providerStore=t,this.detector=n,this.configurationManager=r}resolveProvider(e,t){if(t.kind===`official-default`)return null;let n=this.providerStore.getProvider(t.providerId);if(n?.runtime!==e)throw new B(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);return n}async requireDetection(e){let t=await this.detector.detect(e);if(t.status!==`detected`)throw new B(`RUNTIME_NOT_DETECTED`,t.message??`The Runtime could not be detected.`);return t}async listRuntimes(){let e=new Map(this.runtimeStore.listAssignments().map(e=>[e.runtime,e])),t=await Promise.all(k.map(e=>this.detector.detect(e)));return k.map((n,r)=>{let i=e.get(n);if(!i)throw Error(`Runtime assignment ${n} is missing.`);return{...i,detection:t[r]}})}async previewConfiguration(e,t){let n=await this.requireDetection(e),r=this.resolveProvider(e,t.target);return this.configurationManager.preview(e,n.configurationPath,t.target,r,t.providerKey)}async applyConfiguration(e,t){if(this.inFlightRuntimes.has(e))throw new B(`RUNTIME_APPLY_FAILED`,`A configuration update is already running for this Runtime.`);this.inFlightRuntimes.add(e);try{let n=await this.requireDetection(e),r=this.resolveProvider(e,t.target),i=await this.configurationManager.apply(e,n.configurationPath,t.target,r,t.expectedFileHash,t.providerKey);try{return{...this.runtimeStore.recordAssignment(e,t.target),detection:{...n,configurationExists:!0}}}catch(e){throw await i.rollback(),e}}finally{this.inFlightRuntimes.delete(e)}}},Jn=class{database;now;constructor(e,t=Date.now){this.database=e,this.now=t}listAssignments(){let e=new Map(this.database.select().from(W).all().map(e=>[e.runtime,{appliedAt:e.appliedAt,managed:e.managed,providerId:e.providerId,runtime:e.runtime}]));return k.map(t=>{let n=e.get(t);if(!n)throw Error(`Runtime assignment ${t} is missing.`);return n})}recordAssignment(e,t){return this.database.transaction(()=>{let n=t.kind===`provider`?t.providerId:null;if(n!==null&&!this.database.select({runtime:U.runtime}).from(U).where(y(b(U.id,n),b(U.runtime,e),x(U.deletedAt))).get())throw new B(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);let r=this.now();if(this.database.update(W).set({appliedAt:r,managed:!0,providerId:n}).where(b(W.runtime,e)).run().changes!==1)throw Error(`Runtime assignment ${e} could not be saved.`);return{appliedAt:r,managed:!0,providerId:n,runtime:e}})}};const Yn=`color_mode`,Xn=p.enum(O);var Zn=class{database;now;constructor(e,t=Date.now){this.database=e,this.now=t}getApplicationSettings(){let e=this.database.select({deletedAt:H.deletedAt,key:H.key,value:H.value}).from(H).all();if(e.length!==1)throw Error(`Stored Application Settings are invalid.`);let[t]=e;if(t.key!==Yn||t.deletedAt!==null)throw Error(`Stored Application Settings are invalid.`);return{colorMode:Xn.parse(t.value)}}updateApplicationSettings(e){if(this.database.update(H).set({updatedAt:this.now(),value:e.colorMode}).where(b(H.key,Yn)).run().changes!==1)throw Error(`Stored Application Settings are invalid.`);return this.getApplicationSettings()}};const $=`127.0.0.1`;function Qn(e){return new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})})}async function $n(e={}){let t=e.port??54321,n=await Qt({databasePath:e.databasePath,migrationsFolder:e.migrationsFolder}),r=new en(n.db),i=Bt({providerConnectionTester:new ln,providerStore:r,runtimeService:new qn(new Jn(n.db),r,new Kn,new Vn),settingsStore:new Zn(n.db)});return new Promise((e,r)=>{let a=e=>{n.client.close(),r(e)},s=o({fetch:i.fetch,hostname:$,port:t},t=>{s.off(`error`,a);let r,i=t.port,o=async()=>{try{await Qn(s)}finally{n.client.close()}};e({close:()=>(r??=o(),r),hostname:$,port:i,url:`http://${$}:${i}`})});s.once(`error`,a)})}function er(e,t){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`?`Port ${t} is already in use on 127.0.0.1.`:`Could not start Foundry Server: ${e instanceof Error?e.message:String(e)}`}function tr(e,t=i,n=console.error){let r=!1,a=()=>{r||(r=!0,t.off(`SIGINT`,a),t.off(`SIGTERM`,a),e.close().catch(e=>{n(`Could not stop Foundry Server: ${e instanceof Error?e.message:String(e)}`),t.exitCode=1}))};return t.once(`SIGINT`,a),t.once(`SIGTERM`,a),()=>{t.off(`SIGINT`,a),t.off(`SIGTERM`,a)}}const nr={error:console.error,log:console.info,openBrowser:a,registerShutdown:e=>{tr(e)},setExitCode:e=>{i.exitCode=e},startServer:$n};function rr(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n===`--port`){if(t+1>=e.length||e[t+1].startsWith(`--`))return`Missing value for option: --port`;t+=1;continue}if(!n.startsWith(`--port=`)&&n!==`--open`&&n!==`--no-open`)return`${n.startsWith(`-`)?`Unknown option`:`Unexpected argument`}: ${n}`}}function ir(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>65535)throw RangeError(`Port must be an integer between 1 and 65535. Received "${e}".`);return t}function ar(e=nr){return t({meta:{description:`Start the Local Web UI`,name:`ui`},args:{port:{default:`54321`,description:`Port for the Local Web UI`,type:`string`,valueHint:`port`},open:{default:!0,description:`Open the Local Web UI in the default browser`,negativeDescription:`Do not open the default browser`,type:`boolean`}},async run({args:t,rawArgs:n}){let r=rr(n);if(r){e.error(`${r}\nRun \`foundry ui --help\` for usage.`),e.setExitCode(1);return}let i;try{i=ir(t.port)}catch(t){e.error(`${t instanceof Error?t.message:String(t)}\nRun \`foundry ui --help\` for usage.`),e.setExitCode(1);return}let a;try{a=await e.startServer({port:i})}catch(t){e.error(er(t,i)),e.setExitCode(1);return}if(e.registerShutdown(a),e.log(`Foundry Local Web UI: ${a.url}`),t.open)try{await e.openBrowser(a.url)}catch{e.error(`Could not open the default browser. Open ${a.url} manually.`)}}})}const or=t({meta:{description:`An AI-native local developer runtime`,name:`foundry`,version:e},subCommands:{ui:ar()}});function sr(e){if(!e.some(e=>e===`--help`||e===`-h`)&&(e.length!==1||e[0]!==`--version`&&e[0]!==`-v`)&&!(e[0]===`ui`||!e[0]?.startsWith(`-`)))return`Unknown option: ${e[0]}`}async function cr(e=i.argv.slice(2)){if(e.length===0){console.info(`${await n(or)}\n`);return}let t=sr(e);if(t){console.error(`${t}\nRun \`foundry --help\` for usage.`),i.exitCode=1;return}await r(or,{rawArgs:e})}cr();export{};
|
|
26
|
+
`)),r?`${i}${n}`:i}function Vn(e,t){return d.join(d.dirname(e),`.${d.basename(e)}.foundry-${t}-${ne()}.tmp`)}async function Hn(e,t,n,r){let i=Vn(e,r);try{await xe(i,t,{encoding:`utf8`,flag:`wx`,mode:n}),await me(i,n),await ye(i,e)}catch(e){try{await D(i,{force:!0})}catch{}throw e}}async function Un(e,t,n,r){if(n.source.hash!==r)throw new J(`RUNTIME_CONFIGURATION_CHANGED`,`The Runtime configuration changed after Preview. Refresh and review it again.`);let{source:i}=n,a=d.dirname(t),o=`${t}.foundry-backup`;if(!(!i.exists||n.content!==i.content))return{rollback:async()=>{}};Pn(e,n.content);try{await E(a,{mode:448,recursive:!0}),i.exists&&i.content!==null?await Hn(o,i.content,384,`backup`):await D(o,{force:!0}),await Hn(t,n.content,i.mode,`write`)}catch(e){throw e instanceof J?e:new J(`RUNTIME_APPLY_FAILED`,`The Runtime configuration could not be safely updated.`)}return{rollback:async()=>{try{i.exists&&i.content!==null?await Hn(t,i.content,i.mode,`rollback`):await D(t,{force:!0})}catch{throw new J(`RUNTIME_APPLY_FAILED`,`The previous Runtime configuration could not be restored.`)}}}}const Wn=[`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`],Gn=[``,`_NAME`,`_DESCRIPTION`,`_SUPPORTED_CAPABILITIES`],Kn=Wn.flatMap(e=>Gn.map(t=>`${e}${t}`)),qn=[`CLAUDE_CODE_SUBAGENT_MODEL`,`CLAUDE_CODE_SUBAGENT_MODEL_FORCE`],Jn=[`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS`,`ENABLE_TOOL_SEARCH`,`CLAUDE_CODE_EFFORT_LEVEL`,`DISABLE_AUTOUPDATER`],Yn=[`commit`,`pr`,`sessionUrl`],Xn=[`ANTHROPIC_BASE_URL`,`ANTHROPIC_AUTH_TOKEN`,`ANTHROPIC_API_KEY`,`ANTHROPIC_MODEL`,...Kn,...qn,...Jn];function Zn(e){return e===null?[void 0,void 0,void 0,void 0]:[e.model,e.displayName??void 0,e.description??void 0,e.supportedCapabilities.length>0?e.supportedCapabilities.join(`,`):void 0]}function Qn(e){let t=Object.fromEntries(Xn.map(e=>[e,void 0]));if(e===null)return t;t.ANTHROPIC_BASE_URL=e.baseUrl,t.ANTHROPIC_AUTH_TOKEN=e.apiKeyHeader===`authorization`?e.apiKey:void 0,t.ANTHROPIC_API_KEY=e.apiKeyHeader===`x-api-key`?e.apiKey:void 0,t.ANTHROPIC_MODEL=e.defaultModel;let n=[e.opusModel,e.sonnetModel,e.haikuModel,e.fableModel];for(let[e,r]of Wn.entries()){let i=Zn(n[e]);for(let[e,n]of Gn.entries())t[`${r}${n}`]=i[e]}return t.CLAUDE_CODE_SUBAGENT_MODEL=e.subagentModel??void 0,t.CLAUDE_CODE_SUBAGENT_MODEL_FORCE=e.subagentModelForce?`1`:void 0,t.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=e.teammatesMode?`1`:void 0,t.ENABLE_TOOL_SEARCH=e.enableToolSearch?`true`:void 0,t.CLAUDE_CODE_EFFORT_LEVEL=e.maxEffortThinking?`max`:void 0,t.DISABLE_AUTOUPDATER=e.disableAutoUpdater?`1`:void 0,t}function $n(e){let t=e?.hideAiAttribution===!0;return{commit:t?``:void 0,pr:t?``:void 0,sessionUrl:!t&&void 0}}function er(e,t,n,r){let i=e.values.env;if(i!==void 0&&!Z(i))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`Claude Code env must be an object.`);let a=i??{},o=Qn(r?.configuration??null),s=e.values.attribution;if(s!==void 0&&!Z(s))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`Claude Code attribution must be an object.`);let c=s??{},l=$n(r?.configuration??null),u=[...Xn.map(e=>Q(`env.${e}`,a[e],o[e],e===`ANTHROPIC_AUTH_TOKEN`||e===`ANTHROPIC_API_KEY`)),...Yn.map(e=>Q(`attribution.${e}`,c[e],l[e]))],d=In(e.values),f=Z(d.env)?d.env:{};d.env=f;for(let e of Xn)Ln(f,e,o[e]);Object.keys(f).length===0&&delete d.env;let p=Z(d.attribution)?d.attribution:{};d.attribution=p;for(let e of Yn){let t=l[e];t===void 0?delete p[e]:p[e]=t}Object.keys(p).length===0&&delete d.attribution;let m=Mn(u);return{content:Bn(e,d),preview:{...m,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:null,runtime:`claude-code`,target:n},source:e}}const $=[`model`,`review_model`,`model_provider`],tr=[`name`,`base_url`,`wire_api`,`experimental_bearer_token`];function nr(e){let t=e.model_providers;if(t===void 0)return{};if(!Z(t))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`Codex model_providers must be a table.`);return t}function rr(e){return Object.entries(nr(e)).filter(e=>Z(e[1])).map(([e])=>e)}function ir(e,t){let n=rr(e);if(n.length===0){if(t!==void 0&&t!==`foundry`)throw new J(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:`foundry`,keys:n}}if(n.length===1){if(t!==void 0&&t!==n[0])throw new J(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:n[0],keys:n}}if(t===void 0)return{key:null,keys:n};if(!n.includes(t))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`The selected Codex Provider key is unavailable.`);return{key:t,keys:n}}function ar(e,t){let n=nr(e)[t];if(n===void 0)return{};if(!Z(n))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`Codex model_providers.${t} must be a table.`);return n}function or(e){let t=Z(e.model_providers)?e.model_providers:{};if(typeof e.model_provider==`string`){let n=t[e.model_provider];return{key:e.model_provider,table:Z(n)?n:{}}}let n=Object.entries(t).filter(e=>Z(e[1]));return n.length===1?{key:n[0][0],table:n[0][1]}:{key:`<key>`,table:{}}}function sr(e,t,n,r,i){if(n.kind===`official-default`){let r=or(e.values),i=[...$.map(t=>Q(t,e.values[t],void 0)),...tr.map(e=>Q(`[model_providers.${r.key}].${e}`,r.table[e],r.table[e],e===`experimental_bearer_token`))],a=In(e.values);for(let e of $)delete a[e];let o=Mn(i);return{content:Rn(e,a),preview:{...o,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:null,runtime:`codex`,target:n},source:e}}if(r===null)throw new J(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);let a=ir(e.values,i);if(a.key===null)return{file:{exists:e.exists,hash:e.hash,path:t},kind:`provider-key-selection`,providerKeys:a.keys,runtime:`codex`,target:n};let o=a.key,s=ar(e.values,o),c={model:r.configuration.defaultModel,model_provider:o,review_model:r.configuration.reviewModel??void 0},l={base_url:r.configuration.baseUrl,experimental_bearer_token:r.configuration.apiKey??void 0,name:r.name,wire_api:`responses`},u=[...$.map(t=>Q(t,e.values[t],c[t])),...tr.map(e=>Q(`[model_providers.${o}].${e}`,s[e],l[e],e===`experimental_bearer_token`))],d=In(e.values);for(let e of $)Ln(d,e,c[e]);let f=Z(d.model_providers)?d.model_providers:{};d.model_providers=f;let p=Z(f[o])?f[o]:{};f[o]=p;for(let e of tr)Ln(p,e,l[e]);let m=Mn(u);return{content:Rn(e,d),preview:{...m,file:{exists:e.exists,hash:e.hash,path:t},kind:`ready`,providerKey:o,runtime:`codex`,target:n},source:e}}function cr(e,t,n){if(t.kind===`official-default`)return null;if(n?.id!==t.providerId||n.runtime!==e)throw new J(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);return n}async function lr(e,t,n,r,i){let a=await Fn(e,t),o=cr(e,n,r);return e===`codex`?sr(a,t,n,o,i):er(a,t,n,o)}function ur(e){return`preview`in e}var dr=class{async preview(e,t,n,r,i){let a=await lr(e,t,n,r,i);return ur(a)?a.preview:a}async apply(e,t,n,r,i,a){let o=await lr(e,t,n,r,a);if(!ur(o))throw new J(`RUNTIME_CONFIGURATION_INVALID`,`Select a Codex Provider key before applying changes.`);return Un(e,t,o,i)}};const fr=ae(Oe),pr={"claude-code":{command:`claude`,configurationDirectory:`.claude`,configurationDirectoryEnvironmentVariable:`CLAUDE_CONFIG_DIR`,configurationFilename:`settings.json`},codex:{command:`codex`,configurationDirectory:`.codex`,configurationDirectoryEnvironmentVariable:`CODEX_HOME`,configurationFilename:`config.toml`}};async function mr(e){try{return await be(e),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code!==`ENOENT`)}}async function hr(e,t){let n=i.platform===`win32`?(i.env.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`):[``];for(let r of t.split(d.delimiter))if(r)for(let t of n){let n=d.join(r,`${e}${t}`);try{return await pe(n,i.platform===`win32`?l.F_OK:l.X_OK),await ve(n)}catch{}}return null}var gr=class{homeDirectory;environmentPath;runVersion;environment;constructor(e=we(),t=i.env.PATH??``,n=async e=>{let t=await fr(e,[`--version`],{timeout:3e3,windowsHide:!0});return(t.stdout||t.stderr).trim()},r=i.env){this.homeDirectory=e,this.environmentPath=t,this.runVersion=n,this.environment=r}async detect(e){let t=pr[e],n=this.environment[t.configurationDirectoryEnvironmentVariable]?.trim(),r=n?d.resolve(n):d.join(this.homeDirectory,t.configurationDirectory),i=d.join(r,t.configurationFilename),a=await mr(i),o=await hr(t.command,this.environmentPath);if(!o)return{configurationExists:a,configurationPath:i,executablePath:null,message:`${t.command} was not found in PATH.`,status:`not-detected`,version:null};try{return{configurationExists:a,configurationPath:i,executablePath:o,message:null,status:`detected`,version:await this.runVersion(o)}}catch{return{configurationExists:a,configurationPath:i,executablePath:o,message:`${t.command} --version could not be completed.`,status:`failed`,version:null}}}},_r=class{runtimeStore;providerStore;detector;configurationManager;inFlightRuntimes=new Set;constructor(e,t,n,r){this.runtimeStore=e,this.providerStore=t,this.detector=n,this.configurationManager=r}resolveProvider(e,t){if(t.kind===`official-default`)return null;let n=this.providerStore.getProvider(t.providerId);if(n?.runtime!==e)throw new J(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);return n}async requireDetection(e){let t=await this.detector.detect(e);if(t.status!==`detected`)throw new J(`RUNTIME_NOT_DETECTED`,t.message??`The Runtime could not be detected.`);return t}async listRuntimes(){let e=new Map(this.runtimeStore.listAssignments().map(e=>[e.runtime,e])),t=await Promise.all(A.map(e=>this.detector.detect(e)));return A.map((n,r)=>{let i=e.get(n);if(!i)throw Error(`Runtime assignment ${n} is missing.`);return{...i,detection:t[r]}})}async previewConfiguration(e,t){let n=await this.requireDetection(e),r=this.resolveProvider(e,t.target);return this.configurationManager.preview(e,n.configurationPath,t.target,r,t.providerKey)}async applyConfiguration(e,t){if(this.inFlightRuntimes.has(e))throw new J(`RUNTIME_APPLY_FAILED`,`A configuration update is already running for this Runtime.`);this.inFlightRuntimes.add(e);try{let n=await this.requireDetection(e),r=this.resolveProvider(e,t.target),i=await this.configurationManager.apply(e,n.configurationPath,t.target,r,t.expectedFileHash,t.providerKey);try{return{...this.runtimeStore.recordAssignment(e,t.target),detection:{...n,configurationExists:!0}}}catch(e){throw await i.rollback(),e}}finally{this.inFlightRuntimes.delete(e)}}},vr=class{database;now;constructor(e,t=Date.now){this.database=e,this.now=t}listAssignments(){let e=new Map(this.database.select().from(G).all().map(e=>[e.runtime,{appliedAt:e.appliedAt,managed:e.managed,providerId:e.providerId,runtime:e.runtime}]));return A.map(t=>{let n=e.get(t);if(!n)throw Error(`Runtime assignment ${t} is missing.`);return n})}recordAssignment(e,t){return this.database.transaction(()=>{let n=t.kind===`provider`?t.providerId:null;if(n!==null&&!this.database.select({runtime:U.runtime}).from(U).where(v(y(U.id,n),y(U.runtime,e),b(U.deletedAt))).get())throw new J(`PROVIDER_NOT_FOUND`,`The selected Provider is unavailable.`);let r=this.now();if(this.database.update(G).set({appliedAt:r,managed:!0,providerId:n}).where(y(G.runtime,e)).run().changes!==1)throw Error(`Runtime assignment ${e} could not be saved.`);return{appliedAt:r,managed:!0,providerId:n,runtime:e}})}};const yr=`color_mode`,br=p.enum(k);var xr=class{database;now;constructor(e,t=Date.now){this.database=e,this.now=t}getApplicationSettings(){let e=this.database.select({deletedAt:H.deletedAt,key:H.key,value:H.value}).from(H).all();if(e.length!==1)throw Error(`Stored Application Settings are invalid.`);let[t]=e;if(t.key!==yr||t.deletedAt!==null)throw Error(`Stored Application Settings are invalid.`);return{colorMode:br.parse(t.value)}}updateApplicationSettings(e){if(this.database.update(H).set({updatedAt:this.now(),value:e.colorMode}).where(y(H.key,yr)).run().changes!==1)throw Error(`Stored Application Settings are invalid.`);return this.getApplicationSettings()}};const Sr=`127.0.0.1`;function Cr(e){return new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})})}async function wr(e={}){let t=e.port??54321,n=await yn({databasePath:e.databasePath,migrationsFolder:e.migrationsFolder}),r=new xn(n.db),i=cn({promptStore:new qt(n.db),providerConnectionTester:new kn,providerStore:r,runtimeService:new _r(new vr(n.db),r,new gr,new dr),settingsStore:new xr(n.db)});return new Promise((e,r)=>{let a=e=>{n.client.close(),r(e)},s=o({fetch:i.fetch,hostname:Sr,port:t},t=>{s.off(`error`,a);let r,i=t.port,o=async()=>{try{await Cr(s)}finally{n.client.close()}};e({close:()=>(r??=o(),r),hostname:Sr,port:i,url:`http://${Sr}:${i}`})});s.once(`error`,a)})}function Tr(e,t){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`?`Port ${t} is already in use on 127.0.0.1.`:`Could not start Foundry Server: ${e instanceof Error?e.message:String(e)}`}function Er(e,t=i,n=console.error){let r=!1,a=()=>{r||(r=!0,t.off(`SIGINT`,a),t.off(`SIGTERM`,a),e.close().catch(e=>{n(`Could not stop Foundry Server: ${e instanceof Error?e.message:String(e)}`),t.exitCode=1}))};return t.once(`SIGINT`,a),t.once(`SIGTERM`,a),()=>{t.off(`SIGINT`,a),t.off(`SIGTERM`,a)}}const Dr={error:console.error,log:console.info,openBrowser:a,registerShutdown:e=>{Er(e)},setExitCode:e=>{i.exitCode=e},startServer:wr};function Or(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n===`--port`){if(t+1>=e.length||e[t+1].startsWith(`--`))return`Missing value for option: --port`;t+=1;continue}if(!n.startsWith(`--port=`)&&n!==`--open`&&n!==`--no-open`)return`${n.startsWith(`-`)?`Unknown option`:`Unexpected argument`}: ${n}`}}function kr(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>65535)throw RangeError(`Port must be an integer between 1 and 65535. Received "${e}".`);return t}function Ar(e=Dr){return t({meta:{description:`Start the Local Web UI`,name:`ui`},args:{port:{default:`54321`,description:`Port for the Local Web UI`,type:`string`,valueHint:`port`},open:{default:!0,description:`Open the Local Web UI in the default browser`,negativeDescription:`Do not open the default browser`,type:`boolean`}},async run({args:t,rawArgs:n}){let r=Or(n);if(r){e.error(`${r}\nRun \`foundry ui --help\` for usage.`),e.setExitCode(1);return}let i;try{i=kr(t.port)}catch(t){e.error(`${t instanceof Error?t.message:String(t)}\nRun \`foundry ui --help\` for usage.`),e.setExitCode(1);return}let a;try{a=await e.startServer({port:i})}catch(t){e.error(Tr(t,i)),e.setExitCode(1);return}if(e.registerShutdown(a),e.log(`Foundry Local Web UI: ${a.url}`),t.open)try{await e.openBrowser(a.url)}catch{e.error(`Could not open the default browser. Open ${a.url} manually.`)}}})}const jr=t({meta:{description:`An AI-native local developer runtime`,name:`foundry`,version:e},subCommands:{ui:Ar()}});function Mr(e){if(!e.some(e=>e===`--help`||e===`-h`)&&(e.length!==1||e[0]!==`--version`&&e[0]!==`-v`)&&!(e[0]===`ui`||!e[0]?.startsWith(`-`)))return`Unknown option: ${e[0]}`}async function Nr(e=i.argv.slice(2)){if(e.length===0){console.info(`${await n(jr)}\n`);return}let t=Mr(e);if(t){console.error(`${t}\nRun \`foundry --help\` for usage.`),i.exitCode=1;return}await r(jr,{rawArgs:e})}Nr();export{};
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
import{t as e}from"./package-
|
|
2
|
+
import{t as e}from"./package-DS5RZ0CH.mjs";function t(){return e}export{t as getVersion};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
CREATE TABLE `prompts` (
|
|
2
|
+
`id` text PRIMARY KEY NOT NULL,
|
|
3
|
+
`title` text NOT NULL,
|
|
4
|
+
`description` text,
|
|
5
|
+
`content` text NOT NULL,
|
|
6
|
+
`created_at` integer NOT NULL,
|
|
7
|
+
`updated_at` integer NOT NULL,
|
|
8
|
+
`deleted_at` integer,
|
|
9
|
+
CONSTRAINT "prompts_id_not_empty" CHECK(length("prompts"."id") > 0),
|
|
10
|
+
CONSTRAINT "prompts_title_valid" CHECK(length(trim("prompts"."title")) BETWEEN 1 AND 100),
|
|
11
|
+
CONSTRAINT "prompts_description_valid" CHECK("prompts"."description" IS NULL OR length("prompts"."description") <= 2000),
|
|
12
|
+
CONSTRAINT "prompts_content_valid" CHECK(length(trim("prompts"."content")) > 0 AND length(CAST("prompts"."content" AS BLOB)) <= 1048576),
|
|
13
|
+
CONSTRAINT "prompts_created_at_nonnegative" CHECK("prompts"."created_at" >= 0),
|
|
14
|
+
CONSTRAINT "prompts_updated_at_valid" CHECK("prompts"."updated_at" >= "prompts"."created_at"),
|
|
15
|
+
CONSTRAINT "prompts_deleted_at_valid" CHECK("prompts"."deleted_at" IS NULL OR "prompts"."deleted_at" >= "prompts"."created_at")
|
|
16
|
+
);
|
|
17
|
+
--> statement-breakpoint
|
|
18
|
+
CREATE INDEX `prompts_updated_at_index` ON `prompts` (`updated_at`);
|