blade-code 0.7.5 → 0.7.6

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.
Files changed (77) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-10q3krvh.js +6 -0
  3. package/dist/chunk-1tzcptyb.js +3 -0
  4. package/dist/{chunk-ay3rhhx8.js → chunk-1y33d6xh.js} +1 -1
  5. package/dist/chunk-5accz8n9.js +1 -0
  6. package/dist/{chunk-kfg3vx5z.js → chunk-64x50qbc.js} +1 -1
  7. package/dist/chunk-8raa4q9y.js +1564 -0
  8. package/dist/chunk-ad19yrq6.js +1 -0
  9. package/dist/{chunk-jsn8476q.js → chunk-arwynrtf.js} +2 -2
  10. package/dist/chunk-bvn4e2vq.js +1 -0
  11. package/dist/{chunk-63dzf6hr.js → chunk-cadngkwr.js} +1 -1
  12. package/dist/{chunk-98jpdmgc.js → chunk-cdx3hp1r.js} +5 -5
  13. package/dist/{chunk-373pmz70.js → chunk-d9qh7bat.js} +1 -1
  14. package/dist/chunk-ebynn53v.js +26 -0
  15. package/dist/{chunk-cyxb6fxe.js → chunk-ezkbqmvd.js} +1 -1
  16. package/dist/{chunk-a8znntss.js → chunk-fceeqn6k.js} +2 -2
  17. package/dist/{chunk-c3yn8ds8.js → chunk-g60w2r7f.js} +2 -2
  18. package/dist/{chunk-k4behavv.js → chunk-h7qab07x.js} +1 -1
  19. package/dist/{chunk-bmcc85nj.js → chunk-jhzf05kz.js} +1 -1
  20. package/dist/chunk-k76q8cyc.js +151 -0
  21. package/dist/chunk-krrm6bjr.js +1 -0
  22. package/dist/{chunk-gjf2d2yg.js → chunk-m3hsaaq5.js} +1 -1
  23. package/dist/chunk-n2yq1wn8.js +9 -0
  24. package/dist/{chunk-rtn0rb16.js → chunk-npaj13y3.js} +2 -2
  25. package/dist/{chunk-0rw4tdqy.js → chunk-pf45ctn7.js} +1 -1
  26. package/dist/{chunk-cw125vv3.js → chunk-q6sj33v8.js} +1 -1
  27. package/dist/chunk-qedtzcp2.js +1 -0
  28. package/dist/{chunk-e21htmg4.js → chunk-qyfdt8h1.js} +1 -1
  29. package/dist/{chunk-38h3yh6z.js → chunk-r0hc7wad.js} +1 -1
  30. package/dist/chunk-rhvxr82g.js +2 -0
  31. package/dist/chunk-t6qek6xk.js +1 -0
  32. package/dist/{chunk-jf48kahn.js → chunk-ttf06k8y.js} +3 -3
  33. package/dist/chunk-tyjns370.js +1 -0
  34. package/dist/{chunk-7pcm8vy5.js → chunk-ve6bvba4.js} +28 -28
  35. package/dist/chunk-wdxbjvd5.js +2 -0
  36. package/dist/{chunk-n969rv4v.js → chunk-wg5nxtb2.js} +1 -1
  37. package/dist/{chunk-qxvp127d.js → chunk-wstkn75a.js} +1 -1
  38. package/dist/chunk-x4fx52e7.js +24 -0
  39. package/dist/chunk-xj63cr29.js +1 -0
  40. package/dist/{chunk-yaj4nmmp.js → chunk-zmndvdgb.js} +1 -1
  41. package/dist/{chunk-pvxp2gzr.js → chunk-zr71r1z1.js} +1 -1
  42. package/dist/web/assets/{FilePreview-evNzCuVx.js → FilePreview-CbtOITD1.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-BQoiQTDd.js → MarkdownRenderer-CW8WpEw1.js} +1 -1
  44. package/dist/web/assets/McpModal-DnqrgBON.js +5 -0
  45. package/dist/web/assets/SettingsModal-CRNT-LCq.js +1 -0
  46. package/dist/web/assets/{SettingsStore-CfDjhOkS.js → SettingsStore-B2GIhfKs.js} +1 -1
  47. package/dist/web/assets/SkillsModal-COQMbIdT.js +1 -0
  48. package/dist/web/assets/{TerminalPanel-Cs16_6ew.js → TerminalPanel-dCMUvQaH.js} +1 -1
  49. package/dist/web/assets/index-21gV5nOE.css +1 -0
  50. package/dist/web/assets/index-Cnz-_jPt.js +10 -0
  51. package/dist/web/assets/{useRequest-BJp539HQ.js → useRequest-C7k7cDPD.js} +1 -1
  52. package/dist/web/assets/{vendor-icons-DlzC8I7m.js → vendor-icons-BKXQ7ALf.js} +75 -30
  53. package/dist/web/assets/{vendor-radix-CfxBc_4-.js → vendor-radix-2yBsoRqx.js} +2 -2
  54. package/dist/web/index.html +2 -2
  55. package/package.json +1 -1
  56. package/dist/chunk-1vngdr7p.js +0 -1
  57. package/dist/chunk-5smacbk0.js +0 -24
  58. package/dist/chunk-8ea9h3mb.js +0 -151
  59. package/dist/chunk-8w1hd9ct.js +0 -1534
  60. package/dist/chunk-aevyre2t.js +0 -1
  61. package/dist/chunk-apb1p5q4.js +0 -1
  62. package/dist/chunk-b4hmtjec.js +0 -1
  63. package/dist/chunk-cqrg2pp7.js +0 -1
  64. package/dist/chunk-g1eb7f4q.js +0 -1
  65. package/dist/chunk-jfykets9.js +0 -6
  66. package/dist/chunk-kssr4fbg.js +0 -1
  67. package/dist/chunk-rkhhzc4r.js +0 -26
  68. package/dist/chunk-vhc1yr3v.js +0 -1
  69. package/dist/chunk-w1zb8zac.js +0 -3
  70. package/dist/chunk-yz2jztga.js +0 -7
  71. package/dist/chunk-zye2s6f0.js +0 -2
  72. package/dist/web/assets/McpModal-BT9OivhK.js +0 -5
  73. package/dist/web/assets/SettingsModal-CDRcorCS.js +0 -1
  74. package/dist/web/assets/SkillsModal-DCPaqoOe.js +0 -1
  75. package/dist/web/assets/dialog-C8VDk-ma.js +0 -1
  76. package/dist/web/assets/index-9t-WxRrl.js +0 -10
  77. package/dist/web/assets/index-Bu13aXyE.css +0 -1
@@ -1 +0,0 @@
1
- import{v as a,w as b,x as c}from"./chunk-cw125vv3.js";import"./chunk-k4behavv.js";import"./chunk-e21htmg4.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-63dzf6hr.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
1
- import{Da as a,Ea as b,Fa as c,Ga as d,Ha as e,Ia as f}from"./chunk-jsn8476q.js";import"./chunk-kfg3vx5z.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +0,0 @@
1
- import{ma as a,na as b,oa as c,pa as d,qa as e,ra as f,sa as g,ta as h,ua as i,va as j,wa as k,xa as l,ya as m}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-63dzf6hr.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-gjf2d2yg.js";import"./chunk-kfg3vx5z.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{$a as l,Pa as a,Qa as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,e as ConversationState};
@@ -1,6 +0,0 @@
1
- import{p as A,q as E,r as N,s as f}from"./chunk-yaj4nmmp.js";import{t as D}from"./chunk-n969rv4v.js";import{v as L,w as _,x}from"./chunk-cw125vv3.js";import{y as B}from"./chunk-k4behavv.js";import{H as $,N as b}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as Z}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as Y,tb as T}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
- `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
- `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
- `);else F.stdout.write(`${H}
5
- `);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
6
- `),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-n969rv4v.js";import"./chunk-jsn8476q.js";import"./chunk-kfg3vx5z.js";export{a as globalOptions,b as cliConfig};
@@ -1,26 +0,0 @@
1
- import{tb as $}from"./chunk-63dzf6hr.js";import{Lb as w}from"./chunk-w1zb8zac.js";var F={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as T}from"fs";import{merge as _}from"lodash-es";import I from"os";import G from"path";var M={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function U(J){let q=J.toLowerCase().trim();return M[q]??J}class B{static instance=null;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async initialize(J){try{let q=await this.loadConfigFiles(),H=await this.loadSettingsFiles(),K={...q,...H};if(J)K=this.mergeSettings(K,J);let Q=this.normalizeConfig(K),W={...F,...Q};if(this.resolveEnvInterpolation(W),process.env.BLADE_MODEL&&W.models?.length>0){let X=U(process.env.BLADE_MODEL),Y=W.models.find((Z)=>Z.id===X||Z.model===X||Z.id===process.env.BLADE_MODEL||Z.model===process.env.BLADE_MODEL);if(Y)W.currentModelId=Y.id}if(process.env.BLADE_API_KEY&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.apiKey=process.env.BLADE_API_KEY}if(process.env.BLADE_BASE_URL&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.baseUrl=process.env.BLADE_BASE_URL}if(process.env.BLADE_DEBUG)W.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(W.debug)console.log("[ConfigManager] Configuration loaded successfully");return W}catch(q){return console.error("[ConfigManager] Failed to initialize:",q),F}}async loadConfigFiles(){let J=G.join(I.homedir(),".blade","config.json"),q=G.join($(),".blade","config.json"),H={},K=await this.loadJsonFile(J);if(K)H={...H,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...H.mcpServers||{},...Q.mcpServers||{}};if(H={...H,...Q},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=G.join(I.homedir(),".blade","settings.json"),q=G.join($(),".blade","settings.json"),H=G.join($(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(J);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(H);if(X)K=this.mergeSettings(K,X);return K}mergeSettings(J,q){let H={...JSON.parse(JSON.stringify(J)),...JSON.parse(JSON.stringify(q))};if(q.permissions)H.permissions={allow:Array.from(new Set([...J.permissions?.allow||[],...q.permissions.allow||[]])),ask:Array.from(new Set([...J.permissions?.ask||[],...q.permissions.ask||[]])),deny:Array.from(new Set([...J.permissions?.deny||[],...q.permissions.deny||[]]))};if(q.hooks)H.hooks=_({},H.hooks,q.hooks);if(q.env)H.env=_({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,Z)=>{return process.env[X]||Z||W});if(Array.isArray(Q))return Q.map(H);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return Q},K=J;for(let[Q,W]of Object.entries(K))K[Q]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await T.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await T.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=H(X);else if(Array.isArray(X))X.forEach((Y,Z)=>{if(typeof Y==="string")X[Z]=H(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(J){let q=[],H=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((Q)=>Q.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let K of J.models){let Q=`模型 "${K.name||K.id}"`;if(!K.apiKey)H.push(`${Q}: apiKey 为空`);if(!K.model)q.push(`${Q}: model 字段必填`);if(!K.provider)q.push(`${Q}: provider 字段必填`);if(K.baseUrl&&!K.baseUrl.startsWith("http"))H.push(`${Q}: baseUrl "${K.baseUrl}" 不是有效的 HTTP URL`)}}if(H.length>0)console.warn(`[ConfigManager] 配置警告:
2
- ${H.map((K)=>` ⚠ ${K}`).join(`
3
- `)}`);if(q.length>0)throw Error(`配置验证失败:
4
- ${q.map((K)=>` - ${K}`).join(`
5
- `)}
6
-
7
- `+`请通过以下方式之一提供配置:
8
- `+` 1. 首次启动: 运行 blade,系统会自动引导配置
9
- `+` 2. 添加模型: blade 后输入 /model add
10
- `+` 3. 初始化向导: 输入 /init
11
-
12
- `+`配置文件示例 (~/.blade/config.json):
13
- `+`{
14
- "currentModelId": "model-id-123",
15
- "models": [
16
- {
17
- "id": "model-id-123",
18
- `+` "name": "默认模型",
19
- `+` "provider": "openai-compatible",
20
- "apiKey": "your-api-key",
21
- "baseUrl": "https://api.example.com/v1",
22
- "model": "model-name"
23
- }
24
- ]
25
- }
26
- `)}}function j(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{Mutex as A}from"async-mutex";import{merge as b}from"lodash-es";import{promises as N}from"node:fs";import E from"node:os";import V from"node:path";import x from"write-file-atomic";var L=w("Service"),R={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},Hq=new Set(Object.entries(R).filter(([J,q])=>q.persistable).map(([J])=>J)),Jq=new Set(Object.entries(R).filter(([J,q])=>!q.persistable).map(([J])=>J));class z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!z.instance)z.instance=new z;return z.instance}static resetInstance(){if(z.instance)for(let J of z.instance.timers.values())clearTimeout(J);z.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){let H=q.scope??"local",K=this.resolveFilePath("settings",H);await this.flushTargetWithModifier(K,(Q)=>{let W=Q.permissions??{allow:[],ask:[],deny:[]},X={allow:this.dedupeArray([...W.allow||[],J]),ask:W.ask||[],deny:W.deny||[]};return{...Q,permissions:X}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=R[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q){let H=new Map;for(let[K,Q]of Object.entries(J)){let W=R[K];if(!W)continue;let X=q??W.defaultScope,Y=this.resolveFilePath(W.target,X);if(!H.has(Y))H.set(Y,{});H.get(Y)[K]=Q}return H}resolveFilePath(J,q){if(J==="config")return q==="global"?V.join(E.homedir(),".blade","config.json"):V.join($(),".blade","config.json");switch(q){case"local":return V.join($(),".blade","settings.local.json");case"project":return V.join($(),".blade","settings.json");case"global":return V.join(E.homedir(),".blade","settings.json");default:return V.join($(),".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=Z,L.error(`Failed to save config to ${J}:`,Z.message),L.error("Stack trace:",Z.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=R[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await N.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await N.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=R[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=b({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await x(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function S(){return z.getInstance()}export{F as za,B as Aa,j as Ba,S as Ca};
@@ -1 +0,0 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-zye2s6f0.js";import"./chunk-pvxp2gzr.js";import"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import{sa as q}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,3 +0,0 @@
1
- import{Nb as F}from"./chunk-kfg3vx5z.js";import{appendFileSync as N,existsSync as R,mkdirSync as x,readdirSync as m,statSync as z,unlinkSync as V}from"node:fs";import Y from"node:path";import{execSync as A}from"node:child_process";import*as O from"node:os";import*as Q from"node:path";function B(q){return Q.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function v(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function U(q){let G=B(q);return Q.join(W(),"projects",G)}function _(q){if(q==="."||q===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(q))throw Error(`Invalid session ID: ${q}`)}function P(q,G){return _(G),Q.join(U(q),`${G}.jsonl`)}function f(q,G){return _(G),Q.join(U(q),`${G}.inbox.json`)}function I(q){try{return A("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function W(){return process.env.BLADE_STORAGE_ROOT||Q.join(O.homedir(),".blade")}async function h(){let{readdir:q}=await import("node:fs/promises");try{let G=Q.join(W(),"projects");return(await q(G,{withFileTypes:!0})).filter((H)=>H.isDirectory()).map((H)=>H.name)}catch{return[]}}var Z;((J)=>{J[J.DEBUG=0]="DEBUG";J[J.INFO=1]="INFO";J[J.WARN=2]="WARN";J[J.ERROR=3]="ERROR"})(Z||={});var X=null,k=null,w=!1;function L(q){if(X!==q)X=q}async function d(){}function j(){if(w)return k;w=!0;try{let q=Y.join(W(),"logs");if(!R(q))x(q,{recursive:!0,mode:493});if(z(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return C(q,30),k=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function C(q,G){try{let K=m(q),H=Date.now(),J=G*24*60*60*1000;for(let T of K){if(!T.startsWith("blade-")||!T.endsWith(".log")&&!T.endsWith(".jsonl"))continue;let $=Y.join(q,T);try{let E=z($);if(H-E.mtimeMs>J)V($)}catch(E){}}}catch(K){}}function b(){let q=j();if(!q)return null;let G=X||"default";return Y.join(q,`blade-${G}.jsonl`)}function D(q,G,K){let H=b();if(!H)return;try{let J={timestamp:new Date().toISOString(),level:Z[G],category:q,message:K};N(H,JSON.stringify(J)+`
2
- `)}catch(J){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((J)=>J.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((H)=>H.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((K)=>G.includes(K.toLowerCase()));return!q.categories.some((K)=>G.includes(K.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:K}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(K)}return this.enabled&&q>=this.minLevel}log(q,...G){let K=G.map((H)=>typeof H==="object"?JSON.stringify(H):String(H)).join(" ");if(D(this.category,q,K),this.shouldLogToConsole(q)){let H=Z[q],J=`[${this.category}] [${H}]`;console.error(J,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function n(q,G){return new M({...G,category:q})}var i=new M({category:"General"});
3
- export{v as Bb,U as Cb,P as Db,f as Eb,I as Fb,W as Gb,h as Hb,L as Ib,d as Jb,M as Kb,n as Lb,i as Mb};
@@ -1,7 +0,0 @@
1
- import{B as W,H as P,K as T,L as R,N as M,Q as B,T as j,V as A,W as h}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import{_ as x}from"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import{ra as y}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as L}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{tb as U}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import{Lb as _}from"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import{Readable as c,Writable as p}from"node:stream";import*as w from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as C}from"@agentclientprotocol/sdk";import{nanoid as v}from"nanoid";import{nanoid as k}from"nanoid";var Z=_("Agent");function f(z){return Object.fromEntries(z.map((G)=>[G.name,G.value]))}function S(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function u(z){return Object.fromEntries(z.map((G)=>[G.name,S(G)]))}function O(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((G)=>{if(G.type==="text")return G.text?[{type:"text",text:G.text}]:[];let H=G.image_url.url,J=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!J)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:J[1]??"image/png",data:J[2]??""}]})}class D{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;messages;mode="default";sessionApprovals=new Set;constructor(z,G,H,J,Q={}){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=J;this.options=Q;this.messages=[...Q.initialMessages??[]]}async initialize(){Z.debug(`[AcpSession ${this.id}] Initializing...`),W.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),Z.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?u(this.options.mcpServers):void 0;if(this.runtime=await P.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await M.createWithRuntime(this.runtime,{sessionId:this.id}),Z.debug(`[AcpSession ${this.id}] Agent created successfully`),this.runtime.getPendingSteeringCount()>0)if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){let G=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!G)continue;for(let H of O(z.content))await this.connection.sessionUpdate({sessionId:this.id,update:{sessionUpdate:G,content:H}})}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){Z.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{Z.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(X)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}})},sendToolStart:(X,Y,E)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,$=this.mapToolKind(E);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${X}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:$})},sendToolResult:(X,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},J=await A(z,H),Q=J.content||J.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(J.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${J.error}`}});return{stopReason:J.success?"end_turn":"cancelled"}}catch(H){return Z.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=h(),G=["model","permissions","theme","config","exit","ide"],J=z.filter((Q)=>!G.includes(Q.name)).map((Q)=>{let X;if(Q.usage){let Y=Q.usage.replace(/^\/\w+\s*/,"").trim();if(Y)X=Y}if(Q.aliases?.length){let Y=`Aliases: ${Q.aliases.join(", ")}`;X=X?`${X} | ${Y}`:Y}return{name:Q.name,description:Q.description,input:X?{hint:X}:void 0}});Z.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(J.map((Q)=>Q.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:J}),Z.info(`[AcpSession ${this.id}] Sent ${J.length} available commands`)}catch(z){Z.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,G={}){if(W.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt);if(this.pendingPrompt){let Q=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!Q.accepted)throw Error(Q.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(Z.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Q.queued})`),Q.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let J=new AbortController;this.pendingPrompt=J;try{if(Z.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),j(H))return await this.handleSlashCommand(H,J.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:J.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(X)=>{return this.requestPermission(X)}}};if(await L(this.agent.chatStream(H,Q,{pendingInputOnly:G.pendingInputOnly}),async(X)=>{switch(X.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:X.delta}});break;case"tool_start":{let Y=X.toolCall,E="function"in Y?Y.function.name:Y.type,F=this.mapToolKind(X.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.id,status:"in_progress",title:`Executing ${E}`,content:[],kind:F});break}case"tool_result":{let{toolCall:Y,result:E}=X,F=[],$=E.metadata;if($?.kind==="edit"&&typeof $.file_path==="string"&&typeof $.oldContent==="string"&&(typeof $.newContent==="string"||$.newContent===void 0))F.push({type:"diff",path:$.file_path,oldText:$.oldContent,newText:$.newContent??null});else{let I="function"in Y?Y.function.name:Y.type,K=R(T(I,E));F.push({type:"content",content:{type:"text",text:K}})}let V=E.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.id,status:V,content:F});break}case"task_update":this.sendPlanUpdate(X.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Y of X.messages){if(!Y.recovered||Y.persisted)continue;for(let E of O(Y.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:E})}if(X.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${X.recovered} queued instruction${X.recovered===1?"":"s"} recovered after restart]
2
- `}});break;default:break}}),this.messages=[...Q.messages],J.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(Q){if(J.signal.aborted||Q instanceof Error&&Q.name==="AbortError")return{stopReason:"cancelled"};throw Z.error(`[AcpSession ${this.id}] Prompt error:`,Q),Q}finally{if(this.pendingPrompt===J){if(this.pendingPrompt=null,this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.pendingPrompt||!this.runtime||!this.agent)return;if(this.runtime.getPendingSteeringCount()===0){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:!0}).catch((z)=>{Z.error(`[AcpSession ${this.id}] Failed to resume pending input:`,z)})}cancel(){if(Z.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,Z.info(`[AcpSession ${this.id}] Cancelled successfully`);else Z.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",Z.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(Z.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;W.destroySession(this.id),Z.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let J=H.resource;if("text"in J)G.push(`<file path="${J.uri}">
3
- ${J.text}
4
- </file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
5
- `)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{Z.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));Z.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return Z.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return Z.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return Z.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let J=k(),Q=[];if(z.message)Q.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)Q.push({type:"content",content:{type:"text",text:`Risks:
6
- - ${z.risks.join(`
7
- - `)}`}});let X=this.mapToolKind(G),Y={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:J,status:"pending",title:z.title||"Permission Required",content:Q,kind:X}},F=(await this.connection.requestPermission(Y)).outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let $=F.optionId,V=$==="allow_once"||$==="allow_always";if($==="allow_always")this.sessionApprovals.add(H),Z.debug(`[AcpSession ${this.id}] Cached approval for: ${H}`);return{approved:V,reason:V?void 0:"User denied the operation"}}catch(J){return Z.warn(`[AcpSession ${this.id}] Permission request failed:`,J),{approved:!1,reason:"Permission request failed"}}}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var q=_("Agent");class N{connection;sessions=new Map;clientCapabilities;constructor(z){this.connection=z}async initialize(z){return q.info("[BladeAgent] Initializing ACP connection"),q.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:C,agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){let G=v();q.info(`[BladeAgent] Creating new session: ${G}`),q.debug(`[BladeAgent] Session cwd: ${z.cwd||U()}`);let H=new D(G,z.cwd||U(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await H.initialize()}catch(J){throw await H.destroy().catch(()=>{return}),J}return this.sessions.set(G,H),q.info(`[BladeAgent] Session ${G} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),{sessionId:G,...this.buildSessionState()}}async loadSession(z){q.info(`[BladeAgent] Loading session: ${z.sessionId}`);let G=await B.loadSession(z.sessionId,z.cwd),H=this.sessions.get(z.sessionId);if(H)await H.destroy(),this.sessions.delete(z.sessionId),G=await B.loadSession(z.sessionId,z.cwd);let J=new D(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:G,mcpServers:z.mcpServers});try{await J.initialize(),await J.replayHistory()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(z.sessionId,J),J.sendAvailableCommandsDelayed(),this.buildSessionState()}buildSessionState(){let z=y(),G=z?.models||[],H=z?.currentModelId||G[0]?.id,J=G.map((X)=>({modelId:X.id,name:X.name||X.id,description:X.provider?`Provider: ${X.provider}`:void 0}));return{modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:J.length>0?{availableModels:J,currentModelId:H}:void 0}}async prompt(z){let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return G.prompt(z)}async cancel(z){q.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let G=this.sessions.get(z.sessionId);if(G)q.info("[BladeAgent] Found session, calling session.cancel()"),G.cancel();else q.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){q.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let G=this.sessions.get(z.sessionId);if(G)await G.setMode(z.modeId);return{}}async unstable_setSessionModel(z){q.info(`[BladeAgent] Setting session model: ${z.modelId}`);let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return await G.setModel(z.modelId),{}}async destroy(){for(let z of this.sessions.values())await z.destroy();this.sessions.clear(),await x.getInstance().disconnectAll()}}async function Ez(){let z=p.toWeb(process.stdout),G=c.toWeb(process.stdin),H=w.ndJsonStream(z,G);await new w.AgentSideConnection((Q)=>new N(Q),H).closed}export{Ez as runAcpIntegration};
@@ -1,2 +0,0 @@
1
- import{j as mf,k as kf}from"./chunk-pvxp2gzr.js";import{A as uf,C as Zf,D as xf,H as Xf,I as v,K as Df,L as wf,N as bf,Q as I,X as pf}from"./chunk-8w1hd9ct.js";import{_ as k}from"./chunk-a8znntss.js";import{ra as r,ta as _f,ua as Cf,ya as m}from"./chunk-5smacbk0.js";import{Ea as o}from"./chunk-jsn8476q.js";import{Ka as hf,Ma as Jf,Va as Nf}from"./chunk-7pcm8vy5.js";import{tb as A}from"./chunk-63dzf6hr.js";import{Lb as q}from"./chunk-w1zb8zac.js";import{Nb as Uf}from"./chunk-kfg3vx5z.js";var o0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function a0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as k0}from"hono";import{cors as S0}from"hono/cors";import{existsSync as ef,readFileSync as Kf}from"node:fs";import{createServer as h0}from"node:http";import{networkInterfaces as I0}from"node:os";import{dirname as v0,extname as u0,join as g}from"node:path";import{fileURLToPath as p0}from"node:url";import{WebSocketServer as g0}from"ws";import{z as $f}from"zod";class i extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class l extends i{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class w extends i{constructor(V){super("BAD_REQUEST",V,400)}}var i0=$f.object({error:$f.object({code:$f.string(),message:$f.string()})});import{Hono as V0}from"hono";import{z as c}from"zod";var jf=q("Service"),J0=c.object({updates:c.record(c.any()),options:c.object({scope:c.enum(["local","project","global"]).optional(),immediate:c.boolean().optional()}).optional()}),Af=()=>{let V=new V0;return V.get("/",async($)=>{try{let f=r();return $.json(f||{})}catch(f){return jf.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),J=J0.safeParse(f);if(!J.success)throw new w("Invalid config update format");let{updates:Q,options:K}=J.data;return await m().updateConfig(Q,K),$.json({success:!0,updates:Q})}catch(f){throw jf.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=r();return $.json(f?.permissions||{})}catch(f){return jf.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as Q0}from"hono";var Tf=()=>{let V=new Q0;return V.get("/health",($)=>{return $.json({healthy:!0,version:o()})}),V.get("/info",($)=>{return $.json({version:o(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:A()})}),V};import{Hono as Y0}from"hono";var e=q("Service"),Hf=()=>{let V=new Y0;return V.get("/",async($)=>{try{let J=k.getInstance().getAllServers(),Q=Array.from(J.entries()).map(([K,Z])=>({id:K,name:K,status:Z.status==="connected"?"connected":Z.status==="connecting"?"connecting":Z.lastError?"error":"offline",endpoint:Z.config.command?`${Z.config.command} ${(Z.config.args||[]).join(" ")}`.trim():Z.config.url||"Unknown",description:`MCP server: ${K}`,tools:Z.tools.map((X)=>X.name),connectedAt:Z.connectedAt?.toISOString(),error:Z.lastError?.message}));return $.json(Q)}catch(f){return e.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await k.getInstance().connectServer(f),$.json({success:!0})}catch(f){return e.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await k.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return e.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await k.getInstance().unregisterServer(f);let Q=r();if(Q?.mcpServers){let{[f]:K,...Z}=Q.mcpServers;await m().updateConfig({mcpServers:Z})}return $.json({success:!0})}catch(f){return e.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:J,config:Q}=f;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await k.getInstance().registerServer(J,Q);let Z=r();return await m().updateConfig({mcpServers:{...Z?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(f){return e.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as Z0}from"hono";var Vf=q("Service"),zf=()=>{let V=new Z0;return V.get("/",async($)=>{try{let f=_f(),J=Cf();return $.json({configured:f,current:J})}catch(f){return Vf.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:J,name:Q,model:K,baseUrl:Z,apiKey:X}=f;if(!K)throw new w("model is required");let E=await m().addModel({provider:J||"openai-compatible",name:Q||K,model:K,baseUrl:Z||void 0,apiKey:X||void 0});return $.json({success:!0,model:E})}catch(f){throw Vf.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),J=await $.req.json(),{baseUrl:Q,apiKey:K,model:Z}=J;return await m().updateModel(f,{baseUrl:Q||void 0,apiKey:K||void 0,model:Z||void 0}),$.json({success:!0})}catch(f){throw Vf.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await m().removeModel(f),$.json({success:!0})}catch(f){throw Vf.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as U0}from"hono";import{z as y}from"zod";import{Mutex as K0}from"async-mutex";import{Hono as G0}from"hono";import{streamSSE as O0}from"hono/streaming";import{LRUCache as j0}from"lru-cache";import{nanoid as u}from"nanoid";import{z as H}from"zod";var T=q("Service"),N0=H.object({title:H.string().optional(),projectPath:H.string().optional()}),X0=H.object({content:H.string(),attachments:H.array(H.object({type:H.enum(["file","image","url"]),path:H.string().optional(),url:H.string().optional(),content:H.string().optional(),mimeType:H.string().optional(),name:H.string().optional()})).optional(),permissionMode:H.enum(["default","autoEdit","plan","yolo"]).optional()}),M0=H.object({title:H.string().optional()}),R=new Map,L=new j0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),T.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),E0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function Mf(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
- `)}function F0(V,$){let f=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(f.length===0)return V;let J=[];if(V.trim())J.push({type:"text",text:V});return J.push(...f),J}var Rf=()=>{let V=new G0,$=new Map,f=new Map,J=new Map,Q=new Map,K=(Y)=>{let G=Q.get(Y);if(!G)G=new K0,Q.set(Y,G);return G},Z=async(Y)=>{let G=$.get(Y.id);if(G)return G;let j=f.get(Y.id);if(!j)j=Xf.create({sessionId:Y.id,workspaceRoot:Y.projectPath}),f.set(Y.id,j);try{let O=await j;return $.set(Y.id,O),O}finally{if(f.get(Y.id)===j)f.delete(Y.id)}},X=async(Y,G)=>{let j=R.get(Y);if(j)return j;let O=J.get(Y);if(!O)O=(async()=>{let F=(await I.listSessions()).find((_)=>_.sessionId===Y),x=F?.projectPath??G,W=F?await I.loadSession(Y,x).catch(()=>[]):[],U={id:Y,projectPath:x,title:`Session ${Y.slice(0,6)}`,createdAt:F?new Date(F.firstMessageTime):new Date,messages:W,relationType:F?.relationType};return R.set(Y,U),U})(),J.set(Y,O);try{return await O}finally{if(J.get(Y)===O)J.delete(Y)}},E=(Y,G,j,O={})=>{let F=u(12),x={id:F,sessionId:Y.id,status:"running",abortController:new AbortController,createdAt:new Date};return L.set(F,x),Y.currentRunId=F,x0(x,Y,G,j,Z,{pendingInputOnly:O.pendingInputOnly,preparedInputTurn:O.preparedInputTurn}).catch((W)=>{T.error(`[SessionRoutes] Run ${F} failed:`,W)}),x},N=async(Y)=>{let G=Y.currentRunId?L.get(Y.currentRunId):void 0;if(G&&(G.status==="running"||G.status==="waiting_permission"))return;if(!await Xf.hasPendingInbox(Y.projectPath,Y.id))return;let j=await Z(Y),O=Y.currentRunId?L.get(Y.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))return;if(j.getPendingSteeringCount()===0||j.hasTurnOwner())return;E(Y,"","default",{pendingInputOnly:!0})};return V.get("/",async(Y)=>{try{let G=await I.listSessions(),j=new Set(G.filter((B)=>B.relationType==="subagent").map((B)=>B.sessionId)),O=Array.from(R.values()).filter((B)=>!j.has(B.id)&&B.relationType!=="subagent").map((B)=>({sessionId:B.id,projectPath:B.projectPath,title:B.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:B.messages.length,firstMessageTime:B.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),F=new Set(O.map((B)=>B.sessionId)),x=G.filter((B)=>!R.has(B.sessionId)&&!F.has(B.sessionId)&&B.relationType!=="subagent"),W=new Set(F),U=x.filter((B)=>{if(W.has(B.sessionId))return!1;return W.add(B.sessionId),!0}),_=[...O,...U];return Y.json(_)}catch(G){return T.error("[SessionRoutes] Failed to list sessions:",G),Y.json([])}}),V.post("/",async(Y)=>{try{let G=await Y.req.json(),j=N0.safeParse(G);if(!j.success)throw new w("Invalid request body");let{title:O,projectPath:F}=j.data,x=u(12),W=F||Y.get("directory")||A(),U={id:x,projectPath:W,title:O||`Session ${x.slice(0,6)}`,createdAt:new Date,messages:[]};return R.set(x,U),Y.json({sessionId:x,projectPath:W,title:U.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:U.createdAt.toISOString(),lastMessageTime:U.createdAt.toISOString(),hasErrors:!1})}catch(G){throw T.error("[SessionRoutes] Failed to create session:",G),G}}),V.get("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j)return Y.json({sessionId:j.id,projectPath:j.projectPath,title:j.title,messageCount:j.messages.length,firstMessageTime:j.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let F=(await I.listSessions()).find((x)=>x.sessionId===G);if(!F)throw new l("Session",G);return Y.json(F)}catch(O){if(O instanceof l)throw O;throw T.error("[SessionRoutes] Failed to get session:",O),O}}),V.patch("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId");try{let j=await Y.req.json(),O=M0.safeParse(j);if(!O.success)throw new w("Invalid request body");let{title:F}=O.data,x=R.get(G);if(x&&F)x.title=F;return Y.json({success:!0,title:F})}catch(j){throw T.error("[SessionRoutes] Failed to update session:",j),j}}),V.delete("/:sessionId",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j?.currentRunId){let F=L.get(j.currentRunId);if(F)F.abortController.abort(),v.publish(G,"run.cancelled",{runId:F.id}),L.delete(j.currentRunId)}try{await I.deleteSession(G)}catch(F){T.warn("[SessionRoutes] Failed to delete session file:",F)}R.delete(G),J.delete(G),f.delete(G),Q.delete(G);let O=$.get(G);if(O){if(await O.dispose(),$.delete(G),$.size===0)await k.getInstance().disconnectAll()}return Y.json({success:!0})}),V.get("/:sessionId/message",async(Y)=>{let G=Y.req.param("sessionId");try{let j=await I.loadSession(G);return Y.json(j)}catch(j){return T.error("[SessionRoutes] Failed to get messages:",j),Y.json([])}}),V.get("/:sessionId/events",async(Y)=>{let G=Y.req.param("sessionId"),j=await X(G,Y.get("directory")||A());return O0(Y,async(O)=>{await O.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:G,timestamp:Date.now()}})});let x=v.subscribe((U)=>{if(U.sessionId!==G)return;O.writeSSE({data:JSON.stringify({type:U.type,properties:{sessionId:U.sessionId,...U.properties}})}).catch(()=>{})});N(j).catch((U)=>{T.error(`[SessionRoutes] Failed to resume pending input for ${G}:`,U)});let W=setInterval(()=>{if(!O.aborted)O.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);O.onAbort(()=>{clearInterval(W),x()});while(!0)if(await new Promise((U)=>setTimeout(U,1000)),O.aborted)break})}),V.post("/:sessionId/message",async(Y)=>{let G=Y.req.param("sessionId"),j=await Y.req.json(),O=X0.safeParse(j);if(!O.success)throw new w("Invalid message format");let{content:F,attachments:x,permissionMode:W}=O.data,U=W||"default",_=Y.get("directory")||A(),B=F0(F,x),z=await X(G,_);return K(G).runExclusive(async()=>{let M=z.currentRunId?L.get(z.currentRunId):void 0;if(M&&(M.status==="running"||M.status==="waiting_permission")){let b=await(await Z(z)).enqueueSteering(B,{allowBeforeTurn:!0});if(!b.accepted)return Y.json({status:"rejected",reason:b.reason??"turn_unavailable"},409);let n=b.messageId??u(12),ff=b.queued;v.publish(G,"message.created",{messageId:n,role:"user",content:Mf(B)});let f0=b.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(v.publish(G,f0,{runId:M.id,messageId:n,queued:ff}),b.delivery==="next_turn"&&M.status!=="running"&&M.status!=="waiting_permission")N(z).catch(($0)=>{T.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,$0)});if(b.delivery==="next_turn")M.pendingFollowUpRequested=!0;return Y.json({runId:M.id,messageId:n,status:b.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:ff},202)}let d=await(await Z(z)).prepareInputTurn(B);if(!d.accepted)return Y.json({status:"rejected",reason:d.reason},d.reason==="queue_full"?429:409);let Gf=E(z,B,U,{preparedInputTurn:d});return Y.json({runId:Gf.id,messageId:d.messageId,status:"running"},202)})}),V.post("/:sessionId/abort",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(j?.currentRunId){let O=L.get(j.currentRunId);if(O)O.abortController.abort(),O.status="cancelled",v.publish(G,"run.cancelled",{runId:O.id})}return Y.json({success:!0})}),V.get("/:sessionId/status",async(Y)=>{let G=Y.req.param("sessionId"),j=R.get(G);if(!j?.currentRunId)return Y.json({sessionId:G,status:"idle"});let O=L.get(j.currentRunId);return Y.json({sessionId:G,runId:j.currentRunId,status:O?.status||"idle"})}),V};async function x0(V,$,f,J,Q,K={}){let{abortController:Z,sessionId:X,id:E}=V,N=K.preparedInputTurn?.messageId??u(12),G=K.pendingInputOnly===!0||K.preparedInputTurn?.mode==="pending"?void 0:u(12),j,O=(F,x)=>{v.publish(X,F,x)};try{if(!K.pendingInputOnly)O("message.created",{messageId:N,role:"user",content:Mf(f)});if(O("session.status",{status:"running"}),G)O("message.created",{messageId:G,role:"assistant",content:""});j=await Q($);let F=j,x=await bf.createWithRuntime(F,{sessionId:X}),W=async(M)=>{let C=u(12),d=300000;V.status="waiting_permission";let Gf=new Promise((b)=>{let n=setTimeout(()=>{T.warn(`[SessionRoutes] Permission ${C} timed out after 300000ms`),O("permission.timeout",{requestId:C}),b({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:C,resolve:(ff)=>{clearTimeout(n),b(ff)},details:M}});O("permission.asked",{requestId:C,toolName:M.toolName,description:M.message,args:M.args,details:M}),T.info(`[SessionRoutes] Permission request created: ${C}, runId: ${E}`);let Of=await Gf;return T.info(`[SessionRoutes] Permission response received: ${C}, approved: ${Of.approved}`),V.status="running",V.pendingPermission=void 0,Of},U={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:Z.signal,permissionMode:J,confirmationHandler:{requestConfirmation:W}},_=()=>{if(!G)G=u(12),O("message.created",{messageId:G,role:"assistant",content:""});return G},B=async(M)=>{switch(M.kind){case"content_delta":O("message.delta",{messageId:_(),delta:M.delta});break;case"thinking_delta":O("thinking.delta",{delta:M.delta});break;case"tool_start":if("function"in M.toolCall)O("tool.start",{messageId:_(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,arguments:M.toolCall.function.arguments,toolKind:M.toolKind});break;case"tool_result":if("function"in M.toolCall)O("tool.result",{messageId:_(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,success:M.result.success,summary:M.result.metadata?.summary,output:wf(Df(M.toolCall.function.name,M.result)),metadata:E0(M.result.metadata)});break;case"token_usage":O("token.usage",{...M.usage});break;case"turn_start":O("turn.started",{turn:M.turn,maxTurns:M.maxTurns});break;case"steering_applied":O("steering.applied",{runId:E,messageIds:M.messageIds,count:M.count,recovered:M.recovered,delivery:M.delivery,queued:F.getPendingSteeringCount()});break;case"follow_up_started":{if(G)O("message.complete",{messageId:G}),G=void 0;for(let C of M.messages){if(!C.recovered||C.persisted)continue;O("message.created",{messageId:C.id,role:"user",content:Mf(C.content),recovered:!0})}O("follow_up.started",{runId:E,queued:M.queued,recovered:M.recovered}),_();break}case"compaction":O(M.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":O("model.fallback",{});break;case"task_update":O("task.updated",{tasks:M.tasks});break;default:break}},z=await Nf(x.chatStream(f,U,{stream:!0,pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn}),B);if(!z.success)throw Error(z.error?.message??"Agent run failed");for(let M=0;M<20;M++){let C=V.pendingFollowUpRequested===!0;if(V.pendingFollowUpRequested=!1,F.getPendingSteeringCount()===0){if(!C)break;continue}if(Z.signal.aborted)break;if(z=await Nf(x.chatStream("",U,{stream:!0,pendingInputOnly:!0}),B),!z.success)throw Error(z.error?.message??"Agent follow-up failed")}if($.messages=[...U.messages],G)O("message.complete",{messageId:G});O("thinking.completed",{}),V.status="completed",O("session.completed",{runId:E,outputTruncated:z.metadata?.outputTruncated??!1}),O("session.status",{status:"idle"})}catch(F){if(j&&K.preparedInputTurn)await j.finishTurn(K.preparedInputTurn.handle).catch(()=>{return});T.error("[SessionRoutes] Agent execution error:",F),V.status="failed",O("session.error",{error:F instanceof Error?F.message:"Unknown error"}),O("session.status",{status:"error"})}}function yf(V,$,f){T.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),T.info(`[SessionRoutes] Active runs: ${L.size}`);for(let[J,Q]of L.entries())if(T.info(`[SessionRoutes] Checking run ${J}: sessionId=${Q.sessionId}, pendingPermission=${Q.pendingPermission?.permissionId}`),Q.sessionId===V&&Q.pendingPermission?.permissionId===$)return Q.pendingPermission.resolve(f),T.info(`[SessionRoutes] Permission ${$} responded, runId: ${Q.id}`),!0;return T.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Ef=q("Service"),B0=y.object({approved:y.boolean(),remember:y.boolean().optional(),scope:y.enum(["once","session"]).optional(),targetMode:y.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:y.string().optional(),answers:y.record(y.union([y.string(),y.array(y.string())])).optional()}),Lf=()=>{let V=new U0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),J=$.req.query("sessionId");Ef.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${J}`);try{let Q=await $.req.json(),K=B0.safeParse(Q);if(!K.success)throw new w("Invalid permission response format");let{approved:Z,remember:X,scope:E,targetMode:N,feedback:Y,answers:G}=K.data;if(!J)throw new w("sessionId query parameter is required");if(!yf(J,f,{approved:Z,reason:Y,scope:E,targetMode:N,feedback:Y,answers:G}))throw new l("Permission request",f);return Ef.info(`[PermissionRoutes] Permission ${f} ${Z?"approved":"denied"}`),$.json({success:!0,approved:Z,remember:X})}catch(Q){throw Ef.error("[PermissionRoutes] Failed to respond to permission:",Q),Q}}),V};import{Hono as W0}from"hono";var Pf=q("Service"),Sf=()=>{let V=new W0;return V.get("/",async($)=>{try{let f=await mf();return $.json(f)}catch(f){return Pf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let J=await kf(f);return $.json(J)}catch(J){return Pf.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),V};import{Hono as q0}from"hono";import*as S from"node:fs/promises";import{homedir as A0}from"node:os";import*as Qf from"node:path";var p=q("Service"),Ff=Qf.join(A0(),".blade","skills-config.json");async function If(){try{let V=await S.readFile(Ff,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function T0(V){await S.mkdir(Qf.dirname(Ff),{recursive:!0}),await S.writeFile(Ff,JSON.stringify(V,null,2))}async function H0(V,$){let f=await If();if($)f.disabled=f.disabled.filter((J)=>J!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await T0(f)}var a=null,_0=300000;async function C0(){if(a&&Date.now()-a.timestamp<_0)return a.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return p.warn(`GitHub API returned ${V.status}`),a?.data||[];let $=await V.json(),f=[];for(let J of $){if(J.type!=="dir")continue;let Q=`Official ${J.name} skill`;try{let K=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${J.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(K.ok){let X=(await K.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)Q=X[1].trim().slice(0,100)}}catch{}f.push({name:J.name,description:Q,tag:"Official",author:"Anthropic"})}return a={data:f,timestamp:Date.now()},f}catch(V){return p.warn("Failed to fetch skills catalog from GitHub:",V),a?.data||[]}}var vf=()=>{let V=new q0;return V.get("/",async($)=>{try{let f=Jf();await f.initialize();let J=f.getAll(),Q=await If(),K=J.map((Z)=>({id:Z.name,name:Z.name,enabled:!Q.disabled.includes(Z.name),description:Z.description||"",version:Z.version||"1.0.0",provider:"Local",location:Z.source==="builtin"?"Built-in":Z.basePath,capabilities:["prompts"],allowedTools:Z.allowedTools||[]}));return $.json(K)}catch(f){return p.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),J=await $.req.json();return await H0(f,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(f){return p.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),J=`${process.env.HOME}/.blade/skills/${f}`;return await S.rm(J,{recursive:!0,force:!0}),await Jf().refresh(),$.json({success:!0})}catch(f){return p.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),J=hf(),Q=Jf(),K=!1;if(f.source==="catalog"&&f.name){if(K=await J.installOfficialSkill(f.name),!K)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(K=await J.installFromRepo(f.url,f.name),!K)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(K=await J.installFromLocal(f.path,f.name),!K)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Q.refresh(),$.json({success:!0})}catch(f){return p.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await C0();return $.json(f)}catch(f){return p.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import z0 from"fast-glob";import{Hono as D0}from"hono";import{execSync as w0}from"node:child_process";import{readdir as b0}from"node:fs/promises";import Yf from"node:path";var s=q("Service"),R0=(V)=>{try{return w0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},y0=[...Zf.map((V)=>`${V}/**`),...Zf,...xf.map((V)=>`**/${V}`)],L0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),gf=()=>{let V=new D0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",J=pf(f).filter((Q)=>!L0.has(Q.command));return $.json(J)}catch(f){return s.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",J=$.get("directory")||A(),Q=Math.min(Number($.req.query("limit"))||100,1000),Z=(await z0("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:y0})).map((N)=>N.replace(/\\/g,"/"));if(!f)return $.json(Z.slice(0,Q));let X=f.toLowerCase(),E=Z.filter((N)=>N.toLowerCase().includes(X)).slice(0,Q);return $.json(E)}catch(f){return s.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||A(),J=$.req.query("path")||"",Q=J?Yf.join(f,J):f,Z=(await b0(Q,{withFileTypes:!0})).map((N)=>({name:N.name,path:J?`${J}/${N.name}`:N.name,type:N.isDirectory()?"dir":"file"}));Z.sort((N,Y)=>{if(N.type!==Y.type)return N.type==="dir"?-1:1;return N.name.localeCompare(Y.name)});let X=new Set(Zf),E=Z.filter((N)=>{let Y=N.name;if(Y.startsWith("."))return!1;if(X.has(Y))return!1;for(let G of xf)if(Y.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(E)}catch(f){return s.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let J=$.get("directory")||A(),Q=Yf.resolve(J,f),K=Yf.relative(J,Q);if(K.startsWith("..")||Yf.isAbsolute(K))return $.json({error:"Invalid file path"},400);let Z=uf(),X=await Z.stat(Q);if(!X?.isFile)return $.json({error:"File not found"},404);let E=200000,N=await Z.readTextFile(Q),Y=N.length>E;return $.json({path:f,content:Y?N.slice(0,E):N,truncated:Y,size:X.size})}catch(f){return s.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||A(),J=R0(f);return $.json({branch:J})}catch(f){return s.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as P0}from"hono";var h=q("Service"),t=new Map,df=2097152,lf=65536;function cf(){return typeof globalThis.Bun<"u"}async function m0(V,$,f){if(cf()){let{spawn:K}=await import("bun-pty"),Z=K(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:Z.pid,write:(X)=>Z.write(X),resize:(X,E)=>Z.resize(X,E),kill:()=>Z.kill(),onData:(X)=>Z.onData(X),onExit:(X)=>Z.onExit(X)}}let Q=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:Q.pid,write:(K)=>Q.write(K),resize:(K,Z)=>Q.resize(K,Z),kill:()=>Q.kill(),onData:(K)=>{Q.onData(K)},onExit:(K)=>{Q.onExit(K)}}}var Wf=void 0,Bf;if(cf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Bf=$.upgradeWebSocket,Wf=$.websocket}catch(V){h.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function rf(V,$){let f=`term-${Date.now()}`;h.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],K=await m0(J,Q,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Z={id:f,process:K,cwd:V,buffer:"",subscribers:new Set};if(t.set(f,Z),Z.subscribers.add($),K.onData((X)=>{let E=!1;for(let N of Z.subscribers)try{N.send(X),E=!0}catch{Z.subscribers.delete(N)}if(E)return;if(Z.buffer+=X,Z.buffer.length>df)Z.buffer=Z.buffer.slice(-df)}),K.onExit(({exitCode:X})=>{h.info(`[Terminal] Process exited: ${f}, code: ${X}`);for(let E of Z.subscribers)try{E.close()}catch{}t.delete(f)}),Z.buffer){let X=Z.buffer;Z.buffer="";for(let E=0;E<X.length;E+=lf)$.send(X.slice(E,E+lf))}return{session:Z,cleanup:()=>{if(h.info(`[Terminal] Connection closed: ${f}`),Z.subscribers.delete($),Z.subscribers.size===0){try{Z.process.kill()}catch{}t.delete(f)}}}}function of(V,$){V.on("connection",async(f,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){f.close();return}let K=Q.searchParams.get("cwd")||$()||A();try{let{session:Z,cleanup:X}=await rf(K,{send:(E)=>f.send(E),close:()=>f.close()});f.on("message",(E)=>{try{Z.process.write(String(E))}catch(N){h.error("[Terminal] Failed to write to PTY:",N)}}),f.on("close",X),f.on("error",X)}catch(Z){h.error("[Terminal] Failed to spawn PTY:",Z),f.close()}})}var af=()=>{let V=new P0;if(V.get("/status",($)=>{let f=Array.from(t.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),J=t.get(f);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return t.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Bf)V.get("/ws",Bf(($)=>{let f=$.req.query("cwd")||$.get("directory")||A(),J;return{async onOpen(Q,K){try{J=await rf(f,{send:(Z)=>K.send(Z),close:()=>K.close()})}catch(Z){h.error("[Terminal] Failed to spawn PTY:",Z),K.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(K){h.error("[Terminal] Failed to write to PTY:",K)}},onClose(){J?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var D=q("Service"),qf=[];function d0(){let V=v0(p0(import.meta.url)),$=[g(V,"web"),g(A(),"dist/web"),g(A(),"packages/cli/dist/web")];for(let f of $){let J=g(f,"index.html");if(ef(J)){if(Kf(J,"utf-8").includes("/assets/"))return D.debug(`[Server] Found web dist at: ${f}`),f}}return null}function l0(){let V=new k0;V.onError((f,J)=>{if(D.error("[Server] Request error:",f),f instanceof i)return J.json(f.toObject(),f.statusCode);let Q=f instanceof Error?f.message:String(f);return J.json({error:{code:"INTERNAL_ERROR",message:Q}},500)}),V.use(async(f,J)=>{let Q=process.env.BLADE_SERVER_PASSWORD;if(!Q)return J();let K=f.req.path;if(K==="/"||K.startsWith("/assets/")||K.endsWith(".html")||K.endsWith(".js")||K.endsWith(".css"))return J();let Z=f.req.header("Authorization");if(!Z?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(Z.slice(6),"base64").toString(),[E,N]=X.split(":"),Y=process.env.BLADE_SERVER_USERNAME??"blade";if(E!==Y||N!==Q)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return J()}),V.use(async(f,J)=>{let Q=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!Q)D.debug(`[Server] ${f.req.method} ${f.req.path}`);let K=Date.now();if(await J(),!Q){let Z=Date.now()-K;D.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${Z}ms)`)}}),V.use(S0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(qf.includes(f))return f;return}})),V.use(async(f,J)=>{let Q=f.req.query("directory")||f.req.header("x-blade-directory")||A();try{Q=decodeURIComponent(Q)}catch{}return f.set("directory",Q),J()}),V.route("/global",Tf()),V.route("/sessions",Rf()),V.route("/configs",Af()),V.route("/permissions",Lf()),V.route("/providers",Sf()),V.route("/models",zf()),V.route("/suggestions",gf()),V.route("/terminal",af()),V.route("/mcp",Hf()),V.route("/skills",vf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:o()})});let $=d0();if($)D.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let J=g($,f.req.path);if(!ef(J))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let Q=Kf(J),K=u0(J).toLowerCase(),X={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[K]||"application/octet-stream";return new Response(Q,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let J=g($,"index.html"),Q=Kf(J,"utf-8");return f.html(Q)}),V.get("*",(f)=>{let J=f.req.path;if(J.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${J}`}},404);let Q=g($,"index.html"),K=Kf(Q,"utf-8");return f.html(K)});else D.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:o(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function c0(){let V=I0(),$=[];for(let f of Object.keys(V)){let J=V[f];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function tf(){return typeof globalThis.Bun<"u"}function nf(V,$){let f=globalThis.Bun,J=(K)=>{try{return f.serve({hostname:$.hostname,port:K,fetch:V.fetch,idleTimeout:0,websocket:Wf})}catch(Z){D.error("Failed to start Bun server:",Z);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function r0(V,$){return new Promise((f,J)=>{let Q=h0(async(N,Y)=>{let G=new URL(N.url||"/",`http://${N.headers.host}`),j=new Headers;for(let[x,W]of Object.entries(N.headers))if(W)if(Array.isArray(W))for(let U of W)j.append(x,U);else j.set(x,W);let O;if(N.method!=="GET"&&N.method!=="HEAD")O=(await new Promise((W)=>{let U=[];N.on("data",(_)=>U.push(_)),N.on("end",()=>W(Buffer.concat(U)))})).toString();let F=new Request(G.toString(),{method:N.method,headers:j,body:O});try{let x=await V.fetch(F);if(Y.statusCode=x.status,x.headers.forEach((W,U)=>{Y.setHeader(U,W)}),x.body){let W=x.body.getReader(),U=async()=>{let{done:_,value:B}=await W.read();if(_){Y.end();return}return Y.write(B),U()};await U()}else{let W=await x.text();Y.end(W)}}catch(x){D.error("[Server] Node request error:",x),Y.statusCode=500,Y.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),K=new g0({noServer:!0}),Z=A();of(K,()=>Z),Q.on("upgrade",(N,Y,G)=>{if(new URL(N.url||"/",`http://${N.headers.host}`).pathname==="/terminal/ws")K.handleUpgrade(N,Y,G,(O)=>{K.emit("connection",O,N)});else Y.destroy()});let X=(N)=>{return new Promise((Y,G)=>{Q.once("error",(j)=>{if(j.code==="EADDRINUSE")G(j);else G(j)}),Q.listen(N,$.hostname,()=>{let j=Q.address();if(j&&typeof j==="object")Y(j.port);else Y(N)})})};(async()=>{let N;if($.port===0)try{N=await X(4096)}catch{N=await X(0)}else N=await X($.port);let Y=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${N}`);f({url:Y,port:N,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{K.close(()=>{Q.close(()=>G())})})}})})().catch(J)})}var sf;((vV)=>{let V,$;function f(){if(!$)$=l0();return $}vV.getApp=f;function J(Z){qf=Z.cors??[];let X=f();if(tf())V=nf(X,Z),D.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let E=V;return{url:E.url,port:E.port,hostname:E.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,D.info("[Server] Blade server stopped")}}}vV.listen=J;async function Q(Z){qf=Z.cors??[];let X=f();if(tf())V=nf(X,Z),D.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await r0(X,Z),D.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let E=V;return{url:E.url,port:E.port,hostname:E.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,D.info("[Server] Blade server stopped")}}}vV.listenAsync=Q;function K(){return V!==void 0}vV.isRunning=K})(sf||={});export{o0 as f,a0 as g,c0 as h,sf as i};
@@ -1,5 +0,0 @@
1
- import{r as o,j as e}from"./vendor-react-Dm1xU4bP.js";import{D as V,a as ee,b as te}from"./dialog-C8VDk-ma.js";import{u as ge,c as A}from"./index-9t-WxRrl.js";import{_ as T,l as w,m as se,n as oe,o as W}from"./vendor-radix-CfxBc_4-.js";import{i as ve,a as Ee,d as le,u as pe,b as be,c as je,e as R,f as G,g as ke}from"./useRequest-BJp539HQ.js";import{R as Ne,P as Ce,X as ne,p as ye,L as ce,q as de,c as we,D as Ae}from"./vendor-icons-DlzC8I7m.js";import"./vendor-markdown-DIcugY1e.js";import"./vendor-monaco-w6PwaWGP.js";function Y(n,a){if(ve){if(!n)return a;var r;return Ee(n)?r=n():"current"in n?r=n.current:r=n,r}}var Se=function(n){var a=function(r,c,d){var l=o.useRef(!1),s=o.useRef([]),m=o.useRef([]),h=o.useRef(void 0);n(function(){var i,k=Array.isArray(d)?d:[d],v=k.map(function(N){return Y(N)});if(!l.current){l.current=!0,s.current=v,m.current=c,h.current=r();return}(v.length!==s.current.length||!le(s.current,v)||!le(m.current,c))&&((i=h.current)===null||i===void 0||i.call(h),s.current=v,m.current=c,h.current=r())}),pe(function(){var i;(i=h.current)===null||i===void 0||i.call(h),l.current=!1})};return a},Fe=Se(o.useEffect);function Be(){var n=(typeof global>"u"?"undefined":typeof global)=="object"&&global&&global.Object===Object&&global,a=typeof self=="object"&&self&&self.Object===Object&&self;return n||a}Be()||(global.Date=Date);function Me(n,a){var r,c=be(n),d=(r=a==null?void 0:a.wait)!==null&&r!==void 0?r:1e3,l=o.useMemo(function(){return je(function(){for(var s=[],m=0;m<arguments.length;m++)s[m]=arguments[m];return c.current.apply(c,T([],w(s),!1))},d,a)},[]);return pe(function(){l.cancel()}),{run:l,cancel:l.cancel,flush:l.flush}}function De(n,a,r){r===void 0&&(r={});var c=r.enable,d=c===void 0?!0:c,l=be(a);Fe(function(){if(d){var s=Y(r.target,window);if(s!=null&&s.addEventListener){var m=function(i){return l.current(i)},h=Array.isArray(n)?n:[n];return h.forEach(function(i){s.addEventListener(i,m,{capture:r.capture,once:r.once,passive:r.passive})}),function(){h.forEach(function(i){s.removeEventListener(i,m,{capture:r.capture})})}}}},[n,r.capture,r.once,r.passive,d],r.target)}var Te=function(n){return n===document||n===document.documentElement||n===document.body?Math.max(window.pageYOffset,document.documentElement.scrollTop,document.body.scrollTop):n.scrollTop},ie=function(n){return n.scrollHeight||Math.max(document.documentElement.scrollHeight,document.body.scrollHeight)},_e=function(n){return n.clientHeight||Math.max(document.documentElement.clientHeight,document.body.clientHeight)},Ie=function(n,a){a===void 0&&(a={});var r=a.target,c=a.isNoMore,d=a.threshold,l=d===void 0?100:d,s=a.direction,m=s===void 0?"bottom":s,h=a.reloadDeps,i=h===void 0?[]:h,k=a.manual,v=a.onBefore,N=a.onSuccess,S=a.onError,p=a.onFinally,_=w(o.useState(),2),C=_[0],F=_[1],P=w(o.useState(!1),2),O=P[0],g=P[1],B=m==="top",y=o.useRef(void 0),E=o.useRef(0),L=o.useMemo(function(){return c?c(C):!1},[C]),M=R(function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,n(x)];case 1:return f=t.sent(),[2,{currentData:f,lastData:x}]}})})},{manual:k,onFinally:function(x,f,t){g(!1),p==null||p(f==null?void 0:f.currentData,t)},onBefore:function(){return v==null?void 0:v()},onSuccess:function(x){var f,t,j;x.lastData?F(W(W({},x.currentData),{list:B?T(T([],w(x.currentData.list),!1),w((t=x.lastData.list)!==null&&t!==void 0?t:[]),!1):T(T([],w((j=x.lastData.list)!==null&&j!==void 0?j:[]),!1),w(x.currentData.list),!1)})):F(W(W({},x.currentData),{list:T([],w((f=x.currentData.list)!==null&&f!==void 0?f:[]),!1)})),setTimeout(function(){if(B){var b=Y(r);if(b=b===document?document.documentElement:b,b){var z=ie(b);b.scrollTo(0,z-E.current)}}else J()}),N==null||N(x.currentData)},onError:function(x){return S==null?void 0:S(x)}}),$=M.loading,q=M.error,H=M.run,Q=M.runAsync,X=M.cancel,I=G(function(){L||(g(!0),H(C))}),u=function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,Q(x)];case 1:return f=t.sent(),[2,f.currentData]}})})},D=G(function(){return L?Promise.reject():(g(!0),u(C))}),U=function(){return g(!1),H()},Z=function(){return g(!1),u()},J=function(){var x=Y(r);if(x){var f=x===document?document.documentElement:x,t=Te(f),j=ie(f),b=_e(f);B?(y.current!==void 0&&y.current>t&&t<=l&&I(),y.current=t,E.current=j-t):j-t<=b+l&&I()}};return De("scroll",function(){$||O||J()},{target:r}),ke(function(){H()},T([],w(i),!1)),{data:C,loading:!O&&$,error:q,loadingMore:O,noMore:L,loadMore:I,loadMoreAsync:D,reload:G(U),reloadAsync:G(Z),mutate:F,cancel:X}};const xe={connected:"text-[#16A34A] dark:text-[#22C55E]",connecting:"text-[#2563eb] dark:text-[#3b82f6]",offline:"text-[#f59e0b]",error:"text-[#ef4444]"},me={connected:"Connected",connecting:"Connecting...",offline:"Offline",error:"Error"},ue=20,Re=async()=>{const n=await fetch("/mcp");if(!n.ok)throw new Error("Failed to fetch servers");return n.json()},Pe="mcp server @modelcontextprotocol",Oe=3,Le=async(n,a)=>{const r=n&&n.length>=Oe?n:Pe,c=`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(r)}&size=${ue}&from=${a}`,d=await fetch(c);if(!d.ok)throw new Error("Failed to fetch packages");const l=await d.json();return{list:l.objects.map(s=>s.package),total:l.total,hasMore:a+ue<l.total}};function Ze(){const{isMcpOpen:n,toggleMcp:a}=ge(),[r,c]=o.useState("installed"),[d,l]=o.useState(!1),[s,m]=o.useState(null),[h,i]=o.useState({}),[k,v]=o.useState(""),[N,S]=o.useState(""),[p,_]=o.useState(null),[C,F]=o.useState(null),P=o.useRef(null),{run:O}=Me(t=>{S(t)},{wait:500}),{data:g=[],loading:B,run:y}=R(Re,{refreshDeps:[n],ready:n,onSuccess:t=>{t.length>0&&!s&&m(t[0].id)}}),{data:E,loading:L,loadingMore:M,noMore:$,reload:q}=Ie(async t=>{var b;const j=((b=t==null?void 0:t.list)==null?void 0:b.length)??0;return Le(N,j)},{target:P,isNoMore:t=>!(t!=null&&t.hasMore),reloadDeps:[N],manual:!n||r!=="catalog"}),{runAsync:H}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:Q}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:X}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})},{manual:!0,onSuccess:y}),{runAsync:I}=R(async t=>{await fetch("/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name,config:t})})},{manual:!0,onSuccess:()=>{y(),l(!1),F(null),_(null)},onError:()=>{_(null)}}),u=o.useMemo(()=>g.find(t=>t.id===s)??g[0],[g,s]),D=u?h[u.id]??{read:!0,write:!1,shell:!1}:{read:!0,write:!1,shell:!1},U=t=>{u&&i(j=>({...j,[u.id]:{...D,[t]:!D[t]}}))},Z=o.useMemo(()=>new Set(g.map(t=>t.name.toLowerCase())),[g]),J=t=>{F(t)},x=t=>t.startsWith("@modelcontextprotocol/"),f=t=>x(t.name)?"Official":"Community";return e.jsxs(e.Fragment,{children:[e.jsx(V,{open:n,onOpenChange:a,children:e.jsxs(ee,{className:"sm:max-w-[900px] h-[680px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl flex flex-col","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(te,{className:"sr-only",children:"MCP"}),e.jsx("div",{className:"flex flex-1 min-h-0",children:e.jsxs("div",{className:"flex-1 p-8 flex flex-col gap-5 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"MCP"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:y,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",disabled:B,children:e.jsx(Ne,{className:A("h-4 w-4",B&&"animate-spin")})}),e.jsxs("button",{onClick:()=>l(!0),className:"h-8 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-xs font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a]",children:[e.jsx(Ce,{className:"h-3.5 w-3.5"}),"Add server"]}),e.jsx("button",{onClick:a,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(ne,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] w-fit shrink-0",children:[e.jsxs(fe,{active:r==="installed",onClick:()=>c("installed"),children:["Installed (",g.length,")"]}),e.jsx(fe,{active:r==="catalog",onClick:()=>{c("catalog"),E||q()},children:"Catalog"})]}),r==="installed"?e.jsxs("div",{className:"flex gap-5 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-[220px] flex flex-col gap-3 min-h-0 overflow-hidden",children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] shrink-0",children:"Servers"}),e.jsx("div",{className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 text-[12px] text-[#9CA3AF] dark:text-[#71717a] font-mono shrink-0",children:"Search servers..."}),e.jsxs("div",{className:"flex flex-col gap-2 overflow-y-auto flex-1 min-h-0 pr-1",children:[g.length===0&&!B&&e.jsx("div",{className:"text-center py-8 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No MCP servers configured"}),g.map(t=>e.jsxs("button",{onClick:()=>m(t.id),className:A("text-left rounded-lg px-3 py-2 flex flex-col gap-1 transition-colors shrink-0",t.id===s?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b]"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:t.name}),e.jsx("span",{className:A("text-[11px] font-mono font-semibold",xe[t.status]),children:me[t.status]})]}),e.jsx("span",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] truncate",children:t.endpoint})]},t.id))]})]}),u?e.jsxs("div",{className:"flex-1 flex flex-col gap-3 overflow-y-auto pr-2 min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-base font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:u.name}),e.jsx("span",{className:A("text-xs font-mono font-semibold",xe[u.status]),children:me[u.status]})]}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:u.description}),u.error&&e.jsxs("p",{className:"text-[12px] font-mono text-[#ef4444]",children:["Error: ",u.error]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u.status==="connected"?e.jsx("button",{onClick:()=>Q(u.name),className:"h-7 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Disconnect"}):e.jsx("button",{onClick:()=>H(u.name),className:"h-7 px-3 rounded-md bg-[#16A34A] dark:bg-[#22C55E] text-white dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Connect"}),e.jsx("button",{onClick:()=>X(u.name),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#ef4444] text-[11px] font-mono font-semibold",children:"Delete"})]}),e.jsx("div",{className:"h-px bg-[#E5E7EB] dark:bg-[#1f2937]"}),e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Permissions"}),e.jsx(K,{label:"File read",enabled:D.read,onToggle:()=>U("read")}),e.jsx(K,{label:"File write",enabled:D.write,onToggle:()=>U("write")}),e.jsx(K,{label:"Shell exec",enabled:D.shell,onToggle:()=>U("shell")}),e.jsxs("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:["Tools (",u.tools.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.tools.length===0?e.jsx("span",{className:"text-[12px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No tools available"}):u.tools.map(t=>e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#111827] dark:text-[#E5E5E5]",children:t},t))})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"Select a server to view details"})})]}):e.jsxs("div",{className:"flex flex-col gap-4 flex-1 min-h-0",children:[e.jsx("div",{className:"flex items-center gap-3 shrink-0",children:e.jsxs("div",{className:"flex-1 h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 gap-2",children:[e.jsx(ye,{className:"h-3.5 w-3.5 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("input",{type:"text",value:k,onChange:t=>{v(t.target.value),O(t.target.value)},placeholder:"Search MCP servers on npm (min 3 chars)...",className:"flex-1 bg-transparent text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none"})]})}),e.jsxs("div",{ref:P,className:"flex-1 overflow-y-auto min-h-0",children:[L&&!E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ce,{className:"h-6 w-6 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}):e.jsx("div",{className:"grid grid-cols-2 gap-3 pb-4",children:E==null?void 0:E.list.map(t=>{var ae,re;const j=Z.has(t.name.toLowerCase().replace(/\s+/g,"-")),b=p===t.name,z=f(t);return e.jsxs("div",{className:"rounded-lg bg-white dark:bg-[#0C0C0C] p-4 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name}),e.jsx("span",{className:A("text-[10px] font-mono px-2 py-0.5 rounded shrink-0",z==="Official"?"bg-[#16A34A]/20 dark:bg-[#22C55E]/20 text-[#16A34A] dark:text-[#22C55E]":"bg-[#3b82f6]/20 text-[#3b82f6]"),children:z})]}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] line-clamp-2",children:t.description||"No description"}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[e.jsxs("span",{children:["v",t.version]}),((ae=t.publisher)==null?void 0:ae.username)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{children:["by ",t.publisher.username]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-auto pt-2",children:[e.jsxs("a",{href:((re=t.links)==null?void 0:re.npm)||`https://www.npmjs.com/package/${t.name}`,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a] hover:text-[#111827] dark:hover:text-[#E5E5E5] flex items-center gap-1",children:[e.jsx(de,{className:"h-3 w-3"}),"npm"]}),j?e.jsxs("span",{className:"text-[11px] font-mono text-[#16A34A] dark:text-[#22C55E] flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),"Installed"]}):e.jsxs("button",{onClick:()=>J(t),disabled:b,className:"h-6 px-2 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[10px] font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a] disabled:opacity-50",children:[e.jsx(Ae,{className:A("h-3 w-3",b&&"animate-pulse")}),b?"Installing...":"Install"]})]})]},t.name)})}),M&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ce,{className:"h-5 w-5 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}),$&&E&&E.list.length>0&&e.jsx("div",{className:"text-center py-4 text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No more packages"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-[#E5E7EB] dark:border-[#1f2937] shrink-0",children:[e.jsxs("span",{className:"text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[(E==null?void 0:E.total)??0," packages found"]}),e.jsxs("a",{href:"https://glama.ai/mcp/servers",target:"_blank",rel:"noopener noreferrer",className:"text-[11px] font-mono text-[#3b82f6] hover:underline flex items-center gap-1",children:["Browse more on Glama",e.jsx(de,{className:"h-3 w-3"})]})]})]})]})})]})}),e.jsx(Ue,{open:d,onOpenChange:l,onAdd:I}),C&&e.jsx($e,{pkg:C,onClose:()=>F(null),onInstall:t=>{_(C.name),I(t)}})]})}function fe({active:n,children:a,onClick:r}){return e.jsx("button",{onClick:r,className:A("px-3 py-1 rounded text-[12px] font-mono font-semibold transition-colors",n?"bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]":"text-[#6B7280] dark:text-[#a1a1aa]"),children:a})}function K({label:n,enabled:a,onToggle:r}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:n}),e.jsx(He,{enabled:a,onChange:r})]})}function He({enabled:n,onChange:a}){return e.jsx("button",{onClick:a,className:A("w-9 h-5 rounded-full px-0.5 flex items-center transition-colors",n?"bg-[#16A34A] dark:bg-[#22C55E] justify-end":"bg-[#E5E7EB] dark:bg-[#27272a] justify-start"),children:e.jsx("span",{className:"h-4 w-4 rounded-full bg-white"})})}function Ue({open:n,onOpenChange:a,onAdd:r}){const[c,d]=o.useState("form"),[l,s]=o.useState(""),[m,h]=o.useState(""),[i,k]=o.useState(""),[v,N]=o.useState(`{
2
- "name": "my-server",
3
- "command": "npx",
4
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
5
- }`),S=()=>{if(c==="json")try{const p=JSON.parse(v);r(p)}catch{alert("Invalid JSON")}else{if(!l||!m){alert("Name and command are required");return}r({name:l,command:m,args:i.split(" ").filter(Boolean)})}};return e.jsx(V,{open:n,onOpenChange:a,children:e.jsxs(ee,{className:"sm:max-w-[540px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(te,{className:"sr-only",children:"Add MCP Server"}),e.jsxs("div",{className:"p-6 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-base font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Add MCP Server"}),e.jsx("button",{onClick:()=>a(!1),className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(ne,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 p-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] w-fit",children:[e.jsx(he,{active:c==="form",onClick:()=>d("form"),children:"Form"}),e.jsx(he,{active:c==="json",onClick:()=>d("json"),children:"JSON"})]}),c==="json"?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"JSON config"}),e.jsx("textarea",{className:"min-h-[140px] rounded-md bg-white dark:bg-[#0C0C0C] text-[#111827] dark:text-[#E5E5E5] font-mono text-[12px] p-3 border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]",value:v,onChange:p=>N(p.target.value)})]}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Server name"}),e.jsx("input",{type:"text",value:l,onChange:p=>s(p.target.value),placeholder:"my-server",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Command"}),e.jsx("input",{type:"text",value:m,onChange:p=>h(p.target.value),placeholder:"npx",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Arguments (space separated)"}),e.jsx("input",{type:"text",value:i,onChange:p=>k(p.target.value),placeholder:"-y @modelcontextprotocol/server-filesystem /tmp",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx("button",{onClick:()=>a(!1),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Cancel"}),e.jsx("button",{onClick:S,className:"h-7 px-3 rounded-md bg-[#16A34A] dark:bg-[#22C55E] text-white dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Add Server"})]})]})]})})}function $e({pkg:n,onClose:a,onInstall:r}){var i;const c=((i=n.name.split("/").pop())==null?void 0:i.replace(/^server-/,""))||n.name,[d,l]=o.useState(c),[s,m]=o.useState(`-y ${n.name}`),h=()=>{if(!d.trim()){alert("Server name is required");return}r({name:d.trim(),command:"npx",args:s.split(" ").filter(Boolean)})};return e.jsx(V,{open:!0,onOpenChange:a,children:e.jsxs(ee,{className:"sm:max-w-[480px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsxs(te,{className:"sr-only",children:["Install ",n.name]}),e.jsxs("div",{className:"p-6 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-base font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Install MCP Server"}),e.jsx("button",{onClick:a,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(ne,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"rounded-md bg-white dark:bg-[#0C0C0C] p-3",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:n.name}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] mt-1",children:n.description||"No description"})]}),e.jsx("div",{className:"h-px bg-[#E5E7EB] dark:bg-[#1f2937]"}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Server name"}),e.jsx("input",{type:"text",value:d,onChange:k=>l(k.target.value),placeholder:"my-server",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Arguments"}),e.jsx("input",{type:"text",value:s,onChange:k=>m(k.target.value),placeholder:"-y package-name",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:border-[#27272a]"}),e.jsxs("span",{className:"text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:["Command: npx ",s]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx("button",{onClick:a,className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Cancel"}),e.jsx("button",{onClick:h,className:"h-7 px-3 rounded-md bg-[#16A34A] dark:bg-[#22C55E] text-white dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Install"})]})]})]})})}function he({active:n,children:a,onClick:r}){return e.jsx("button",{onClick:r,className:A("px-3 py-1 rounded text-[12px] font-mono font-semibold transition-colors",n?"bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]":"text-[#6B7280] dark:text-[#a1a1aa]"),children:a})}export{Ze as McpModal};
@@ -1 +0,0 @@
1
- import{r as n,j as e}from"./vendor-react-Dm1xU4bP.js";import{D as U,a as z,b as K}from"./dialog-C8VDk-ma.js";import{c as b,u as J,a as Q}from"./index-9t-WxRrl.js";import{u as V}from"./SettingsStore-CfDjhOkS.js";import{X as P,i as M,E as G,m as _,d as W,e as X}from"./vendor-icons-DlzC8I7m.js";import"./vendor-markdown-DIcugY1e.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CfxBc_4-.js";const L={id:"custom",name:"Custom (OpenAI Compatible)",icon:"🔌",description:"Any OpenAI-compatible API",envVars:[],bladeProvider:"openai-compatible"};function Y({open:p,onOpenChange:c,onSave:u}){const[E,d]=n.useState([L]),[x,s]=n.useState([]),[r,j]=n.useState("custom"),[o,i]=n.useState({bladeProvider:"openai-compatible",baseUrl:"",apiKey:"",modelId:"",name:""}),[y,N]=n.useState(!1),[w,v]=n.useState(!1),[k,S]=n.useState(!1);n.useEffect(()=>{p&&fetch("/providers").then(a=>a.json()).then(a=>d([L,...a])).catch(a=>console.error("Failed to load providers:",a))},[p]),n.useEffect(()=>{r&&r!=="custom"?fetch(`/providers/${r}/models`).then(a=>a.json()).then(a=>s(a)).catch(a=>console.error("Failed to load models:",a)):s([])},[r]);const F=a=>{j(a.id),i({...o,bladeProvider:a.bladeProvider,baseUrl:a.defaultBaseUrl||"",modelId:"",name:""}),N(!1)},A=()=>{!o.modelId||!o.apiKey||(u({...o,name:o.name||o.modelId}),i({bladeProvider:"openai-compatible",baseUrl:"",apiKey:"",modelId:"",name:""}),j("custom"),c(!1))},h=E.find(a=>a.id===r),B=x.find(a=>a.id===o.modelId),C=!(r==="custom")&&x.length>0,I=o.modelId&&o.apiKey;return e.jsx(U,{open:p,onOpenChange:c,children:e.jsxs(z,{className:"sm:max-w-[480px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(K,{className:"sr-only",children:"Add Model"}),e.jsxs("div",{className:"p-6 flex flex-col gap-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Add Model"}),e.jsx("button",{onClick:()=>c(!1),className:"text-[#9CA3AF] hover:text-[#111827] dark:text-[#71717a] dark:hover:text-[#E5E5E5] transition-colors",children:e.jsx(P,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Provider"}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>N(!y),className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono flex items-center justify-between hover:bg-[#E5E7EB] dark:hover:bg-[#27272a] transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{children:h==null?void 0:h.icon}),e.jsx("span",{children:h==null?void 0:h.name})]}),e.jsx(M,{className:"h-4 w-4 text-[#9CA3AF] dark:text-[#71717a]"})]}),y&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>N(!1)}),e.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white dark:bg-[#18181b] border border-[#E5E7EB] dark:border-zinc-800 rounded-md py-1 z-50 max-h-64 overflow-y-auto shadow-lg",children:E.map(a=>e.jsx("button",{type:"button",className:b("w-full text-left px-3 py-2 text-sm font-mono hover:bg-[#F3F4F6] dark:hover:bg-[#27272a] transition-colors",r===a.id?"text-[#111827] dark:text-[#E5E5E5] bg-[#F3F4F6] dark:bg-[#27272a]":"text-[#6B7280] dark:text-[#a1a1aa]"),onClick:()=>F(a),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:a.icon}),e.jsx("span",{className:"font-medium",children:a.name})]})},a.id))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Base URL"}),e.jsx("input",{type:"text",value:o.baseUrl,onChange:a=>i({...o,baseUrl:a.target.value}),placeholder:(h==null?void 0:h.defaultBaseUrl)||"https://api.openai.com/v1",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:k?"text":"password",value:o.apiKey,onChange:a=>i({...o,apiKey:a.target.value}),placeholder:"sk-........................",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 pr-10 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"}),e.jsx("button",{type:"button",onClick:()=>S(!k),className:"absolute right-3 top-1/2 -translate-y-1/2 text-[#9CA3AF] hover:text-[#111827] dark:text-[#71717a] dark:hover:text-[#E5E5E5] transition-colors",children:k?e.jsx(G,{className:"h-4 w-4"}):e.jsx(_,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Model ID"}),C&&e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>v(!w),className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono flex items-center justify-between hover:bg-[#E5E7EB] dark:hover:bg-[#27272a] transition-colors",children:[(B==null?void 0:B.name)||o.modelId||"Select model",e.jsx(M,{className:"h-4 w-4 text-[#9CA3AF] dark:text-[#71717a]"})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>v(!1)}),e.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white dark:bg-[#18181b] border border-[#E5E7EB] dark:border-zinc-800 rounded-md py-1 z-50 max-h-48 overflow-y-auto shadow-lg",children:x.map(a=>e.jsx("button",{type:"button",className:b("w-full text-left px-3 py-2 text-sm font-mono hover:bg-[#F3F4F6] dark:hover:bg-[#27272a] transition-colors",o.modelId===a.id?"text-[#111827] dark:text-[#E5E5E5] bg-[#F3F4F6] dark:bg-[#27272a]":"text-[#6B7280] dark:text-[#a1a1aa]"),onClick:()=>{i({...o,modelId:a.id,name:a.name}),v(!1)},children:a.name},a.id))})]})]}),e.jsx("input",{type:"text",value:o.modelId,onChange:a=>i({...o,modelId:a.target.value,name:a.target.value}),placeholder:"gpt-4o, claude-3-opus, deepseek-chat, etc.",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"}),C&&e.jsx("p",{className:"text-[12px] text-[#9CA3AF] dark:text-[#71717a] font-mono",children:"You can select a listed model or type a custom model ID."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:()=>c(!1),className:"flex-1 px-4 py-2 rounded-md text-sm text-[#6B7280] dark:text-[#a1a1aa] font-mono hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:"Cancel"}),e.jsx("button",{type:"button",onClick:A,disabled:!I,className:"flex-1 px-4 py-2 rounded-md text-sm text-white font-semibold font-mono bg-[#16A34A] hover:bg-[#15803d] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Save Model"})]})]})]})})}function q({open:p,onOpenChange:c,model:u,onSave:E}){const[d,x]=n.useState({baseUrl:"",apiKey:"",model:""}),[s,r]=n.useState(!1);n.useEffect(()=>{u&&x({baseUrl:u.baseUrl||"",apiKey:u.apiKey||"",model:u.model||""})},[u]);const j=()=>{!u||!d.model||(E(u.id,{baseUrl:d.baseUrl||void 0,apiKey:d.apiKey||void 0,model:d.model}),c(!1))},o=d.model;return e.jsx(U,{open:p,onOpenChange:c,children:e.jsxs(z,{className:"sm:max-w-[480px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(K,{className:"sr-only",children:"Edit Model"}),e.jsxs("div",{className:"p-6 flex flex-col gap-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Edit Model"}),e.jsx("button",{onClick:()=>c(!1),className:"text-[#9CA3AF] hover:text-[#111827] dark:text-[#71717a] dark:hover:text-[#E5E5E5] transition-colors",children:e.jsx(P,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Model ID"}),e.jsx("input",{type:"text",value:d.model,onChange:i=>x({...d,model:i.target.value}),placeholder:"gpt-4o, claude-3-opus, etc.",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Base URL"}),e.jsx("input",{type:"text",value:d.baseUrl,onChange:i=>x({...d,baseUrl:i.target.value}),placeholder:"https://api.openai.com/v1",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:s?"text":"password",value:d.apiKey,onChange:i=>x({...d,apiKey:i.target.value}),placeholder:"Leave empty to keep current key",className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 py-2.5 pr-10 text-sm text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none focus:ring-1 focus:ring-[#D1D5DB] dark:focus:ring-zinc-600"}),e.jsx("button",{type:"button",onClick:()=>r(!s),className:"absolute right-3 top-1/2 -translate-y-1/2 text-[#9CA3AF] hover:text-[#111827] dark:text-[#71717a] dark:hover:text-[#E5E5E5] transition-colors",children:s?e.jsx(G,{className:"h-4 w-4"}):e.jsx(_,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:()=>c(!1),className:"flex-1 px-4 py-2 rounded-md text-sm text-[#6B7280] dark:text-[#a1a1aa] font-mono hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:"Cancel"}),e.jsx("button",{type:"button",onClick:j,disabled:!o,className:"flex-1 px-4 py-2 rounded-md text-sm text-white font-semibold font-mono bg-[#16A34A] hover:bg-[#15803d] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Save Changes"})]})]})]})})}const Z={"openai-compatible":{bg:"#10a37f",label:"OA"},anthropic:{bg:"#d97757",label:"A"},gemini:{bg:"#4285f4",label:"G"},"azure-openai":{bg:"#0078d4",label:"Az"},"gpt-openai-platform":{bg:"#10a37f",label:"GP"}};function de(){var O;const{isSettingsOpen:p,toggleSettings:c,isSidebarOpen:u,setSidebarOpen:E}=J(),{configuredModels:d,loadModels:x}=Q(),s=V(),[r,j]=n.useState("general"),[o,i]=n.useState(!1),[y,N]=n.useState(null),[w,v]=n.useState(null),[k,S]=n.useState(""),[F,A]=n.useState("all"),h=[{value:"general",label:"General"},{value:"models",label:"Models"},{value:"shortcuts",label:"Shortcuts"}],D=n.useMemo(()=>[{action:"Open command palette",combo:["Ctrl","K"],scope:"Global"},{action:"New chat",combo:["Ctrl","N"],scope:"Chat"},{action:"Focus input",combo:["Ctrl","L"],scope:"Chat"},{action:"Toggle sidebar",combo:["Ctrl","B"],scope:"Layout"},{action:"Search history",combo:["Ctrl","H"],scope:"History"}],[]).filter(t=>{const l=t.action.toLowerCase().includes(k.toLowerCase()),m=F==="all"||t.scope.toLowerCase()===F;return l&&m}),C=d.reduce((t,l)=>{const m=l.provider||"unknown";return t[m]||(t[m]=[]),t[m].push(l),t},{});n.useEffect(()=>{p&&(x(),s.loadSettings())},[p,x,s.loadSettings]);const I=async t=>{try{if(!(await fetch("/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t.bladeProvider,name:t.name||t.modelId,model:t.modelId,baseUrl:t.baseUrl||void 0,apiKey:t.apiKey||void 0})})).ok)throw new Error("Failed to save model");await x()}catch(l){console.error("Failed to save model:",l)}},a=async t=>{try{if(!(await fetch(`/models/${t}`,{method:"DELETE"})).ok)throw new Error("Failed to delete model");await x()}catch(l){console.error("Failed to delete model:",l)}},$=async(t,l)=>{try{if(!(await fetch(`/models/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).ok)throw new Error("Failed to update model");await x()}catch(m){console.error("Failed to update model:",m)}},H=t=>{N(y===t?null:t)};return e.jsxs(e.Fragment,{children:[e.jsx(U,{open:p,onOpenChange:c,children:e.jsxs(z,{className:"sm:max-w-[800px] h-[600px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl flex flex-col","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(K,{className:"sr-only",children:"Settings"}),e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"w-[200px] h-full bg-[#F3F4F6] dark:bg-[#18181b] p-6 flex flex-col gap-2",children:h.map(t=>e.jsx("button",{onClick:()=>j(t.value),className:b("w-full text-left px-3 py-2 rounded-md text-sm font-mono transition-colors",r===t.value?"bg-[#E5E7EB] dark:bg-[#27272a] text-[#111827] dark:text-[#E5E5E5] font-medium":"text-[#6B7280] hover:text-[#111827] hover:bg-[#E5E7EB]/60 dark:text-[#a1a1aa] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a]/50"),children:t.label},t.value))}),e.jsxs("div",{className:"flex-1 p-8 flex flex-col gap-6 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:r==="general"?"Settings":(O=h.find(t=>t.value===r))==null?void 0:O.label}),e.jsx("button",{onClick:c,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(P,{className:"h-4 w-4"})})]}),r==="models"&&e.jsxs("div",{className:"flex flex-col gap-6 flex-1 min-h-0 overflow-hidden",children:[e.jsx("p",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono shrink-0",children:"Configure API keys and model settings for different providers."}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:e.jsxs("div",{className:"flex flex-col gap-2 pr-2",children:[Object.entries(C).map(([t,l])=>{const m=Z[t]||{bg:"#71717a",label:"?"},T=l.some(f=>f.apiKey),R=y===t;return e.jsxs("div",{className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>H(t),className:"w-full p-4 flex items-center justify-between hover:bg-[#E5E7EB] dark:hover:bg-[#1f1f23] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded flex items-center justify-center text-white text-xs font-bold",style:{backgroundColor:m.bg},children:m.label}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-left",children:[e.jsx("span",{className:"text-sm font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono capitalize",children:t.replace(/-/g," ")}),e.jsxs("span",{className:"text-xs text-[#9CA3AF] dark:text-[#71717a] font-mono",children:[l.length," model",l.length>1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:b("text-xs font-mono",T?"text-[#16A34A]":"text-[#9CA3AF] dark:text-[#71717a]"),children:T?"● Connected":"○ Not Connected"}),e.jsx(M,{className:b("h-4 w-4 text-[#9CA3AF] dark:text-[#71717a] transition-transform",R&&"rotate-180")})]})]}),R&&e.jsx("div",{className:"border-t border-[#E5E7EB] dark:border-zinc-800",children:l.map(f=>e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between hover:bg-[#E5E7EB] dark:hover:bg-[#1f1f23] group",children:[e.jsxs("div",{className:"flex flex-col gap-0.5 flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm text-[#111827] dark:text-[#E5E5E5] font-mono truncate",children:f.model}),e.jsx("span",{className:"text-xs text-[#9CA3AF] dark:text-[#71717a] font-mono truncate",children:f.baseUrl||"Default URL"})]}),e.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>v(f),className:"p-1.5 text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] rounded transition-colors",children:e.jsx(W,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>a(f.id),className:"p-1.5 text-[#9CA3AF] hover:text-red-500 hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-red-400 dark:hover:bg-[#27272a] rounded transition-colors",children:e.jsx(X,{className:"h-3.5 w-3.5"})})]})]},f.id))})]},t)}),Object.keys(C).length===0&&e.jsx("div",{className:"text-center py-8 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No models configured yet"})]})}),e.jsx("button",{onClick:()=>i(!0),className:"w-full py-3 rounded-md text-[#6B7280] dark:text-[#a1a1aa] text-[13px] font-mono hover:bg-[#F3F4F6] dark:bg-[#18181b] transition-colors shrink-0",children:"+ Add New Model"})]}),r==="general"&&e.jsxs("div",{className:"flex flex-col gap-6 overflow-y-auto pr-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono font-semibold",children:"General"}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Response Language"}),e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#71717a] font-mono",children:"AI will respond in this language"})]}),e.jsxs("select",{value:s.language,onChange:t=>s.updateSettings({language:t.target.value}),className:"h-8 bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[12px] font-mono rounded-md px-3 border border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("option",{value:"en-US",children:"English (US)"}),e.jsx("option",{value:"zh-CN",children:"简体中文"}),e.jsx("option",{value:"zh-TW",children:"繁體中文"}),e.jsx("option",{value:"ja-JP",children:"日本語"}),e.jsx("option",{value:"ko-KR",children:"한국어"}),e.jsx("option",{value:"es-ES",children:"Español"}),e.jsx("option",{value:"fr-FR",children:"Français"}),e.jsx("option",{value:"de-DE",children:"Deutsch"}),e.jsx("option",{value:"pt-BR",children:"Português (BR)"}),e.jsx("option",{value:"ru-RU",children:"Русский"})]})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Auto-save sessions"}),e.jsx(g,{enabled:s.autoSaveSessions,onChange:t=>s.updateSettings({autoSaveSessions:t})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono font-semibold",children:"Appearance"}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Theme Preference"}),e.jsx("div",{className:"flex items-center gap-2 bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md p-1",children:["dark","light","system"].map(t=>e.jsx("button",{onClick:()=>s.updateSettings({uiTheme:t}),className:b("px-3 py-1 rounded text-[12px] font-mono transition-colors",s.uiTheme===t?"bg-[#E5E7EB] dark:bg-[#27272a] text-[#111827] dark:text-[#E5E5E5]":"text-[#9CA3AF] dark:text-[#71717a] hover:text-[#111827] dark:hover:text-[#E5E5E5]"),children:t==="dark"?"Dark":t==="light"?"Light":"System"},t))})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Compact sidebar"}),e.jsx(g,{enabled:!u,onChange:t=>E(!t)})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Code theme"}),e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#71717a] font-mono",children:"Syntax highlighting colors"})]}),e.jsxs("select",{value:s.theme,onChange:t=>s.updateSettings({theme:t.target.value}),className:"h-8 bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[12px] font-mono rounded-md px-3 border border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("option",{value:"dracula",children:"Dracula"}),e.jsx("option",{value:"monokai",children:"Monokai"}),e.jsx("option",{value:"nord",children:"Nord"}),e.jsx("option",{value:"tokyo-night",children:"Tokyo Night"}),e.jsx("option",{value:"one-dark",children:"One Dark"}),e.jsx("option",{value:"catppuccin",children:"Catppuccin"}),e.jsx("option",{value:"gruvbox",children:"Gruvbox"}),e.jsx("option",{value:"github",children:"GitHub"}),e.jsx("option",{value:"solarized-light",children:"Solarized Light"}),e.jsx("option",{value:"solarized-dark",children:"Solarized Dark"}),e.jsx("option",{value:"ayu-dark",children:"Ayu Dark"}),e.jsx("option",{value:"rose-pine",children:"Rose Pine"}),e.jsx("option",{value:"kanagawa",children:"Kanagawa"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono font-semibold",children:"Notifications"}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Build finished"}),e.jsx(g,{enabled:s.notifyBuild,onChange:t=>s.updateSettings({notifyBuild:t})})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Errors only"}),e.jsx(g,{enabled:s.notifyErrors,onChange:t=>s.updateSettings({notifyErrors:t})})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"System sounds"}),e.jsx(g,{enabled:s.notifySounds,onChange:t=>s.updateSettings({notifySounds:t})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono font-semibold",children:"Privacy"}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Telemetry"}),e.jsx(g,{enabled:s.privacyTelemetry,onChange:t=>s.updateSettings({privacyTelemetry:t})})]}),e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-[13px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:"Crash reports"}),e.jsx(g,{enabled:s.privacyCrash,onChange:t=>s.updateSettings({privacyCrash:t})})]})]})]}),r==="shortcuts"&&e.jsxs("div",{className:"flex flex-col gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx("input",{value:k,onChange:t=>S(t.target.value),placeholder:"Search actions...",className:"flex-1 h-9 bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono"}),e.jsxs("select",{value:F,onChange:t=>A(t.target.value),className:"h-9 bg-[#F3F4F6] dark:bg-[#18181b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:[e.jsx("option",{value:"all",children:"All scopes"}),e.jsx("option",{value:"global",children:"Global"}),e.jsx("option",{value:"chat",children:"Chat"}),e.jsx("option",{value:"layout",children:"Layout"}),e.jsx("option",{value:"history",children:"History"})]}),e.jsx("button",{onClick:()=>{S(""),A("all")},className:"h-9 px-3 rounded-md bg-[#E5E7EB] dark:bg-[#27272a] text-[#111827] dark:text-[#E5E5E5] text-[12px] font-mono font-semibold",children:"Reset"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto border border-[#E5E7EB] dark:border-[#27272a] rounded-lg bg-[#E5E7EB] dark:bg-[#111827]",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_180px_120px] gap-2 px-3 py-2 bg-white dark:bg-[#0C0C0C] text-[12px] text-[#6B7280] dark:text-[#94a3b8] font-mono font-semibold",children:[e.jsx("span",{children:"Action"}),e.jsx("span",{children:"Shortcut"}),e.jsx("span",{children:"Scope"})]}),D.map((t,l)=>e.jsxs("div",{className:b("grid grid-cols-[1fr_180px_120px] gap-2 px-3 py-2 text-[13px] font-mono",l%2===0?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C]"),children:[e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5]",children:t.action}),e.jsx("div",{className:"flex items-center gap-1",children:t.combo.map(m=>e.jsx("span",{className:"px-2 py-0.5 rounded bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[12px] font-mono font-semibold",children:m},m))}),e.jsx("span",{className:"text-[#6B7280] dark:text-[#94a3b8] text-[12px]",children:t.scope})]},`${t.action}-${t.scope}`)),D.length===0&&e.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-[#6B7280] dark:text-[#94a3b8] font-mono",children:"No shortcuts found."})]})]})]})]})]})}),e.jsx(Y,{open:o,onOpenChange:i,onSave:I}),e.jsx(q,{open:!!w,onOpenChange:t=>!t&&v(null),model:w,onSave:$})]})}function g({enabled:p,onChange:c}){return e.jsx("button",{onClick:()=>c(!p),className:b("w-10 h-5 rounded-full px-0.5 flex items-center transition-colors",p?"bg-[#22C55E]":"bg-[#E5E7EB] dark:bg-[#27272a]"),children:e.jsx("span",{className:b("h-4 w-4 rounded-full transition-transform",p?"translate-x-5 bg-white":"translate-x-0 bg-white dark:bg-[#a1a1aa]")})})}export{de as SettingsModal};
@@ -1 +0,0 @@
1
- import{r as o,j as e}from"./vendor-react-Dm1xU4bP.js";import{D as I,a as D,b as T}from"./dialog-C8VDk-ma.js";import{u as q,c as h}from"./index-9t-WxRrl.js";import{e as v}from"./useRequest-BJp539HQ.js";import{P as M,R as z,X as R,e as H}from"./vendor-icons-DlzC8I7m.js";import"./vendor-markdown-DIcugY1e.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CfxBc_4-.js";const J=async()=>{const a=await fetch("/skills");if(!a.ok)throw new Error("Failed to fetch skills");return a.json()},$=async()=>{const a=await fetch("/skills/catalog");if(!a.ok)throw new Error("Failed to fetch catalog");return a.json()};function se(){const{isSkillsOpen:a,toggleSkills:r}=q(),[d,c]=o.useState(null),[f,n]=o.useState(""),[p,u]=o.useState(!1),[C,i]=o.useState(!1),[F,x]=o.useState("confirm"),[w,m]=o.useState(null),[k,j]=o.useState(null),{data:b=[],loading:E,run:g}=v(J,{refreshDeps:[a],ready:a,onSuccess:t=>{t.length>0&&!d&&c(t[0].id)}}),{data:s=[]}=v($,{refreshDeps:[a],ready:a}),{runAsync:y}=v(async t=>{await fetch(`/skills/${encodeURIComponent(t)}`,{method:"DELETE"})},{manual:!0,onSuccess:g}),{runAsync:A,loading:S}=v(async(t,N)=>{if(!(await fetch(`/skills/${encodeURIComponent(t)}/toggle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:N})})).ok)throw new Error("Failed to toggle skill")},{manual:!0,onSuccess:g}),O=b.filter(t=>t.name.toLowerCase().includes(f.toLowerCase())),l=o.useMemo(()=>b.find(t=>t.id===d)??b[0],[b,d]),L=()=>{u(!0)},P=t=>{j(t),m(null),x("confirm"),i(!0)},U=async()=>{if(k){x("installing"),m(null);try{const t=await fetch("/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)}),N=await t.json().catch(()=>({}));if(!t.ok||N.success===!1)throw new Error(N.error||"Failed to install skill");await g(),i(!1),u(!1)}catch(t){m(t instanceof Error?t.message:"Failed to install skill"),x("failed")}}};return e.jsxs(o.Fragment,{children:[e.jsx(I,{open:a,onOpenChange:r,children:e.jsxs(D,{className:"sm:max-w-[820px] h-[620px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl flex flex-col","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(T,{className:"sr-only",children:"Skills"}),e.jsx("div",{className:"flex h-full min-h-0",children:e.jsxs("div",{className:"flex-1 p-8 flex flex-col gap-5 min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Skills"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:L,className:"h-8 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-xs font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a]",children:[e.jsx(M,{className:"h-3.5 w-3.5"}),"Install skill"]}),e.jsx("button",{onClick:g,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",disabled:E,children:e.jsx(z,{className:h("h-4 w-4",E&&"animate-spin")})}),e.jsx("button",{onClick:r,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(R,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex gap-5 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-[220px] flex flex-col gap-3 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] shrink-0",children:"Installed"}),e.jsx("input",{value:f,onChange:t=>n(t.target.value),placeholder:"Search skills...",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:focus:border-[#27272a] shrink-0"}),e.jsxs("div",{className:"flex flex-col gap-2 overflow-y-auto flex-1 min-h-0 pr-1",children:[O.length===0&&!E&&e.jsx("div",{className:"text-center py-8 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No skills installed"}),O.map(t=>e.jsxs("button",{onClick:()=>c(t.id),className:h("text-left rounded-lg px-3 py-2 flex flex-col gap-1 transition-colors",t.id===d?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b]"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:t.name}),e.jsx("span",{className:h("text-[11px] font-mono font-semibold",t.enabled?"text-[#16A34A] dark:text-[#22C55E]":"text-[#f59e0b]"),children:t.enabled?"Enabled":"Disabled"})]}),e.jsx("span",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] truncate",children:t.description||"No description"})]},t.id))]})]}),l?e.jsxs("div",{className:"flex-1 flex flex-col gap-3 overflow-y-auto pr-2 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-base font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:l.name}),e.jsxs("span",{className:"text-xs font-mono text-[#9CA3AF] dark:text-[#71717a]",children:["v",l.version]})]}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:l.description||"No description available"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>A(l.name,!l.enabled),disabled:S,className:h("h-7 px-3 rounded-md text-[11px] font-mono font-semibold",l.enabled?"bg-[#E5E7EB] text-[#111827] hover:bg-[#D1D5DB] dark:bg-[#27272a] dark:text-[#E5E5E5] dark:hover:bg-[#32323a]":"bg-[#16A34A] text-white hover:bg-[#15803D] dark:bg-[#22C55E] dark:text-[#0C0C0C] dark:hover:bg-[#1ea34b]",S&&"opacity-60 cursor-not-allowed"),children:S?"Saving...":l.enabled?"Disable":"Enable"}),e.jsx("button",{disabled:!0,title:"Editing not supported yet",className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold opacity-60 cursor-not-allowed",children:"Edit"}),e.jsxs("button",{onClick:()=>y(l.name),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#ef4444] text-[11px] font-mono font-semibold flex items-center gap-1",children:[e.jsx(H,{className:"h-3 w-3"}),"Uninstall"]})]}),e.jsx("div",{className:"h-px bg-[#E5E7EB] dark:bg-[#1f2937]"}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[12px] font-mono",children:[e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a]",children:"Provider"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5]",children:l.provider}),e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a]",children:"Location"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:l.location})]})]}),l.capabilities.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.capabilities.map(t=>e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#111827] dark:text-[#E5E5E5]",children:t},t))})]}),l.allowedTools.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:["Allowed Tools (",l.allowedTools.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.allowedTools.map(t=>e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#111827] dark:text-[#E5E5E5]",children:t},t))})]})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"Select a skill to view details"})})]})]})})]})}),e.jsx(G,{open:p,catalog:s,installed:b.map(t=>t.name),onOpenChange:u,onInstall:P}),e.jsx(Q,{open:C,status:F,error:w,onCancel:()=>i(!1),onConfirm:U,onRetry:()=>x("confirm")})]})}function B({active:a,children:r,onClick:d}){return e.jsx("button",{onClick:d,className:h("px-3 py-1 rounded text-[12px] font-mono font-semibold transition-colors",a?"bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]":"text-[#6B7280] dark:text-[#a1a1aa]"),children:r})}function G({open:a,onOpenChange:r,onInstall:d,catalog:c,installed:f}){const[n,p]=o.useState("catalog"),[u,C]=o.useState(""),[i,F]=o.useState(null),[x,w]=o.useState(""),[m,k]=o.useState(""),j=c.filter(s=>s.name.toLowerCase().includes(u.toLowerCase())),b=()=>{if(n==="catalog"){if(!i)return;d({source:"catalog",name:i});return}if(n==="repo"){if(!x)return;d({source:"repo",url:x});return}m&&d({source:"local",path:m})},E=i?f.includes(i):!1,g=n==="catalog"&&(!i||E)||n==="repo"&&!x||n==="local"&&!m;return e.jsx(I,{open:a,onOpenChange:r,children:e.jsxs(D,{className:"sm:max-w-[540px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(T,{className:"sr-only",children:"Install Skill"}),e.jsxs("div",{className:"p-6 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-base font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"Install Skill"}),e.jsx("button",{onClick:()=>r(!1),className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(R,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 p-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] w-fit",children:[e.jsx(B,{active:n==="catalog",onClick:()=>p("catalog"),children:"Catalog"}),e.jsx(B,{active:n==="repo",onClick:()=>p("repo"),children:"Repo"}),e.jsx(B,{active:n==="local",onClick:()=>p("local"),children:"Local"})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[n==="catalog"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{value:u,onChange:s=>C(s.target.value),placeholder:"Search catalog...",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:focus:border-[#27272a]"}),e.jsxs("div",{className:"flex flex-col gap-2 max-h-[240px] overflow-y-auto",children:[j.length===0&&e.jsx("div",{className:"text-center py-6 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No skills found"}),j.map(s=>{const y=f.includes(s.name),A=i===s.name;return e.jsxs("button",{onClick:()=>F(s.name),className:h("rounded-lg px-3 py-2 flex flex-col gap-1 text-left transition-colors",A?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b]"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:s.name}),e.jsx("span",{className:h("text-[10px] font-mono px-2 py-0.5 rounded",s.tag==="Official"?"bg-[#22C55E]/20 text-[#16A34A] dark:text-[#22C55E]":"bg-[#3b82f6]/20 text-[#3b82f6]"),children:s.tag})]}),e.jsx("span",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:s.description}),e.jsxs("span",{className:"text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:["by ",s.author]}),y&&e.jsx("span",{className:"text-[10px] font-mono text-[#16A34A] dark:text-[#22C55E]",children:"Installed"})]},s.name)})]})]}),n==="repo"&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"GitHub URL"}),e.jsx("input",{value:x,onChange:s=>w(s.target.value),placeholder:"https://github.com/org/skill",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:focus:border-[#27272a]"}),e.jsx("span",{className:"inline-flex w-fit px-2 py-0.5 rounded bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:"Private repo supported (backend support required)"})]}),n==="local"&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:"Local path"}),e.jsx("input",{value:m,onChange:s=>k(s.target.value),placeholder:"/Users/bytedance/skills/my-skill",className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] px-3 text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] border border-transparent focus:outline-none focus:border-[#E5E7EB] dark:focus:border-[#27272a]"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx("button",{onClick:()=>r(!1),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Cancel"}),e.jsx("button",{onClick:b,disabled:g,className:h("h-7 px-3 rounded-md text-[11px] font-mono font-semibold",g?"bg-[#E5E7EB] text-[#9CA3AF] cursor-not-allowed dark:bg-[#27272a] dark:text-[#71717a]":"bg-[#16A34A] text-white dark:bg-[#22C55E] dark:text-[#0C0C0C]"),children:"Install"})]})]})]})})}function Q({open:a,status:r,error:d,onCancel:c,onConfirm:f,onRetry:n}){return e.jsx(I,{open:a,onOpenChange:p=>!p&&c(),children:e.jsxs(D,{className:"sm:max-w-[320px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(T,{className:"sr-only",children:"Install Status"}),e.jsxs("div",{className:"p-5 flex flex-col gap-3",children:[r==="confirm"&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Confirm Install"}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:"Install selected skill?"}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:c,className:"h-6 px-2.5 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Cancel"}),e.jsx("button",{onClick:f,className:"h-6 px-2.5 rounded-md bg-[#16A34A] text-white dark:bg-[#22C55E] dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Install"})]})]}),r==="installing"&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Installing"}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:"Downloading and verifying…"}),e.jsx("div",{className:"h-1.5 rounded-full bg-[#E5E7EB] dark:bg-[#18181b] overflow-hidden",children:e.jsx("div",{className:"h-full w-[45%] bg-[#16A34A] dark:bg-[#22C55E]"})}),e.jsx("span",{className:"text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"~35%"}),e.jsx("button",{onClick:c,className:"self-end h-6 px-2.5 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Hide"})]}),r==="failed"&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Install Failed"}),e.jsx("p",{className:"text-[12px] font-mono text-[#f87171]",children:d||"Installation failed."}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:"Check access and try again."}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:c,className:"h-6 px-2.5 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#111827] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Close"}),e.jsx("button",{onClick:n,className:"h-6 px-2.5 rounded-md bg-[#16A34A] text-white dark:bg-[#22C55E] dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Retry"})]})]})]})]})})}export{se as SkillsModal};
@@ -1 +0,0 @@
1
- import{r as o,j as a}from"./vendor-react-Dm1xU4bP.js";import{q as f,r as g,s as d,t as u,u as i,O as l,D as r}from"./vendor-radix-CfxBc_4-.js";import{c as n}from"./index-9t-WxRrl.js";import{X as x}from"./vendor-icons-DlzC8I7m.js";const k=f,y=g,c=o.forwardRef(({className:t,...e},s)=>a.jsx(l,{ref:s,className:n("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));c.displayName=l.displayName;const N=o.forwardRef(({className:t,children:e,hideCloseButton:s,...m},p)=>a.jsxs(y,{children:[a.jsx(c,{}),a.jsxs(d,{ref:p,className:n("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...m,children:[e,!s&&a.jsxs(u,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[a.jsx(x,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));N.displayName=d.displayName;const b=o.forwardRef(({className:t,...e},s)=>a.jsx(i,{ref:s,className:n("text-lg font-semibold leading-none tracking-tight",t),...e}));b.displayName=i.displayName;const j=o.forwardRef(({className:t,...e},s)=>a.jsx(r,{ref:s,className:n("text-sm text-muted-foreground",t),...e}));j.displayName=r.displayName;export{k as D,N as a,b};