blade-code 0.8.1 → 0.8.2

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 (75) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-hjx5n3dw.js → chunk-0g9cb41d.js} +2 -2
  3. package/dist/{chunk-ctqf59q1.js → chunk-0z5qe4m2.js} +1 -1
  4. package/dist/{chunk-d4ex0qvs.js → chunk-11s7t9dp.js} +2 -2
  5. package/dist/{chunk-6yqzfz8t.js → chunk-1evg2hdd.js} +2 -2
  6. package/dist/{chunk-xhnyy54e.js → chunk-1x3846v7.js} +1 -1
  7. package/dist/chunk-3wghk9bp.js +1 -0
  8. package/dist/{chunk-twem6p0g.js → chunk-4fye39a8.js} +2 -2
  9. package/dist/chunk-510rwhx6.js +1 -0
  10. package/dist/{chunk-kawv31m3.js → chunk-5ad4qmfj.js} +1 -1
  11. package/dist/{chunk-0dj326ms.js → chunk-5fw9k1ff.js} +2 -2
  12. package/dist/{chunk-1pt090dg.js → chunk-6avkjdjc.js} +3 -3
  13. package/dist/{chunk-k47ssv3b.js → chunk-6jq8h5s9.js} +2 -2
  14. package/dist/{chunk-1smf2dj3.js → chunk-6x6zqjcs.js} +1 -1
  15. package/dist/{chunk-jt62ctz7.js → chunk-81p4kz0b.js} +1 -1
  16. package/dist/chunk-83dkggbx.js +1 -0
  17. package/dist/{chunk-pdydx73a.js → chunk-887qxhn5.js} +2 -2
  18. package/dist/{chunk-syj3anec.js → chunk-8epvwyg8.js} +2 -2
  19. package/dist/{chunk-tv4r86ez.js → chunk-8fp3q919.js} +2 -2
  20. package/dist/{chunk-yhpm9azy.js → chunk-9b297mzh.js} +1 -1
  21. package/dist/chunk-9jkbykwq.js +1 -0
  22. package/dist/{chunk-34pdtz4q.js → chunk-9xvnrq7m.js} +2 -2
  23. package/dist/chunk-a83s9mww.js +1 -0
  24. package/dist/{chunk-06h100e2.js → chunk-a90mfxv9.js} +1 -1
  25. package/dist/chunk-btst30by.js +6 -0
  26. package/dist/chunk-e9t5ga1b.js +1 -0
  27. package/dist/chunk-eycs00af.js +1577 -0
  28. package/dist/{chunk-49g067ek.js → chunk-f3pvwxp8.js} +3 -3
  29. package/dist/{chunk-neenhtxw.js → chunk-fkaebj8c.js} +1 -1
  30. package/dist/{chunk-bm8vwfez.js → chunk-fpdqvnmq.js} +2 -2
  31. package/dist/chunk-gvf4gff0.js +9 -0
  32. package/dist/{chunk-qwdbqjh7.js → chunk-j14rn2dx.js} +2 -2
  33. package/dist/{chunk-61952mn3.js → chunk-j77gyhpf.js} +1 -1
  34. package/dist/chunk-kcjgbbec.js +1 -0
  35. package/dist/{chunk-9ad7tt9s.js → chunk-kne7h7p5.js} +1 -1
  36. package/dist/{chunk-9xkjb87h.js → chunk-p4yrmzyr.js} +1 -1
  37. package/dist/chunk-q223bq79.js +1 -0
  38. package/dist/chunk-qwfqp465.js +2 -0
  39. package/dist/{chunk-gsfkrr25.js → chunk-rxjt7ma7.js} +1 -1
  40. package/dist/{chunk-wmes2tt9.js → chunk-s1y8w68s.js} +1 -1
  41. package/dist/{chunk-sr3bzb95.js → chunk-w11ht6f9.js} +2 -2
  42. package/dist/{chunk-dr06x0cw.js → chunk-w4xcmzjm.js} +1 -1
  43. package/dist/chunk-x83a97eh.js +1 -0
  44. package/dist/{chunk-x6gt63vz.js → chunk-y08szyf9.js} +28 -28
  45. package/dist/chunk-yfcfx0zk.js +6 -0
  46. package/dist/chunk-zns65xsy.js +2 -0
  47. package/dist/web/assets/FilePreview-60E51igH.js +7 -0
  48. package/dist/web/assets/{MarkdownRenderer-JJScfgAO.js → MarkdownRenderer-DU7jPn9K.js} +1 -1
  49. package/dist/web/assets/{McpModal-CiCuIUxC.js → McpModal-CAMU6yrS.js} +2 -2
  50. package/dist/web/assets/{SettingsModal-Bew818xl.js → SettingsModal-Cjj8NUQy.js} +1 -1
  51. package/dist/web/assets/{SettingsStore-B_4zN-c-.js → SettingsStore-CjvkbtuZ.js} +1 -1
  52. package/dist/web/assets/{SkillsModal-Cot4Rb89.js → SkillsModal-Cyc2JAFj.js} +1 -1
  53. package/dist/web/assets/{TerminalPanel-DxB67ObY.js → TerminalPanel-DI-Ls-U8.js} +1 -1
  54. package/dist/web/assets/index-BC0ssrep.js +16 -0
  55. package/dist/web/assets/index-Ci6gCUjf.css +1 -0
  56. package/dist/web/assets/{vendor-icons-DqO8ishN.js → vendor-icons-DBM55KTG.js} +70 -40
  57. package/dist/web/index.html +2 -2
  58. package/package.json +1 -1
  59. package/dist/chunk-04920kz2.js +0 -1570
  60. package/dist/chunk-07jvw0kn.js +0 -1
  61. package/dist/chunk-14erxdhd.js +0 -1
  62. package/dist/chunk-42ch5zg4.js +0 -1
  63. package/dist/chunk-7j6rxyt8.js +0 -9
  64. package/dist/chunk-a12tmmfr.js +0 -1
  65. package/dist/chunk-cnftrx3g.js +0 -1
  66. package/dist/chunk-epp5jx5f.js +0 -6
  67. package/dist/chunk-j39q2kx7.js +0 -1
  68. package/dist/chunk-j6hpzkpq.js +0 -6
  69. package/dist/chunk-n4f8tseg.js +0 -2
  70. package/dist/chunk-nc4kfwef.js +0 -1
  71. package/dist/chunk-v3ctg84r.js +0 -1
  72. package/dist/chunk-v5rn5r1h.js +0 -1
  73. package/dist/web/assets/FilePreview-Chqi7chf.js +0 -7
  74. package/dist/web/assets/index-B-b3Yc5H.css +0 -1
  75. package/dist/web/assets/index-B3dW1Scg.js +0 -16
@@ -0,0 +1,6 @@
1
+ import{q as A,r as E,s as N,t as f}from"./chunk-w11ht6f9.js";import{u as D}from"./chunk-1evg2hdd.js";import{w as L,x as _,y as x}from"./chunk-8epvwyg8.js";import{z as B}from"./chunk-4fye39a8.js";import{P as $,U as b}from"./chunk-eycs00af.js";import"./chunk-kne7h7p5.js";import"./chunk-6jq8h5s9.js";import"./chunk-fpdqvnmq.js";import"./chunk-8fp3q919.js";import"./chunk-j14rn2dx.js";import"./chunk-11s7t9dp.js";import"./chunk-887qxhn5.js";import{cb as Z}from"./chunk-6avkjdjc.js";import"./chunk-p4yrmzyr.js";import"./chunk-f3pvwxp8.js";import"./chunk-0z5qe4m2.js";import"./chunk-81p4kz0b.js";import{Jb as Y,Kb as T}from"./chunk-rxjt7ma7.js";import"./chunk-5fw9k1ff.js";import"./chunk-9xvnrq7m.js";import"./chunk-0g9cb41d.js";import"./chunk-w4xcmzjm.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};
@@ -0,0 +1,2 @@
1
+ import{e as kO,f as EO}from"./chunk-1x3846v7.js";import{p as bO}from"./chunk-qwfqp465.js";import{B as CO,D as XO,E as hS,F as IS,H as yS,I as GS,J as q,K as M,L as _O,M as F,N as qS,P as DO,R as FS,S as CS,U as mO,ba as PO}from"./chunk-eycs00af.js";import{ea as e}from"./chunk-6jq8h5s9.js";import{Aa as eS,Ba as sS,Ea as r,xa as $S,za as rS}from"./chunk-8fp3q919.js";import{Ma as NS}from"./chunk-887qxhn5.js";import{Sa as zO,Ua as DS,cb as ES}from"./chunk-6avkjdjc.js";import{ub as yO}from"./chunk-p4yrmzyr.js";import{Ab as O,Bb as h,Cb as pS,Db as E,yb as t}from"./chunk-0z5qe4m2.js";import{Eb as kS}from"./chunk-81p4kz0b.js";import{Kb as L}from"./chunk-rxjt7ma7.js";import{Vb as W}from"./chunk-9xvnrq7m.js";import{_b as wO,cc as oS,fc as s}from"./chunk-0g9cb41d.js";import{gc as tS}from"./chunk-w4xcmzjm.js";var G0={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 Q0(S){return{port:S.port??0,hostname:S.hostname??"127.0.0.1",cors:S.cors??[]}}import{existsSync as oO,readFileSync as BS}from"node:fs";import{createServer as S0}from"node:http";import{networkInterfaces as O0}from"node:os";import{dirname as x0,extname as j0,join as jS}from"node:path";import{fileURLToPath as $0}from"node:url";import{Hono as N0}from"hono";import{cors as V0}from"hono/cors";import{WebSocketServer as J0}from"ws";class g extends Error{code;statusCode;constructor(S,x,j=500){super(x);this.code=S;this.statusCode=j;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class z extends g{constructor(S,x){super("NOT_FOUND",x?`${S} not found: ${x}`:`${S} not found`,404)}}class m extends g{constructor(S){super("BAD_REQUEST",S,400)}}class I extends g{constructor(S){super("CONFLICT",S,409)}}class o extends g{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class u extends g{constructor(S="Internal server error"){super("INTERNAL_ERROR",S,500)}}var f0=O.Object({error:O.Object({code:O.String(),message:O.String()})});import{Hono as eO}from"hono";var HS=W("Service"),sO=O.Object({updates:O.Record(O.String(),O.Any()),options:O.Optional(O.Object({scope:O.Optional(E(["local","project","global"])),immediate:O.Optional(O.Boolean())}))});function Sx(S){return{currentModelId:S.currentModelId,permissionMode:S.permissionMode,language:S.language,theme:S.theme,uiTheme:S.uiTheme,autoSaveSessions:S.autoSaveSessions,notifyBuild:S.notifyBuild,notifyErrors:S.notifyErrors,notifySounds:S.notifySounds,privacyTelemetry:S.privacyTelemetry,privacyCrash:S.privacyCrash}}var dS=()=>{let S=new eO;return S.get("/",async(x)=>{try{let j=$S();return x.json(j?Sx(j):{})}catch(j){return HS.error("[ConfigRoutes] Failed to get config:",j),x.json({})}}),S.put("/",async(x)=>{try{let j=await x.req.json(),$=t(sO,j);if(!$.success)throw new m("Invalid config update format");let{updates:V,options:A}=$.data;return await r().updateConfig(V,A),x.json({success:!0,updates:V})}catch(j){throw HS.error("[ConfigRoutes] Failed to update config:",j),j}}),S.get("/permissions",async(x)=>{try{let j=$S();return x.json(j?.permissions||{})}catch(j){return HS.error("[ConfigRoutes] Failed to get permissions:",j),x.json({})}}),S};import{Hono as Ox}from"hono";import{streamSSE as xx}from"hono/streaming";var jx=15000,$x=new Set(["task.status"]),Nx=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function Vx(S){if(!S||typeof S!=="object"||Array.isArray(S))return;let x=S,j=["changedFiles","additions","deletions","commits"];if(j.some(($)=>typeof x[$]!=="number"||!Number.isInteger(x[$])||x[$]<0))return;return Object.fromEntries(j.map(($)=>[$,x[$]]))}var aS=()=>{let S=new Ox;return S.get("/",(x)=>xx(x,async(j)=>{let $,V,A=!1,Y=()=>{if(V!==void 0)clearInterval(V),V=void 0;$?.(),$=void 0},f=()=>{if(A)return;A=!0,Y()};j.onAbort(f),$=M.subscribe((Z)=>{if(!$x.has(Z.type))return;let w=Z.properties.taskStatus;if(typeof w!=="string"||!Nx.has(w))return;let b=Vx(Z.properties.taskDiffStat);j.writeSSE({data:JSON.stringify({type:Z.type,properties:{sessionId:Z.sessionId,projectPath:Z.projectPath,taskStatus:w,...typeof Z.properties.taskStatusReason==="string"?{taskStatusReason:Z.properties.taskStatusReason}:{},...typeof Z.properties.taskStartedAt==="string"?{taskStartedAt:Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{taskCompletedAt:Z.properties.taskCompletedAt}:{},...typeof Z.properties.updatedAt==="string"?{updatedAt:Z.properties.updatedAt}:{},...b?{taskDiffStat:b}:{}}})}).catch(f)});try{if(j.aborted||A)return;if(await j.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),j.aborted||A)return;V=setInterval(()=>{if(j.aborted||A)return;j.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(f)},jx);while(!j.aborted&&!A)await new Promise((Z)=>setTimeout(Z,1000))}finally{f()}})),S};import{Hono as Jx}from"hono";var iS=()=>{let S=new Jx;return S.get("/health",(x)=>{return x.json({healthy:!0,version:NS()})}),S.get("/info",(x)=>{let j=L();return x.json({version:NS(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:j,gitBranch:oS(j)})}),S};import{Hono as Tx}from"hono";var YS=W("Service"),nS=()=>{let S=new Tx;return S.get("/",async(x)=>{try{let $=e.getInstance().getAllServers(),V=Array.from($.entries()).map(([A,Y])=>({id:A,name:A,status:Y.status==="connected"?"connected":Y.status==="connecting"?"connecting":Y.lastError?"error":"offline",endpoint:Y.config.command?`${Y.config.command} ${(Y.config.args||[]).join(" ")}`.trim():Y.config.url||"Unknown",description:`MCP server: ${A}`,tools:Y.tools.map((f)=>f.name),connectedAt:Y.connectedAt?.toISOString(),error:Y.lastError?.message}));return x.json(V)}catch(j){return YS.error("[McpRoutes] Failed to get MCP servers:",j),x.json([])}}),S.post("/:name/connect",async(x)=>{try{let j=x.req.param("name");return await e.getInstance().connectServer(j),x.json({success:!0})}catch(j){return YS.error("[McpRoutes] Failed to connect MCP server:",j),x.json({success:!1,error:j.message},500)}}),S.post("/:name/disconnect",async(x)=>{try{let j=x.req.param("name");return await e.getInstance().disconnectServer(j),x.json({success:!0})}catch(j){return YS.error("[McpRoutes] Failed to disconnect MCP server:",j),x.json({success:!1,error:j.message},500)}}),S.delete("/:name",async(x)=>{try{let j=x.req.param("name");await e.getInstance().unregisterServer(j);let V=$S();if(V?.mcpServers){let{[j]:A,...Y}=V.mcpServers;await r().updateConfig({mcpServers:Y})}return x.json({success:!0})}catch(j){return YS.error("[McpRoutes] Failed to delete MCP server:",j),x.json({success:!1,error:j.message},500)}}),S.post("/",async(x)=>{try{let j=await x.req.json(),{name:$,config:V}=j;if(!$||!V)return x.json({success:!1,error:"Missing name or config"},400);await e.getInstance().registerServer($,V);let Y=$S();return await r().updateConfig({mcpServers:{...Y?.mcpServers,[$]:V}}),x.json({success:!0})}catch(j){return YS.error("[McpRoutes] Failed to add MCP server:",j),x.json({success:!1,error:j.message},500)}}),S};import{Hono as Ax}from"hono";var US=W("Service");function Yx(S,x){return{id:S.id,displayName:S.displayName,provider:S.provider,model:S.model,overrides:S.overrides,fallbackModels:S.fallbackModels,contextWindow:x.contextWindow,maxTokens:x.maxTokens,reasoning:x.reasoning,input:x.input}}function px(S){let x={displayName:S.displayName||void 0,overrides:S.overrides||void 0};if(S.model)x.model=S.model;return x}var SO=()=>{let S=new Ax;return S.get("/",async(x)=>{try{let j=rS(),$=eS(),V=s(),A=(Y)=>Yx(Y,V.resolveConfig(Y));return x.json({configured:j.map(A),current:$?A($):null})}catch(j){return US.error("[ModelsRoutes] Failed to get models:",j),x.json({configured:[],current:null})}}),S.post("/",async(x)=>{try{let j=await x.req.json(),{provider:$,displayName:V,model:A,overrides:Y,apiKey:f}=j;if(!$||!A)throw new m("provider and model are required");if(s().getModel($,A),f?.trim())await s().setApiKey($,f.trim());let Z=await r().addModel({provider:$,displayName:V||void 0,model:A,overrides:Y||void 0});return x.json({success:!0,model:Z})}catch(j){throw US.error("[ModelsRoutes] Failed to add model:",j),j}}),S.put("/:modelId",async(x)=>{try{let j=x.req.param("modelId"),$=await x.req.json(),{displayName:V,overrides:A,model:Y}=$,f=sS(j);if(!f)throw new m("model config not found");if(Y)s().getModel(f.provider,Y);return await r().updateModel(j,px({displayName:V,overrides:A,model:Y})),x.json({success:!0})}catch(j){throw US.error("[ModelsRoutes] Failed to update model:",j),j}}),S.delete("/:modelId",async(x)=>{try{let j=x.req.param("modelId");return await r().removeModel(j),x.json({success:!0})}catch(j){throw US.error("[ModelsRoutes] Failed to delete model:",j),j}}),S};import{Hono as Fx}from"hono";import ZO from"node:path";import{Mutex as _x}from"async-mutex";import{Hono as Dx}from"hono";import{streamSSE as mx}from"hono/streaming";import{LRUCache as bx}from"lru-cache";import{nanoid as VS}from"nanoid";var KS=h(E(["default","autoEdit","yolo","plan"]));var WS=h(E(["user","assistant","system","tool"])),Gx=h(O.Union([O.Object({type:O.Literal("text"),text:O.String()}),O.Object({type:O.Literal("image_url"),image_url:O.Object({url:O.String()})})])),xO=O.Union([O.String(),O.Array(Gx)]),o0=h(O.Object({id:O.String(),role:WS,content:xO,timestamp:O.Number(),metadata:O.Optional(O.Record(O.String(),O.Unknown())),thinkingContent:O.Optional(O.String()),tool_call_id:O.Optional(O.String()),name:O.Optional(O.String()),tool_calls:O.Optional(O.Unknown())})),Qx=h(E(["queued","running","completed","failed","cancelled","interrupted"])),jO=h(E(["local","worktree"])),Zx=h(O.Object({changedFiles:O.Integer({minimum:0}),additions:O.Integer({minimum:0}),deletions:O.Integer({minimum:0}),commits:O.Integer({minimum:0})})),Ux=h(O.Object({path:O.String({minLength:1}),patch:O.String({maxLength:2097152}),additions:O.Integer({minimum:0}),deletions:O.Integer({minimum:0}),binary:O.Boolean(),truncated:O.Boolean()})),$O=h(O.Object({sessionId:O.String(),projectPath:O.String(),baseCommit:O.String(),files:O.Array(Ux,{maxItems:100}),truncated:O.Boolean()})),NO=h(O.Object({sessionId:O.String(),projectPath:O.String(),title:O.Optional(O.String()),gitBranch:O.Optional(O.String()),rootId:O.String(),parentId:O.Optional(O.String()),relationType:O.Optional(E(["subagent","fork"])),resumedFrom:O.Optional(O.String()),rootAgentId:O.Optional(O.String()),resumeDepth:O.Optional(O.Integer({minimum:0})),taskStatus:pS(Qx,"completed"),taskStatusReason:O.Optional(O.String()),taskStartedAt:O.Optional(O.String()),taskCompletedAt:O.Optional(O.String()),taskPromptSummary:O.Optional(O.String()),taskIsolation:O.Optional(jO),taskSourceProjectPath:O.Optional(O.String()),taskWorktreePath:O.Optional(O.String()),taskWorktreeBranch:O.Optional(O.String()),taskBaseCommit:O.Optional(O.String()),taskDiffStat:O.Optional(Zx),messageCount:O.Number(),firstMessageTime:O.String(),lastMessageTime:O.String(),hasErrors:O.Boolean()})),i0=h(O.Object({version:O.Literal(1),sessionId:O.String(),goalId:O.String(),objective:O.String(),status:E(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:O.Optional(O.Number()),tokensUsed:O.Number(),timeUsedSeconds:O.Number(),continuationCount:O.Number(),statusReason:O.Optional(O.String()),createdAt:O.String(),updatedAt:O.String()})),VO=h(O.Object({role:WS,content:xO,metadata:O.Optional(O.Unknown()),reasoningContent:O.Optional(O.String()),thinkingContent:O.Optional(O.String()),tool_call_id:O.Optional(O.String()),name:O.Optional(O.String()),tool_calls:O.Optional(O.Unknown())})),n0=h(O.Object({session:NO,messages:O.Array(VO)})),JO=h(E(["conversation","code","both"])),fx=h(O.Object({messageId:O.String(),preview:O.String(),createdAt:O.String(),fileCount:O.Integer({minimum:0})})),TO=h(O.Object({targetMessageId:O.String({minLength:1}),mode:pS(JO,"conversation")})),r0=h(O.Object({checkpoint:fx,mode:JO,removedTurns:O.Integer({minimum:1}),restoredFiles:O.Array(O.String()),messages:O.Array(VO)})),wx=E(["running","completed","failed","cancelled"]),OO=h(O.Object({id:O.String(),subagentType:O.String(),description:O.String(),status:wx,rootAgentId:O.String(),resumedFrom:O.Optional(O.String()),resumeDepth:O.Integer({minimum:0}),createdAt:O.Number(),lastActiveAt:O.Number(),completedAt:O.Optional(O.Number()),result:O.Optional(O.Object({success:O.Boolean(),message:O.String(),error:O.Optional(O.String()),verificationCommands:O.Optional(O.Array(O.String()))})),stats:O.Optional(O.Object({tokens:O.Optional(O.Number()),toolCalls:O.Optional(O.Number()),duration:O.Optional(O.Number())}))})),AO=h(O.Object({prompt:O.String({minLength:1,maxLength:32000,pattern:"\\S"})})),e0=h(O.Object({source:OO,session:OO})),s0=h(O.Object({sessionId:O.String(),projectPath:O.String()})),S1=h(O.Object({type:O.String(),properties:O.Record(O.String(),O.Unknown())})),YO=O.Object({type:E(["file","image","url"]),path:O.Optional(O.String()),url:O.Optional(O.String()),content:O.Optional(O.String()),mimeType:O.Optional(O.String()),name:O.Optional(O.String())}),pO=h(O.Object({prompt:O.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:O.Optional(O.String({minLength:1,maxLength:200})),projectPath:O.Optional(O.String()),isolation:pS(jO,"worktree"),permissionMode:pS(KS,"default"),attachments:O.Optional(O.Array(YO))})),GO=h(O.Object({session:NO,runId:O.String(),messageId:O.String(),status:O.Literal("running")})),QO=h(O.Object({content:O.String(),projectPath:O.Optional(O.String()),permissionMode:O.Optional(KS),attachments:O.Optional(O.Array(YO))})),O1=h(O.Object({messageId:O.String(),role:WS,content:O.String(),timestamp:O.String()})),x1=h(O.Object({approved:O.Boolean(),remember:O.Optional(O.Boolean()),scope:O.Optional(E(["once","session","project"])),targetMode:O.Optional(KS),feedback:O.Optional(O.String()),answers:O.Optional(O.Record(O.String(),O.Union([O.String(),O.Array(O.String())])))})),j1=h(O.Object({id:O.String(),displayName:O.Optional(O.String()),provider:O.String(),model:O.String(),contextWindow:O.Optional(O.Number()),maxTokens:O.Optional(O.Number()),reasoning:O.Optional(O.Boolean()),input:O.Optional(O.Array(E(["text","image"]))),overrides:O.Optional(O.Object({baseUrl:O.Optional(O.String()),temperature:O.Optional(O.Number()),maxOutputTokens:O.Optional(O.Number()),timeout:O.Optional(O.Number())}))})),$1=h(E(["vs-dark","vs-light","hc-black"])),yx=h(E(["light","dark","system"])),Xx=h(O.Object({language:O.String(),theme:O.String(),uiTheme:yx,autoSaveSessions:O.Boolean(),notifyBuild:O.Boolean(),notifyErrors:O.Boolean(),notifySounds:O.Boolean(),privacyTelemetry:O.Boolean(),privacyCrash:O.Boolean()})),N1=h(O.Partial(Xx));var H=W("Service"),hx=O.Object({title:O.Optional(O.String()),projectPath:O.Optional(O.String())}),Bx=QO,Mx=O.Object({title:O.Optional(O.String()),projectPath:O.Optional(O.String())}),Hx=O.Object({projectPath:O.String()}),Kx=O.Object({objective:O.String({minLength:1}),tokenBudget:O.Optional(O.Integer({minimum:1})),permissionMode:O.Optional(E(["default","autoEdit","plan","yolo"]))}),Wx=O.Union([O.Object({action:O.Literal("pause")}),O.Object({action:O.Literal("resume")}),O.Object({action:O.Literal("edit"),objective:O.String({minLength:1})})]),R=new Map,C=new bx({max:100,ttl:1800000,dispose:(S,x)=>{if(S.status==="running"||S.status==="waiting_permission")S.abortController.abort(),H.debug(`[SessionRoutes] Run ${x} disposed due to cache eviction`)}});function kx(S){return{sessionId:S.sessionId,projectPath:S.projectPath}}function _S(S,x="user-cancel"){if(S.status==="cancelled"||S.status==="completed"||S.status==="failed")return!1;let j=S.pendingPermission;return S.pendingPermission=void 0,j?.resolve({approved:!1,reason:yO}),S.abortController.abort(x),S.status="cancelled",M.publish(kx(S),"run.cancelled",{runId:S.id}),!0}function hO(S,x=!1){let{permissionId:j,details:$}=S;if($.type==="askUserQuestion"&&$.questions)return{type:"question.required",properties:{requestId:j,toolCallId:j,questions:$.questions,details:$,...x?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:j,toolName:$.toolName,description:$.message,args:$.args,details:$,...x?{replayed:!0}:{}}}}function Ex(){for(let S of C.values())_S(S,"route-reset");C.clear(),R.clear()}var BO=(S)=>{if(!S||typeof S!=="object")return S;let x={...S},j=200000;if(typeof x.oldContent==="string"&&x.oldContent.length>j)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>j)delete x.newContent;return x};function qx(S,x,j){switch(j.kind){case"tool_start":if("function"in j.toolCall)M.publish(S,"subagent.update",{subagentSessionId:x,toolName:j.toolCall.function.name}),M.publish(S,"subagent.tool.start",{subagentSessionId:x,toolCallId:j.toolCall.id,toolName:j.toolCall.function.name,arguments:j.toolCall.function.arguments,toolKind:j.toolKind});break;case"tool_result":if("function"in j.toolCall)M.publish(S,"subagent.tool.result",{subagentSessionId:x,toolCallId:j.toolCall.id,toolName:j.toolCall.function.name,success:!j.result.error,summary:j.result.metadata?.summary,output:CS(FS(j.toolCall.function.name,j.result)),metadata:BO(j.result.metadata)});break;case"content_delta":M.publish(S,"subagent.delta",{subagentSessionId:x,delta:j.delta});break;case"thinking_delta":M.publish(S,"subagent.thinking.delta",{subagentSessionId:x,delta:j.delta});break;case"stream_end":M.publish(S,"subagent.stream.end",{subagentSessionId:x});break;default:break}}function XS(S,x="projectPath"){if(!ZO.isAbsolute(S))throw new m(`${x} must be absolute`);return ZO.resolve(S)}function zS(S){try{wO(S)}catch(x){throw new m(x instanceof Error?x.message:`Invalid session ID: ${S}`)}}function v(S){return{sessionId:S.id,projectPath:S.projectPath}}function fS(S,x,j){return{id:S.sessionId,projectPath:S.projectPath,title:S.title??`Session ${S.sessionId.slice(0,6)}`,createdAt:new Date(S.firstMessageTime),updatedAt:new Date(S.lastMessageTime),rootId:S.rootId,parentId:S.parentId,relationType:S.relationType,taskStatus:S.taskStatus,taskStatusReason:S.taskStatusReason,taskStartedAt:S.taskStartedAt,taskCompletedAt:S.taskCompletedAt,taskPromptSummary:S.taskPromptSummary,taskIsolation:S.taskIsolation,taskSourceProjectPath:S.taskSourceProjectPath,taskWorktreePath:S.taskWorktreePath,taskWorktreeBranch:S.taskWorktreeBranch,taskBaseCommit:S.taskBaseCommit,taskDiffStat:S.taskDiffStat,taskWorktree:j,messages:x}}function zx(S,x){S.taskStatus=x.taskStatus,S.taskStatusReason=x.taskStatusReason,S.taskStartedAt=x.taskStartedAt,S.taskCompletedAt=x.taskCompletedAt,S.taskPromptSummary=x.taskPromptSummary,S.taskIsolation=x.taskIsolation,S.taskSourceProjectPath=x.taskSourceProjectPath,S.taskWorktreePath=x.taskWorktreePath,S.taskWorktreeBranch=x.taskWorktreeBranch,S.taskBaseCommit=x.taskBaseCommit,S.taskDiffStat=x.taskDiffStat,S.updatedAt=new Date(x.lastMessageTime)}async function UO(S){let x=await F.findSessionMetadata(S.id,S.projectPath);if(x)zx(S,x)}function wS(S){let x=S.currentRunId?C.get(S.currentRunId):void 0,j=x?.status==="waiting_permission"?"running":x?.status??S.taskStatus;return{sessionId:S.id,projectPath:S.projectPath,title:S.title,rootId:S.rootId,parentId:S.parentId,relationType:S.relationType,status:void 0,taskStatus:j,taskStatusReason:S.taskStatusReason,taskStartedAt:S.taskStartedAt,taskCompletedAt:S.taskCompletedAt,taskPromptSummary:S.taskPromptSummary,taskIsolation:S.taskIsolation,taskSourceProjectPath:S.taskSourceProjectPath,taskWorktreePath:S.taskWorktreePath,taskWorktreeBranch:S.taskWorktreeBranch,taskBaseCommit:S.taskBaseCommit,taskDiffStat:S.taskDiffStat,agentType:void 0,model:void 0,messageCount:S.messages.length,firstMessageTime:S.createdAt.toISOString(),lastMessageTime:S.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function n(S,x){if(zS(S),x!==void 0){let $=GS({sessionId:S,projectPath:XS(x)});if(R.has(q($)))return $;let V=await F.findSessionMetadata($.sessionId,$.projectPath);if(!V)throw new z("Session",S);return GS({sessionId:V.sessionId,projectPath:V.projectPath})}let j=new Map;for(let $ of R.values()){if($.id!==S)continue;let V=v($);j.set(q(V),V)}for(let $ of await F.listSessions()){if($.sessionId!==S)continue;let V=GS({sessionId:$.sessionId,projectPath:$.projectPath});j.set(q(V),V)}if(j.size===0)try{let $=await F.findSessionMetadata(S);if(!$)throw new z("Session",S);return GS({sessionId:$.sessionId,projectPath:$.projectPath})}catch($){if($ instanceof z)throw $;if($ instanceof Error&&$.message.startsWith("Ambiguous session ID:"))throw new o;throw $}if(j.size>1)throw new o;return j.values().next().value}function LS(S){if(typeof S==="string")return S;return S.filter((x)=>x.type==="text").map((x)=>x.text).join(`
2
+ `)}function fO(S,x){let j=(x??[]).filter((V)=>V.type==="image"&&typeof V.content==="string").map((V)=>({type:"image_url",image_url:{url:V.content}}));if(j.length===0)return S;let $=[];if(S.trim())$.push({type:"text",text:S});return $.push(...j),$}var MO=()=>{Ex();let S=new Dx;S.onError((N,T)=>{if(N instanceof g)return T.json(N.toObject(),N.statusCode);return H.error("[SessionRoutes] Unhandled route error:",N),T.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let x=new Map,j=new Map,$=new Map,V=new Map,A=(N)=>{let T=q(N),J=V.get(T);if(!J)J=new _x,V.set(T,J);return J},Y=async(N)=>{let T=q(v(N)),J=x.get(T);if(J)return J;let G=j.get(T);if(!G)G=DO.create({sessionId:N.id,workspaceRoot:N.projectPath,...N.taskWorktree?{taskWorktree:N.taskWorktree}:{}}),j.set(T,G);try{let p=await G;return x.set(T,p),p}finally{if(j.get(T)===G)j.delete(T)}},f=async(N)=>{let T=q(N),J=R.get(T);if(J)return J;let G=$.get(T);if(!G)G=(async()=>{let p=await F.findSessionMetadata(N.sessionId,N.projectPath);if(!p)throw new z("Session",N.sessionId);let[X,U]=await Promise.all([F.loadSession(N.sessionId,N.projectPath),F.findSessionTaskWorktree(N.sessionId,N.projectPath)]),_=fS(p,X,U);return R.set(T,_),_})(),$.set(T,G);try{return await G}finally{if($.get(T)===G)$.delete(T)}},Z=async(N,T)=>{return f(await n(N,T))},w=(N,T,J,G={})=>{let p=VS(12),X={id:p,sessionId:N.id,projectPath:N.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return C.set(p,X),N.currentRunId=p,X.completion=Lx(X,N,T,J,Y,{pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly}).catch((U)=>{H.error(`[SessionRoutes] Run ${p} failed:`,U)}),X},b=async(N)=>{let T=kS("task",12),J=XS(N.sourceProjectPath),G,p;try{let X=await bO.createSessionTask({sessionId:T,prompt:N.prompt,title:N.title,sourceProjectPath:J,isolation:N.isolation}),{metadata:U}=X;G=X.taskWorktree,p=fS(U,[],G);let _=v(p);R.set(q(_),p),M.publish(_,"task.status",{taskStatus:U.taskStatus,updatedAt:U.lastMessageTime});let D=fO(N.prompt,N.attachments),y=await(await Y(p)).prepareInputTurn(D);if(!y.accepted)throw new I(`Task prompt was not accepted: ${y.reason}`);let l=w(p,D,N.permissionMode,{preparedInputTurn:y});return{session:wS(p),runId:l.id,messageId:y.messageId,status:"running"}}catch(X){if(p){let U=await F.findSessionMetadata(p.id,p.projectPath).catch(()=>{return});if(!U||U.taskStatus==="queued"){let _=await F.updateSessionMetadata(p.id,p.projectPath,{taskStatus:"failed",taskStatusReason:"Task dispatch failed",taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});p.taskStatus=_?.taskStatus??"failed",p.taskStatusReason=_?.taskStatusReason??"Task dispatch failed",p.taskCompletedAt=_?.taskCompletedAt}else p.taskStatus=U.taskStatus,p.taskStatusReason=U.taskStatusReason,p.taskCompletedAt=U.taskCompletedAt}throw X}},B=async(N,T)=>{let J=await Z(N,T);if(!J.taskWorktree)throw new m("Session does not have a task worktree");try{await qS.restoreSession(J.taskWorktree);let G=await qS.getDiffArtifact(J.id);if(!G)throw new I("Task diff artifact is unavailable");return{sessionId:J.id,projectPath:J.projectPath,...G}}catch(G){if(G instanceof I)throw G;throw H.error("[SessionRoutes] Failed to load task diff artifact:",G),new I("Task diff artifact is unavailable")}},K=async(N)=>{let T=N.currentRunId?C.get(N.currentRunId):void 0;if(T&&(T.status==="running"||T.status==="waiting_permission"))return;let J=await Y(N),G=N.currentRunId?C.get(N.currentRunId):void 0;if(G&&(G.status==="running"||G.status==="waiting_permission"))return;let p=J.getPendingSteeringCount()>0,U=(p?null:await J.getGoal())?.status==="active";if(!p&&!U||J.hasTurnOwner())return;w(N,"","default",{pendingInputOnly:p,goalContinuationOnly:U})};return S.get("/",async(N)=>{try{let T=await F.listSessions(),J=new Set(T.filter((Q)=>Q.relationType==="subagent").map((Q)=>q({sessionId:Q.sessionId,projectPath:Q.projectPath}))),G=Array.from(R.values()).filter((Q)=>!J.has(q(v(Q)))&&Q.relationType!=="subagent").map((Q)=>wS(Q)),p=new Set(G.map((Q)=>q({sessionId:Q.sessionId,projectPath:Q.projectPath}))),X=T.filter((Q)=>{if(Q.relationType==="subagent")return!1;return!p.has(q({sessionId:Q.sessionId,projectPath:Q.projectPath}))}),U=new Set(p),_=X.filter((Q)=>{let y=q({sessionId:Q.sessionId,projectPath:Q.projectPath});if(U.has(y))return!1;return U.add(y),!0}),D=[...G,..._];return N.json(D)}catch(T){throw H.error("[SessionRoutes] Failed to list sessions:",T),new u("Failed to list sessions")}}),S.post("/",async(N)=>{try{let T=await N.req.json(),J=t(hx,T);if(!J.success)throw new m("Invalid request body");let{title:G,projectPath:p}=J.data,X=kS("web",12),U=XS(p||N.get("directory")||L(),p?"projectPath":"directory"),_=await F.createSessionMetadata(X,U,{title:G}),D=fS(_,[]),Q=v(D);return R.set(q(Q),D),M.publish(Q,"task.status",{taskStatus:_.taskStatus,updatedAt:_.lastMessageTime}),N.json({...wS(D),status:void 0,agentType:void 0,model:void 0})}catch(T){if(H.error("[SessionRoutes] Failed to create session:",T),T instanceof m)throw T;throw new u("Failed to create session")}}),S.post("/:sessionId/fork",async(N)=>{let T=N.req.param("sessionId");try{zS(T);let J=await N.req.json(),G=t(Hx,J);if(!G.success)throw new m("Invalid request body");let p=XS(G.data.projectPath),X=await F.findSessionMetadata(T,p);if(!X)throw new z("Session",T);let U=await F.forkSession(T,{sourceProjectPath:X.projectPath,targetProjectPath:X.projectPath}),_=fS(U.metadata,U.messages),D=v(_);return R.set(q(D),_),M.publish(D,"task.status",{taskStatus:U.metadata.taskStatus,...U.metadata.taskCompletedAt?{taskCompletedAt:U.metadata.taskCompletedAt}:{},updatedAt:U.metadata.lastMessageTime}),N.json({session:U.metadata,messages:U.messages},201)}catch(J){if(J instanceof m||J instanceof z||J instanceof I)throw J;if(J instanceof _O)throw new I("Session has no durable creation record");throw H.error("[SessionRoutes] Failed to fork session:",J),new u("Failed to fork session")}}),S.get("/:sessionId",async(N)=>{let T=N.req.param("sessionId");try{let J=await n(T,N.req.query("projectPath")),G=R.get(q(J));if(G)return N.json(wS(G));let p=await F.findSessionMetadata(J.sessionId,J.projectPath);if(!p)throw new z("Session",T);return N.json(p)}catch(J){if(J instanceof m||J instanceof z||J instanceof o)throw J;throw H.error("[SessionRoutes] Failed to get session:",J),new u("Failed to get session")}}),S.patch("/:sessionId",async(N)=>{let T=N.req.param("sessionId");try{let J=await N.req.json(),G=t(Mx,J);if(!G.success)throw new m("Invalid request body");if(G.data.title===void 0)throw new m("title is required");let p=await n(T,G.data.projectPath),X=await F.updateSessionMetadata(p.sessionId,p.projectPath,{title:G.data.title}),U=R.get(q(p));if(U)U.title=X.title??U.title,U.updatedAt=new Date(X.lastMessageTime);return N.json({success:!0,title:X.title})}catch(J){if(H.error("[SessionRoutes] Failed to update session:",J),J instanceof m||J instanceof z||J instanceof o)throw J;throw new u("Failed to update session")}}),S.get("/:sessionId/rewind",async(N)=>{let T=await Z(N.req.param("sessionId"),N.req.query("projectPath")),J=await Y(T);return N.json({checkpoints:await J.listRewindCheckpoints()})}),S.post("/:sessionId/rewind",async(N)=>{let T=t(TO,await N.req.json());if(!T.success)throw new m("Invalid rewind request");let J=await Z(N.req.param("sessionId"),N.req.query("projectPath")),G=v(J);return A(G).runExclusive(async()=>{let p=J.currentRunId?C.get(J.currentRunId):void 0;if(p&&(p.status==="running"||p.status==="waiting_permission"))throw new I("Cannot rewind while a run is active");let X=await Y(J),U;try{U=await X.rewindSession(T.data)}catch(_){if(_ instanceof Error&&_.message.startsWith("Cannot rewind while"))throw new I(_.message);throw _}return J.messages=[...U.messages],J.updatedAt=new Date,M.publish(G,"session.rewound",{targetMessageId:U.checkpoint.messageId,mode:U.mode,removedTurns:U.removedTurns,restoredFiles:U.restoredFiles,messages:U.messages}),N.json(U)})}),S.get("/:sessionId/subagents",async(N)=>{let T=await Z(N.req.param("sessionId"),N.req.query("projectPath")),J=await Y(T);return N.json({subagents:J.listSubagents().map(yS)})}),S.post("/:sessionId/subagents/:agentId/resume",async(N)=>{zS(N.req.param("agentId"));let T=AO.safeParse(await N.req.json());if(!T.success)throw new m("Invalid subagent resume request");let J=await Z(N.req.param("sessionId"),N.req.query("projectPath")),G=v(J);return A(G).runExclusive(async()=>{let p=J.currentRunId?C.get(J.currentRunId):void 0;if(p&&(p.status==="running"||p.status==="waiting_permission"))throw new I("Cannot resume a subagent while a parent run is active");let X=await Y(J),U=!1,_,D=(y)=>{M.publish(G,"subagent.complete",{subagentSessionId:y.id,success:y.status==="completed",status:y.status,summary:y.result?.message?.slice(0,500),resumedFrom:y.resumedFrom,rootAgentId:y.rootAgentId,resumeDepth:y.resumeDepth})},Q;try{Q=X.resumeSubagent({agentId:N.req.param("agentId"),prompt:T.data.prompt,onEvent:(y,l)=>{qx(G,l,y)},onCompleted:(y)=>{if(U)D(y);else _=y}})}catch(y){if(y instanceof Error&&(y.message.startsWith("Cannot resume")||y.message.startsWith("Subagent cannot")))throw new I(y.message);if(y instanceof Error&&y.message.startsWith("Subagent not found"))throw new z(y.message);throw y}if(M.publish(G,"subagent.start",{subagentSessionId:Q.session.id,type:Q.session.subagentType,description:Q.session.description,resumedFrom:Q.source.id,rootAgentId:Q.session.rootAgentId,resumeDepth:Q.session.resumeDepth}),U=!0,_)D(_);return N.json({source:yS(Q.source),session:yS(Q.session)})})}),S.get("/:sessionId/goal",async(N)=>{let T=await Z(N.req.param("sessionId"),N.req.query("projectPath"));return N.json({goal:await new XO(T.projectPath,T.id).get()})}),S.put("/:sessionId/goal",async(N)=>{let T=t(Kx,await N.req.json());if(!T.success)throw new m("Invalid goal request");let J=await Z(N.req.param("sessionId"),N.req.query("projectPath")),G=v(J);return A(G).runExclusive(async()=>{let p=J.currentRunId?C.get(J.currentRunId):void 0;if(p&&(p.status==="running"||p.status==="waiting_permission"))return N.json({status:"rejected",reason:"run_active"},409);let U=await(await Y(J)).createGoal(T.data);M.publish(G,"goal.updated",{goal:U});let _=T.data.permissionMode??"default",D=w(J,"",_,{goalContinuationOnly:!0});return N.json({status:"running",runId:D.id,goal:U},202)})}),S.patch("/:sessionId/goal",async(N)=>{let T=t(Wx,await N.req.json());if(!T.success)throw new m("Invalid goal update");let J=await Z(N.req.param("sessionId"),N.req.query("projectPath")),G=v(J);return A(G).runExclusive(async()=>{let p=await Y(J),X;if(T.data.action==="pause")X=await p.pauseGoal();else if(T.data.action==="edit")X=await p.editGoal(T.data.objective);else X=await p.resumeGoal();if(M.publish(G,"goal.updated",{goal:X}),X.status==="active"&&(!J.currentRunId||!["running","waiting_permission"].includes(C.get(J.currentRunId)?.status??""))){let U=w(J,"","default",{goalContinuationOnly:!0});return N.json({status:"running",runId:U.id,goal:X},202)}return N.json({status:X.status,goal:X})})}),S.delete("/:sessionId/goal",async(N)=>{let T=await Z(N.req.param("sessionId"),N.req.query("projectPath")),J=v(T),p=await(await Y(T)).clearGoal();if(p)M.publish(J,"goal.cleared",{});return N.json({cleared:p})}),S.delete("/:sessionId",async(N)=>{let T=N.req.param("sessionId"),J=N.req.query("projectPath");try{let G=await n(T,J),p=q(G),X=R.get(p),U=x.get(p),_;if(X?.currentRunId){let D=C.get(X.currentRunId);if(D)_S(D),await D.completion,_=D.id}if(U)await U.clearGoal().catch((D)=>{H.warn("[SessionRoutes] Failed to clear session goal:",D)});if(await F.deleteSession(G.sessionId,G.projectPath),_)C.delete(_);if(R.delete(p),$.delete(p),j.delete(p),V.delete(p),U){if(await U.dispose(),x.delete(p),x.size===0)await e.getInstance().disconnectAll()}return N.json({success:!0})}catch(G){if(H.error("[SessionRoutes] Failed to delete session:",G),G instanceof m||G instanceof z||G instanceof o)throw G;throw new u("Failed to delete session")}}),S.get("/:sessionId/message",async(N)=>{let T=N.req.param("sessionId");try{let J=await n(T,N.req.query("projectPath")),G=R.get(q(J)),p=G?.messages?G.messages:await F.loadSession(J.sessionId,J.projectPath);return N.json(p)}catch(J){if(H.error("[SessionRoutes] Failed to get messages:",J),J instanceof m||J instanceof z||J instanceof o)throw J;throw new u("Failed to get messages")}}),S.get("/:sessionId/events",async(N)=>{let T=N.req.param("sessionId"),J=await n(T,N.req.query("projectPath")),G=await f(J);return mx(N,async(p)=>{let U,_,D=!1,Q=()=>{if(_!==void 0)clearInterval(_),_=void 0;U?.(),U=void 0},y=()=>{if(D)return;D=!0,Q()},l=new Set;p.onAbort(y),U=M.subscribe((k)=>{if(k.sessionId!==J.sessionId||k.projectPath!==J.projectPath)return;let d=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required")&&typeof d==="string"){if(l.has(d))return;l.add(d)}p.writeSSE({data:JSON.stringify({type:k.type,properties:{...k.properties,sessionId:k.sessionId,projectPath:k.projectPath}})}).catch(y)});try{if(p.aborted||D)return;if(await p.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:J.sessionId,projectPath:J.projectPath,timestamp:Date.now()}})}).catch((P)=>{throw y(),P}),p.aborted||D)return;let d=(G.currentRunId?C.get(G.currentRunId):void 0)?.pendingPermission;if(d){l.add(d.permissionId);let P=hO(d,!0);await p.writeSSE({data:JSON.stringify({type:P.type,properties:{...P.properties,sessionId:J.sessionId,projectPath:J.projectPath}})})}K(G).catch((P)=>{H.error(`[SessionRoutes] Failed to resume pending input for ${T}:`,P)}),_=setInterval(()=>{if(!p.aborted)p.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(y)},15000);while(!p.aborted&&!D)await new Promise((P)=>setTimeout(P,1000))}finally{y()}})}),S.post("/:sessionId/message",async(N)=>{let T=N.req.param("sessionId"),J=await N.req.json(),G=t(Bx,J);if(!G.success)throw new m("Invalid message format");let{content:p,attachments:X,permissionMode:U,projectPath:_}=G.data,D=U||"default",Q=fO(p,X),y=await Z(T,_??N.req.query("projectPath")),l=v(y);return A(l).runExclusive(async()=>{let k=y.currentRunId?C.get(y.currentRunId):void 0;if(k&&(k.status==="running"||k.status==="waiting_permission")){let a=await(await Y(y)).enqueueSteering(Q,{allowBeforeTurn:!0});if(!a.accepted)return N.json({status:"rejected",reason:a.reason??"turn_unavailable"},409);let AS=a.messageId??VS(12),lS=a.queued;M.publish(l,"message.created",{messageId:AS,role:"user",content:LS(Q)});let nO=a.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(M.publish(l,nO,{runId:k.id,messageId:AS,queued:lS}),a.delivery==="next_turn"&&k.status!=="running"&&k.status!=="waiting_permission")K(y).catch((rO)=>{H.error(`[SessionRoutes] Failed to wake queued follow-up for ${T}:`,rO)});if(a.delivery==="next_turn")k.pendingFollowUpRequested=!0;return N.json({runId:k.id,messageId:AS,status:a.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:lS},202)}let P=await(await Y(y)).prepareInputTurn(Q);if(!P.accepted)return N.json({status:"rejected",reason:P.reason},P.reason==="queue_full"?429:409);let ZS=w(y,Q,D,{preparedInputTurn:P});return N.json({runId:ZS.id,messageId:P.messageId,status:"running"},202)})}),S.post("/:sessionId/abort",async(N)=>{let T=N.req.param("sessionId"),J=await n(T,N.req.query("projectPath")),G=R.get(q(J));if(G?.currentRunId){let p=C.get(G.currentRunId);if(p)_S(p),await p.completion}return N.json({success:!0})}),S.get("/:sessionId/status",async(N)=>{let T=N.req.param("sessionId"),J=await n(T,N.req.query("projectPath")),G=R.get(q(J));if(!G?.currentRunId)return N.json({sessionId:T,projectPath:J.projectPath,status:"idle"});let p=C.get(G.currentRunId);return N.json({sessionId:T,projectPath:J.projectPath,runId:G.currentRunId,status:p?.status||"idle"})}),{app:S,dispatchTask:b,getTaskDiff:B}};async function Lx(S,x,j,$,V,A={}){let{abortController:Y,sessionId:f,id:Z}=S,w=A.preparedInputTurn?.messageId??VS(12),B=A.pendingInputOnly===!0||A.preparedInputTurn?.mode==="pending"||A.goalContinuationOnly===!0?void 0:VS(12),K,N=v(x),T=(J,G)=>{M.publish(N,J,G)};try{if(x.taskStatus="running",x.taskStatusReason=void 0,x.taskStartedAt=new Date().toISOString(),x.taskCompletedAt=void 0,!A.pendingInputOnly&&!A.goalContinuationOnly)T("message.created",{messageId:w,role:"user",content:LS(j)});if(T("session.status",{status:"running"}),B)T("message.created",{messageId:B,role:"assistant",content:""});K=await V(x);let J=K,G=await mO.createWithRuntime(J,{sessionId:f,...x.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}}),p=async(Q)=>{let y=VS(12),l=300000;S.status="waiting_permission";let k=new Promise((MS)=>{let a=setTimeout(()=>{H.warn(`[SessionRoutes] Permission ${y} timed out after 300000ms`),T("permission.timeout",{requestId:y}),MS({approved:!1,reason:"timeout"})},300000);S.pendingPermission={permissionId:y,resolve:(AS)=>{clearTimeout(a),MS(AS)},details:Q}}),d=S.pendingPermission;if(!d)throw Error("Permission request was not registered");let P=hO(d);T(P.type,P.properties),H.info(`[SessionRoutes] Permission request created: ${y}, runId: ${Z}`);let ZS=await k;if(H.info(`[SessionRoutes] Permission response received: ${y}, approved: ${ZS.approved}`),!Y.signal.aborted)S.status="running";if(S.pendingPermission===d)S.pendingPermission=void 0;return ZS},X={messages:[...x.messages],userId:"web-user",sessionId:f,workspaceRoot:x.projectPath,signal:Y.signal,permissionMode:$,...x.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:p}},U=()=>{if(!B)B=VS(12),T("message.created",{messageId:B,role:"assistant",content:""});return B},_=async(Q)=>{switch(Q.kind){case"content_delta":T("message.delta",{messageId:U(),delta:Q.delta});break;case"thinking_delta":T("thinking.delta",{delta:Q.delta});break;case"tool_start":if("function"in Q.toolCall)T("tool.start",{messageId:U(),toolName:Q.toolCall.function.name,toolCallId:Q.toolCall.id,arguments:Q.toolCall.function.arguments,toolKind:Q.toolKind});break;case"tool_result":if("function"in Q.toolCall)T("tool.result",{messageId:U(),toolName:Q.toolCall.function.name,toolCallId:Q.toolCall.id,success:Q.result.success,summary:Q.result.metadata?.summary,output:CS(FS(Q.toolCall.function.name,Q.result)),metadata:BO(Q.result.metadata)});break;case"token_usage":T("token.usage",{...Q.usage});break;case"turn_start":T("turn.started",{turn:Q.turn,maxTurns:Q.maxTurns});break;case"steering_applied":T("steering.applied",{runId:Z,messageIds:Q.messageIds,count:Q.count,recovered:Q.recovered,delivery:Q.delivery,queued:J.getPendingSteeringCount()});break;case"follow_up_started":{if(B)T("message.complete",{messageId:B}),B=void 0;for(let y of Q.messages){if(!y.recovered||y.persisted)continue;T("message.created",{messageId:y.id,role:"user",content:LS(y.content),recovered:!0})}T("follow_up.started",{runId:Z,queued:Q.queued,recovered:Q.recovered}),U();break}case"goal_updated":T("goal.updated",{goal:Q.goal});break;case"goal_continuation_started":T("goal.continuation.started",{goal:Q.goal,continuation:Q.continuation}),U();break;case"compaction":T(Q.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":T("model.fallback",{});break;case"task_update":T("task.updated",{tasks:Q.tasks});break;default:break}},D=await ES(G.chatStream(j,X,{stream:!0,pendingInputOnly:A.pendingInputOnly,preparedInputTurn:A.preparedInputTurn,goalContinuationOnly:A.goalContinuationOnly}),_);if(!D.success)throw Error(D.error?.message??"Agent run failed");for(let Q=0;Q<20;Q++){let y=S.pendingFollowUpRequested===!0;if(S.pendingFollowUpRequested=!1,J.getPendingSteeringCount()===0){if(!y)break;continue}if(Y.signal.aborted)break;if(D=await ES(G.chatStream("",X,{stream:!0,pendingInputOnly:!0}),_),!D.success)throw Error(D.error?.message??"Agent follow-up failed")}if(x.messages=[...X.messages],x.updatedAt=new Date,await UO(x),Y.signal.aborted||S.status==="cancelled"){x.taskStatus="cancelled",x.taskCompletedAt??=new Date().toISOString(),T("session.status",{status:"idle"});return}if(B)T("message.complete",{messageId:B});T("thinking.completed",{}),S.status="completed",x.taskStatus="completed",x.taskCompletedAt??=new Date().toISOString(),T("session.completed",{runId:Z,outputTruncated:D.metadata?.outputTruncated??!1}),T("session.status",{status:"idle"})}catch(J){if(K&&A.preparedInputTurn)await K.finishTurn(A.preparedInputTurn.handle).catch(()=>{return});if(await UO(x).catch(()=>{return}),Y.signal.aborted||S.status==="cancelled"){_S(S,"runtime-abort"),x.taskStatus="cancelled",x.taskCompletedAt??=new Date().toISOString(),T("session.status",{status:"idle"});return}H.error("[SessionRoutes] Agent execution error:",J),S.status="failed",x.taskStatus="failed",x.taskStatusReason??="Agent execution failed",x.taskCompletedAt??=new Date().toISOString(),T("session.error",{error:J instanceof Error?J.message:"Unknown error"}),T("session.status",{status:"error"})}}function HO(S,x,j){H.info(`[SessionRoutes] Looking for permission ${x} in session ${S.sessionId}`),H.info(`[SessionRoutes] Active runs: ${C.size}`);for(let[$,V]of C.entries())if(H.info(`[SessionRoutes] Checking run ${$}: sessionId=${V.sessionId}, projectPath=${V.projectPath}, pendingPermission=${V.pendingPermission?.permissionId}`),V.sessionId===S.sessionId&&V.projectPath===S.projectPath&&V.pendingPermission?.permissionId===x)return V.pendingPermission.resolve(j),H.info(`[SessionRoutes] Permission ${x} responded, runId: ${V.id}`),!0;return H.error(`[SessionRoutes] Permission not found: ${x}`),!1}var PS=W("Service"),Cx=O.Object({approved:O.Boolean(),remember:O.Optional(O.Boolean()),scope:O.Optional(E(["once","session","project"])),targetMode:O.Optional(E(["default","autoEdit","plan","yolo"])),feedback:O.Optional(O.String()),answers:O.Optional(O.Record(O.String(),O.Union([O.String(),O.Array(O.String())])))}),KO=()=>{let S=new Fx;return S.post("/:permissionId",async(x)=>{let j=x.req.param("permissionId"),$=x.req.query("sessionId"),V=x.req.query("projectPath");PS.info(`[PermissionRoutes] Received permission response: permissionId=${j}, sessionId=${$}`);try{let A=await x.req.json(),Y=t(Cx,A);if(!Y.success)throw new m("Invalid permission response format");let{approved:f,remember:Z,scope:w,targetMode:b,feedback:B,answers:K}=Y.data;if(!$)throw new m("sessionId query parameter is required");let N=await n($,V);if(!HO(N,j,{approved:f,reason:B,scope:w,targetMode:b,feedback:B,answers:K}))throw new z("Permission request",j);return PS.info(`[PermissionRoutes] Permission ${j} ${f?"approved":"denied"}`),x.json({success:!0,approved:f,remember:Z})}catch(A){if(PS.error("[PermissionRoutes] Failed to respond to permission:",A),A instanceof m||A instanceof o||A instanceof z||A instanceof g)throw A;throw A}}),S};import{Hono as Px}from"hono";var WO=W("Service"),qO=()=>{let S=new Px;return S.get("/",async(x)=>{try{let j=await kO();return x.json(j)}catch(j){return WO.error("[ProviderRoutes] Failed to list providers:",j),x.json([])}}),S.get("/:provider/models",async(x)=>{let j=x.req.param("provider");try{let $=await EO(j);return x.json($)}catch($){return WO.error("[ProviderRoutes] Failed to list models:",$),x.json([])}}),S.put("/:provider/credential",async(x)=>{let j=x.req.param("provider"),$=await x.req.json();if(!$.apiKey?.trim())throw new m("apiKey is required");return await s().setApiKey(j,$.apiKey.trim()),x.json({success:!0})}),S.delete("/:provider/credential",async(x)=>{return await s().clearCredential(x.req.param("provider")),x.json({success:!0})}),S};import{Hono as Rx}from"hono";import*as SS from"node:fs/promises";import{homedir as Ix}from"node:os";import*as mS from"node:path";var xS=W("Service"),RS=mS.join(Ix(),".blade","skills-config.json");async function LO(){try{let S=await SS.readFile(RS,"utf-8");return JSON.parse(S)}catch{return{disabled:[]}}}async function gx(S){await SS.mkdir(mS.dirname(RS),{recursive:!0}),await SS.writeFile(RS,JSON.stringify(S,null,2))}async function tx(S,x){let j=await LO();if(x)j.disabled=j.disabled.filter(($)=>$!==S);else if(!j.disabled.includes(S))j.disabled.push(S);await gx(j)}var JS=null,ux=300000;async function vx(){if(JS&&Date.now()-JS.timestamp<ux)return JS.data;try{let S=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!S.ok)return xS.warn(`GitHub API returned ${S.status}`),JS?.data||[];let x=await S.json(),j=[];for(let $ of x){if($.type!=="dir")continue;let V=`Official ${$.name} skill`;try{let A=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${$.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(A.ok){let f=(await A.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(f)V=f[1].trim().slice(0,100)}}catch{}j.push({name:$.name,description:V,tag:"Official",author:"Anthropic"})}return JS={data:j,timestamp:Date.now()},j}catch(S){return xS.warn("Failed to fetch skills catalog from GitHub:",S),JS?.data||[]}}var FO=()=>{let S=new Rx;return S.get("/",async(x)=>{try{let j=DS();await j.initialize();let $=j.getAll(),V=await LO(),A=$.map((Y)=>({id:Y.name,name:Y.name,enabled:!V.disabled.includes(Y.name),description:Y.description||"",version:Y.version||"1.0.0",provider:"Local",location:Y.source==="builtin"?"Built-in":Y.basePath,capabilities:["prompts"],allowedTools:Y.allowedTools||[]}));return x.json(A)}catch(j){return xS.error("[SkillsRoutes] Failed to get skills:",j),x.json([])}}),S.post("/:name/toggle",async(x)=>{try{let j=x.req.param("name"),$=await x.req.json();return await tx(j,$.enabled),x.json({success:!0,enabled:$.enabled})}catch(j){return xS.error("[SkillsRoutes] Failed to toggle skill:",j),x.json({success:!1,error:j.message},500)}}),S.delete("/:name",async(x)=>{try{let j=x.req.param("name"),$=`${process.env.HOME}/.blade/skills/${j}`;return await SS.rm($,{recursive:!0,force:!0}),await DS().refresh(),x.json({success:!0})}catch(j){return xS.error("[SkillsRoutes] Failed to uninstall skill:",j),x.json({success:!1,error:j.message},500)}}),S.post("/install",async(x)=>{try{let j=await x.req.json(),$=zO(),V=DS(),A=!1;if(j.source==="catalog"&&j.name){if(A=await $.installOfficialSkill(j.name),!A)return x.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(j.source==="repo"&&j.url){if(A=await $.installFromRepo(j.url,j.name),!A)return x.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(j.source==="local"&&j.path){if(A=await $.installFromLocal(j.path,j.name),!A)return x.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 x.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await V.refresh(),x.json({success:!0})}catch(j){return xS.error("[SkillsRoutes] Failed to install skill:",j),x.json({success:!1,error:j.message},500)}}),S.get("/catalog",async(x)=>{try{let j=await vx();return x.json(j)}catch(j){return xS.error("[SkillsRoutes] Failed to get catalog:",j),x.json([])}}),S};import cx from"fast-glob";import{Hono as lx}from"hono";import{execSync as dx}from"node:child_process";import{readdir as ax}from"node:fs/promises";import bS from"node:path";var QS=W("Service"),ox=(S)=>{try{return dx("git rev-parse --abbrev-ref HEAD",{cwd:S,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},ix=[...hS.map((S)=>`${S}/**`),...hS,...IS.map((S)=>`**/${S}`)],nx=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),RO=()=>{let S=new lx;return S.get("/commands",async(x)=>{try{let j=x.req.query("q")||"",$=PO(j).filter((V)=>!nx.has(V.command));return x.json($)}catch(j){return QS.error("[SuggestionsRoutes] Failed to get command suggestions:",j),x.json([])}}),S.get("/files",async(x)=>{try{let j=x.req.query("q")||"",$=x.get("directory")||L(),V=Math.min(Number(x.req.query("limit"))||100,1000),Y=(await cx("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:ix})).map((w)=>w.replace(/\\/g,"/"));if(!j)return x.json(Y.slice(0,V));let f=j.toLowerCase(),Z=Y.filter((w)=>w.toLowerCase().includes(f)).slice(0,V);return x.json(Z)}catch(j){return QS.error("[SuggestionsRoutes] Failed to get file suggestions:",j),x.json([])}}),S.get("/files/tree",async(x)=>{try{let j=x.get("directory")||L(),$=x.req.query("path")||"",V=$?bS.join(j,$):j,Y=(await ax(V,{withFileTypes:!0})).map((w)=>({name:w.name,path:$?`${$}/${w.name}`:w.name,type:w.isDirectory()?"dir":"file"}));Y.sort((w,b)=>{if(w.type!==b.type)return w.type==="dir"?-1:1;return w.name.localeCompare(b.name)});let f=new Set(hS),Z=Y.filter((w)=>{let b=w.name;if(b.startsWith("."))return!1;if(f.has(b))return!1;for(let B of IS)if(b.match(new RegExp(B.replace("*",".*"))))return!1;return!0});return x.json(Z)}catch(j){return QS.error("[SuggestionsRoutes] Failed to get file tree:",j),x.json([])}}),S.get("/files/content",async(x)=>{try{let j=x.req.query("path");if(!j)return x.json({error:"Missing file path"},400);let $=x.get("directory")||L(),V=bS.resolve($,j),A=bS.relative($,V);if(A.startsWith("..")||bS.isAbsolute(A))return x.json({error:"Invalid file path"},400);let Y=CO(),f=await Y.stat(V);if(!f?.isFile)return x.json({error:"File not found"},404);let Z=200000,w=await Y.readTextFile(V),b=w.length>Z;return x.json({path:j,content:b?w.slice(0,Z):w,truncated:b,size:f.size})}catch(j){return QS.error("[SuggestionsRoutes] Failed to get file content:",j),x.json({error:"Failed to read file"},500)}}),S.get("/git-info",async(x)=>{try{let j=x.get("directory")||L(),$=ox(j);return x.json({branch:$})}catch(j){return QS.error("[SuggestionsRoutes] Failed to get git info:",j),x.json({branch:null})}}),S};import{Hono as rx}from"hono";var gS=W("Service"),IO=(S)=>{let x=new rx;return x.onError((j,$)=>{if(j instanceof g)return $.json(j.toObject(),j.statusCode);return gS.error("[TaskRoutes] Unhandled route error:",j),$.json(new u("Failed to dispatch task").toObject(),500)}),x.post("/",async(j)=>{let $;try{$=await j.req.json()}catch{throw new m("Invalid request body")}let V=t(pO,$);if(!V.success)throw new m("Invalid task request");try{let A=await S.dispatchTask({prompt:V.data.prompt,title:V.data.title,sourceProjectPath:V.data.projectPath||j.get("directory")||L(),isolation:V.data.isolation,permissionMode:V.data.permissionMode,attachments:V.data.attachments});return j.json(GO.parse(A),202)}catch(A){if(A instanceof m||A instanceof I)throw A;throw gS.error("[TaskRoutes] Failed to dispatch task:",A),new u("Failed to dispatch task")}}),x.get("/:sessionId/diff",async(j)=>{try{let $=await S.getTaskDiff(j.req.param("sessionId"),j.req.query("projectPath"));return j.json($O.parse($))}catch($){if($ instanceof m||$ instanceof z||$ instanceof I)throw $;throw gS.error("[TaskRoutes] Failed to load task diff:",$),new u("Failed to load task diff")}}),x};import{Hono as ex}from"hono";var OS=W("Service"),TS=new Map,gO=2097152,tO=65536;function uO(){return typeof globalThis.Bun<"u"}async function sx(S,x,j){if(uO()){let{spawn:A}=await import("bun-pty"),Y=A(S,x,{name:"xterm-256color",cwd:j.cwd,env:j.env});return{pid:Y.pid,write:(f)=>Y.write(f),resize:(f,Z)=>Y.resize(f,Z),kill:()=>Y.kill(),onData:(f)=>Y.onData(f),onExit:(f)=>Y.onExit(f)}}let V=(await import("node-pty")).spawn(S,x,{name:"xterm-256color",cwd:j.cwd,env:j.env,cols:80,rows:24});return{pid:V.pid,write:(A)=>V.write(A),resize:(A,Y)=>V.resize(A,Y),kill:()=>V.kill(),onData:(A)=>{V.onData(A)},onExit:(A)=>{V.onExit(A)}}}var vS=void 0,uS;if(uO())try{let{createBunWebSocket:S}=await import("hono/bun"),x=S();uS=x.upgradeWebSocket,vS=x.websocket}catch(S){OS.warn("[Terminal] Failed to initialize Bun WebSocket support:",S)}async function vO(S,x){let j=`term-${Date.now()}`;OS.info(`[Terminal] New connection: ${j}, cwd: ${S}`);let $=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",V=$.endsWith("sh")?["-l"]:[],A=await sx($,V,{cwd:S,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),Y={id:j,process:A,cwd:S,buffer:"",subscribers:new Set};if(TS.set(j,Y),Y.subscribers.add(x),A.onData((f)=>{let Z=!1;for(let w of Y.subscribers)try{w.send(f),Z=!0}catch{Y.subscribers.delete(w)}if(Z)return;if(Y.buffer+=f,Y.buffer.length>gO)Y.buffer=Y.buffer.slice(-gO)}),A.onExit(({exitCode:f})=>{OS.info(`[Terminal] Process exited: ${j}, code: ${f}`);for(let Z of Y.subscribers)try{Z.close()}catch{}TS.delete(j)}),Y.buffer){let f=Y.buffer;Y.buffer="";for(let Z=0;Z<f.length;Z+=tO)x.send(f.slice(Z,Z+tO))}return{session:Y,cleanup:()=>{if(OS.info(`[Terminal] Connection closed: ${j}`),Y.subscribers.delete(x),Y.subscribers.size===0){try{Y.process.kill()}catch{}TS.delete(j)}}}}function cO(S,x){S.on("connection",async(j,$)=>{let V=new URL($.url||"/",`http://${$.headers.host}`);if(!V.pathname.endsWith("/terminal/ws")){j.close();return}let A=V.searchParams.get("cwd")||x()||L();try{let{session:Y,cleanup:f}=await vO(A,{send:(Z)=>j.send(Z),close:()=>j.close()});j.on("message",(Z)=>{try{Y.process.write(String(Z))}catch(w){OS.error("[Terminal] Failed to write to PTY:",w)}}),j.on("close",f),j.on("error",f)}catch(Y){OS.error("[Terminal] Failed to spawn PTY:",Y),j.close()}})}var lO=()=>{let S=new ex;if(S.get("/status",(x)=>{let j=Array.from(TS.values()).map(($)=>({id:$.id,cwd:$.cwd}));return x.json({active:j.length,terminals:j})}),S.post("/kill/:terminalId",(x)=>{let j=x.req.param("terminalId"),$=TS.get(j);if($){try{$.process.kill()}catch{}for(let V of $.subscribers)V.close();return TS.delete(j),x.json({success:!0})}return x.json({success:!1,error:"Terminal not found"},404)}),uS)S.get("/ws",uS((x)=>{let j=x.req.query("cwd")||x.get("directory")||L(),$;return{async onOpen(V,A){try{$=await vO(j,{send:(Y)=>A.send(Y),close:()=>A.close()})}catch(Y){OS.error("[Terminal] Failed to spawn PTY:",Y),A.close()}},onMessage(V){if(!$)return;try{$.session.process.write(String(V.data))}catch(A){OS.error("[Terminal] Failed to write to PTY:",A)}},onClose(){$?.cleanup()}}}));else S.get("/ws",(x)=>{return x.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return S};var c=W("Service"),cS=[];function T0(){let S=x0($0(import.meta.url)),x=[jS(S,"web"),jS(L(),"dist/web"),jS(L(),"packages/cli/dist/web")];for(let j of x){let $=jS(j,"index.html");if(oO($)){if(BS($,"utf-8").includes("/assets/"))return c.debug(`[Server] Found web dist at: ${j}`),j}}return null}function A0(){let S=new N0;S.onError(($,V)=>{if(c.error("[Server] Request error:",$),$ instanceof g)return V.json($.toObject(),$.statusCode);let A=$ instanceof Error?$.message:String($);return V.json({error:{code:"INTERNAL_ERROR",message:A}},500)}),S.use(async($,V)=>{let A=process.env.BLADE_SERVER_PASSWORD;if(!A)return V();let Y=$.req.path;if(Y==="/"||Y.startsWith("/assets/")||Y.endsWith(".html")||Y.endsWith(".js")||Y.endsWith(".css"))return V();let f=$.req.header("Authorization");if(!f?.startsWith("Basic "))return $.header("WWW-Authenticate",'Basic realm="Blade Server"'),$.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Z=Buffer.from(f.slice(6),"base64").toString(),[w,b]=Z.split(":"),B=process.env.BLADE_SERVER_USERNAME??"blade";if(w!==B||b!==A)return $.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),S.use(async($,V)=>{let A=$.req.path==="/health"||$.req.path==="/global/health"||$.req.path.startsWith("/assets/");if(!A)c.debug(`[Server] ${$.req.method} ${$.req.path}`);let Y=Date.now();if(await V(),!A){let f=Date.now()-Y;c.debug(`[Server] ${$.req.method} ${$.req.path} - ${$.res.status} (${f}ms)`)}}),S.use(V0({origin($){if(!$)return;if($.startsWith("http://localhost:"))return $;if($.startsWith("http://127.0.0.1:"))return $;if($==="tauri://localhost"||$==="http://tauri.localhost")return $;if(cS.includes($))return $;return}})),S.use(async($,V)=>{let A=$.req.query("directory")||$.req.header("x-blade-directory")||L();try{A=decodeURIComponent(A)}catch{}return $.set("directory",A),V()});let x=MO();S.route("/global",iS()),S.route("/events",aS()),S.route("/sessions",x.app),S.route("/tasks",IO(x)),S.route("/configs",dS()),S.route("/permissions",KO()),S.route("/providers",qO()),S.route("/models",SO()),S.route("/suggestions",RO()),S.route("/terminal",lO()),S.route("/mcp",nS()),S.route("/skills",FO()),S.get("/health",($)=>{return $.json({healthy:!0,version:NS()})});let j=T0();if(j)c.info(`[Server] Serving static files from ${j}`),S.get("/assets/*",($)=>{let V=jS(j,$.req.path);if(!oO(V))return $.json({error:{code:"NOT_FOUND",message:`File not found: ${$.req.path}`}},404);let A=BS(V),Y=j0(V).toLowerCase(),Z={".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"}[Y]||"application/octet-stream";return new Response(A,{headers:{"Content-Type":Z,"Cache-Control":"public, max-age=31536000, immutable"}})}),S.get("/",($)=>{let V=jS(j,"index.html"),A=BS(V,"utf-8");return $.html(A)}),S.get("*",($)=>{let V=$.req.path;if(V.includes("."))return $.json({error:{code:"NOT_FOUND",message:`File not found: ${V}`}},404);let A=jS(j,"index.html"),Y=BS(A,"utf-8");return $.html(Y)});else c.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),S.get("/",($)=>{return $.json({message:"Blade API Server",version:NS(),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"}})}),S.all("*",($)=>{return $.json({error:{code:"NOT_FOUND",message:`Route not found: ${$.req.path}`}},404)});return S}function Y0(){let S=O0(),x=[];for(let j of Object.keys(S)){let $=S[j];if(!$)continue;for(let V of $){if(V.internal||V.family!=="IPv4")continue;if(V.address.startsWith("172."))continue;x.push(V.address)}}return x}function dO(){return typeof globalThis.Bun<"u"}function aO(S,x){let j=globalThis.Bun,$=(A)=>{try{return j.serve({hostname:x.hostname,port:A,fetch:S.fetch,idleTimeout:0,websocket:vS})}catch(Y){c.error("Failed to start Bun server:",Y);return}},V=x.port===0?$(4096)??$(0):$(x.port);if(!V)throw Error(`Failed to start Bun server on port ${x.port}`);return{url:V.url,port:V.port,hostname:V.hostname,stop:async()=>{V.stop(!0)}}}function p0(S,x){return new Promise((j,$)=>{let V=S0(async(w,b)=>{let B=new URL(w.url||"/",`http://${w.headers.host}`),K=new Headers;for(let[J,G]of Object.entries(w.headers))if(G)if(Array.isArray(G))for(let p of G)K.append(J,p);else K.set(J,G);let N;if(w.method!=="GET"&&w.method!=="HEAD")N=(await new Promise((G)=>{let p=[];w.on("data",(X)=>p.push(X)),w.on("end",()=>G(Buffer.concat(p)))})).toString();let T=new Request(B.toString(),{method:w.method,headers:K,body:N});try{let J=await S.fetch(T);if(b.statusCode=J.status,J.headers.forEach((G,p)=>{b.setHeader(p,G)}),J.body){let G=J.body.getReader(),p=async()=>{let{done:X,value:U}=await G.read();if(X){b.end();return}return b.write(U),p()};await p()}else{let G=await J.text();b.end(G)}}catch(J){c.error("[Server] Node request error:",J),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),A=new J0({noServer:!0}),Y=L();cO(A,()=>Y),V.on("upgrade",(w,b,B)=>{if(new URL(w.url||"/",`http://${w.headers.host}`).pathname==="/terminal/ws")A.handleUpgrade(w,b,B,(N)=>{A.emit("connection",N,w)});else b.destroy()});let f=(w)=>{return new Promise((b,B)=>{V.once("error",(K)=>{if(K.code==="EADDRINUSE")B(K);else B(K)}),V.listen(w,x.hostname,()=>{let K=V.address();if(K&&typeof K==="object")b(K.port);else b(w)})})};(async()=>{let w;if(x.port===0)try{w=await f(4096)}catch{w=await f(0)}else w=await f(x.port);let b=new URL(`http://${x.hostname==="0.0.0.0"?"localhost":x.hostname}:${w}`);j({url:b,port:w,hostname:x.hostname,stop:async()=>{return new Promise((B)=>{A.close(()=>{V.close(()=>B())})})}})})().catch($)})}var iO;((aj)=>{let S,x;function j(){if(!x)x=A0();return x}aj.getApp=j;function $(Y){cS=Y.cors??[];let f=j();if(dO())S=aO(f,Y),c.info(`[Server] Blade server listening on ${S.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 Z=S;return{url:Z.url,port:Z.port,hostname:Z.hostname,stop:async()=>{if(S)await S.stop(),S=void 0,x=void 0,c.info("[Server] Blade server stopped")}}}aj.listen=$;async function V(Y){cS=Y.cors??[];let f=j();if(dO())S=aO(f,Y),c.info(`[Server] Blade server listening on ${S.url} (Bun runtime)`);else S=await p0(f,Y),c.info(`[Server] Blade server listening on ${S.url} (Node.js runtime)`);let Z=S;return{url:Z.url,port:Z.port,hostname:Z.hostname,stop:async()=>{if(S)await S.stop(),S=void 0,x=void 0,c.info("[Server] Blade server stopped")}}}aj.listenAsync=V;function A(){return S!==void 0}aj.isRunning=A})(iO||={});export{G0 as a,Q0 as b,Y0 as c,iO as d};
@@ -0,0 +1,7 @@
1
+ import{_ as ye}from"./vendor-markdown-b9iCqZWK.js";import{r as d,j as e}from"./vendor-react-FPIC4Czm.js";import{c as D,u as _e,e as _,s as z,f as Ie,B as qe,g as fe}from"./index-BC0ssrep.js";import{n as Pe,L as ke,o as ve,p as Ee}from"./vendor-radix-DyP_DOwV.js";import{u as ze}from"./SettingsStore-CjvkbtuZ.js";import{X as We,b as ue,d as xe,a as je,I as Ge,J as Oe}from"./vendor-icons-DBM55KTG.js";import"./vendor-monaco-w6PwaWGP.js";const Je=Pe,we=d.forwardRef(({className:t,...n},a)=>e.jsx(ke,{ref:a,className:D("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...n}));we.displayName=ke.displayName;const W=d.forwardRef(({className:t,...n},a)=>e.jsx(ve,{ref:a,className:D("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...n}));W.displayName=ve.displayName;const G=d.forwardRef(({className:t,...n},a)=>e.jsx(Ee,{ref:a,className:D("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...n}));G.displayName=Ee.displayName;const Ve={"ayu-dark":{background:{primary:"#0f1419",secondary:"#14191f"},text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773"},border:{light:"#2d323b"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},dracula:{background:{primary:"#282a36",secondary:"#44475a"},text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4"},border:{light:"#44475a"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},monokai:{background:{primary:"#272822",secondary:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e"},border:{light:"#3e3d32"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},nord:{background:{primary:"#2e3440",secondary:"#3b4252"},text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a"},border:{light:"#434c5e"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},"solarized-light":{background:{primary:"#fdf6e3",secondary:"#eee8d5"},text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1"},border:{light:"#eee8d5"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},"solarized-dark":{background:{primary:"#002b36",secondary:"#073642"},text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75"},border:{light:"#073642"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},"tokyo-night":{background:{primary:"#1a1b26",secondary:"#292e42"},text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89"},border:{light:"#292e42"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},github:{background:{primary:"#ffffff",secondary:"#f6f8fa"},text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781"},border:{light:"#d0d7de"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},gruvbox:{background:{primary:"#282828",secondary:"#3c3836"},text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374"},border:{light:"#3c3836"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#b8bb26",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#fabd2f",default:"#ebdbb2"}},"one-dark":{background:{primary:"#282c34",secondary:"#21252b"},text:{primary:"#abb2bf",secondary:"#e5c07b",muted:"#5c6370"},border:{light:"#3e4451"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},catppuccin:{background:{primary:"#1e1e2e",secondary:"#313244"},text:{primary:"#cdd6f4",secondary:"#f5e0dc",muted:"#6c7086"},border:{light:"#313244"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#f5e0dc",operator:"#89dceb",type:"#f9e2af",tag:"#f38ba8",attr:"#f9e2af",default:"#cdd6f4"}},"rose-pine":{background:{primary:"#191724",secondary:"#1f1d2e"},text:{primary:"#e0def4",secondary:"#908caa",muted:"#6e6a86"},border:{light:"#26233a"},syntax:{comment:"#6e6a86",string:"#f6c177",number:"#ebbcba",keyword:"#c4a7e7",function:"#9ccfd8",variable:"#e0def4",operator:"#31748f",type:"#eb6f92",tag:"#eb6f92",attr:"#c4a7e7",default:"#e0def4"}},kanagawa:{background:{primary:"#1f1f28",secondary:"#2a2a37"},text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169"},border:{light:"#2a2a37"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#e46876",attr:"#ffa066",default:"#dcd7ba"}}};function He(t){const n=t.replace("#",""),a=parseInt(n.substring(0,2),16),s=parseInt(n.substring(2,4),16),o=parseInt(n.substring(4,6),16);return(.299*a+.587*s+.114*o)/255<.5}function Ke(t){return{base:He(t.background.primary)?"vs-dark":"vs",inherit:!0,rules:[{token:"",foreground:t.text.primary.replace("#",""),background:t.background.primary.replace("#","")},{token:"comment",foreground:t.syntax.comment.replace("#",""),fontStyle:"italic"},{token:"string",foreground:t.syntax.string.replace("#","")},{token:"number",foreground:t.syntax.number.replace("#","")},{token:"keyword",foreground:t.syntax.keyword.replace("#","")},{token:"type",foreground:t.syntax.type.replace("#","")},{token:"identifier",foreground:t.syntax.variable.replace("#","")},{token:"function",foreground:t.syntax.function.replace("#","")},{token:"variable",foreground:t.syntax.variable.replace("#","")},{token:"operator",foreground:t.syntax.operator.replace("#","")},{token:"delimiter",foreground:t.syntax.operator.replace("#","")},{token:"tag",foreground:t.syntax.tag.replace("#","")},{token:"attribute.name",foreground:t.syntax.attr.replace("#","")},{token:"attribute.value",foreground:t.syntax.string.replace("#","")}],colors:{"editor.background":t.background.primary,"editor.foreground":t.text.primary,"editor.lineHighlightBackground":t.background.secondary,"editor.selectionBackground":`${t.syntax.function}40`,"editorLineNumber.foreground":t.text.muted,"editorLineNumber.activeForeground":t.text.secondary,"editorCursor.foreground":t.text.primary,"editorIndentGuide.background":t.border.light,"editorWidget.background":t.background.secondary,"editorWidget.border":t.border.light,"scrollbarSlider.background":`${t.text.muted}40`,"scrollbarSlider.hoverBackground":`${t.text.muted}60`}}}const me=new Set;function pe(t,n){const a=n.toLowerCase().replace(/\s+/g,"-"),s=Ve[a];if(!s)return"vs-dark";if(!me.has(a)){const o=Ke(s);t.editor.defineTheme(a,o),me.add(a)}return a}d.lazy(async()=>({default:(await ye(()=>import("./vendor-react-FPIC4Czm.js").then(n=>n.i),[])).DiffEditor}));const Ue=d.lazy(async()=>({default:(await ye(()=>import("./vendor-react-FPIC4Czm.js").then(n=>n.i),[])).Editor}));function te(t,n){return t instanceof Error?t.message:n}function dt(){const{toggleFilePreview:t}=_e(),{messages:n,currentSessionRef:a,sessions:s}=_(),[o,f]=d.useState("diff"),[c,i]=d.useState([]),[p,b]=d.useState({}),[x,y]=d.useState(!1),[m,R]=d.useState(null),[w,N]=d.useState({}),[O,J]=d.useState({}),[E,ae]=d.useState(null),[Fe,V]=d.useState(""),[H,K]=d.useState(!1),[U,X]=d.useState(null),[re,M]=d.useState(!1),ne=d.useRef(a),T=d.useRef(0),I=d.useRef(0),q=d.useRef({}),Q=d.useRef(0),F=d.useRef(0),A=d.useRef({}),C=d.useRef({}),Y=d.useRef(null);d.useLayoutEffect(()=>{z(ne.current,a)||(T.current+=1),ne.current=a},[a]);const Z=(r,l)=>l===T.current&&z(_.getState().currentSessionRef,r),se=async(r,l="")=>{const g=l?`/suggestions/files/tree?path=${encodeURIComponent(l)}`:"/suggestions/files/tree",u=await fetch(g,{headers:fe(r)});if(!u.ok)throw new Error("Failed to load tree");return(await u.json()).map(h=>({...h,children:h.type==="dir"?[]:void 0}))};d.useEffect(()=>{const r=++I.current;return(async()=>{if(!a){i([]),y(!1),R(null);return}const g={...a},u=T.current,k=()=>r===I.current&&Z(g,u);if(k()){i([]),y(!0),R(null);try{const h=await se(g);k()&&i(h)}catch(h){k()&&R(te(h,"Failed to load tree"))}finally{k()&&y(!1)}}})(),()=>{I.current===r&&(I.current+=1)}},[a==null?void 0:a.projectPath,a==null?void 0:a.sessionId]),d.useEffect(()=>{Y.current=null,A.current={},C.current={},q.current={},Q.current+=1,ae(null),V(""),K(!1),X(null),M(!1),N({}),b({})},[a==null?void 0:a.projectPath,a==null?void 0:a.sessionId]);const v=d.useMemo(()=>s.find(r=>z({sessionId:r.sessionId,projectPath:r.projectPath},a)),[a,s]),Ce=d.useMemo(()=>Qe(n),[n]),[Se,oe]=d.useState(null),[Be,ee]=d.useState(!1),[ie,de]=d.useState(null),S=Se??Ce,ce=d.useMemo(()=>Me(n),[n]),[Le,De]=d.useState({});d.useEffect(()=>{const r=++F.current;if(oe(null),de(null),ee(!1),!a||(v==null?void 0:v.taskIsolation)!=="worktree"||!v.taskDiffStat||v.taskDiffStat.changedFiles===0)return;const l={...a};return ee(!0),Ie.getTaskDiff(l).then(g=>{r!==F.current||!z(_.getState().currentSessionRef,l)||oe(g.files.map(u=>({filePath:u.path,diff:{patch:u.patch},summary:u.binary?"binary":`+${u.additions} -${u.deletions}${u.truncated?" (truncated)":""}`})))}).catch(g=>{r===F.current&&de(te(g,"Failed to load task diff"))}).finally(()=>{r===F.current&&ee(!1)}),()=>{F.current===r&&(F.current+=1)}},[v==null?void 0:v.taskCompletedAt,v==null?void 0:v.taskDiffStat,v==null?void 0:v.taskIsolation,a]);const Re=r=>{De(l=>({...l,[r]:!l[r]}))},Te=async r=>{const l=_.getState().currentSessionRef;if(!l)return;const g=T.current,u=++Q.current,k=()=>u===Q.current&&Y.current===r&&Z(l,g);Y.current=r,ae(r),V(""),K(!0),X(null),M(!1);try{const h=await fetch(`/suggestions/files/content?path=${encodeURIComponent(r)}`,{headers:fe(l)});if(!h.ok)throw new Error("Failed to load file");const $=await h.json();k()&&(V($.content||""),M(!!$.truncated))}catch(h){k()&&X(te(h,"Failed to load file"))}finally{k()&&K(!1)}},Ae=async r=>{const l=(q.current[r]??0)+1;q.current[r]=l;const g=!A.current[r],u={...A.current,[r]:g};if(A.current=u,N(u),!g||C.current[r])return;const k=_.getState().currentSessionRef;if(!k)return;const h=T.current,$=()=>q.current[r]===l&&A.current[r]===!0&&Z(k,h);try{const P=await se(k,r);if($()){const le={...C.current,[r]:P};C.current=le,b(le)}}catch{if($()){const P={...C.current,[r]:[]};C.current=P,b(P)}}},$e=r=>{J(l=>({...l,[r]:!l[r]}))};return e.jsxs("div",{className:"w-[55%] min-w-[420px] max-w-[860px] border-l border-[#E5E7EB] dark:border-zinc-800 bg-white dark:bg-[#09090b] flex flex-col h-full shadow-xl shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-12 border-b border-[#E5E7EB] dark:border-zinc-800 shrink-0",children:[e.jsx("span",{className:"font-normal text-[13px] text-[#6B7280] dark:text-zinc-400 font-mono",children:"Preview"}),e.jsx(qe,{variant:"ghost",size:"icon",onClick:t,className:"h-8 w-8 text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB]/60 dark:text-zinc-500 dark:hover:text-zinc-300 dark:hover:bg-zinc-800/50",children:e.jsx(We,{className:"w-4 h-4"})})]}),e.jsxs(Je,{value:o,onValueChange:r=>f(r),className:"flex flex-col flex-1 min-h-0",children:[e.jsx("div",{className:"px-4 py-3 border-b border-[#E5E7EB] dark:border-zinc-800",children:e.jsxs(we,{className:"bg-white dark:bg-[#111113] border border-[#E5E7EB] dark:border-[#27272a] h-9 p-1 rounded-md w-full justify-start",children:[e.jsx(W,{value:"diff",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Diff"}),e.jsx(W,{value:"files",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Files"}),e.jsx(W,{value:"logs",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Logs"})]})}),e.jsx(G,{value:"diff",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:Be&&S.length===0?e.jsx(j,{title:"Loading task diff…",subtitle:"Reading the durable worktree artifact."}):ie&&S.length===0?e.jsx(j,{title:"Failed to load task diff",subtitle:ie}):S.length===0?e.jsx(j,{title:"No patch yet",subtitle:"Run a tool that changes files to see diffs here."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mb-2",children:[S.length," changed file",S.length>1?"s":""]}),S.map(r=>{var u;const l=((u=r.filePath)==null?void 0:u.split("/").pop())||"unknown",g=Le[r.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>Re(r.filePath||""),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:[g?e.jsx(ue,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(xe,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(je,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono flex-1 text-left truncate",children:l}),r.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:r.summary})]}),g&&e.jsxs("div",{className:"border-t border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("div",{className:"px-3 py-1 text-[11px] text-[#9CA3AF] dark:text-[#52525b] font-mono truncate",children:r.filePath}),e.jsx(et,{diff:r.diff})]})]},r.filePath)})]})})}),e.jsx(G,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(j,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&m&&e.jsx(j,{title:"Failed to load files",subtitle:m}),!x&&!m&&c.length===0&&e.jsx(j,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!m&&c.length>0&&e.jsxs("div",{className:"h-full grid grid-cols-[220px_1fr] gap-4 min-h-0",children:[e.jsx("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-2 overflow-y-auto min-h-0",children:c.map(r=>e.jsx(Ne,{node:r,depth:0,expandedDirs:w,childrenCache:p,toggleDir:Ae,selectedPath:E,onSelectFile:Te},r.path))}),e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono flex items-center justify-between",children:[e.jsx("span",{children:E||"Select a file to preview"}),E&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:H?"Loading…":re?"Truncated":"Ready"})]}),re&&!H&&e.jsx("div",{className:"px-3 py-2 bg-[#FEF3C7] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[11px] text-[#b45309] dark:text-[#facc15] font-mono",children:"Preview truncated to 200k characters."}),e.jsxs("div",{className:"flex-1 min-h-0",children:[!E&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Pick a file from the tree to preview."}),E&&U&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:U}),E&&!U&&e.jsx("div",{className:"h-full",children:H?e.jsx(he,{}):e.jsx(d.Suspense,{fallback:e.jsx(he,{}),children:e.jsx(Ye,{content:Fe,filename:E})})})]})]})]})]})}),e.jsx(G,{value:"logs",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:ce.length===0?e.jsx(j,{title:"No logs yet",subtitle:"Tool runs will appear here."}):ce.map(r=>{var h;const l=O[r.id],g=(r.content||"").split(`
2
+ `),u=g.length>10||(((h=r.content)==null?void 0:h.length)||0)>800,k=l||!u?g:g.slice(0,8);return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:r.title}),r.subtitle&&e.jsx("div",{className:"text-[11px] text-[#6B7280] dark:text-[#71717a] font-mono",children:r.subtitle})]}),e.jsx(Xe,{status:r.status})]}),r.content&&e.jsxs("div",{className:"px-3 py-3 space-y-2",children:[e.jsxs("pre",{className:"text-[12px] text-[#374151] dark:text-[#d4d4d8] bg-[#F3F4F6] dark:bg-[#09090b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md p-3 overflow-x-auto whitespace-pre-wrap font-mono",children:[k.join(`
3
+ `),!l&&u&&`
4
+ …`]}),u&&e.jsxs("button",{onClick:()=>$e(r.id),className:"flex items-center gap-1 text-[12px] text-[#6B7280] dark:text-[#a1a1aa] font-mono hover:text-[#111827] dark:hover:text-[#E5E5E5] transition-colors",children:[l?e.jsx(ue,{className:"w-3 h-3"}):e.jsx(xe,{className:"w-3 h-3"}),l?"Collapse":"Expand"]})]})]},r.id)})})})]})]})}function j({title:t,subtitle:n}){return e.jsxs("div",{className:"border border-dashed border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-6 text-center",children:[e.jsx("div",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:t}),e.jsx("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mt-1",children:n})]})}function Xe({status:t}){const n=t==="success"?"Success":t==="error"?"Failed":"Running",a=t==="success"?"bg-[#22C55E] text-white":t==="error"?"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]":"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]";return e.jsx("span",{className:D("text-[11px] px-2 py-0.5 rounded-full font-mono",a),children:n})}function Ne({node:t,depth:n,expandedDirs:a,childrenCache:s,toggleDir:o,onSelectFile:f,selectedPath:c}){const i=t.type==="dir",p=a[t.path],b=!i&&c===t.path,x=s[t.path]||[];return e.jsxs("div",{children:[e.jsx("button",{onClick:()=>{i?o(t.path):f(t.path)},className:D("flex items-center gap-2 w-full text-left text-[12px] font-mono px-2 py-1 rounded-md transition-colors",b?"bg-[#16A34A]/10 text-[#111827] dark:bg-[#22C55E]/10 dark:text-[#E5E5E5]":"hover:bg-[#F3F4F6] text-[#6B7280] dark:hover:bg-[#111113] dark:text-[#a1a1aa]",i&&"cursor-pointer",b&&"border border-[#16A34A]/30 dark:border-[#22C55E]/30"),style:{paddingLeft:n*14+8},children:i?e.jsxs(e.Fragment,{children:[p?e.jsx(Ge,{className:"h-3.5 w-3.5 shrink-0 text-[#111827] dark:text-[#E5E5E5]"}):e.jsx(Oe,{className:"h-3.5 w-3.5 shrink-0 text-[#6B7280] dark:text-[#a1a1aa]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:"h-3.5 w-3.5 shrink-0 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]})}),i&&p&&e.jsx("div",{children:x.map(y=>e.jsx(Ne,{node:y,depth:n+1,expandedDirs:a,childrenCache:s,toggleDir:o,onSelectFile:f,selectedPath:c},y.path))})]})}function Me(t){return t.flatMap(n=>{var o,f,c;const a=[];if((o=n.agentContent)!=null&&o.toolCalls)for(const i of n.agentContent.toolCalls){const p=ge(i.arguments),b=i.output,x=b?(f=L(b))!=null&&f.diff?be(b):b:void 0;a.push({id:`${n.id}-${i.toolCallId}`,title:i.toolName||"Tool",subtitle:i.summary,status:i.status==="success"?"success":i.status==="error"?"error":"running",content:x||(p?`Arguments:
5
+ ${p}`:void 0),timestamp:n.timestamp})}const s=n.metadata;if(s){if(s.kind==="tool_call"){const i=s.toolName||"Tool",p=ge(s.arguments);a.push({id:n.id,title:`Tool Call · ${i}`,subtitle:s.toolKind?String(s.toolKind):void 0,status:s.status==="success"?"success":s.status==="error"?"error":"running",content:p?`Arguments:
6
+ ${p}`:void 0,timestamp:n.timestamp})}if(s.kind==="tool_result"){const i=s.toolName||"Tool",p=s.success,b=s.summary,x=s.output,y=x?(c=L(x))!=null&&c.diff?be(x):x:void 0;a.push({id:n.id,title:`Tool Result · ${i}`,subtitle:b,status:p===void 0?"running":p?"success":"error",content:y,timestamp:n.timestamp})}}return a})}function Qe(t){var s;const n=[],a=new Set;for(let o=t.length-1;o>=0;o-=1){const f=t[o];if((s=f.agentContent)!=null&&s.toolCalls)for(let x=f.agentContent.toolCalls.length-1;x>=0;x-=1){const y=f.agentContent.toolCalls[x],m=y.metadata,R=y.output||"",w=L(R)||L((m==null?void 0:m.diff_snippet)||"");if(w!=null&&w.diff){const N=(m==null?void 0:m.file_path)||y.toolName||"unknown";if(!a.has(N)){a.add(N);const O=typeof(m==null?void 0:m.oldContent)=="string"?m.oldContent:void 0,J=typeof(m==null?void 0:m.newContent)=="string"?m.newContent:void 0;n.push({diff:w.diff,filePath:N,summary:y.summary,oldContent:O,newContent:J})}}}const c=f.metadata;if(!c||c.kind!=="tool_result")continue;const i=c.metadata,p=c.output||(typeof f.content=="string"?f.content:"")||"",b=L(p)||L((i==null?void 0:i.diff_snippet)||"");if(b!=null&&b.diff){const x=(i==null?void 0:i.file_path)||c.toolName||"unknown";if(!a.has(x)){a.add(x);const y=typeof(i==null?void 0:i.oldContent)=="string"?i.oldContent:void 0,m=typeof(i==null?void 0:i.newContent)=="string"?i.newContent:void 0;n.push({diff:b.diff,filePath:x,summary:c.summary,oldContent:y,newContent:m})}}}return n.reverse()}function L(t){if(!t)return null;const n=/<<<DIFF>>>\s*([\s\S]*?)\s*<<<\/DIFF>>>/m,a=t.match(n);if(!a)return null;try{return{diff:JSON.parse(a[1])}}catch{return null}}function be(t){return t?t.replace(/<<<DIFF>>>[\s\S]*?<<<\/DIFF>>>/m,"").trim():""}function ge(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}function he(){return e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Loading editor…"})}function Ye({content:t,filename:n}){const{theme:a}=ze(),s=d.useRef(null),[o,f]=d.useState("vs-dark"),c=Ze(n),i=p=>{s.current=p;const b=pe(p,a);f(b)};return d.useEffect(()=>{if(s.current){const p=pe(s.current,a);f(p)}},[a]),e.jsx(Ue,{value:t,language:c,theme:o,height:"100%",beforeMount:i,options:{readOnly:!0,minimap:{enabled:!1},fontSize:12,lineNumbers:"on",wordWrap:"on",scrollBeyondLastLine:!1,automaticLayout:!0}},n)}function Ze(t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",json:"json",md:"markdown",css:"css",scss:"scss",html:"html",yml:"yaml",yaml:"yaml",go:"go",rs:"rust",py:"python",java:"java",c:"c",cpp:"cpp",h:"cpp",hpp:"cpp",sh:"shell",zsh:"shell",toml:"toml",xml:"xml"}[n]||"plaintext"}function et({diff:t}){const n=t.patch.split(`
7
+ `);let a=0,s=0;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-md overflow-hidden bg-white dark:bg-[#111113]",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#111113] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:[e.jsx("span",{children:"Patch"}),t.matchLine&&e.jsxs("span",{children:["Line ",t.matchLine]})]}),e.jsx("div",{className:"text-[12px] font-mono",children:n.map((o,f)=>{if(o.startsWith("@@")){const c=/@@ -(?<old>\d+),?(?<oldCount>\d*) \+(?<new>\d+),?(?<newCount>\d*) @@/.exec(o);return c!=null&&c.groups&&(a=parseInt(c.groups.old,10),s=parseInt(c.groups.new,10)),e.jsx(B,{line:o},`${o}-${f}`)}if(o.startsWith("---")||o.startsWith("+++")||o.startsWith("Index:")||o.startsWith("==="))return e.jsx(B,{line:o},`${o}-${f}`);if(o.startsWith("+")){const c=s;return s+=1,e.jsx(B,{line:o,oldLine:null,newLine:c},`${o}-${f}`)}if(o.startsWith("-")){const c=a;return a+=1,e.jsx(B,{line:o,oldLine:c,newLine:null},`${o}-${f}`)}if(o.startsWith(" ")){const c=a,i=s;return a+=1,s+=1,e.jsx(B,{line:o,oldLine:c,newLine:i},`${o}-${f}`)}return e.jsx(B,{line:o},`${o}-${f}`)})})]})}function B({line:t,oldLine:n,newLine:a}){const s=t.startsWith("---")||t.startsWith("+++")||t.startsWith("Index:")||t.startsWith("==="),o=t.startsWith("@@"),f=t[0],c=s||o?t:t.slice(1),i=s?"text-[#6B7280] dark:text-[#a1a1aa]":f==="+"?"text-[#166534] bg-[#22C55E]/10 dark:text-[#86efac] dark:bg-[#22C55E]/10":f==="-"?"text-[#b91c1c] bg-[#EF4444]/10 dark:text-[#fca5a5] dark:bg-[#EF4444]/10":o?"text-[#1d4ed8] bg-[#DBEAFE] dark:text-[#93c5fd] dark:bg-[#1e3a8a]/30":"text-[#374151] dark:text-[#d4d4d8]";return e.jsxs("div",{className:D("grid grid-cols-[40px_40px_1fr] gap-2 px-3 py-0.5",i),children:[e.jsx("span",{className:"text-right text-[#9CA3AF] dark:text-[#71717a]",children:n?String(n).padStart(2," "):""}),e.jsx("span",{className:"text-right text-[#9CA3AF] dark:text-[#71717a]",children:a?String(a).padStart(2," "):""}),e.jsx("span",{className:"whitespace-pre",children:c})]})}export{dt as FilePreview};
@@ -1 +1 @@
1
- import{M as k,r as h,_ as j}from"./vendor-markdown-b9iCqZWK.js";import{r as o,j as r}from"./vendor-react-FPIC4Czm.js";import{c as b}from"./index-B3dW1Scg.js";import{a as f}from"./SettingsStore-B_4zN-c-.js";import{j as g,I as N}from"./vendor-icons-DqO8ishN.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-DyP_DOwV.js";const v=[h],y=o.lazy(()=>j(()=>import("./CodeBlockHighlighter-D8_cOYpG.js"),[]).then(t=>({default:t.CodeBlockHighlighter}))),P=o.memo(function({content:s,className:a,syntaxHighlight:d=!0}){const i=f(),E=o.useMemo(()=>({code({className:e,children:n,...x}){const c=/language-(\w+)/.exec(e||""),p=!c,m=c?c[1]:"",l=String(n).replace(/\n$/,"");return p?r.jsx("code",{className:b("bg-[#F3F4F6] dark:bg-[#27272a] px-1.5 py-0.5 rounded text-[#111827] dark:text-[#E5E5E5] font-mono text-[13px]",e),...x,children:n}):d?r.jsxs("div",{className:"relative my-4 rounded-lg overflow-hidden border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e]",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[#F3F4F6] dark:bg-[#27272a] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[r.jsx("span",{className:"text-xs text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:m||"text"}),r.jsx(F,{content:l})]}),r.jsx(o.Suspense,{fallback:r.jsx(u,{className:e,code:l,props:x}),children:r.jsx(y,{code:l,language:m,isDark:i})})]}):r.jsx(u,{className:e,code:l,props:x})},p({children:e}){return r.jsx("p",{className:"mb-4 leading-relaxed last:mb-0",children:e})},ul({children:e}){return r.jsx("ul",{className:"pl-4 mb-4 space-y-1 list-disc last:mb-0",children:e})},ol({children:e}){return r.jsx("ol",{className:"pl-4 mb-4 space-y-1 list-decimal last:mb-0",children:e})},li({children:e}){return r.jsx("li",{className:"leading-relaxed",children:e})},h1({children:e}){return r.jsx("h1",{className:"text-2xl font-bold mb-4 mt-6 text-[#111827] dark:text-[#E5E5E5]",children:e})},h2({children:e}){return r.jsx("h2",{className:"text-xl font-bold mb-3 mt-5 text-[#111827] dark:text-[#E5E5E5]",children:e})},h3({children:e}){return r.jsx("h3",{className:"text-lg font-bold mb-2 mt-4 text-[#111827] dark:text-[#E5E5E5]",children:e})},blockquote({children:e}){return r.jsx("blockquote",{className:"border-l-2 border-[#22C55E] pl-4 italic text-[#6B7280] dark:text-[#a1a1aa] mb-4",children:e})},a({href:e,children:n}){return r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-[#22C55E] hover:underline transition-colors",children:n})},table({children:e}){return r.jsx("div",{className:"overflow-x-auto mb-4 border border-[#E5E7EB] dark:border-[#27272a] rounded-lg",children:r.jsx("table",{className:"w-full text-sm text-left",children:e})})},thead({children:e}){return r.jsx("thead",{className:"bg-[#F3F4F6] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]",children:e})},tbody({children:e}){return r.jsx("tbody",{className:"divide-y divide-[#E5E7EB] dark:divide-[#27272a]",children:e})},tr({children:e}){return r.jsx("tr",{className:"hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]/50 transition-colors",children:e})},th({children:e}){return r.jsx("th",{className:"px-4 py-3 font-medium whitespace-nowrap",children:e})},td({children:e}){return r.jsx("td",{className:"px-4 py-3 text-[#374151] dark:text-[#d4d4d8]",children:e})},hr(){return r.jsx("hr",{className:"my-6 border-[#E5E7EB] dark:border-[#27272a]"})}}),[i,d]);return r.jsx("div",{className:b("text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono break-words min-w-0 w-full",a),children:r.jsx(k,{remarkPlugins:v,components:E,children:s})})});function u({className:t,code:s,props:a}){return r.jsx("pre",{className:"my-4 overflow-x-auto rounded-lg border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e] p-4 text-[13px] leading-normal",children:r.jsx("code",{className:t,...a,children:s})})}function F({content:t}){const[s,a]=o.useState(!1),d=async()=>{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)};return r.jsx("button",{onClick:d,className:"p-1 hover:bg-[#E5E7EB] dark:hover:bg-[#3f3f46] rounded-md transition-colors text-[#9CA3AF] dark:text-[#a1a1aa] hover:text-[#111827] dark:hover:text-[#E5E5E5]",title:"Copy code",children:s?r.jsx(g,{className:"h-3.5 w-3.5 text-[#22C55E]"}):r.jsx(N,{className:"h-3.5 w-3.5"})})}export{P as MarkdownRenderer};
1
+ import{M as p,r as h,_ as j}from"./vendor-markdown-b9iCqZWK.js";import{r as o,j as r}from"./vendor-react-FPIC4Czm.js";import{c as b}from"./index-BC0ssrep.js";import{a as f}from"./SettingsStore-CjvkbtuZ.js";import{k as g,Q as N}from"./vendor-icons-DBM55KTG.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-DyP_DOwV.js";const v=[h],y=o.lazy(()=>j(()=>import("./CodeBlockHighlighter-D8_cOYpG.js"),[]).then(t=>({default:t.CodeBlockHighlighter}))),R=o.memo(function({content:s,className:a,syntaxHighlight:d=!0}){const i=f(),E=o.useMemo(()=>({code({className:e,children:n,...x}){const c=/language-(\w+)/.exec(e||""),k=!c,m=c?c[1]:"",l=String(n).replace(/\n$/,"");return k?r.jsx("code",{className:b("bg-[#F3F4F6] dark:bg-[#27272a] px-1.5 py-0.5 rounded text-[#111827] dark:text-[#E5E5E5] font-mono text-[13px]",e),...x,children:n}):d?r.jsxs("div",{className:"relative my-4 rounded-lg overflow-hidden border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e]",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[#F3F4F6] dark:bg-[#27272a] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[r.jsx("span",{className:"text-xs text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:m||"text"}),r.jsx(F,{content:l})]}),r.jsx(o.Suspense,{fallback:r.jsx(u,{className:e,code:l,props:x}),children:r.jsx(y,{code:l,language:m,isDark:i})})]}):r.jsx(u,{className:e,code:l,props:x})},p({children:e}){return r.jsx("p",{className:"mb-4 leading-relaxed last:mb-0",children:e})},ul({children:e}){return r.jsx("ul",{className:"pl-4 mb-4 space-y-1 list-disc last:mb-0",children:e})},ol({children:e}){return r.jsx("ol",{className:"pl-4 mb-4 space-y-1 list-decimal last:mb-0",children:e})},li({children:e}){return r.jsx("li",{className:"leading-relaxed",children:e})},h1({children:e}){return r.jsx("h1",{className:"text-2xl font-bold mb-4 mt-6 text-[#111827] dark:text-[#E5E5E5]",children:e})},h2({children:e}){return r.jsx("h2",{className:"text-xl font-bold mb-3 mt-5 text-[#111827] dark:text-[#E5E5E5]",children:e})},h3({children:e}){return r.jsx("h3",{className:"text-lg font-bold mb-2 mt-4 text-[#111827] dark:text-[#E5E5E5]",children:e})},blockquote({children:e}){return r.jsx("blockquote",{className:"border-l-2 border-[#22C55E] pl-4 italic text-[#6B7280] dark:text-[#a1a1aa] mb-4",children:e})},a({href:e,children:n}){return r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-[#22C55E] hover:underline transition-colors",children:n})},table({children:e}){return r.jsx("div",{className:"overflow-x-auto mb-4 border border-[#E5E7EB] dark:border-[#27272a] rounded-lg",children:r.jsx("table",{className:"w-full text-sm text-left",children:e})})},thead({children:e}){return r.jsx("thead",{className:"bg-[#F3F4F6] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]",children:e})},tbody({children:e}){return r.jsx("tbody",{className:"divide-y divide-[#E5E7EB] dark:divide-[#27272a]",children:e})},tr({children:e}){return r.jsx("tr",{className:"hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]/50 transition-colors",children:e})},th({children:e}){return r.jsx("th",{className:"px-4 py-3 font-medium whitespace-nowrap",children:e})},td({children:e}){return r.jsx("td",{className:"px-4 py-3 text-[#374151] dark:text-[#d4d4d8]",children:e})},hr(){return r.jsx("hr",{className:"my-6 border-[#E5E7EB] dark:border-[#27272a]"})}}),[i,d]);return r.jsx("div",{className:b("text-[14px] text-[#111827] dark:text-[#E5E5E5] font-mono break-words min-w-0 w-full",a),children:r.jsx(p,{remarkPlugins:v,components:E,children:s})})});function u({className:t,code:s,props:a}){return r.jsx("pre",{className:"my-4 overflow-x-auto rounded-lg border border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#1e1e1e] p-4 text-[13px] leading-normal",children:r.jsx("code",{className:t,...a,children:s})})}function F({content:t}){const[s,a]=o.useState(!1),d=async()=>{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)};return r.jsx("button",{onClick:d,className:"p-1 hover:bg-[#E5E7EB] dark:hover:bg-[#3f3f46] rounded-md transition-colors text-[#9CA3AF] dark:text-[#a1a1aa] hover:text-[#111827] dark:hover:text-[#E5E5E5]",title:"Copy code",children:s?r.jsx(g,{className:"h-3.5 w-3.5 text-[#22C55E]"}):r.jsx(N,{className:"h-3.5 w-3.5"})})}export{R as MarkdownRenderer};
@@ -1,5 +1,5 @@
1
- import{r as o,j as e}from"./vendor-react-FPIC4Czm.js";import{u as ge,D as V,a as ee,b as te,c as A}from"./index-B3dW1Scg.js";import{_ as T,q as w,r as se,s as oe,t as W}from"./vendor-radix-DyP_DOwV.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-B4kP-cmG.js";import{z as Ne,n as Ce,X as ne,A as ye,L as ce,B as de,j as we,D as Ae}from"./vendor-icons-DqO8ishN.js";import"./vendor-markdown-b9iCqZWK.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],O=w(o.useState(!1),2),P=O[0],g=O[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 J=ie(b);b.scrollTo(0,J-E.current)}}else z()}),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()},z=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(){$||P||z()},{target:r}),ke(function(){H()},T([],w(i),!1)),{data:C,loading:!P&&$,error:q,loadingMore:P,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()},Oe="mcp server @modelcontextprotocol",Pe=3,Le=async(n,a)=>{const r=n&&n.length>=Pe?n:Oe,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 Xe(){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),O=o.useRef(null),{run:P}=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:O,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]),z=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),P(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:O,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,J=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",J==="Official"?"bg-[#16A34A]/20 dark:bg-[#22C55E]/20 text-[#16A34A] dark:text-[#22C55E]":"bg-[#3b82f6]/20 text-[#3b82f6]"),children:J})]}),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:()=>z(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(`{
1
+ import{r as o,j as e}from"./vendor-react-FPIC4Czm.js";import{u as ge,D as V,a as ee,b as te,c as A}from"./index-BC0ssrep.js";import{_ as T,q as w,r as se,s as oe,t as W}from"./vendor-radix-DyP_DOwV.js";import{i as ve,a as Ee,d as le,u as pe,b as be,c as je,e as O,f as G,g as ke}from"./useRequest-B4kP-cmG.js";import{K as Ne,q as Ce,X as ae,y as ye,L as ce,N as de,k as we,O as Ae}from"./vendor-icons-DBM55KTG.js";import"./vendor-markdown-b9iCqZWK.js";import"./vendor-monaco-w6PwaWGP.js";function q(a,n){if(ve){if(!a)return n;var r;return Ee(a)?r=a():"current"in a?r=a.current:r=a,r}}var Se=function(a){var n=function(r,c,d){var l=o.useRef(!1),s=o.useRef([]),m=o.useRef([]),h=o.useRef(void 0);a(function(){var i,k=Array.isArray(d)?d:[d],v=k.map(function(N){return q(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 n},Fe=Se(o.useEffect);function Be(){var a=(typeof global>"u"?"undefined":typeof global)=="object"&&global&&global.Object===Object&&global,n=typeof self=="object"&&self&&self.Object===Object&&self;return a||n}Be()||(global.Date=Date);function Me(a,n){var r,c=be(a),d=(r=n==null?void 0:n.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,n)},[]);return pe(function(){l.cancel()}),{run:l,cancel:l.cancel,flush:l.flush}}function De(a,n,r){r===void 0&&(r={});var c=r.enable,d=c===void 0?!0:c,l=be(n);Fe(function(){if(d){var s=q(r.target,window);if(s!=null&&s.addEventListener){var m=function(i){return l.current(i)},h=Array.isArray(a)?a:[a];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})})}}}},[a,r.capture,r.once,r.passive,d],r.target)}var Te=function(a){return a===document||a===document.documentElement||a===document.body?Math.max(window.pageYOffset,document.documentElement.scrollTop,document.body.scrollTop):a.scrollTop},ie=function(a){return a.scrollHeight||Math.max(document.documentElement.scrollHeight,document.body.scrollHeight)},_e=function(a){return a.clientHeight||Math.max(document.documentElement.clientHeight,document.body.clientHeight)},Ie=function(a,n){n===void 0&&(n={});var r=n.target,c=n.isNoMore,d=n.threshold,l=d===void 0?100:d,s=n.direction,m=s===void 0?"bottom":s,h=n.reloadDeps,i=h===void 0?[]:h,k=n.manual,v=n.onBefore,N=n.onSuccess,S=n.onError,p=n.onFinally,_=w(o.useState(),2),C=_[0],F=_[1],R=w(o.useState(!1),2),P=R[0],g=R[1],B=m==="top",y=o.useRef(void 0),E=o.useRef(0),L=o.useMemo(function(){return c?c(C):!1},[C]),M=O(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,a(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=q(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,Y=M.error,H=M.run,Q=M.runAsync,K=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()},X=function(){return g(!1),u()},J=function(){var x=q(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(){$||P||J()},{target:r}),ke(function(){H()},T([],w(i),!1)),{data:C,loading:!P&&$,error:Y,loadingMore:P,noMore:L,loadMore:I,loadMoreAsync:D,reload:G(U),reloadAsync:G(X),mutate:F,cancel:K}};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,Oe=async()=>{const a=await fetch("/mcp");if(!a.ok)throw new Error("Failed to fetch servers");return a.json()},Re="mcp server @modelcontextprotocol",Pe=3,Le=async(a,n)=>{const r=a&&a.length>=Pe?a:Re,c=`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(r)}&size=${ue}&from=${n}`,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:n+ue<l.total}};function Ke(){const{isMcpOpen:a,toggleMcp:n}=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),R=o.useRef(null),{run:P}=Me(t=>{S(t)},{wait:500}),{data:g=[],loading:B,run:y}=O(Oe,{refreshDeps:[a],ready:a,onSuccess:t=>{t.length>0&&!s&&m(t[0].id)}}),{data:E,loading:L,loadingMore:M,noMore:$,reload:Y}=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:R,isNoMore:t=>!(t!=null&&t.hasMore),reloadDeps:[N],manual:!a||r!=="catalog"}),{runAsync:H}=O(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:Q}=O(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:K}=O(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})},{manual:!0,onSuccess:y}),{runAsync:I}=O(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]}}))},X=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:a,onOpenChange:n,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:n,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(ae,{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||Y()},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:()=>K(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(Z,{label:"File read",enabled:D.read,onToggle:()=>U("read")}),e.jsx(Z,{label:"File write",enabled:D.write,onToggle:()=>U("write")}),e.jsx(Z,{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),P(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:R,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 ne,re;const j=X.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]}),((ne=t.publisher)==null?void 0:ne.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:a,children:n,onClick:r}){return e.jsx("button",{onClick:r,className:A("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:n})}function Z({label:a,enabled:n,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:a}),e.jsx(He,{enabled:n,onChange:r})]})}function He({enabled:a,onChange:n}){return e.jsx("button",{onClick:n,className:A("w-9 h-5 rounded-full px-0.5 flex items-center transition-colors",a?"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:a,onOpenChange:n,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
2
  "name": "my-server",
3
3
  "command": "npx",
4
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{Xe as McpModal};
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:a,onOpenChange:n,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:()=>n(!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(ae,{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:()=>n(!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:a,onClose:n,onInstall:r}){var i;const c=((i=a.name.split("/").pop())==null?void 0:i.replace(/^server-/,""))||a.name,[d,l]=o.useState(c),[s,m]=o.useState(`-y ${a.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:n,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 ",a.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:n,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(ae,{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:a.name}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] mt-1",children:a.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:n,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:a,children:n,onClick:r}){return e.jsx("button",{onClick:r,className:A("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:n})}export{Ke as McpModal};
@@ -1 +1 @@
1
- import{r as l,j as e}from"./vendor-react-FPIC4Czm.js";import{D as O,a as M,b as T,c as u,u as _,d as H}from"./index-B3dW1Scg.js";import{u as J}from"./SettingsStore-B_4zN-c-.js";import{X as P,E as Q,w as W,a as L,e as q,h as V}from"./vendor-icons-DqO8ishN.js";import"./vendor-markdown-b9iCqZWK.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-DyP_DOwV.js";function X({open:a,onOpenChange:r,onSave:j}){const[f,v]=l.useState([]),[h,n]=l.useState([]),[s,c]=l.useState(),[i,m]=l.useState(),[k,w]=l.useState(""),[b,C]=l.useState(""),[F,E]=l.useState(!1),[S,N]=l.useState(!1),[y,B]=l.useState(!1);l.useEffect(()=>{a&&(n([]),c(void 0),m(void 0),w(""),C(""),E(!1),N(!1),B(!1),fetch("/providers").then(o=>o.json()).then(v))},[a]),l.useEffect(()=>{s&&fetch(`/providers/${s.id}/models`).then(o=>o.json()).then(n)},[s]);const A=()=>{!s||!i||!s.configured&&!b||(j({provider:s.id,model:i.id,displayName:k||i.name,apiKey:b||void 0}),r(!1))};return e.jsx(O,{open:a,onOpenChange:r,children:e.jsxs(M,{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(T,{className:"sr-only",children:"Add Model"}),e.jsxs("div",{className:"flex flex-col gap-6 p-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:"Add Model"}),e.jsx("button",{type:"button",onClick:()=>r(!1),children:e.jsx(P,{className:"w-4 h-4"})})]}),e.jsx($,{label:"Provider",value:(s==null?void 0:s.name)??"Select provider",open:F,setOpen:E,options:f.map(o=>({id:o.id,label:`${o.name} (${o.modelCount})${o.configured?" · configured":""}`,selected:(s==null?void 0:s.id)===o.id,select:()=>{c(o),m(void 0),E(!1)}}))}),e.jsx($,{label:"Model",value:(i==null?void 0:i.name)??"Select model",open:S,setOpen:N,options:h.map(o=>({id:o.id,label:`${o.name} · ${Math.round(o.contextWindow/1e3)}K${o.reasoning?" · reasoning":""}${o.input.includes("image")?" · vision":""}`,selected:(i==null?void 0:i.id)===o.id,select:()=>{m(o),w(o.name),N(!1)}}))}),e.jsx(Y,{label:"Display name",value:k,onChange:w,placeholder:(i==null?void 0:i.name)??"Optional alias"}),(s==null?void 0:s.supportsApiKey)&&!s.configured&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y?"text":"password",value:b,onChange:o=>C(o.target.value),className:"pr-10 field",placeholder:"Stored separately in auth.json"}),e.jsx("button",{type:"button",onClick:()=>B(!y),className:"absolute right-3 top-1/2 -translate-y-1/2",children:y?e.jsx(Q,{className:"w-4 h-4"}):e.jsx(W,{className:"w-4 h-4"})})]})]}),s&&!s.configured&&!s.supportsApiKey&&e.jsx("p",{className:"font-mono text-sm text-amber-600",children:"This provider requires OAuth or ambient credentials. Configure it externally before selecting the model."}),e.jsx("button",{type:"button",disabled:!s||!i||!s.configured&&(!s.supportsApiKey||b.trim().length===0),onClick:A,className:"px-4 py-2 font-mono text-sm font-semibold text-white bg-green-600 rounded-md disabled:opacity-50",children:"Save Model"})]})]})})}function $(a){return e.jsxs("div",{className:"flex relative flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:a.label}),e.jsxs("button",{type:"button",onClick:()=>a.setOpen(!a.open),className:"flex justify-between field",children:[a.value,e.jsx(L,{className:"w-4 h-4"})]}),a.open&&e.jsx("div",{className:"overflow-y-auto absolute right-0 left-0 top-full z-50 max-h-64 bg-white rounded-md border dark:bg-zinc-900",children:a.options.map(r=>e.jsx("button",{type:"button",onClick:r.select,className:u("w-full text-left px-3 py-2 text-sm font-mono",r.selected&&"bg-zinc-100 dark:bg-zinc-800"),children:r.label},r.id))})]})}function Y(a){return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:a.label}),e.jsx("input",{value:a.value,onChange:r=>a.onChange(r.target.value),placeholder:a.placeholder,className:"field"})]})}function Z(a){const[r,j]=l.useState(""),[f,v]=l.useState(""),[h,n]=l.useState("");l.useEffect(()=>{var c,i,m;j(((c=a.model)==null?void 0:c.displayName)??""),v(((m=(i=a.model)==null?void 0:i.overrides)==null?void 0:m.baseUrl)??"")},[a.model]);const s=async()=>{if(a.model){if(h.trim()&&!(await fetch(`/providers/${a.model.provider}/credential`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:h.trim()})})).ok)throw new Error("Failed to update provider credential");a.onSave(a.model.id,{displayName:r||void 0,overrides:f?{...a.model.overrides,baseUrl:f}:void 0}),a.onOpenChange(!1)}};return e.jsx(O,{open:a.open,onOpenChange:a.onOpenChange,children:e.jsxs(M,{className:"sm:max-w-[480px] p-6 bg-white dark:bg-[#09090b]","aria-describedby":void 0,children:[e.jsx(T,{className:"sr-only",children:"Edit Model"}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("h2",{className:"font-semibold font-mono",children:"Edit Model Overrides"}),e.jsx("button",{type:"button",onClick:()=>a.onOpenChange(!1),children:e.jsx(P,{className:"h-4 w-4"})})]}),e.jsx("label",{className:"font-mono text-sm",children:"Display name"}),e.jsx("input",{value:r,onChange:c=>j(c.target.value),className:"field"}),e.jsx("label",{className:"font-mono text-sm",children:"Replace provider API key"}),e.jsx("input",{type:"password",value:h,onChange:c=>n(c.target.value),placeholder:"Leave empty to keep current credential",className:"field"}),e.jsx("label",{className:"font-mono text-sm",children:"Base URL override"}),e.jsx("input",{value:f,onChange:c=>v(c.target.value),placeholder:"Leave empty to use default endpoint",className:"field"}),e.jsx("button",{type:"button",onClick:()=>void s(),className:"px-4 py-2 rounded-md text-white bg-green-600",children:"Save"})]})})}const ee={anthropic:{bg:"#d97757",label:"A"},gemini:{bg:"#4285f4",label:"G"},"azure-openai":{bg:"#0078d4",label:"Az"},"gpt-openai-platform":{bg:"#10a37f",label:"GP"}};function ie(){var z;const{isSettingsOpen:a,toggleSettings:r,isSidebarOpen:j,setSidebarOpen:f}=_(),{configuredModels:v,loadModels:h}=H(),n=J(),[s,c]=l.useState("general"),[i,m]=l.useState(!1),[k,w]=l.useState(null),[b,C]=l.useState(null),[F,E]=l.useState(""),[S,N]=l.useState("all"),y=[{value:"general",label:"General"},{value:"models",label:"Models"},{value:"shortcuts",label:"Shortcuts"}],A=l.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 d=t.action.toLowerCase().includes(F.toLowerCase()),x=S==="all"||t.scope.toLowerCase()===S;return d&&x}),o=v.reduce((t,d)=>{const x=d.provider||"unknown";return t[x]||(t[x]=[]),t[x].push(d),t},{});l.useEffect(()=>{a&&(h(),n.loadSettings())},[a,h,n.loadSettings]);const R=async t=>{try{if(!(await fetch("/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t.provider,displayName:t.displayName,model:t.model,apiKey:t.apiKey})})).ok)throw new Error("Failed to save model");await h()}catch(d){console.error("Failed to save model:",d)}},U=async t=>{try{if(!(await fetch(`/models/${t}`,{method:"DELETE"})).ok)throw new Error("Failed to delete model");await h()}catch(d){console.error("Failed to delete model:",d)}},G=async(t,d)=>{try{if(!(await fetch(`/models/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).ok)throw new Error("Failed to update model");await h()}catch(x){console.error("Failed to update model:",x)}},I=t=>{w(k===t?null:t)};return e.jsxs(e.Fragment,{children:[e.jsx(O,{open:a,onOpenChange:r,children:e.jsxs(M,{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(T,{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:y.map(t=>e.jsx("button",{onClick:()=>c(t.value),className:u("w-full text-left px-3 py-2 rounded-md text-sm font-mono transition-colors",s===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:s==="general"?"Settings":(z=y.find(t=>t.value===s))==null?void 0:z.label}),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(P,{className:"h-4 w-4"})})]}),s==="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(o).map(([t,d])=>{const x=ee[t]||{bg:"#71717a",label:"?"},K=k===t;return e.jsxs("div",{className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>I(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:x.bg},children:x.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:[d.length," model",d.length>1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:u("text-xs font-mono","text-[#16A34A]"),children:"● Connected"}),e.jsx(L,{className:u("h-4 w-4 text-[#9CA3AF] dark:text-[#71717a] transition-transform",K&&"rotate-180")})]})]}),K&&e.jsx("div",{className:"border-t border-[#E5E7EB] dark:border-zinc-800",children:d.map(p=>{var D;return 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:p.displayName||p.model}),e.jsxs("span",{className:"text-xs text-[#9CA3AF] dark:text-[#71717a] font-mono truncate",children:[p.displayName&&`${p.model} · `,((D=p.overrides)==null?void 0:D.baseUrl)||"default endpoint"]})]}),e.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>C(p),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(q,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>U(p.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(V,{className:"h-3.5 w-3.5"})})]})]},p.id)})})]},t)}),Object.keys(o).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:()=>m(!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"})]}),s==="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:n.language,onChange:t=>n.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:n.autoSaveSessions,onChange:t=>n.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:()=>n.updateSettings({uiTheme:t}),className:u("px-3 py-1 rounded text-[12px] font-mono transition-colors",n.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:!j,onChange:t=>f(!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:n.theme,onChange:t=>n.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:n.notifyBuild,onChange:t=>n.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:n.notifyErrors,onChange:t=>n.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:n.notifySounds,onChange:t=>n.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:n.privacyTelemetry,onChange:t=>n.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:n.privacyCrash,onChange:t=>n.updateSettings({privacyCrash:t})})]})]})]}),s==="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:F,onChange:t=>E(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:S,onChange:t=>N(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:()=>{E(""),N("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"})]}),A.map((t,d)=>e.jsxs("div",{className:u("grid grid-cols-[1fr_180px_120px] gap-2 px-3 py-2 text-[13px] font-mono",d%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(x=>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:x},x))}),e.jsx("span",{className:"text-[#6B7280] dark:text-[#94a3b8] text-[12px]",children:t.scope})]},`${t.action}-${t.scope}`)),A.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(X,{open:i,onOpenChange:m,onSave:R}),e.jsx(Z,{open:!!b,onOpenChange:t=>!t&&C(null),model:b,onSave:G})]})}function g({enabled:a,onChange:r}){return e.jsx("button",{onClick:()=>r(!a),className:u("w-10 h-5 rounded-full px-0.5 flex items-center transition-colors",a?"bg-[#22C55E]":"bg-[#E5E7EB] dark:bg-[#27272a]"),children:e.jsx("span",{className:u("h-4 w-4 rounded-full transition-transform",a?"translate-x-5 bg-white":"translate-x-0 bg-white dark:bg-[#a1a1aa]")})})}export{ie as SettingsModal};
1
+ import{r as l,j as e}from"./vendor-react-FPIC4Czm.js";import{D as O,a as M,b as T,c as u,u as _,d as H}from"./index-BC0ssrep.js";import{u as J}from"./SettingsStore-CjvkbtuZ.js";import{X as P,E as Q,D as W,b as L,f as q,i as V}from"./vendor-icons-DBM55KTG.js";import"./vendor-markdown-b9iCqZWK.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-DyP_DOwV.js";function X({open:a,onOpenChange:r,onSave:j}){const[f,v]=l.useState([]),[h,n]=l.useState([]),[s,c]=l.useState(),[i,m]=l.useState(),[k,w]=l.useState(""),[b,C]=l.useState(""),[F,E]=l.useState(!1),[S,N]=l.useState(!1),[y,B]=l.useState(!1);l.useEffect(()=>{a&&(n([]),c(void 0),m(void 0),w(""),C(""),E(!1),N(!1),B(!1),fetch("/providers").then(o=>o.json()).then(v))},[a]),l.useEffect(()=>{s&&fetch(`/providers/${s.id}/models`).then(o=>o.json()).then(n)},[s]);const A=()=>{!s||!i||!s.configured&&!b||(j({provider:s.id,model:i.id,displayName:k||i.name,apiKey:b||void 0}),r(!1))};return e.jsx(O,{open:a,onOpenChange:r,children:e.jsxs(M,{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(T,{className:"sr-only",children:"Add Model"}),e.jsxs("div",{className:"flex flex-col gap-6 p-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:"Add Model"}),e.jsx("button",{type:"button",onClick:()=>r(!1),children:e.jsx(P,{className:"w-4 h-4"})})]}),e.jsx($,{label:"Provider",value:(s==null?void 0:s.name)??"Select provider",open:F,setOpen:E,options:f.map(o=>({id:o.id,label:`${o.name} (${o.modelCount})${o.configured?" · configured":""}`,selected:(s==null?void 0:s.id)===o.id,select:()=>{c(o),m(void 0),E(!1)}}))}),e.jsx($,{label:"Model",value:(i==null?void 0:i.name)??"Select model",open:S,setOpen:N,options:h.map(o=>({id:o.id,label:`${o.name} · ${Math.round(o.contextWindow/1e3)}K${o.reasoning?" · reasoning":""}${o.input.includes("image")?" · vision":""}`,selected:(i==null?void 0:i.id)===o.id,select:()=>{m(o),w(o.name),N(!1)}}))}),e.jsx(Y,{label:"Display name",value:k,onChange:w,placeholder:(i==null?void 0:i.name)??"Optional alias"}),(s==null?void 0:s.supportsApiKey)&&!s.configured&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y?"text":"password",value:b,onChange:o=>C(o.target.value),className:"pr-10 field",placeholder:"Stored separately in auth.json"}),e.jsx("button",{type:"button",onClick:()=>B(!y),className:"absolute right-3 top-1/2 -translate-y-1/2",children:y?e.jsx(Q,{className:"w-4 h-4"}):e.jsx(W,{className:"w-4 h-4"})})]})]}),s&&!s.configured&&!s.supportsApiKey&&e.jsx("p",{className:"font-mono text-sm text-amber-600",children:"This provider requires OAuth or ambient credentials. Configure it externally before selecting the model."}),e.jsx("button",{type:"button",disabled:!s||!i||!s.configured&&(!s.supportsApiKey||b.trim().length===0),onClick:A,className:"px-4 py-2 font-mono text-sm font-semibold text-white bg-green-600 rounded-md disabled:opacity-50",children:"Save Model"})]})]})})}function $(a){return e.jsxs("div",{className:"flex relative flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:a.label}),e.jsxs("button",{type:"button",onClick:()=>a.setOpen(!a.open),className:"flex justify-between field",children:[a.value,e.jsx(L,{className:"w-4 h-4"})]}),a.open&&e.jsx("div",{className:"overflow-y-auto absolute right-0 left-0 top-full z-50 max-h-64 bg-white rounded-md border dark:bg-zinc-900",children:a.options.map(r=>e.jsx("button",{type:"button",onClick:r.select,className:u("w-full text-left px-3 py-2 text-sm font-mono",r.selected&&"bg-zinc-100 dark:bg-zinc-800"),children:r.label},r.id))})]})}function Y(a){return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"text-[13px] text-zinc-500 font-mono",children:a.label}),e.jsx("input",{value:a.value,onChange:r=>a.onChange(r.target.value),placeholder:a.placeholder,className:"field"})]})}function Z(a){const[r,j]=l.useState(""),[f,v]=l.useState(""),[h,n]=l.useState("");l.useEffect(()=>{var c,i,m;j(((c=a.model)==null?void 0:c.displayName)??""),v(((m=(i=a.model)==null?void 0:i.overrides)==null?void 0:m.baseUrl)??"")},[a.model]);const s=async()=>{if(a.model){if(h.trim()&&!(await fetch(`/providers/${a.model.provider}/credential`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:h.trim()})})).ok)throw new Error("Failed to update provider credential");a.onSave(a.model.id,{displayName:r||void 0,overrides:f?{...a.model.overrides,baseUrl:f}:void 0}),a.onOpenChange(!1)}};return e.jsx(O,{open:a.open,onOpenChange:a.onOpenChange,children:e.jsxs(M,{className:"sm:max-w-[480px] p-6 bg-white dark:bg-[#09090b]","aria-describedby":void 0,children:[e.jsx(T,{className:"sr-only",children:"Edit Model"}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("h2",{className:"font-semibold font-mono",children:"Edit Model Overrides"}),e.jsx("button",{type:"button",onClick:()=>a.onOpenChange(!1),children:e.jsx(P,{className:"h-4 w-4"})})]}),e.jsx("label",{className:"font-mono text-sm",children:"Display name"}),e.jsx("input",{value:r,onChange:c=>j(c.target.value),className:"field"}),e.jsx("label",{className:"font-mono text-sm",children:"Replace provider API key"}),e.jsx("input",{type:"password",value:h,onChange:c=>n(c.target.value),placeholder:"Leave empty to keep current credential",className:"field"}),e.jsx("label",{className:"font-mono text-sm",children:"Base URL override"}),e.jsx("input",{value:f,onChange:c=>v(c.target.value),placeholder:"Leave empty to use default endpoint",className:"field"}),e.jsx("button",{type:"button",onClick:()=>void s(),className:"px-4 py-2 rounded-md text-white bg-green-600",children:"Save"})]})})}const ee={anthropic:{bg:"#d97757",label:"A"},gemini:{bg:"#4285f4",label:"G"},"azure-openai":{bg:"#0078d4",label:"Az"},"gpt-openai-platform":{bg:"#10a37f",label:"GP"}};function ie(){var z;const{isSettingsOpen:a,toggleSettings:r,isSidebarOpen:j,setSidebarOpen:f}=_(),{configuredModels:v,loadModels:h}=H(),n=J(),[s,c]=l.useState("general"),[i,m]=l.useState(!1),[k,w]=l.useState(null),[b,C]=l.useState(null),[F,E]=l.useState(""),[S,N]=l.useState("all"),y=[{value:"general",label:"General"},{value:"models",label:"Models"},{value:"shortcuts",label:"Shortcuts"}],A=l.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 d=t.action.toLowerCase().includes(F.toLowerCase()),x=S==="all"||t.scope.toLowerCase()===S;return d&&x}),o=v.reduce((t,d)=>{const x=d.provider||"unknown";return t[x]||(t[x]=[]),t[x].push(d),t},{});l.useEffect(()=>{a&&(h(),n.loadSettings())},[a,h,n.loadSettings]);const R=async t=>{try{if(!(await fetch("/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t.provider,displayName:t.displayName,model:t.model,apiKey:t.apiKey})})).ok)throw new Error("Failed to save model");await h()}catch(d){console.error("Failed to save model:",d)}},U=async t=>{try{if(!(await fetch(`/models/${t}`,{method:"DELETE"})).ok)throw new Error("Failed to delete model");await h()}catch(d){console.error("Failed to delete model:",d)}},G=async(t,d)=>{try{if(!(await fetch(`/models/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).ok)throw new Error("Failed to update model");await h()}catch(x){console.error("Failed to update model:",x)}},I=t=>{w(k===t?null:t)};return e.jsxs(e.Fragment,{children:[e.jsx(O,{open:a,onOpenChange:r,children:e.jsxs(M,{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(T,{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:y.map(t=>e.jsx("button",{onClick:()=>c(t.value),className:u("w-full text-left px-3 py-2 rounded-md text-sm font-mono transition-colors",s===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:s==="general"?"Settings":(z=y.find(t=>t.value===s))==null?void 0:z.label}),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(P,{className:"h-4 w-4"})})]}),s==="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(o).map(([t,d])=>{const x=ee[t]||{bg:"#71717a",label:"?"},K=k===t;return e.jsxs("div",{className:"w-full bg-[#F3F4F6] dark:bg-[#18181b] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>I(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:x.bg},children:x.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:[d.length," model",d.length>1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:u("text-xs font-mono","text-[#16A34A]"),children:"● Connected"}),e.jsx(L,{className:u("h-4 w-4 text-[#9CA3AF] dark:text-[#71717a] transition-transform",K&&"rotate-180")})]})]}),K&&e.jsx("div",{className:"border-t border-[#E5E7EB] dark:border-zinc-800",children:d.map(p=>{var D;return 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:p.displayName||p.model}),e.jsxs("span",{className:"text-xs text-[#9CA3AF] dark:text-[#71717a] font-mono truncate",children:[p.displayName&&`${p.model} · `,((D=p.overrides)==null?void 0:D.baseUrl)||"default endpoint"]})]}),e.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>C(p),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(q,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>U(p.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(V,{className:"h-3.5 w-3.5"})})]})]},p.id)})})]},t)}),Object.keys(o).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:()=>m(!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"})]}),s==="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:n.language,onChange:t=>n.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:n.autoSaveSessions,onChange:t=>n.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:()=>n.updateSettings({uiTheme:t}),className:u("px-3 py-1 rounded text-[12px] font-mono transition-colors",n.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:!j,onChange:t=>f(!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:n.theme,onChange:t=>n.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:n.notifyBuild,onChange:t=>n.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:n.notifyErrors,onChange:t=>n.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:n.notifySounds,onChange:t=>n.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:n.privacyTelemetry,onChange:t=>n.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:n.privacyCrash,onChange:t=>n.updateSettings({privacyCrash:t})})]})]})]}),s==="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:F,onChange:t=>E(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:S,onChange:t=>N(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:()=>{E(""),N("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"})]}),A.map((t,d)=>e.jsxs("div",{className:u("grid grid-cols-[1fr_180px_120px] gap-2 px-3 py-2 text-[13px] font-mono",d%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(x=>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:x},x))}),e.jsx("span",{className:"text-[#6B7280] dark:text-[#94a3b8] text-[12px]",children:t.scope})]},`${t.action}-${t.scope}`)),A.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(X,{open:i,onOpenChange:m,onSave:R}),e.jsx(Z,{open:!!b,onOpenChange:t=>!t&&C(null),model:b,onSave:G})]})}function g({enabled:a,onChange:r}){return e.jsx("button",{onClick:()=>r(!a),className:u("w-10 h-5 rounded-full px-0.5 flex items-center transition-colors",a?"bg-[#22C55E]":"bg-[#E5E7EB] dark:bg-[#27272a]"),children:e.jsx("span",{className:u("h-4 w-4 rounded-full transition-transform",a?"translate-x-5 bg-white":"translate-x-0 bg-white dark:bg-[#a1a1aa]")})})}export{ie as SettingsModal};
@@ -1 +1 @@
1
- import{g as n}from"./index-B3dW1Scg.js";const c=s=>s==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches:s==="dark",i=s=>{const t=document.documentElement;if(t.classList.remove("light","dark"),s==="system"){const r=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";t.classList.add(r)}else t.classList.add(s)},o={language:"zh-CN",theme:"dracula",uiTheme:"system",autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0},l=n((s,t)=>({...o,isLoading:!1,error:null,loadSettings:async()=>{s({isLoading:!0,error:null});try{const r=await fetch("/configs");if(!r.ok)throw new Error("Failed to load settings");const e=await r.json(),a=e.uiTheme??o.uiTheme;s({language:e.language??o.language,theme:e.theme??o.theme,uiTheme:a,autoSaveSessions:e.autoSaveSessions??o.autoSaveSessions,notifyBuild:e.notifyBuild??o.notifyBuild,notifyErrors:e.notifyErrors??o.notifyErrors,notifySounds:e.notifySounds??o.notifySounds,privacyTelemetry:e.privacyTelemetry??o.privacyTelemetry,privacyCrash:e.privacyCrash??o.privacyCrash,isLoading:!1}),i(a)}catch(r){s({error:r.message,isLoading:!1})}},updateSettings:async r=>{const e=t();s({...r,error:null}),r.uiTheme&&i(r.uiTheme);try{if(!(await fetch("/configs",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:r,options:{scope:"global"}})})).ok)throw new Error("Failed to save settings")}catch(a){s({language:e.language,theme:e.theme,uiTheme:e.uiTheme,autoSaveSessions:e.autoSaveSessions,notifyBuild:e.notifyBuild,notifyErrors:e.notifyErrors,notifySounds:e.notifySounds,privacyTelemetry:e.privacyTelemetry,privacyCrash:e.privacyCrash,error:a.message}),r.uiTheme&&i(e.uiTheme)}}}));i(o.uiTheme);const u=()=>l(s=>c(s.uiTheme));export{u as a,l as u};
1
+ import{h as n}from"./index-BC0ssrep.js";const c=s=>s==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches:s==="dark",i=s=>{const t=document.documentElement;if(t.classList.remove("light","dark"),s==="system"){const r=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";t.classList.add(r)}else t.classList.add(s)},o={language:"zh-CN",theme:"dracula",uiTheme:"system",autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0},l=n((s,t)=>({...o,isLoading:!1,error:null,loadSettings:async()=>{s({isLoading:!0,error:null});try{const r=await fetch("/configs");if(!r.ok)throw new Error("Failed to load settings");const e=await r.json(),a=e.uiTheme??o.uiTheme;s({language:e.language??o.language,theme:e.theme??o.theme,uiTheme:a,autoSaveSessions:e.autoSaveSessions??o.autoSaveSessions,notifyBuild:e.notifyBuild??o.notifyBuild,notifyErrors:e.notifyErrors??o.notifyErrors,notifySounds:e.notifySounds??o.notifySounds,privacyTelemetry:e.privacyTelemetry??o.privacyTelemetry,privacyCrash:e.privacyCrash??o.privacyCrash,isLoading:!1}),i(a)}catch(r){s({error:r.message,isLoading:!1})}},updateSettings:async r=>{const e=t();s({...r,error:null}),r.uiTheme&&i(r.uiTheme);try{if(!(await fetch("/configs",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:r,options:{scope:"global"}})})).ok)throw new Error("Failed to save settings")}catch(a){s({language:e.language,theme:e.theme,uiTheme:e.uiTheme,autoSaveSessions:e.autoSaveSessions,notifyBuild:e.notifyBuild,notifyErrors:e.notifyErrors,notifySounds:e.notifySounds,privacyTelemetry:e.privacyTelemetry,privacyCrash:e.privacyCrash,error:a.message}),r.uiTheme&&i(e.uiTheme)}}}));i(o.uiTheme);const u=()=>l(s=>c(s.uiTheme));export{u as a,l as u};