blade-code 0.7.7 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-0b3m5qn6.js → chunk-06h100e2.js} +1 -1
  3. package/dist/chunk-07jvw0kn.js +1 -0
  4. package/dist/chunk-0dj326ms.js +5 -0
  5. package/dist/chunk-14erxdhd.js +1 -0
  6. package/dist/chunk-1pt090dg.js +615 -0
  7. package/dist/{chunk-2qckpa16.js → chunk-1smf2dj3.js} +2 -2
  8. package/dist/chunk-34pdtz4q.js +3 -0
  9. package/dist/chunk-3gw66r7a.js +2 -0
  10. package/dist/chunk-49g067ek.js +41 -0
  11. package/dist/chunk-6es6av6j.js +2 -0
  12. package/dist/{chunk-6y58y4rx.js → chunk-9xkjb87h.js} +1 -1
  13. package/dist/chunk-a12tmmfr.js +1 -0
  14. package/dist/chunk-bggvft3z.js +1 -0
  15. package/dist/{chunk-60se4kxq.js → chunk-bm8vwfez.js} +1 -1
  16. package/dist/chunk-bxbagv76.js +9 -0
  17. package/dist/chunk-ctqf59q1.js +2 -0
  18. package/dist/chunk-d08wbxjr.js +1 -0
  19. package/dist/chunk-d4ex0qvs.js +2 -0
  20. package/dist/{chunk-zet4zjc3.js → chunk-dr06x0cw.js} +1 -1
  21. package/dist/chunk-e4a240t7.js +34 -0
  22. package/dist/{chunk-v61bja34.js → chunk-gsfkrr25.js} +1 -1
  23. package/dist/chunk-gytwh5y1.js +6 -0
  24. package/dist/chunk-hjx5n3dw.js +3 -0
  25. package/dist/chunk-hrnd3wjg.js +6 -0
  26. package/dist/chunk-j39q2kx7.js +1 -0
  27. package/dist/chunk-jakzknh3.js +1570 -0
  28. package/dist/chunk-jqr2pknb.js +151 -0
  29. package/dist/{chunk-2n8a87ds.js → chunk-jt62ctz7.js} +1 -1
  30. package/dist/{chunk-5xjj88wd.js → chunk-kawv31m3.js} +1 -1
  31. package/dist/chunk-n8ymp6nd.js +1 -0
  32. package/dist/{chunk-yyw9bbfd.js → chunk-nned222j.js} +1 -1
  33. package/dist/chunk-qwdbqjh7.js +22 -0
  34. package/dist/chunk-syj3anec.js +6 -0
  35. package/dist/chunk-tv4r86ez.js +24 -0
  36. package/dist/chunk-twem6p0g.js +2 -0
  37. package/dist/chunk-v3ctg84r.js +1 -0
  38. package/dist/chunk-v5rn5r1h.js +1 -0
  39. package/dist/{chunk-w1m1ehs1.js → chunk-wmes2tt9.js} +1 -1
  40. package/dist/chunk-xhnyy54e.js +2 -0
  41. package/dist/{chunk-6087cgst.js → chunk-ychj0e5q.js} +1 -1
  42. package/dist/{chunk-7e5hzpmp.js → chunk-ydb9myhe.js} +1 -1
  43. package/dist/{chunk-p7rf3zp8.js → chunk-yhpm9azy.js} +1 -1
  44. package/dist/{chunk-c6rtexw1.js → chunk-yqxw7zz4.js} +1 -1
  45. package/dist/web/assets/{FilePreview-B2anY2d1.js → FilePreview-DvgnEspB.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-BVfRG88x.js → MarkdownRenderer-e1ZUy6jV.js} +1 -1
  47. package/dist/web/assets/{McpModal-BVvb-dzr.js → McpModal-Raois2g1.js} +1 -1
  48. package/dist/web/assets/SettingsModal-Dzuatoea.js +1 -0
  49. package/dist/web/assets/{SettingsStore-B87y64B4.js → SettingsStore-BxDA0Usw.js} +1 -1
  50. package/dist/web/assets/{SkillsModal-BXYaF2KK.js → SkillsModal-Cg2-befH.js} +1 -1
  51. package/dist/web/assets/{TerminalPanel-B-NRhOXN.js → TerminalPanel-CEoQI9Lu.js} +1 -1
  52. package/dist/web/assets/index-BvGeIa_-.js +16 -0
  53. package/dist/web/assets/index-DDJnZJcp.css +1 -0
  54. package/dist/web/index.html +2 -2
  55. package/package.json +4 -11
  56. package/dist/chunk-0y895nft.js +0 -9
  57. package/dist/chunk-2j3tb2dm.js +0 -1
  58. package/dist/chunk-3fcze972.js +0 -1
  59. package/dist/chunk-4n7fsts0.js +0 -2
  60. package/dist/chunk-54vk4tw8.js +0 -615
  61. package/dist/chunk-6cry51vb.js +0 -9
  62. package/dist/chunk-778h8815.js +0 -26
  63. package/dist/chunk-89j9pm90.js +0 -24
  64. package/dist/chunk-8e0rv3j5.js +0 -41
  65. package/dist/chunk-8p98nt9v.js +0 -151
  66. package/dist/chunk-94vj1hjp.js +0 -1
  67. package/dist/chunk-c8cxeve8.js +0 -1
  68. package/dist/chunk-d61d6m07.js +0 -2
  69. package/dist/chunk-ebcmqx1k.js +0 -2
  70. package/dist/chunk-gsn659hw.js +0 -1
  71. package/dist/chunk-h79044h0.js +0 -3
  72. package/dist/chunk-kppxkh33.js +0 -1
  73. package/dist/chunk-ptt8s7nd.js +0 -6
  74. package/dist/chunk-qnh7np1s.js +0 -6
  75. package/dist/chunk-ran4gsmy.js +0 -1
  76. package/dist/chunk-swyvd7hd.js +0 -1
  77. package/dist/chunk-t9zdypqp.js +0 -2
  78. package/dist/chunk-x1khkevy.js +0 -1563
  79. package/dist/chunk-x24ddbhs.js +0 -6
  80. package/dist/chunk-x466sb8s.js +0 -34
  81. package/dist/web/assets/SettingsModal-aseVv-gp.js +0 -1
  82. package/dist/web/assets/index-9kl44E8k.js +0 -9
  83. package/dist/web/assets/index-CUVe9dGs.css +0 -1
@@ -1,6 +0,0 @@
1
- import{y as w}from"./chunk-ebcmqx1k.js";import{ra as S}from"./chunk-89j9pm90.js";import{Da as u,Ea as y}from"./chunk-778h8815.js";import{Bb as d,wb as r,zb as m}from"./chunk-v61bja34.js";import{Yb as b}from"./chunk-h79044h0.js";import{promises as h}from"node:fs";import P from"node:path";import{z as o}from"zod";var M=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],T=new Set([...Object.keys(u),...M]),k=o.object({currentModelId:o.string().optional(),models:o.array(o.object({id:o.string().min(1),name:o.string().min(1),provider:o.string().min(1),apiKey:o.string(),baseUrl:o.string(),model:o.string().min(1),temperature:o.number().optional(),maxContextTokens:o.number().positive().optional(),maxOutputTokens:o.number().positive().optional(),topP:o.number().optional(),topK:o.number().optional(),supportsThinking:o.boolean().optional(),thinkingBudget:o.number().positive().optional(),thinkingMode:o.enum(["off","budget","adaptive"]).optional(),apiVersion:o.string().optional(),projectId:o.string().optional(),fallbackModels:o.array(o.string()).optional(),enablePromptCaching:o.boolean().optional(),customHeaders:o.record(o.string()).optional(),timeout:o.number().positive().optional(),maxRetries:o.number().int().min(0).optional()})).optional(),temperature:o.number().optional(),maxContextTokens:o.number().positive().optional(),maxOutputTokens:o.number().positive().optional(),stream:o.boolean().optional(),topP:o.number().optional(),topK:o.number().optional(),timeout:o.number().positive().optional(),theme:o.string().optional(),uiTheme:o.enum(["light","dark","system"]).optional(),language:o.string().optional(),fontSize:o.number().positive().optional(),autoSaveSessions:o.boolean().optional(),notifyBuild:o.boolean().optional(),notifyErrors:o.boolean().optional(),notifySounds:o.boolean().optional(),privacyTelemetry:o.boolean().optional(),privacyCrash:o.boolean().optional(),debug:o.union([o.boolean(),o.string()]).optional(),mcpEnabled:o.boolean().optional(),mcpServers:o.record(o.record(o.unknown())).optional(),permissionMode:o.nativeEnum(m).optional(),maxTurns:o.number().int().min(-1).max(d).optional(),systemPrompt:o.string().optional(),appendSystemPrompt:o.string().optional(),initialMessage:o.string().optional(),resumeSessionId:o.string().optional(),forkSession:o.boolean().optional(),allowedTools:o.array(o.string().min(1)).optional(),disallowedTools:o.array(o.string().min(1)).optional(),mcpConfigPaths:o.array(o.string().min(1)).optional(),strictMcpConfig:o.boolean().optional(),model:o.string().min(1).optional(),addDirs:o.array(o.string().min(1)).optional(),outputFormat:o.enum(["text","json","stream-json","jsonl"]).optional(),inputFormat:o.enum(["text","stream-json"]).optional(),print:o.boolean().optional(),includePartialMessages:o.boolean().optional(),replayUserMessages:o.boolean().optional(),agentsConfig:o.string().optional(),settingSources:o.string().optional(),permissions:o.object({allow:o.array(o.string()).optional(),ask:o.array(o.string()).optional(),deny:o.array(o.string()).optional()}).optional(),env:o.record(o.string()).optional(),hooks:o.record(o.unknown()).optional(),disableAllHooks:o.boolean().optional()}).passthrough(),C=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"]];function a(n,i){let t;try{t=JSON.parse(n)}catch(e){let l=e instanceof Error?`: ${e.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${l}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let e of Object.keys(t))if(!T.has(e))throw Error(`Unknown --settings field: ${e}`);let s=k.safeParse(t);if(!s.success){let e=s.error.issues.map((l)=>`${l.path.join(".")||"settings"}: ${l.message}`).join("; ");throw Error(`Invalid --settings value: ${e}`)}return s.data}async function c(n){if(n===void 0)return;let i=n.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return a(i,"inline JSON");let t=P.resolve(r(),i),s;try{s=await h.readFile(t,"utf8")}catch(e){let l=e instanceof Error?`: ${e.message}`:"";throw Error(`Unable to read --settings file ${t}${l}`)}return a(s,t)}function f(n,i){if(!i)return;let t=i;for(let[s,e]of C){if(s==="permissionMode"&&n.yolo===!0)continue;if(n[e]===void 0&&t[s]!==void 0)n[e]=t[s]}}var p=b("General"),K=(n)=>{if(n.yolo){if(n.permissionMode&&n.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");n.permissionMode="yolo"}if(Array.isArray(n.allowedTools))n.allowedTools=n.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(n.disallowedTools))n.disallowedTools=n.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(n.allowedTools)&&Array.isArray(n.disallowedTools)){let i=n.allowedTools.filter((t)=>n.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},z=async(n)=>{let i=await c(typeof n.settings==="string"?n.settings:void 0);if(f(n,i),typeof n.agents==="string")w(n.agents);E(n);try{let s=await y.getInstance().initialize(i);if(S().config.actions.setConfig(s),n.debug)p.info("[CLI] 配置已加载到 Store")}catch(t){p.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
- [FAIL] 配置初始化失败
3
- `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
- 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
- `),process.exit(1)}};function E(n){if(n.continue&&n.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(n.forkSession&&!n.continue&&!n.resume)throw Error("--fork-session requires --resume or --continue");if(n.sessionId&&(n.continue||n.resume)&&!n.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var B=(n)=>{if(n.outputFormat&&n.outputFormat!=="text"&&!n.print&&!n.headless)throw Error("--output-format can only be used with --print or --headless");if(n.headless&&n.outputFormat&&!["text","jsonl"].includes(n.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${n.outputFormat}". Use --print for json|stream-json support.`);if(n.print&&n.outputFormat&&!["text","json","stream-json"].includes(n.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${n.outputFormat}". Use --headless for jsonl support.`);if(n.inputFormat==="stream-json"&&n.print)p.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{K as v,z as w,B as x};
@@ -1,34 +0,0 @@
1
- import{Ia as S,Ja as h}from"./chunk-d61d6m07.js";import{pb as M}from"./chunk-6y58y4rx.js";import{_b as c}from"./chunk-zet4zjc3.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as p}from"lodash-es";function J(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${J(Y)},实际收到 ${J(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(p(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>J($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${J(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>J($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
2
- ${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
- `)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
4
-
5
- ${B.description.long}`;if(B.description.usageNotes&&B.description.usageNotes.length>0)Q+=`
6
-
7
- Usage Notes:
8
- ${B.description.usageNotes.map((X)=>`- ${X}`).join(`
9
- `)}`;if(B.description.important&&B.description.important.length>0)Q+=`
10
-
11
- Important:
12
- ${B.description.important.map((X)=>`[WARN] ${X}`).join(`
13
- `)}`;return{name:B.name,description:Q,parameters:G}},getMetadata(){return{name:B.name,displayName:B.displayName,kind:B.kind,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],description:B.description,schema:H(B.schema)}},build(G){let Q=y(B.schema,G);return new w(B.name,Q,B.execute)},async execute(G,Q,X){return this.build(G).execute(Q||new AbortController().signal,void 0,X)},extractSignatureContent:B.extractSignatureContent?(G)=>B.extractSignatureContent(G):void 0,abstractPermissionRule:B.abstractPermissionRule?(G)=>B.abstractPermissionRule(G):void 0}}function U(B,G,Q,X){let Y;try{Y=V(Q.inputSchema)}catch(W){console.warn(`[createMcpTool] Schema 转换失败,使用降级 schema: ${Q.name}`,W),Y=L.any()}let $=X||Q.name;return k({name:$,displayName:`${G}: ${Q.name}`,kind:"execute",schema:Y,description:{short:Q.description||`MCP Tool: ${Q.name}`,important:[`From MCP server: ${G}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",G],async execute(W,q){try{let F=await B.callTool(Q.name,W),A="";if(F.content&&Array.isArray(F.content)){for(let K of F.content)if(K.type==="text"&&K.text)A+=K.text;else if(K.type==="image")A+=`[image: ${K.mimeType||"unknown"}]
14
- `;else if(K.type==="resource")A+=`[resource: ${K.mimeType||"unknown"}]
15
- `}if(F.isError)return{success:!1,llmContent:A||"MCP tool execution failed",error:{type:"execution_error",message:A||"MCP tool execution failed"},metadata:{summary:`MCP ${Q.name} 执行失败`,serverName:G,toolName:Q.name}};return{success:!0,llmContent:A||"Execution succeeded",metadata:{summary:`MCP ${Q.name} 执行成功`,serverName:G,toolName:Q.name,mcpResult:F}}}catch(F){return{success:!1,llmContent:`MCP tool execution failed: ${F.message}`,error:{type:"execution_error",message:F.message},metadata:{summary:`MCP ${Q.name} 执行失败`,serverName:G,toolName:Q.name}}}}})}function V(B){if(B.type==="object"||B.properties){let G={},Q=B.required||[];if(B.properties){for(let[X,Y]of Object.entries(B.properties))if(typeof Y==="object"&&Y!==null){let $=V(Y);if(!Q.includes(X))$=$.optional();G[X]=$}}return L.object(G)}if(B.type==="array"&&B.items){if(typeof B.items==="object"&&!Array.isArray(B.items)&&B.items!==null)return L.array(V(B.items));return L.array(L.any())}if(B.type==="string"){let G=L.string();if(B.minLength!==void 0)G=G.min(B.minLength);if(B.maxLength!==void 0)G=G.max(B.maxLength);if(B.pattern)G=G.regex(new RegExp(B.pattern));if(B.enum)return L.enum(B.enum);return G}if(B.type==="number"||B.type==="integer"){let G=L.number();if(B.minimum!==void 0)G=G.min(B.minimum);if(B.maximum!==void 0)G=G.max(B.maximum);return G}if(B.type==="boolean")return L.boolean();if(B.oneOf&&B.oneOf.length>0){let G=B.oneOf.filter((Q)=>typeof Q==="object"&&Q!==null).map((Q)=>V(Q));if(G.length>=2)return L.union(G)}if(B.anyOf&&B.anyOf.length>0){let G=B.anyOf.filter((Q)=>typeof Q==="object"&&Q!==null).map((Q)=>V(Q));if(G.length>=2)return L.union(G)}return L.any()}import{Client as t}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as a}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as s}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as n}from"events";import{spawn as m}from"child_process";import*as _ from"crypto";import*as T from"http";import{URL as C}from"url";import{promises as z}from"fs";import f from"os";import P from"path";class x{tokenFilePath;constructor(){let B=f.homedir(),G=P.join(B,".blade");this.tokenFilePath=P.join(G,"mcp-oauth-tokens.json")}async ensureConfigDir(){let B=P.dirname(this.tokenFilePath);try{await z.mkdir(B,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let B=new Map;try{let G=await z.readFile(this.tokenFilePath,"utf-8"),Q=JSON.parse(G);for(let X of Q)B.set(X.serverName,X)}catch(G){if(G.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",G)}return B}async saveAllCredentials(B){await this.ensureConfigDir();let G=Array.from(B.values());await z.writeFile(this.tokenFilePath,JSON.stringify(G,null,2),{mode:384})}async saveToken(B,G,Q,X){let Y=await this.loadAllCredentials(),$={serverName:B,token:G,clientId:Q,tokenUrl:X,updatedAt:Date.now()};Y.set(B,$),await this.saveAllCredentials(Y)}async getCredentials(B){return(await this.loadAllCredentials()).get(B)||null}async deleteCredentials(B){let G=await this.loadAllCredentials();G.delete(B),await this.saveAllCredentials(G)}async listServers(){let B=await this.loadAllCredentials();return Array.from(B.keys())}isTokenExpired(B){if(!B.expiresAt)return!1;let G=300000;return Date.now()>=B.expiresAt-G}}var Z=7777,D="/oauth/callback",I=200;class O{tokenStorage;constructor(B=new x){this.tokenStorage=B}generatePKCEParams(){let B=_.randomBytes(32).toString("base64url"),G=_.createHash("sha256").update(B).digest("base64url"),Q=_.randomBytes(16).toString("base64url");return{codeVerifier:B,codeChallenge:G,state:Q}}buildAuthorizationUrl(B,G){let Q=B.redirectUri||`http://localhost:${Z}${D}`,X=new URLSearchParams({client_id:B.clientId,response_type:"code",redirect_uri:Q,state:G.state,code_challenge:G.codeChallenge,code_challenge_method:"S256"});if(B.scopes&&B.scopes.length>0)X.append("scope",B.scopes.join(" "));let Y=new C(B.authorizationUrl);return X.forEach(($,W)=>{Y.searchParams.append(W,$)}),Y.toString()}async startCallbackServer(B){return new Promise((G,Q)=>{let X=T.createServer((Y,$)=>{try{let W=new C(Y.url,`http://localhost:${Z}`);if(W.pathname!==D){$.writeHead(404),$.end("Not found");return}let q=W.searchParams.get("code"),F=W.searchParams.get("state"),A=W.searchParams.get("error");if(A){$.writeHead(I,{"Content-Type":"text/html"}),$.end(`
16
- <html>
17
- <body>
18
- <h1>Authentication Failed</h1>
19
- <p>Error: ${A}</p>
20
- <p>You can close this window.</p>
21
- </body>
22
- </html>
23
- `),X.close(),Q(Error(`OAuth error: ${A}`));return}if(!q||!F){$.writeHead(400),$.end("Missing code or state parameter");return}if(F!==B){$.writeHead(400),$.end("Invalid state parameter"),X.close(),Q(Error("State mismatch - possible CSRF attack"));return}$.writeHead(I,{"Content-Type":"text/html"}),$.end(`
24
- <html>
25
- <body>
26
- <h1>Authentication Successful!</h1>
27
- <p>You can close this window and return to Blade.</p>
28
- <script>window.close();</script>
29
- </body>
30
- </html>
31
- `),X.close(),G(q)}catch(W){X.close(),Q(W)}});X.on("error",Q),X.listen(Z,()=>{console.log(`[OAuth] Callback server listening on port ${Z}`)}),setTimeout(()=>{X.close(),Q(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken(B,G,Q){let X=B.redirectUri||`http://localhost:${Z}${D}`,Y=new URLSearchParams({grant_type:"authorization_code",code:G,redirect_uri:X,code_verifier:Q,client_id:B.clientId});if(B.clientSecret)Y.append("client_secret",B.clientSecret);let $=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!$.ok){let W=await $.text();throw Error(`Token exchange failed: ${$.status} - ${W}`)}return await $.json()}async refreshAccessToken(B,G){let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:G,client_id:B.clientId});if(B.clientSecret)Q.append("client_secret",B.clientSecret);if(B.scopes&&B.scopes.length>0)Q.append("scope",B.scopes.join(" "));let X=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let Y=await X.text();throw Error(`Token refresh failed: ${X.status} - ${Y}`)}return await X.json()}async authenticate(B,G){if(!G.clientId||!G.authorizationUrl||!G.tokenUrl)throw Error("Missing required OAuth configuration");let Q=this.generatePKCEParams(),X=this.buildAuthorizationUrl(G,Q);console.log(`
32
- [OAuth] Opening browser for authentication...`),console.log(`
33
- If the browser does not open automatically, copy and paste this URL:`),console.log(X),console.log("");let Y=this.startCallbackServer(Q.state);try{await this.openAuthorizationUrl(X)}catch(F){console.warn("[OAuth] Failed to open browser automatically:",F)}let $=await Y;console.log("[OAuth] Authorization code received, exchanging for tokens...");let W=await this.exchangeCodeForToken(G,$,Q.codeVerifier),q={accessToken:W.access_token,tokenType:W.token_type||"Bearer",refreshToken:W.refresh_token,scope:W.scope};if(W.expires_in)q.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken(B,q,G.clientId,G.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl(B){let{command:G,args:Q}=this.getBrowserCommand(B);await new Promise((X,Y)=>{let $=m(G,Q,{stdio:"ignore"});$.once("error",Y),$.once("close",(W)=>{if(W===0||W===null)X();else Y(Error(`Failed to open browser (exit code ${W})`))})})}getBrowserCommand(B){if(process.platform==="darwin")return{command:"open",args:[B]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",B]};return{command:"xdg-open",args:[B]}}async getValidToken(B,G){let Q=await this.tokenStorage.getCredentials(B);if(!Q)return null;let{token:X}=Q;if(!this.tokenStorage.isTokenExpired(X))return X.accessToken;if(X.refreshToken&&G.clientId&&Q.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${B}`);let Y=await this.refreshAccessToken(G,X.refreshToken),$={accessToken:Y.access_token,tokenType:Y.token_type,refreshToken:Y.refresh_token||X.refreshToken,scope:Y.scope||X.scope};if(Y.expires_in)$.expiresAt=Date.now()+Y.expires_in*1000;return await this.tokenStorage.saveToken(B,$,G.clientId,Q.tokenUrl),$.accessToken}catch(Y){console.error("[OAuth] Failed to refresh token:",Y),await this.tokenStorage.deleteCredentials(B)}return null}}import{EventEmitter as i}from"events";class E extends i{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(B,G={}){super();this.client=B,this.config={interval:G.interval??30000,timeout:G.timeout??1e4,enabled:G.enabled??!1,failureThreshold:G.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let B=this.client.connectionStatus;if(B==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let G={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",G),G}else throw Error(`连接状态异常: ${B}`)}catch(B){this.consecutiveFailures++;let G=B;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,G.message);let Q;if(this.consecutiveFailures>=this.config.failureThreshold)Q="unhealthy",this.emit("unhealthy",this.consecutiveFailures,G),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Y)=>{console.error("[HealthMonitor] 重连失败:",Y)});else Q="degraded";this.setStatus(Q);let X={status:Q,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:G};return this.emit("healthCheck",X),X}finally{this.isChecking=!1}}async pingServer(){let B=new Promise((Q,X)=>{setTimeout(()=>X(Error("Health check timeout")),this.config.timeout)}),G=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([G,B])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise((B)=>setTimeout(B,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch(B){throw console.error("[HealthMonitor] 重连失败:",B),B}}setStatus(B){if(this.currentStatus!==B){let G=this.currentStatus;this.currentStatus=B,this.emit("statusChanged",B,G)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function d(B){if(!(B instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(B))};let G=B.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Y)=>G.includes(Y)))return{type:"config_error",isRetryable:!1,originalError:B};if(G.includes("unauthorized")||G.includes("401")||G.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:B};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Y)=>G.includes(Y)))return{type:"network_temporary",isRetryable:!0,originalError:B};return{type:"unknown",isRetryable:!0,originalError:B}}class N extends n{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor(B,G,Q){super();this.config=B;if(this.serverName=G||"default",B.oauth?.enabled)this.oauthProvider=new O;if(Q?.enabled)this.healthMonitor=new E(this,Q),this.healthMonitor.on("unhealthy",(X,Y)=>{this.emit("unhealthy",X,Y)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(B=3,G=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let Q=null;for(let X=1;X<=B;X++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Y){Q=Y;let $=d(Y);if(!$.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",$.type),Y;if(X<B){let W=G*Math.pow(2,X-1);console.warn(`[McpClient] 连接失败(${X}/${B}),${W}ms 后重试...`),await new Promise((q)=>setTimeout(q,W))}}throw Q||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new t({name:h(),version:S()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let B=await this.createTransport();await this.sdkClient.connect(B);let G=this.sdkClient.getServerVersion();if(this.serverInfo={name:G?.name||"Unknown",version:G?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch(B){throw this.setStatus("error"),this.emit("error",B),B}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let B=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${B}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(G){if(console.error("[McpClient] 重连失败:",G),d(G).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},B)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch(B){console.warn("[McpClient] 断开连接时出错:",B)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool(B,G={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has(B))throw Error(`工具 "${B}" 不存在`);try{return await this.sdkClient.callTool({name:B,arguments:G})}catch(Q){throw console.error(`[McpClient] 调用工具 "${B}" 失败:`,Q),Q}}async createTransport(){let{type:B,command:G,args:Q,env:X,url:Y,headers:$,oauth:W}=this.config,q={...$};if(W?.enabled&&this.oauthProvider&&(B==="sse"||B==="http"))try{let F=await this.oauthProvider.getValidToken(this.serverName,W);if(!F){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let A=await this.oauthProvider.authenticate(this.serverName,W);q.Authorization=`Bearer ${A.accessToken}`}else q.Authorization=`Bearer ${F}`}catch(F){throw console.error("[McpClient] OAuth 认证失败:",F),Error(`OAuth 认证失败: ${F instanceof Error?F.message:String(F)}`)}if(B==="stdio"){if(!G)throw Error("stdio 传输需要 command 参数");let F={};for(let[A,K]of Object.entries(process.env))if(K!==void 0)F[A]=K;return new s({command:G,args:Q||[],env:{...F,...X},stderr:"ignore"})}else if(B==="sse"){if(!Y)throw Error("sse 传输需要 url 参数");return new a(new URL(Y),{requestInit:{headers:q}})}else if(B==="http"){if(!Y)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:F}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new F(new URL(Y),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${B}`)}async loadTools(){if(!this.sdkClient)return;try{let B=await this.sdkClient.listTools();if(this.tools.clear(),B.tools)for(let G of B.tools)this.tools.set(G.name,G);this.emit("toolsUpdated",this.availableTools)}catch(B){throw console.error("[McpClient] 加载工具失败:",B),B}}setStatus(B){let G=this.status;this.status=B,this.emit("statusChanged",B,G)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(B){return this.connect()}async disconnectFromServer(B){return this.disconnect()}async listResources(B){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools(B){return this.availableTools}async readResource(B,G){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:B})).contents?.[0]||{uri:B,text:""}}}class b extends r{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!b.instance)b.instance=new b;return b.instance}static createIsolated(){return new b}async registerServer(B,G){if(this.servers.has(B))throw Error(`MCP服务器 "${B}" 已经注册`);let Q=new N(G,B,G.healthCheck),X={config:G,client:Q,status:"disconnected",tools:[]};this.setupClientEventHandlers(Q,X,B),this.servers.set(B,X),this.emit("serverRegistered",B,X);try{await this.connectServer(B)}catch(Y){console.warn(`MCP服务器 "${B}" 连接失败:`,Y)}}async unregisterServer(B){let G=this.servers.get(B);if(!G)return;try{await G.client.disconnect()}catch(Q){console.warn(`断开MCP服务器 "${B}" 时出错:`,Q)}this.servers.delete(B),this.emit("serverUnregistered",B)}async connectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")return;try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async disconnectServer(B){let G=this.servers.get(B);if(!G)return;await G.client.disconnect(),G.connectedAt=void 0}async reconnectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")await G.client.disconnect();try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async getAvailableTools(){let B=[],G=new Map;for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let $=G.get(Y.name)||0;G.set(Y.name,$+1)}for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let W=(G.get(Y.name)||0)>1?`${Q}__${Y.name}`:Y.name,q=U(X.client,Q,Y,W);B.push(q)}return B}async findTool(B){for(let[G,Q]of this.servers)if(Q.status==="connected"){let X=Q.tools.find((Y)=>Y.name===B);if(X)return U(Q.client,G,X)}return null}getToolsByServer(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return[];return G.tools.map((Q)=>U(G.client,B,Q))}getServerStatus(B){return this.servers.get(B)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(this.refreshServerTools(G));await Promise.allSettled(B)}async refreshServerTools(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return;try{let Q=G.client.availableTools,X=G.tools.length;G.tools=Q,this.emit("toolsUpdated",B,Q,X)}catch(Q){console.warn(`刷新服务器 "${B}" 工具列表失败:`,Q)}}setupClientEventHandlers(B,G,Q){B.on("connected",(X)=>{G.status="connected",G.connectedAt=new Date,G.tools=B.availableTools,this.emit("serverConnected",Q,X)}),B.on("disconnected",()=>{G.status="disconnected",G.connectedAt=void 0,G.tools=[],this.emit("serverDisconnected",Q)}),B.on("error",(X)=>{G.status="error",G.lastError=X,this.emit("serverError",Q,X)}),B.on("toolsUpdated",(X)=>{let Y=G.tools.length;G.tools=X,this.emit("toolsUpdated",Q,X,Y)}),B.on("statusChanged",(X,Y)=>{G.status=X,this.emit("serverStatusChanged",Q,X,Y)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(B){let G=Object.entries(B).map(([Q,X])=>this.registerServer(Q,X).catch((Y)=>{return console.warn(`注册MCP服务器 "${Q}" 失败:`,Y),Y}));await Promise.allSettled(G)}getStatistics(){let B=0,G=0,Q=0;for(let X of this.servers.values())if(X.status==="connected")B++,G+=X.tools.length;else if(X.status==="error")Q++;return{totalServers:this.servers.size,connectedServers:B,errorServers:Q,totalTools:G,isDiscovering:this.isDiscovering}}async disconnectAll(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(Q.client.disconnect().catch((X)=>{console.warn(`断开 MCP 服务器 "${G}" 时出错:`,X)}));await Promise.allSettled(B),this.servers.clear()}}
34
- export{k as ba,b as ca};
@@ -1 +0,0 @@
1
- import{r as n,j as e}from"./vendor-react-BalntB5F.js";import{D as U,a as z,b as K,c as b,u as J,d as Q}from"./index-9kl44E8k.js";import{u as V}from"./SettingsStore-B87y64B4.js";import{X as P,k as M,E as G,w as _,d as W,e as X}from"./vendor-icons-BuFpOlRn.js";import"./vendor-markdown-Bo4W9Tae.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CESj0OOY.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 re(){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{re as SettingsModal};