blade-code 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-1vngdr7p.js +1 -0
- package/dist/{chunk-275gt6q1.js → chunk-373pmz70.js} +1 -1
- package/dist/{chunk-1w719wd9.js → chunk-38h3yh6z.js} +1 -1
- package/dist/{chunk-zcreym5g.js → chunk-3mhbped9.js} +33 -33
- package/dist/{chunk-k18bq4mn.js → chunk-4e2fzyf2.js} +2 -2
- package/dist/{chunk-p9pthxkm.js → chunk-501my8nh.js} +1 -1
- package/dist/{chunk-wc2xb6ge.js → chunk-5smacbk0.js} +2 -2
- package/dist/{chunk-cadngkwr.js → chunk-63dzf6hr.js} +1 -1
- package/dist/{chunk-t6y57501.js → chunk-6rszb7xd.js} +363 -362
- package/dist/{chunk-t3pyakvc.js → chunk-7mnefph6.js} +2 -2
- package/dist/{chunk-m4a480k7.js → chunk-98jpdmgc.js} +2 -2
- package/dist/chunk-aevyre2t.js +1 -0
- package/dist/{chunk-qw2wy4jc.js → chunk-b1d49byc.js} +1 -1
- package/dist/chunk-b4hmtjec.js +1 -0
- package/dist/{chunk-xa8szzc6.js → chunk-bmcc85nj.js} +1 -1
- package/dist/{chunk-67zx7ymj.js → chunk-by93yn92.js} +1 -1
- package/dist/{chunk-8xdqtspw.js → chunk-byxazdwv.js} +1 -1
- package/dist/chunk-cqrg2pp7.js +1 -0
- package/dist/{chunk-ztpseq3n.js → chunk-ctbhcw8h.js} +1 -1
- package/dist/{chunk-m2k4h3bs.js → chunk-cw125vv3.js} +1 -1
- package/dist/{chunk-wcm0nc84.js → chunk-cyxb6fxe.js} +1 -1
- package/dist/chunk-dftaxwg9.js +1 -0
- package/dist/{chunk-z0qxaky4.js → chunk-e21htmg4.js} +1 -1
- package/dist/{chunk-g0h3rans.js → chunk-egavbybx.js} +2 -2
- package/dist/{chunk-rmtcqc8q.js → chunk-erpgkabk.js} +1 -1
- package/dist/{chunk-9zwf87ne.js → chunk-gjf2d2yg.js} +1 -1
- package/dist/chunk-gzc9n5d6.js +2 -0
- package/dist/{chunk-p6d7k1x6.js → chunk-jf48kahn.js} +3 -3
- package/dist/{chunk-1mge0pzv.js → chunk-jpry8h07.js} +1 -1
- package/dist/{chunk-cqrkeq20.js → chunk-k4behavv.js} +1 -1
- package/dist/{chunk-cfrbsnfb.js → chunk-kfg3vx5z.js} +1 -1
- package/dist/chunk-n5rg9dbv.js +151 -0
- package/dist/chunk-pa364yr9.js +1 -0
- package/dist/{chunk-rr62k3ar.js → chunk-pvxp2gzr.js} +1 -1
- package/dist/{chunk-f9b8h03c.js → chunk-qxvp127d.js} +1 -1
- package/dist/{chunk-b6mxeey0.js → chunk-rkhhzc4r.js} +2 -2
- package/dist/{chunk-22gxb9qs.js → chunk-rtn0rb16.js} +2 -2
- package/dist/chunk-w1zb8zac.js +3 -0
- package/dist/chunk-z7x21493.js +7 -0
- package/dist/web/assets/{FilePreview-DXDzoFFc.js → FilePreview-evNzCuVx.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BVPOLK1b.js → MarkdownRenderer-BQoiQTDd.js} +1 -1
- package/dist/web/assets/{McpModal-DeTf34Fw.js → McpModal-BT9OivhK.js} +1 -1
- package/dist/web/assets/{SettingsModal-CDLkPyL-.js → SettingsModal-CDRcorCS.js} +1 -1
- package/dist/web/assets/{SettingsStore-DYKvNeV_.js → SettingsStore-CfDjhOkS.js} +1 -1
- package/dist/web/assets/{SkillsModal-D784AUrt.js → SkillsModal-DCPaqoOe.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BosJuIct.js → TerminalPanel-Cs16_6ew.js} +1 -1
- package/dist/web/assets/{dialog-CgyS_4Eo.js → dialog-C8VDk-ma.js} +1 -1
- package/dist/web/assets/index-9t-WxRrl.js +10 -0
- package/dist/web/assets/index-Bu13aXyE.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-108p1xw7.js +0 -1
- package/dist/chunk-42q476bq.js +0 -1
- package/dist/chunk-4hk7wfat.js +0 -3
- package/dist/chunk-7d1pn8a1.js +0 -2
- package/dist/chunk-abpvdaq2.js +0 -6
- package/dist/chunk-hv0bzn31.js +0 -1
- package/dist/chunk-j3k2c6tm.js +0 -1
- package/dist/chunk-je6r01h4.js +0 -1
- package/dist/chunk-nh37erd3.js +0 -1
- package/dist/chunk-z72cp8f5.js +0 -150
- package/dist/web/assets/index-Abieffcr.js +0 -10
- package/dist/web/assets/index-CQ3JnuUf.css +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Da as a,Ea as b,Fa as c,Ga as d,Ha as e,Ia as f}from"./chunk-4e2fzyf2.js";import"./chunk-kfg3vx5z.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ub as Q,vb as W,wb as Y}from"./chunk-98jpdmgc.js";import{Lb as X}from"./chunk-w1zb8zac.js";var J=X("Service"),$="https://models.dev/api.json",j=3600000,G=null,Z=async()=>{if(G&&Date.now()-G.timestamp<j)return G.data;try{J.info("Fetching models.dev data...");let q=await fetch($,{headers:{"User-Agent":"Blade-CLI/1.0"}});if(!q.ok)throw Error(`HTTP ${q.status}: ${q.statusText}`);let x=await q.json();return G={data:x,timestamp:Date.now()},J.info(`Loaded ${Object.keys(x).length} providers from models.dev`),x}catch(q){throw J.error("Failed to fetch models.dev data:",q),q}},y=async()=>{let q=await Z(),x=[];for(let[w,k]of Object.entries(q)){let z=Object.keys(k.models||{}).length;if(z===0)continue;x.push({id:w,name:k.name||w,icon:W[w]||W.default,description:`${z} 个模型`,envVars:k.env||[],docUrl:k.doc,defaultBaseUrl:Y[w]})}return x.sort((w,k)=>{let z=Q.indexOf(w.id),K=Q.indexOf(k.id);if(z!==-1&&K!==-1)return z-K;if(z!==-1)return-1;if(K!==-1)return 1;return w.name.localeCompare(k.name)})},f=async(q)=>{let w=(await Z())[q];if(!w?.models)return J.warn(`No models found for provider: ${q}`),[];return Object.values(w.models).map((k)=>({id:k.id,name:k.name||k.id,contextWindow:k.limit?.context,maxOutput:k.limit?.output,inputCost:k.cost?.input,outputCost:k.cost?.output}))};
|
|
2
2
|
export{y as j,f as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-kfg3vx5z.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{tb as $}from"./chunk-63dzf6hr.js";import{Lb as w}from"./chunk-w1zb8zac.js";var F={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as T}from"fs";import{merge as _}from"lodash-es";import I from"os";import G from"path";var M={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function U(J){let q=J.toLowerCase().trim();return M[q]??J}class B{static instance=null;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async initialize(J){try{let q=await this.loadConfigFiles(),H=await this.loadSettingsFiles(),K={...q,...H};if(J)K=this.mergeSettings(K,J);let Q=this.normalizeConfig(K),W={...F,...Q};if(this.resolveEnvInterpolation(W),process.env.BLADE_MODEL&&W.models?.length>0){let X=U(process.env.BLADE_MODEL),Y=W.models.find((Z)=>Z.id===X||Z.model===X||Z.id===process.env.BLADE_MODEL||Z.model===process.env.BLADE_MODEL);if(Y)W.currentModelId=Y.id}if(process.env.BLADE_API_KEY&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.apiKey=process.env.BLADE_API_KEY}if(process.env.BLADE_BASE_URL&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.baseUrl=process.env.BLADE_BASE_URL}if(process.env.BLADE_DEBUG)W.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(W.debug)console.log("[ConfigManager] Configuration loaded successfully");return W}catch(q){return console.error("[ConfigManager] Failed to initialize:",q),F}}async loadConfigFiles(){let J=G.join(I.homedir(),".blade","config.json"),q=G.join($(),".blade","config.json"),H={},K=await this.loadJsonFile(J);if(K)H={...H,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...H.mcpServers||{},...Q.mcpServers||{}};if(H={...H,...Q},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=G.join(I.homedir(),".blade","settings.json"),q=G.join($(),".blade","settings.json"),H=G.join($(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(J);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(H);if(X)K=this.mergeSettings(K,X);return K}mergeSettings(J,q){let H={...JSON.parse(JSON.stringify(J)),...JSON.parse(JSON.stringify(q))};if(q.permissions)H.permissions={allow:Array.from(new Set([...J.permissions?.allow||[],...q.permissions.allow||[]])),ask:Array.from(new Set([...J.permissions?.ask||[],...q.permissions.ask||[]])),deny:Array.from(new Set([...J.permissions?.deny||[],...q.permissions.deny||[]]))};if(q.hooks)H.hooks=_({},H.hooks,q.hooks);if(q.env)H.env=_({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,Z)=>{return process.env[X]||Z||W});if(Array.isArray(Q))return Q.map(H);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return Q},K=J;for(let[Q,W]of Object.entries(K))K[Q]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await T.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await T.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=H(X);else if(Array.isArray(X))X.forEach((Y,Z)=>{if(typeof Y==="string")X[Z]=H(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(J){let q=[],H=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((Q)=>Q.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let K of J.models){let Q=`模型 "${K.name||K.id}"`;if(!K.apiKey)H.push(`${Q}: apiKey 为空`);if(!K.model)q.push(`${Q}: model 字段必填`);if(!K.provider)q.push(`${Q}: provider 字段必填`);if(K.baseUrl&&!K.baseUrl.startsWith("http"))H.push(`${Q}: baseUrl "${K.baseUrl}" 不是有效的 HTTP URL`)}}if(H.length>0)console.warn(`[ConfigManager] 配置警告:
|
|
2
2
|
${H.map((K)=>` ⚠ ${K}`).join(`
|
|
3
3
|
`)}`);if(q.length>0)throw Error(`配置验证失败:
|
|
4
4
|
${q.map((K)=>` - ${K}`).join(`
|
|
@@ -23,4 +23,4 @@ ${q.map((K)=>` - ${K}`).join(`
|
|
|
23
23
|
}
|
|
24
24
|
]
|
|
25
25
|
}
|
|
26
|
-
`)}}function j(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{Mutex as A}from"async-mutex";import{merge as b}from"lodash-es";import{promises as N}from"node:fs";import E from"node:os";import V from"node:path";import x from"write-file-atomic";var L=w("Service"),R={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},Hq=new Set(Object.entries(R).filter(([J,q])=>q.persistable).map(([J])=>J)),Jq=new Set(Object.entries(R).filter(([J,q])=>!q.persistable).map(([J])=>J));class z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!z.instance)z.instance=new z;return z.instance}static resetInstance(){if(z.instance)for(let J of z.instance.timers.values())clearTimeout(J);z.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){let H=q.scope??"local",K=this.resolveFilePath("settings",H);await this.flushTargetWithModifier(K,(Q)=>{let W=Q.permissions??{allow:[],ask:[],deny:[]},X={allow:this.dedupeArray([...W.allow||[],J]),ask:W.ask||[],deny:W.deny||[]};return{...Q,permissions:X}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=R[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q){let H=new Map;for(let[K,Q]of Object.entries(J)){let W=R[K];if(!W)continue;let X=q??W.defaultScope,Y=this.resolveFilePath(W.target,X);if(!H.has(Y))H.set(Y,{});H.get(Y)[K]=Q}return H}resolveFilePath(J,q){if(J==="config")return q==="global"?V.join(E.homedir(),".blade","config.json"):V.join($(),".blade","config.json");switch(q){case"local":return V.join($(),".blade","settings.local.json");case"project":return V.join($(),".blade","settings.json");case"global":return V.join(E.homedir(),".blade","settings.json");default:return V.join($(),".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=Z,L.error(`Failed to save config to ${J}:`,Z.message),L.error("Stack trace:",Z.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=R[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await N.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await N.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=R[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=b({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await x(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function S(){return z.getInstance()}export{F as
|
|
26
|
+
`)}}function j(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{Mutex as A}from"async-mutex";import{merge as b}from"lodash-es";import{promises as N}from"node:fs";import E from"node:os";import V from"node:path";import x from"write-file-atomic";var L=w("Service"),R={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},Hq=new Set(Object.entries(R).filter(([J,q])=>q.persistable).map(([J])=>J)),Jq=new Set(Object.entries(R).filter(([J,q])=>!q.persistable).map(([J])=>J));class z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!z.instance)z.instance=new z;return z.instance}static resetInstance(){if(z.instance)for(let J of z.instance.timers.values())clearTimeout(J);z.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){let H=q.scope??"local",K=this.resolveFilePath("settings",H);await this.flushTargetWithModifier(K,(Q)=>{let W=Q.permissions??{allow:[],ask:[],deny:[]},X={allow:this.dedupeArray([...W.allow||[],J]),ask:W.ask||[],deny:W.deny||[]};return{...Q,permissions:X}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=R[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q){let H=new Map;for(let[K,Q]of Object.entries(J)){let W=R[K];if(!W)continue;let X=q??W.defaultScope,Y=this.resolveFilePath(W.target,X);if(!H.has(Y))H.set(Y,{});H.get(Y)[K]=Q}return H}resolveFilePath(J,q){if(J==="config")return q==="global"?V.join(E.homedir(),".blade","config.json"):V.join($(),".blade","config.json");switch(q){case"local":return V.join($(),".blade","settings.local.json");case"project":return V.join($(),".blade","settings.json");case"global":return V.join(E.homedir(),".blade","settings.json");default:return V.join($(),".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=Z,L.error(`Failed to save config to ${J}:`,Z.message),L.error("Stack trace:",Z.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=R[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new A,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await N.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await N.mkdir(V.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await N.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=R[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=b({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await x(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function S(){return z.getInstance()}export{F as za,B as Aa,j as Ba,S as Ca};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ob as L,tb as _}from"./chunk-63dzf6hr.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
|
|
2
2
|
You have been invoked in the following environment:
|
|
3
3
|
- Primary working directory: ${B.workingDirectory}
|
|
4
4
|
- Is a git repository: ${$?"true":"false"}
|
|
@@ -25,4 +25,4 @@ ${I.join(`
|
|
|
25
25
|
|
|
26
26
|
Project root directory listing:
|
|
27
27
|
${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
|
|
28
|
-
export{v as
|
|
28
|
+
export{v as $,f as aa,x as ba};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Nb as F}from"./chunk-kfg3vx5z.js";import{appendFileSync as N,existsSync as R,mkdirSync as x,readdirSync as m,statSync as z,unlinkSync as V}from"node:fs";import Y from"node:path";import{execSync as A}from"node:child_process";import*as O from"node:os";import*as Q from"node:path";function B(q){return Q.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function v(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function U(q){let G=B(q);return Q.join(W(),"projects",G)}function _(q){if(q==="."||q===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(q))throw Error(`Invalid session ID: ${q}`)}function P(q,G){return _(G),Q.join(U(q),`${G}.jsonl`)}function f(q,G){return _(G),Q.join(U(q),`${G}.inbox.json`)}function I(q){try{return A("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function W(){return process.env.BLADE_STORAGE_ROOT||Q.join(O.homedir(),".blade")}async function h(){let{readdir:q}=await import("node:fs/promises");try{let G=Q.join(W(),"projects");return(await q(G,{withFileTypes:!0})).filter((H)=>H.isDirectory()).map((H)=>H.name)}catch{return[]}}var Z;((J)=>{J[J.DEBUG=0]="DEBUG";J[J.INFO=1]="INFO";J[J.WARN=2]="WARN";J[J.ERROR=3]="ERROR"})(Z||={});var X=null,k=null,w=!1;function L(q){if(X!==q)X=q}async function d(){}function j(){if(w)return k;w=!0;try{let q=Y.join(W(),"logs");if(!R(q))x(q,{recursive:!0,mode:493});if(z(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return C(q,30),k=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function C(q,G){try{let K=m(q),H=Date.now(),J=G*24*60*60*1000;for(let T of K){if(!T.startsWith("blade-")||!T.endsWith(".log")&&!T.endsWith(".jsonl"))continue;let $=Y.join(q,T);try{let E=z($);if(H-E.mtimeMs>J)V($)}catch(E){}}}catch(K){}}function b(){let q=j();if(!q)return null;let G=X||"default";return Y.join(q,`blade-${G}.jsonl`)}function D(q,G,K){let H=b();if(!H)return;try{let J={timestamp:new Date().toISOString(),level:Z[G],category:q,message:K};N(H,JSON.stringify(J)+`
|
|
2
|
+
`)}catch(J){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((J)=>J.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((H)=>H.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((K)=>G.includes(K.toLowerCase()));return!q.categories.some((K)=>G.includes(K.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:K}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(K)}return this.enabled&&q>=this.minLevel}log(q,...G){let K=G.map((H)=>typeof H==="object"?JSON.stringify(H):String(H)).join(" ");if(D(this.category,q,K),this.shouldLogToConsole(q)){let H=Z[q],J=`[${this.category}] [${H}]`;console.error(J,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function n(q,G){return new M({...G,category:q})}var i=new M({category:"General"});
|
|
3
|
+
export{v as Bb,U as Cb,P as Db,f as Eb,I as Fb,W as Gb,h as Hb,L as Ib,d as Jb,M as Kb,n as Lb,i as Mb};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{B as W,H as P,K as T,L as R,N as M,Q as B,T as j,V as A,W as h}from"./chunk-6rszb7xd.js";import"./chunk-e21htmg4.js";import{_ as x}from"./chunk-7mnefph6.js";import"./chunk-rtn0rb16.js";import{ra as y}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-4e2fzyf2.js";import{Va as L}from"./chunk-3mhbped9.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{tb as U}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import{Lb as _}from"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import{Readable as c,Writable as p}from"node:stream";import*as w from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as C}from"@agentclientprotocol/sdk";import{nanoid as v}from"nanoid";import{nanoid as k}from"nanoid";var Z=_("Agent");function f(z){return Object.fromEntries(z.map((G)=>[G.name,G.value]))}function S(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function u(z){return Object.fromEntries(z.map((G)=>[G.name,S(G)]))}function O(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((G)=>{if(G.type==="text")return G.text?[{type:"text",text:G.text}]:[];let H=G.image_url.url,J=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!J)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:J[1]??"image/png",data:J[2]??""}]})}class D{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;messages;mode="default";sessionApprovals=new Set;constructor(z,G,H,J,Q={}){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=J;this.options=Q;this.messages=[...Q.initialMessages??[]]}async initialize(){Z.debug(`[AcpSession ${this.id}] Initializing...`),W.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),Z.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?u(this.options.mcpServers):void 0;if(this.runtime=await P.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await M.createWithRuntime(this.runtime,{sessionId:this.id}),Z.debug(`[AcpSession ${this.id}] Agent created successfully`),this.runtime.getPendingSteeringCount()>0)if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){let G=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!G)continue;for(let H of O(z.content))await this.connection.sessionUpdate({sessionId:this.id,update:{sessionUpdate:G,content:H}})}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){Z.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{Z.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(X)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}})},sendToolStart:(X,Y,E)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,$=this.mapToolKind(E);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${X}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:$})},sendToolResult:(X,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},J=await A(z,H),Q=J.content||J.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(J.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${J.error}`}});return{stopReason:J.success?"end_turn":"cancelled"}}catch(H){return Z.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=h(),G=["model","permissions","theme","config","exit","ide"],J=z.filter((Q)=>!G.includes(Q.name)).map((Q)=>{let X;if(Q.usage){let Y=Q.usage.replace(/^\/\w+\s*/,"").trim();if(Y)X=Y}if(Q.aliases?.length){let Y=`Aliases: ${Q.aliases.join(", ")}`;X=X?`${X} | ${Y}`:Y}return{name:Q.name,description:Q.description,input:X?{hint:X}:void 0}});Z.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(J.map((Q)=>Q.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:J}),Z.info(`[AcpSession ${this.id}] Sent ${J.length} available commands`)}catch(z){Z.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,G={}){if(W.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt);if(this.pendingPrompt){let Q=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!Q.accepted)throw Error(Q.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(Z.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Q.queued})`),Q.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let J=new AbortController;this.pendingPrompt=J;try{if(Z.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),j(H))return await this.handleSlashCommand(H,J.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:J.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(X)=>{return this.requestPermission(X)}}};if(await L(this.agent.chatStream(H,Q,{pendingInputOnly:G.pendingInputOnly}),async(X)=>{switch(X.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:X.delta}});break;case"tool_start":{let Y=X.toolCall,E="function"in Y?Y.function.name:Y.type,F=this.mapToolKind(X.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.id,status:"in_progress",title:`Executing ${E}`,content:[],kind:F});break}case"tool_result":{let{toolCall:Y,result:E}=X,F=[],$=E.metadata;if($?.kind==="edit"&&typeof $.file_path==="string"&&typeof $.oldContent==="string"&&(typeof $.newContent==="string"||$.newContent===void 0))F.push({type:"diff",path:$.file_path,oldText:$.oldContent,newText:$.newContent??null});else{let I="function"in Y?Y.function.name:Y.type,K=R(T(I,E));F.push({type:"content",content:{type:"text",text:K}})}let V=E.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.id,status:V,content:F});break}case"task_update":this.sendPlanUpdate(X.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Y of X.messages){if(!Y.recovered||Y.persisted)continue;for(let E of O(Y.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:E})}if(X.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${X.recovered} queued instruction${X.recovered===1?"":"s"} recovered after restart]
|
|
2
|
+
`}});break;default:break}}),this.messages=[...Q.messages],J.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(Q){if(J.signal.aborted||Q instanceof Error&&Q.name==="AbortError")return{stopReason:"cancelled"};throw Z.error(`[AcpSession ${this.id}] Prompt error:`,Q),Q}finally{if(this.pendingPrompt===J){if(this.pendingPrompt=null,this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.pendingPrompt||!this.runtime||!this.agent)return;if(this.runtime.getPendingSteeringCount()===0){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:!0}).catch((z)=>{Z.error(`[AcpSession ${this.id}] Failed to resume pending input:`,z)})}cancel(){if(Z.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,Z.info(`[AcpSession ${this.id}] Cancelled successfully`);else Z.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",Z.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(Z.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;W.destroySession(this.id),Z.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let J=H.resource;if("text"in J)G.push(`<file path="${J.uri}">
|
|
3
|
+
${J.text}
|
|
4
|
+
</file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
|
|
5
|
+
`)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{Z.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));Z.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return Z.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return Z.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return Z.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let J=k(),Q=[];if(z.message)Q.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)Q.push({type:"content",content:{type:"text",text:`Risks:
|
|
6
|
+
- ${z.risks.join(`
|
|
7
|
+
- `)}`}});let X=this.mapToolKind(G),Y={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:J,status:"pending",title:z.title||"Permission Required",content:Q,kind:X}},F=(await this.connection.requestPermission(Y)).outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let $=F.optionId,V=$==="allow_once"||$==="allow_always";if($==="allow_always")this.sessionApprovals.add(H),Z.debug(`[AcpSession ${this.id}] Cached approval for: ${H}`);return{approved:V,reason:V?void 0:"User denied the operation"}}catch(J){return Z.warn(`[AcpSession ${this.id}] Permission request failed:`,J),{approved:!1,reason:"Permission request failed"}}}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var q=_("Agent");class N{connection;sessions=new Map;clientCapabilities;constructor(z){this.connection=z}async initialize(z){return q.info("[BladeAgent] Initializing ACP connection"),q.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:C,agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){let G=v();q.info(`[BladeAgent] Creating new session: ${G}`),q.debug(`[BladeAgent] Session cwd: ${z.cwd||U()}`);let H=new D(G,z.cwd||U(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await H.initialize()}catch(J){throw await H.destroy().catch(()=>{return}),J}return this.sessions.set(G,H),q.info(`[BladeAgent] Session ${G} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),{sessionId:G,...this.buildSessionState()}}async loadSession(z){q.info(`[BladeAgent] Loading session: ${z.sessionId}`);let G=await B.loadSession(z.sessionId,z.cwd),H=this.sessions.get(z.sessionId);if(H)await H.destroy(),this.sessions.delete(z.sessionId),G=await B.loadSession(z.sessionId,z.cwd);let J=new D(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:G,mcpServers:z.mcpServers});try{await J.initialize(),await J.replayHistory()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(z.sessionId,J),J.sendAvailableCommandsDelayed(),this.buildSessionState()}buildSessionState(){let z=y(),G=z?.models||[],H=z?.currentModelId||G[0]?.id,J=G.map((X)=>({modelId:X.id,name:X.name||X.id,description:X.provider?`Provider: ${X.provider}`:void 0}));return{modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:J.length>0?{availableModels:J,currentModelId:H}:void 0}}async prompt(z){let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return G.prompt(z)}async cancel(z){q.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let G=this.sessions.get(z.sessionId);if(G)q.info("[BladeAgent] Found session, calling session.cancel()"),G.cancel();else q.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){q.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let G=this.sessions.get(z.sessionId);if(G)await G.setMode(z.modeId);return{}}async unstable_setSessionModel(z){q.info(`[BladeAgent] Setting session model: ${z.modelId}`);let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return await G.setModel(z.modelId),{}}async destroy(){for(let z of this.sessions.values())await z.destroy();this.sessions.clear(),await x.getInstance().disconnectAll()}}async function Ez(){let z=p.toWeb(process.stdout),G=c.toWeb(process.stdin),H=w.ndJsonStream(z,G);await new w.AgentSideConnection((Q)=>new N(Q),H).closed}export{Ez as runAcpIntegration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as Q}from"./vendor-markdown-DIcugY1e.js";import{r as l,j as e}from"./vendor-react-Dm1xU4bP.js";import{c as j,u as le,b as fe,B as ue}from"./index-Abieffcr.js";import{i as xe,L as Y,j as Z,k as M}from"./vendor-radix-CfxBc_4-.js";import{u as me}from"./SettingsStore-DYKvNeV_.js";import{X as pe,i as J,l as H,g as ee,n as be,o as ge}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";const he=xe,te=l.forwardRef(({className:t,...a},r)=>e.jsx(Y,{ref:r,className:j("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...a}));te.displayName=Y.displayName;const S=l.forwardRef(({className:t,...a},r)=>e.jsx(Z,{ref:r,className:j("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),...a}));S.displayName=Z.displayName;const L=l.forwardRef(({className:t,...a},r)=>e.jsx(M,{ref:r,className:j("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));L.displayName=M.displayName;const ye={"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 ke(t){const a=t.replace("#",""),r=parseInt(a.substring(0,2),16),s=parseInt(a.substring(2,4),16),o=parseInt(a.substring(4,6),16);return(.299*r+.587*s+.114*o)/255<.5}function ve(t){return{base:ke(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 K=new Set;function U(t,a){const r=a.toLowerCase().replace(/\s+/g,"-"),s=ye[r];if(!s)return"vs-dark";if(!K.has(r)){const o=ve(s);t.editor.defineTheme(r,o),K.add(r)}return r}l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).DiffEditor}));const Ee=l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).Editor}));function Re(){const{toggleFilePreview:t}=le(),{messages:a,currentSessionId:r}=fe(),[s,o]=l.useState("diff"),[c,i]=l.useState([]),[d,u]=l.useState({}),[x,p]=l.useState(!1),[g,b]=l.useState(null),[F,k]=l.useState({}),[w,T]=l.useState({}),[h,P]=l.useState(null),[re,A]=l.useState(""),[D,z]=l.useState(!1),[_,$]=l.useState(null),[W,R]=l.useState(!1),I=async(n="")=>{try{const f=n?`/suggestions/files/tree?path=${encodeURIComponent(n)}`:"/suggestions/files/tree",m=await fetch(f);if(!m.ok)throw new Error("Failed to load tree");return(await m.json()).map(B=>({...B,children:B.type==="dir"?[]:void 0}))}catch{return[]}};l.useEffect(()=>{let n=!0;return(async()=>{p(!0),b(null);try{const m=await I();n&&i(m)}catch(m){n&&b(m.message)}finally{n&&p(!1)}})(),()=>{n=!1}},[r]),l.useEffect(()=>{P(null),A(""),$(null),R(!1),k({}),u({})},[r]);const C=l.useMemo(()=>Ne(a),[a]),O=l.useMemo(()=>we(a),[a]),[ne,se]=l.useState({}),oe=n=>{se(f=>({...f,[n]:!f[n]}))},de=async n=>{P(n),A(""),z(!0),$(null),R(!1);try{const f=await fetch(`/suggestions/files/content?path=${encodeURIComponent(n)}`);if(!f.ok)throw new Error("Failed to load file");const m=await f.json();A(m.content||""),R(!!m.truncated)}catch(f){$(f.message)}finally{z(!1)}},ie=async n=>{const f=!F[n];if(k(m=>({...m,[n]:f})),f&&!d[n]){const m=await I(n);u(y=>({...y,[n]:m}))}},ce=n=>{T(f=>({...f,[n]:!f[n]}))};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(ue,{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(pe,{className:"w-4 h-4"})})]}),e.jsxs(he,{value:s,onValueChange:n=>o(n),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(te,{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(S,{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(S,{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(S,{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(L,{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:C.length===0?e.jsx(N,{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:[C.length," changed file",C.length>1?"s":""]}),C.map(n=>{var y;const f=((y=n.filePath)==null?void 0:y.split("/").pop())||"unknown",m=ne[n.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>oe(n.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:[m?e.jsx(J,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(H,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(ee,{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:f}),n.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:n.summary})]}),m&&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:n.filePath}),e.jsx(Be,{diff:n.diff})]})]},n.filePath)})]})})}),e.jsx(L,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(N,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&g&&e.jsx(N,{title:"Failed to load files",subtitle:g}),!x&&!g&&c.length===0&&e.jsx(N,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!g&&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(n=>e.jsx(ae,{node:n,depth:0,expandedDirs:F,childrenCache:d,toggleDir:ie,selectedPath:h,onSelectFile:de},n.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:h||"Select a file to preview"}),h&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:D?"Loading…":W?"Truncated":"Ready"})]}),W&&!D&&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:[!h&&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."}),h&&_&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:_}),h&&!_&&e.jsx("div",{className:"h-full",children:D?e.jsx(q,{}):e.jsx(l.Suspense,{fallback:e.jsx(q,{}),children:e.jsx(Fe,{content:re,filename:h})})})]})]})]})]})}),e.jsx(L,{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:O.length===0?e.jsx(N,{title:"No logs yet",subtitle:"Tool runs will appear here."}):O.map(n=>{var V;const f=w[n.id],m=(n.content||"").split(`
|
|
1
|
+
import{_ as Q}from"./vendor-markdown-DIcugY1e.js";import{r as l,j as e}from"./vendor-react-Dm1xU4bP.js";import{c as j,u as le,b as fe,B as ue}from"./index-9t-WxRrl.js";import{i as xe,L as Y,j as Z,k as M}from"./vendor-radix-CfxBc_4-.js";import{u as me}from"./SettingsStore-CfDjhOkS.js";import{X as pe,i as J,l as H,g as ee,n as be,o as ge}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";const he=xe,te=l.forwardRef(({className:t,...a},r)=>e.jsx(Y,{ref:r,className:j("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...a}));te.displayName=Y.displayName;const S=l.forwardRef(({className:t,...a},r)=>e.jsx(Z,{ref:r,className:j("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),...a}));S.displayName=Z.displayName;const L=l.forwardRef(({className:t,...a},r)=>e.jsx(M,{ref:r,className:j("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));L.displayName=M.displayName;const ye={"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 ke(t){const a=t.replace("#",""),r=parseInt(a.substring(0,2),16),s=parseInt(a.substring(2,4),16),o=parseInt(a.substring(4,6),16);return(.299*r+.587*s+.114*o)/255<.5}function ve(t){return{base:ke(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 K=new Set;function U(t,a){const r=a.toLowerCase().replace(/\s+/g,"-"),s=ye[r];if(!s)return"vs-dark";if(!K.has(r)){const o=ve(s);t.editor.defineTheme(r,o),K.add(r)}return r}l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).DiffEditor}));const Ee=l.lazy(async()=>({default:(await Q(()=>import("./vendor-react-Dm1xU4bP.js").then(a=>a.k),[])).Editor}));function Re(){const{toggleFilePreview:t}=le(),{messages:a,currentSessionId:r}=fe(),[s,o]=l.useState("diff"),[c,i]=l.useState([]),[d,u]=l.useState({}),[x,p]=l.useState(!1),[g,b]=l.useState(null),[F,k]=l.useState({}),[w,T]=l.useState({}),[h,P]=l.useState(null),[re,A]=l.useState(""),[D,z]=l.useState(!1),[_,$]=l.useState(null),[W,R]=l.useState(!1),I=async(n="")=>{try{const f=n?`/suggestions/files/tree?path=${encodeURIComponent(n)}`:"/suggestions/files/tree",m=await fetch(f);if(!m.ok)throw new Error("Failed to load tree");return(await m.json()).map(B=>({...B,children:B.type==="dir"?[]:void 0}))}catch{return[]}};l.useEffect(()=>{let n=!0;return(async()=>{p(!0),b(null);try{const m=await I();n&&i(m)}catch(m){n&&b(m.message)}finally{n&&p(!1)}})(),()=>{n=!1}},[r]),l.useEffect(()=>{P(null),A(""),$(null),R(!1),k({}),u({})},[r]);const C=l.useMemo(()=>Ne(a),[a]),O=l.useMemo(()=>we(a),[a]),[ne,se]=l.useState({}),oe=n=>{se(f=>({...f,[n]:!f[n]}))},de=async n=>{P(n),A(""),z(!0),$(null),R(!1);try{const f=await fetch(`/suggestions/files/content?path=${encodeURIComponent(n)}`);if(!f.ok)throw new Error("Failed to load file");const m=await f.json();A(m.content||""),R(!!m.truncated)}catch(f){$(f.message)}finally{z(!1)}},ie=async n=>{const f=!F[n];if(k(m=>({...m,[n]:f})),f&&!d[n]){const m=await I(n);u(y=>({...y,[n]:m}))}},ce=n=>{T(f=>({...f,[n]:!f[n]}))};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(ue,{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(pe,{className:"w-4 h-4"})})]}),e.jsxs(he,{value:s,onValueChange:n=>o(n),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(te,{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(S,{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(S,{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(S,{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(L,{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:C.length===0?e.jsx(N,{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:[C.length," changed file",C.length>1?"s":""]}),C.map(n=>{var y;const f=((y=n.filePath)==null?void 0:y.split("/").pop())||"unknown",m=ne[n.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>oe(n.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:[m?e.jsx(J,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(H,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(ee,{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:f}),n.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:n.summary})]}),m&&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:n.filePath}),e.jsx(Be,{diff:n.diff})]})]},n.filePath)})]})})}),e.jsx(L,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(N,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&g&&e.jsx(N,{title:"Failed to load files",subtitle:g}),!x&&!g&&c.length===0&&e.jsx(N,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!g&&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(n=>e.jsx(ae,{node:n,depth:0,expandedDirs:F,childrenCache:d,toggleDir:ie,selectedPath:h,onSelectFile:de},n.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:h||"Select a file to preview"}),h&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:D?"Loading…":W?"Truncated":"Ready"})]}),W&&!D&&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:[!h&&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."}),h&&_&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:_}),h&&!_&&e.jsx("div",{className:"h-full",children:D?e.jsx(q,{}):e.jsx(l.Suspense,{fallback:e.jsx(q,{}),children:e.jsx(Fe,{content:re,filename:h})})})]})]})]})]})}),e.jsx(L,{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:O.length===0?e.jsx(N,{title:"No logs yet",subtitle:"Tool runs will appear here."}):O.map(n=>{var V;const f=w[n.id],m=(n.content||"").split(`
|
|
2
2
|
`),y=m.length>10||(((V=n.content)==null?void 0:V.length)||0)>800,B=f||!y?m:m.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:n.title}),n.subtitle&&e.jsx("div",{className:"text-[11px] text-[#6B7280] dark:text-[#71717a] font-mono",children:n.subtitle})]}),e.jsx(je,{status:n.status})]}),n.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:[B.join(`
|
|
3
3
|
`),!f&&y&&`
|
|
4
4
|
…`]}),y&&e.jsxs("button",{onClick:()=>ce(n.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:[f?e.jsx(J,{className:"w-3 h-3"}):e.jsx(H,{className:"w-3 h-3"}),f?"Collapse":"Expand"]})]})]},n.id)})})})]})]})}function N({title:t,subtitle:a}){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:a})]})}function je({status:t}){const a=t==="success"?"Success":t==="error"?"Failed":"Running",r=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:j("text-[11px] px-2 py-0.5 rounded-full font-mono",r),children:a})}function ae({node:t,depth:a,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:c,selectedPath:i}){const d=t.type==="dir",u=r[t.path],x=!d&&i===t.path,p=s[t.path]||[];return e.jsxs("div",{children:[e.jsx("button",{onClick:()=>{d?o(t.path):c(t.path)},className:j("flex items-center gap-2 w-full text-left text-[12px] font-mono px-2 py-1 rounded-md transition-colors",x?"bg-[#16A34A]/10 text-[#111827] dark:bg-[#22C55E]/10 dark:text-[#E5E5E5]":"hover:bg-[#F3F4F6] text-[#6B7280] dark:hover:bg-[#111113] dark:text-[#a1a1aa]",d&&"cursor-pointer",x&&"border border-[#16A34A]/30 dark:border-[#22C55E]/30"),style:{paddingLeft:a*14+8},children:d?e.jsxs(e.Fragment,{children:[u?e.jsx(be,{className:"h-3.5 w-3.5 shrink-0 text-[#111827] dark:text-[#E5E5E5]"}):e.jsx(ge,{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(ee,{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})]})}),d&&u&&e.jsx("div",{children:p.map(g=>e.jsx(ae,{node:g,depth:a+1,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:c,selectedPath:i},g.path))})]})}function we(t){return t.flatMap(a=>{var o,c,i;const r=[];if((o=a.agentContent)!=null&&o.toolCalls)for(const d of a.agentContent.toolCalls){const u=X(d.arguments),x=d.output,p=x?(c=E(x))!=null&&c.diff?G(x):x:void 0;r.push({id:`${a.id}-${d.toolCallId}`,title:d.toolName||"Tool",subtitle:d.summary,status:d.status==="success"?"success":d.status==="error"?"error":"running",content:p||(u?`Arguments:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{M as k,r as h,_ as j}from"./vendor-markdown-DIcugY1e.js";import{r as o,j as r}from"./vendor-react-Dm1xU4bP.js";import{c as b}from"./index-
|
|
1
|
+
import{M as k,r as h,_ as j}from"./vendor-markdown-DIcugY1e.js";import{r as o,j as r}from"./vendor-react-Dm1xU4bP.js";import{c as b}from"./index-9t-WxRrl.js";import{a as f}from"./SettingsStore-CfDjhOkS.js";import{c as g,r as N}from"./vendor-icons-DlzC8I7m.js";import"./vendor-monaco-w6PwaWGP.js";import"./vendor-radix-CfxBc_4-.js";const v=[h],y=o.lazy(()=>j(()=>import("./CodeBlockHighlighter-C86flFwh.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,...c}){const x=/language-(\w+)/.exec(e||""),p=!x,m=x?x[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),...c,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:c}),children:r.jsx(y,{code:l,language:m,isDark:i})})]}):r.jsx(u,{className:e,code:l,props:c})},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{R as MarkdownRenderer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as o,j as e}from"./vendor-react-Dm1xU4bP.js";import{D as V,a as ee,b as te}from"./dialog-CgyS_4Eo.js";import{u as ge,c as A}from"./index-Abieffcr.js";import{_ as T,l as w,m as se,n as oe,o as W}from"./vendor-radix-CfxBc_4-.js";import{i as ve,a as Ee,d as le,u as pe,b as be,c as je,e as R,f as G,g as ke}from"./useRequest-BJp539HQ.js";import{R as Ne,P as Ce,X as ne,p as ye,L as ce,q as de,c as we,D as Ae}from"./vendor-icons-DlzC8I7m.js";import"./vendor-markdown-DIcugY1e.js";import"./vendor-monaco-w6PwaWGP.js";function Y(n,a){if(ve){if(!n)return a;var r;return Ee(n)?r=n():"current"in n?r=n.current:r=n,r}}var Se=function(n){var a=function(r,c,d){var l=o.useRef(!1),s=o.useRef([]),m=o.useRef([]),h=o.useRef(void 0);n(function(){var i,k=Array.isArray(d)?d:[d],v=k.map(function(N){return Y(N)});if(!l.current){l.current=!0,s.current=v,m.current=c,h.current=r();return}(v.length!==s.current.length||!le(s.current,v)||!le(m.current,c))&&((i=h.current)===null||i===void 0||i.call(h),s.current=v,m.current=c,h.current=r())}),pe(function(){var i;(i=h.current)===null||i===void 0||i.call(h),l.current=!1})};return a},Fe=Se(o.useEffect);function Be(){var n=(typeof global>"u"?"undefined":typeof global)=="object"&&global&&global.Object===Object&&global,a=typeof self=="object"&&self&&self.Object===Object&&self;return n||a}Be()||(global.Date=Date);function Me(n,a){var r,c=be(n),d=(r=a==null?void 0:a.wait)!==null&&r!==void 0?r:1e3,l=o.useMemo(function(){return je(function(){for(var s=[],m=0;m<arguments.length;m++)s[m]=arguments[m];return c.current.apply(c,T([],w(s),!1))},d,a)},[]);return pe(function(){l.cancel()}),{run:l,cancel:l.cancel,flush:l.flush}}function De(n,a,r){r===void 0&&(r={});var c=r.enable,d=c===void 0?!0:c,l=be(a);Fe(function(){if(d){var s=Y(r.target,window);if(s!=null&&s.addEventListener){var m=function(i){return l.current(i)},h=Array.isArray(n)?n:[n];return h.forEach(function(i){s.addEventListener(i,m,{capture:r.capture,once:r.once,passive:r.passive})}),function(){h.forEach(function(i){s.removeEventListener(i,m,{capture:r.capture})})}}}},[n,r.capture,r.once,r.passive,d],r.target)}var Te=function(n){return n===document||n===document.documentElement||n===document.body?Math.max(window.pageYOffset,document.documentElement.scrollTop,document.body.scrollTop):n.scrollTop},ie=function(n){return n.scrollHeight||Math.max(document.documentElement.scrollHeight,document.body.scrollHeight)},_e=function(n){return n.clientHeight||Math.max(document.documentElement.clientHeight,document.body.clientHeight)},Ie=function(n,a){a===void 0&&(a={});var r=a.target,c=a.isNoMore,d=a.threshold,l=d===void 0?100:d,s=a.direction,m=s===void 0?"bottom":s,h=a.reloadDeps,i=h===void 0?[]:h,k=a.manual,v=a.onBefore,N=a.onSuccess,S=a.onError,p=a.onFinally,_=w(o.useState(),2),C=_[0],F=_[1],P=w(o.useState(!1),2),O=P[0],g=P[1],B=m==="top",y=o.useRef(void 0),E=o.useRef(0),L=o.useMemo(function(){return c?c(C):!1},[C]),M=R(function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,n(x)];case 1:return f=t.sent(),[2,{currentData:f,lastData:x}]}})})},{manual:k,onFinally:function(x,f,t){g(!1),p==null||p(f==null?void 0:f.currentData,t)},onBefore:function(){return v==null?void 0:v()},onSuccess:function(x){var f,t,j;x.lastData?F(W(W({},x.currentData),{list:B?T(T([],w(x.currentData.list),!1),w((t=x.lastData.list)!==null&&t!==void 0?t:[]),!1):T(T([],w((j=x.lastData.list)!==null&&j!==void 0?j:[]),!1),w(x.currentData.list),!1)})):F(W(W({},x.currentData),{list:T([],w((f=x.currentData.list)!==null&&f!==void 0?f:[]),!1)})),setTimeout(function(){if(B){var b=Y(r);if(b=b===document?document.documentElement:b,b){var z=ie(b);b.scrollTo(0,z-E.current)}}else J()}),N==null||N(x.currentData)},onError:function(x){return S==null?void 0:S(x)}}),$=M.loading,q=M.error,H=M.run,Q=M.runAsync,X=M.cancel,I=G(function(){L||(g(!0),H(C))}),u=function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,Q(x)];case 1:return f=t.sent(),[2,f.currentData]}})})},D=G(function(){return L?Promise.reject():(g(!0),u(C))}),U=function(){return g(!1),H()},Z=function(){return g(!1),u()},J=function(){var x=Y(r);if(x){var f=x===document?document.documentElement:x,t=Te(f),j=ie(f),b=_e(f);B?(y.current!==void 0&&y.current>t&&t<=l&&I(),y.current=t,E.current=j-t):j-t<=b+l&&I()}};return De("scroll",function(){$||O||J()},{target:r}),ke(function(){H()},T([],w(i),!1)),{data:C,loading:!O&&$,error:q,loadingMore:O,noMore:L,loadMore:I,loadMoreAsync:D,reload:G(U),reloadAsync:G(Z),mutate:F,cancel:X}};const xe={connected:"text-[#16A34A] dark:text-[#22C55E]",connecting:"text-[#2563eb] dark:text-[#3b82f6]",offline:"text-[#f59e0b]",error:"text-[#ef4444]"},me={connected:"Connected",connecting:"Connecting...",offline:"Offline",error:"Error"},ue=20,Re=async()=>{const n=await fetch("/mcp");if(!n.ok)throw new Error("Failed to fetch servers");return n.json()},Pe="mcp server @modelcontextprotocol",Oe=3,Le=async(n,a)=>{const r=n&&n.length>=Oe?n:Pe,c=`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(r)}&size=${ue}&from=${a}`,d=await fetch(c);if(!d.ok)throw new Error("Failed to fetch packages");const l=await d.json();return{list:l.objects.map(s=>s.package),total:l.total,hasMore:a+ue<l.total}};function Ze(){const{isMcpOpen:n,toggleMcp:a}=ge(),[r,c]=o.useState("installed"),[d,l]=o.useState(!1),[s,m]=o.useState(null),[h,i]=o.useState({}),[k,v]=o.useState(""),[N,S]=o.useState(""),[p,_]=o.useState(null),[C,F]=o.useState(null),P=o.useRef(null),{run:O}=Me(t=>{S(t)},{wait:500}),{data:g=[],loading:B,run:y}=R(Re,{refreshDeps:[n],ready:n,onSuccess:t=>{t.length>0&&!s&&m(t[0].id)}}),{data:E,loading:L,loadingMore:M,noMore:$,reload:q}=Ie(async t=>{var b;const j=((b=t==null?void 0:t.list)==null?void 0:b.length)??0;return Le(N,j)},{target:P,isNoMore:t=>!(t!=null&&t.hasMore),reloadDeps:[N],manual:!n||r!=="catalog"}),{runAsync:H}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:Q}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:X}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})},{manual:!0,onSuccess:y}),{runAsync:I}=R(async t=>{await fetch("/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name,config:t})})},{manual:!0,onSuccess:()=>{y(),l(!1),F(null),_(null)},onError:()=>{_(null)}}),u=o.useMemo(()=>g.find(t=>t.id===s)??g[0],[g,s]),D=u?h[u.id]??{read:!0,write:!1,shell:!1}:{read:!0,write:!1,shell:!1},U=t=>{u&&i(j=>({...j,[u.id]:{...D,[t]:!D[t]}}))},Z=o.useMemo(()=>new Set(g.map(t=>t.name.toLowerCase())),[g]),J=t=>{F(t)},x=t=>t.startsWith("@modelcontextprotocol/"),f=t=>x(t.name)?"Official":"Community";return e.jsxs(e.Fragment,{children:[e.jsx(V,{open:n,onOpenChange:a,children:e.jsxs(ee,{className:"sm:max-w-[900px] h-[680px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl flex flex-col","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(te,{className:"sr-only",children:"MCP"}),e.jsx("div",{className:"flex flex-1 min-h-0",children:e.jsxs("div",{className:"flex-1 p-8 flex flex-col gap-5 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"MCP"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:y,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",disabled:B,children:e.jsx(Ne,{className:A("h-4 w-4",B&&"animate-spin")})}),e.jsxs("button",{onClick:()=>l(!0),className:"h-8 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-xs font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a]",children:[e.jsx(Ce,{className:"h-3.5 w-3.5"}),"Add server"]}),e.jsx("button",{onClick:a,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(ne,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] w-fit shrink-0",children:[e.jsxs(fe,{active:r==="installed",onClick:()=>c("installed"),children:["Installed (",g.length,")"]}),e.jsx(fe,{active:r==="catalog",onClick:()=>{c("catalog"),E||q()},children:"Catalog"})]}),r==="installed"?e.jsxs("div",{className:"flex gap-5 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-[220px] flex flex-col gap-3 min-h-0 overflow-hidden",children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] shrink-0",children:"Servers"}),e.jsx("div",{className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 text-[12px] text-[#9CA3AF] dark:text-[#71717a] font-mono shrink-0",children:"Search servers..."}),e.jsxs("div",{className:"flex flex-col gap-2 overflow-y-auto flex-1 min-h-0 pr-1",children:[g.length===0&&!B&&e.jsx("div",{className:"text-center py-8 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No MCP servers configured"}),g.map(t=>e.jsxs("button",{onClick:()=>m(t.id),className:A("text-left rounded-lg px-3 py-2 flex flex-col gap-1 transition-colors shrink-0",t.id===s?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b]"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:t.name}),e.jsx("span",{className:A("text-[11px] font-mono font-semibold",xe[t.status]),children:me[t.status]})]}),e.jsx("span",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] truncate",children:t.endpoint})]},t.id))]})]}),u?e.jsxs("div",{className:"flex-1 flex flex-col gap-3 overflow-y-auto pr-2 min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-base font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:u.name}),e.jsx("span",{className:A("text-xs font-mono font-semibold",xe[u.status]),children:me[u.status]})]}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:u.description}),u.error&&e.jsxs("p",{className:"text-[12px] font-mono text-[#ef4444]",children:["Error: ",u.error]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u.status==="connected"?e.jsx("button",{onClick:()=>Q(u.name),className:"h-7 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Disconnect"}):e.jsx("button",{onClick:()=>H(u.name),className:"h-7 px-3 rounded-md bg-[#16A34A] dark:bg-[#22C55E] text-white dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Connect"}),e.jsx("button",{onClick:()=>X(u.name),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#ef4444] text-[11px] font-mono font-semibold",children:"Delete"})]}),e.jsx("div",{className:"h-px bg-[#E5E7EB] dark:bg-[#1f2937]"}),e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Permissions"}),e.jsx(K,{label:"File read",enabled:D.read,onToggle:()=>U("read")}),e.jsx(K,{label:"File write",enabled:D.write,onToggle:()=>U("write")}),e.jsx(K,{label:"Shell exec",enabled:D.shell,onToggle:()=>U("shell")}),e.jsxs("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:["Tools (",u.tools.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.tools.length===0?e.jsx("span",{className:"text-[12px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No tools available"}):u.tools.map(t=>e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#111827] dark:text-[#E5E5E5]",children:t},t))})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"Select a server to view details"})})]}):e.jsxs("div",{className:"flex flex-col gap-4 flex-1 min-h-0",children:[e.jsx("div",{className:"flex items-center gap-3 shrink-0",children:e.jsxs("div",{className:"flex-1 h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 gap-2",children:[e.jsx(ye,{className:"h-3.5 w-3.5 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("input",{type:"text",value:k,onChange:t=>{v(t.target.value),O(t.target.value)},placeholder:"Search MCP servers on npm (min 3 chars)...",className:"flex-1 bg-transparent text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none"})]})}),e.jsxs("div",{ref:P,className:"flex-1 overflow-y-auto min-h-0",children:[L&&!E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ce,{className:"h-6 w-6 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}):e.jsx("div",{className:"grid grid-cols-2 gap-3 pb-4",children:E==null?void 0:E.list.map(t=>{var ae,re;const j=Z.has(t.name.toLowerCase().replace(/\s+/g,"-")),b=p===t.name,z=f(t);return e.jsxs("div",{className:"rounded-lg bg-white dark:bg-[#0C0C0C] p-4 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name}),e.jsx("span",{className:A("text-[10px] font-mono px-2 py-0.5 rounded shrink-0",z==="Official"?"bg-[#16A34A]/20 dark:bg-[#22C55E]/20 text-[#16A34A] dark:text-[#22C55E]":"bg-[#3b82f6]/20 text-[#3b82f6]"),children:z})]}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] line-clamp-2",children:t.description||"No description"}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[e.jsxs("span",{children:["v",t.version]}),((ae=t.publisher)==null?void 0:ae.username)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{children:["by ",t.publisher.username]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-auto pt-2",children:[e.jsxs("a",{href:((re=t.links)==null?void 0:re.npm)||`https://www.npmjs.com/package/${t.name}`,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a] hover:text-[#111827] dark:hover:text-[#E5E5E5] flex items-center gap-1",children:[e.jsx(de,{className:"h-3 w-3"}),"npm"]}),j?e.jsxs("span",{className:"text-[11px] font-mono text-[#16A34A] dark:text-[#22C55E] flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),"Installed"]}):e.jsxs("button",{onClick:()=>J(t),disabled:b,className:"h-6 px-2 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[10px] font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a] disabled:opacity-50",children:[e.jsx(Ae,{className:A("h-3 w-3",b&&"animate-pulse")}),b?"Installing...":"Install"]})]})]},t.name)})}),M&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ce,{className:"h-5 w-5 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}),$&&E&&E.list.length>0&&e.jsx("div",{className:"text-center py-4 text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No more packages"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-[#E5E7EB] dark:border-[#1f2937] shrink-0",children:[e.jsxs("span",{className:"text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[(E==null?void 0:E.total)??0," packages found"]}),e.jsxs("a",{href:"https://glama.ai/mcp/servers",target:"_blank",rel:"noopener noreferrer",className:"text-[11px] font-mono text-[#3b82f6] hover:underline flex items-center gap-1",children:["Browse more on Glama",e.jsx(de,{className:"h-3 w-3"})]})]})]})]})})]})}),e.jsx(Ue,{open:d,onOpenChange:l,onAdd:I}),C&&e.jsx($e,{pkg:C,onClose:()=>F(null),onInstall:t=>{_(C.name),I(t)}})]})}function fe({active:n,children:a,onClick:r}){return e.jsx("button",{onClick:r,className:A("px-3 py-1 rounded text-[12px] font-mono font-semibold transition-colors",n?"bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]":"text-[#6B7280] dark:text-[#a1a1aa]"),children:a})}function K({label:n,enabled:a,onToggle:r}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:n}),e.jsx(He,{enabled:a,onChange:r})]})}function He({enabled:n,onChange:a}){return e.jsx("button",{onClick:a,className:A("w-9 h-5 rounded-full px-0.5 flex items-center transition-colors",n?"bg-[#16A34A] dark:bg-[#22C55E] justify-end":"bg-[#E5E7EB] dark:bg-[#27272a] justify-start"),children:e.jsx("span",{className:"h-4 w-4 rounded-full bg-white"})})}function Ue({open:n,onOpenChange:a,onAdd:r}){const[c,d]=o.useState("form"),[l,s]=o.useState(""),[m,h]=o.useState(""),[i,k]=o.useState(""),[v,N]=o.useState(`{
|
|
1
|
+
import{r as o,j as e}from"./vendor-react-Dm1xU4bP.js";import{D as V,a as ee,b as te}from"./dialog-C8VDk-ma.js";import{u as ge,c as A}from"./index-9t-WxRrl.js";import{_ as T,l as w,m as se,n as oe,o as W}from"./vendor-radix-CfxBc_4-.js";import{i as ve,a as Ee,d as le,u as pe,b as be,c as je,e as R,f as G,g as ke}from"./useRequest-BJp539HQ.js";import{R as Ne,P as Ce,X as ne,p as ye,L as ce,q as de,c as we,D as Ae}from"./vendor-icons-DlzC8I7m.js";import"./vendor-markdown-DIcugY1e.js";import"./vendor-monaco-w6PwaWGP.js";function Y(n,a){if(ve){if(!n)return a;var r;return Ee(n)?r=n():"current"in n?r=n.current:r=n,r}}var Se=function(n){var a=function(r,c,d){var l=o.useRef(!1),s=o.useRef([]),m=o.useRef([]),h=o.useRef(void 0);n(function(){var i,k=Array.isArray(d)?d:[d],v=k.map(function(N){return Y(N)});if(!l.current){l.current=!0,s.current=v,m.current=c,h.current=r();return}(v.length!==s.current.length||!le(s.current,v)||!le(m.current,c))&&((i=h.current)===null||i===void 0||i.call(h),s.current=v,m.current=c,h.current=r())}),pe(function(){var i;(i=h.current)===null||i===void 0||i.call(h),l.current=!1})};return a},Fe=Se(o.useEffect);function Be(){var n=(typeof global>"u"?"undefined":typeof global)=="object"&&global&&global.Object===Object&&global,a=typeof self=="object"&&self&&self.Object===Object&&self;return n||a}Be()||(global.Date=Date);function Me(n,a){var r,c=be(n),d=(r=a==null?void 0:a.wait)!==null&&r!==void 0?r:1e3,l=o.useMemo(function(){return je(function(){for(var s=[],m=0;m<arguments.length;m++)s[m]=arguments[m];return c.current.apply(c,T([],w(s),!1))},d,a)},[]);return pe(function(){l.cancel()}),{run:l,cancel:l.cancel,flush:l.flush}}function De(n,a,r){r===void 0&&(r={});var c=r.enable,d=c===void 0?!0:c,l=be(a);Fe(function(){if(d){var s=Y(r.target,window);if(s!=null&&s.addEventListener){var m=function(i){return l.current(i)},h=Array.isArray(n)?n:[n];return h.forEach(function(i){s.addEventListener(i,m,{capture:r.capture,once:r.once,passive:r.passive})}),function(){h.forEach(function(i){s.removeEventListener(i,m,{capture:r.capture})})}}}},[n,r.capture,r.once,r.passive,d],r.target)}var Te=function(n){return n===document||n===document.documentElement||n===document.body?Math.max(window.pageYOffset,document.documentElement.scrollTop,document.body.scrollTop):n.scrollTop},ie=function(n){return n.scrollHeight||Math.max(document.documentElement.scrollHeight,document.body.scrollHeight)},_e=function(n){return n.clientHeight||Math.max(document.documentElement.clientHeight,document.body.clientHeight)},Ie=function(n,a){a===void 0&&(a={});var r=a.target,c=a.isNoMore,d=a.threshold,l=d===void 0?100:d,s=a.direction,m=s===void 0?"bottom":s,h=a.reloadDeps,i=h===void 0?[]:h,k=a.manual,v=a.onBefore,N=a.onSuccess,S=a.onError,p=a.onFinally,_=w(o.useState(),2),C=_[0],F=_[1],P=w(o.useState(!1),2),O=P[0],g=P[1],B=m==="top",y=o.useRef(void 0),E=o.useRef(0),L=o.useMemo(function(){return c?c(C):!1},[C]),M=R(function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,n(x)];case 1:return f=t.sent(),[2,{currentData:f,lastData:x}]}})})},{manual:k,onFinally:function(x,f,t){g(!1),p==null||p(f==null?void 0:f.currentData,t)},onBefore:function(){return v==null?void 0:v()},onSuccess:function(x){var f,t,j;x.lastData?F(W(W({},x.currentData),{list:B?T(T([],w(x.currentData.list),!1),w((t=x.lastData.list)!==null&&t!==void 0?t:[]),!1):T(T([],w((j=x.lastData.list)!==null&&j!==void 0?j:[]),!1),w(x.currentData.list),!1)})):F(W(W({},x.currentData),{list:T([],w((f=x.currentData.list)!==null&&f!==void 0?f:[]),!1)})),setTimeout(function(){if(B){var b=Y(r);if(b=b===document?document.documentElement:b,b){var z=ie(b);b.scrollTo(0,z-E.current)}}else J()}),N==null||N(x.currentData)},onError:function(x){return S==null?void 0:S(x)}}),$=M.loading,q=M.error,H=M.run,Q=M.runAsync,X=M.cancel,I=G(function(){L||(g(!0),H(C))}),u=function(x){return se(void 0,void 0,void 0,function(){var f;return oe(this,function(t){switch(t.label){case 0:return[4,Q(x)];case 1:return f=t.sent(),[2,f.currentData]}})})},D=G(function(){return L?Promise.reject():(g(!0),u(C))}),U=function(){return g(!1),H()},Z=function(){return g(!1),u()},J=function(){var x=Y(r);if(x){var f=x===document?document.documentElement:x,t=Te(f),j=ie(f),b=_e(f);B?(y.current!==void 0&&y.current>t&&t<=l&&I(),y.current=t,E.current=j-t):j-t<=b+l&&I()}};return De("scroll",function(){$||O||J()},{target:r}),ke(function(){H()},T([],w(i),!1)),{data:C,loading:!O&&$,error:q,loadingMore:O,noMore:L,loadMore:I,loadMoreAsync:D,reload:G(U),reloadAsync:G(Z),mutate:F,cancel:X}};const xe={connected:"text-[#16A34A] dark:text-[#22C55E]",connecting:"text-[#2563eb] dark:text-[#3b82f6]",offline:"text-[#f59e0b]",error:"text-[#ef4444]"},me={connected:"Connected",connecting:"Connecting...",offline:"Offline",error:"Error"},ue=20,Re=async()=>{const n=await fetch("/mcp");if(!n.ok)throw new Error("Failed to fetch servers");return n.json()},Pe="mcp server @modelcontextprotocol",Oe=3,Le=async(n,a)=>{const r=n&&n.length>=Oe?n:Pe,c=`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(r)}&size=${ue}&from=${a}`,d=await fetch(c);if(!d.ok)throw new Error("Failed to fetch packages");const l=await d.json();return{list:l.objects.map(s=>s.package),total:l.total,hasMore:a+ue<l.total}};function Ze(){const{isMcpOpen:n,toggleMcp:a}=ge(),[r,c]=o.useState("installed"),[d,l]=o.useState(!1),[s,m]=o.useState(null),[h,i]=o.useState({}),[k,v]=o.useState(""),[N,S]=o.useState(""),[p,_]=o.useState(null),[C,F]=o.useState(null),P=o.useRef(null),{run:O}=Me(t=>{S(t)},{wait:500}),{data:g=[],loading:B,run:y}=R(Re,{refreshDeps:[n],ready:n,onSuccess:t=>{t.length>0&&!s&&m(t[0].id)}}),{data:E,loading:L,loadingMore:M,noMore:$,reload:q}=Ie(async t=>{var b;const j=((b=t==null?void 0:t.list)==null?void 0:b.length)??0;return Le(N,j)},{target:P,isNoMore:t=>!(t!=null&&t.hasMore),reloadDeps:[N],manual:!n||r!=="catalog"}),{runAsync:H}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:Q}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})},{manual:!0,onSuccess:y}),{runAsync:X}=R(async t=>{await fetch(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})},{manual:!0,onSuccess:y}),{runAsync:I}=R(async t=>{await fetch("/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name,config:t})})},{manual:!0,onSuccess:()=>{y(),l(!1),F(null),_(null)},onError:()=>{_(null)}}),u=o.useMemo(()=>g.find(t=>t.id===s)??g[0],[g,s]),D=u?h[u.id]??{read:!0,write:!1,shell:!1}:{read:!0,write:!1,shell:!1},U=t=>{u&&i(j=>({...j,[u.id]:{...D,[t]:!D[t]}}))},Z=o.useMemo(()=>new Set(g.map(t=>t.name.toLowerCase())),[g]),J=t=>{F(t)},x=t=>t.startsWith("@modelcontextprotocol/"),f=t=>x(t.name)?"Official":"Community";return e.jsxs(e.Fragment,{children:[e.jsx(V,{open:n,onOpenChange:a,children:e.jsxs(ee,{className:"sm:max-w-[900px] h-[680px] p-0 overflow-hidden gap-0 bg-white dark:bg-[#09090b] border border-[#E5E7EB] dark:border-zinc-800 rounded-xl flex flex-col","aria-describedby":void 0,hideCloseButton:!0,children:[e.jsx(te,{className:"sr-only",children:"MCP"}),e.jsx("div",{className:"flex flex-1 min-h-0",children:e.jsxs("div",{className:"flex-1 p-8 flex flex-col gap-5 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("h2",{className:"text-lg font-semibold text-[#111827] dark:text-[#E5E5E5] font-mono",children:"MCP"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:y,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",disabled:B,children:e.jsx(Ne,{className:A("h-4 w-4",B&&"animate-spin")})}),e.jsxs("button",{onClick:()=>l(!0),className:"h-8 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-xs font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a]",children:[e.jsx(Ce,{className:"h-3.5 w-3.5"}),"Add server"]}),e.jsx("button",{onClick:a,className:"h-8 w-8 rounded-md text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB] dark:text-[#71717a] dark:hover:text-[#E5E5E5] dark:hover:bg-[#27272a] transition-colors flex items-center justify-center",children:e.jsx(ne,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] w-fit shrink-0",children:[e.jsxs(fe,{active:r==="installed",onClick:()=>c("installed"),children:["Installed (",g.length,")"]}),e.jsx(fe,{active:r==="catalog",onClick:()=>{c("catalog"),E||q()},children:"Catalog"})]}),r==="installed"?e.jsxs("div",{className:"flex gap-5 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"w-[220px] flex flex-col gap-3 min-h-0 overflow-hidden",children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] shrink-0",children:"Servers"}),e.jsx("div",{className:"h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 text-[12px] text-[#9CA3AF] dark:text-[#71717a] font-mono shrink-0",children:"Search servers..."}),e.jsxs("div",{className:"flex flex-col gap-2 overflow-y-auto flex-1 min-h-0 pr-1",children:[g.length===0&&!B&&e.jsx("div",{className:"text-center py-8 text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"No MCP servers configured"}),g.map(t=>e.jsxs("button",{onClick:()=>m(t.id),className:A("text-left rounded-lg px-3 py-2 flex flex-col gap-1 transition-colors shrink-0",t.id===s?"bg-[#E5E7EB] dark:bg-[#111827]":"bg-white dark:bg-[#0C0C0C] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b]"),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:t.name}),e.jsx("span",{className:A("text-[11px] font-mono font-semibold",xe[t.status]),children:me[t.status]})]}),e.jsx("span",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] truncate",children:t.endpoint})]},t.id))]})]}),u?e.jsxs("div",{className:"flex-1 flex flex-col gap-3 overflow-y-auto pr-2 min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-base font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:u.name}),e.jsx("span",{className:A("text-xs font-mono font-semibold",xe[u.status]),children:me[u.status]})]}),e.jsx("p",{className:"text-[12px] font-mono text-[#6B7280] dark:text-[#94a3b8]",children:u.description}),u.error&&e.jsxs("p",{className:"text-[12px] font-mono text-[#ef4444]",children:["Error: ",u.error]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u.status==="connected"?e.jsx("button",{onClick:()=>Q(u.name),className:"h-7 px-3 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[11px] font-mono font-semibold",children:"Disconnect"}):e.jsx("button",{onClick:()=>H(u.name),className:"h-7 px-3 rounded-md bg-[#16A34A] dark:bg-[#22C55E] text-white dark:text-[#0C0C0C] text-[11px] font-mono font-semibold",children:"Connect"}),e.jsx("button",{onClick:()=>X(u.name),className:"h-7 px-3 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[#ef4444] text-[11px] font-mono font-semibold",children:"Delete"})]}),e.jsx("div",{className:"h-px bg-[#E5E7EB] dark:bg-[#1f2937]"}),e.jsx("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:"Permissions"}),e.jsx(K,{label:"File read",enabled:D.read,onToggle:()=>U("read")}),e.jsx(K,{label:"File write",enabled:D.write,onToggle:()=>U("write")}),e.jsx(K,{label:"Shell exec",enabled:D.shell,onToggle:()=>U("shell")}),e.jsxs("span",{className:"text-sm font-mono font-semibold text-[#111827] dark:text-[#E5E5E5]",children:["Tools (",u.tools.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.tools.length===0?e.jsx("span",{className:"text-[12px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No tools available"}):u.tools.map(t=>e.jsx("span",{className:"px-2 py-1 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] text-[11px] font-mono text-[#111827] dark:text-[#E5E5E5]",children:t},t))})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("span",{className:"text-[#9CA3AF] dark:text-[#71717a] text-sm font-mono",children:"Select a server to view details"})})]}):e.jsxs("div",{className:"flex flex-col gap-4 flex-1 min-h-0",children:[e.jsx("div",{className:"flex items-center gap-3 shrink-0",children:e.jsxs("div",{className:"flex-1 h-8 rounded-md bg-[#F3F4F6] dark:bg-[#18181b] flex items-center px-3 gap-2",children:[e.jsx(ye,{className:"h-3.5 w-3.5 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("input",{type:"text",value:k,onChange:t=>{v(t.target.value),O(t.target.value)},placeholder:"Search MCP servers on npm (min 3 chars)...",className:"flex-1 bg-transparent text-[12px] font-mono text-[#111827] dark:text-[#E5E5E5] placeholder:text-[#9CA3AF] dark:placeholder:text-[#71717a] focus:outline-none"})]})}),e.jsxs("div",{ref:P,className:"flex-1 overflow-y-auto min-h-0",children:[L&&!E?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ce,{className:"h-6 w-6 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}):e.jsx("div",{className:"grid grid-cols-2 gap-3 pb-4",children:E==null?void 0:E.list.map(t=>{var ae,re;const j=Z.has(t.name.toLowerCase().replace(/\s+/g,"-")),b=p===t.name,z=f(t);return e.jsxs("div",{className:"rounded-lg bg-white dark:bg-[#0C0C0C] p-4 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[13px] font-mono font-semibold text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name}),e.jsx("span",{className:A("text-[10px] font-mono px-2 py-0.5 rounded shrink-0",z==="Official"?"bg-[#16A34A]/20 dark:bg-[#22C55E]/20 text-[#16A34A] dark:text-[#22C55E]":"bg-[#3b82f6]/20 text-[#3b82f6]"),children:z})]}),e.jsx("p",{className:"text-[11px] font-mono text-[#6B7280] dark:text-[#94a3b8] line-clamp-2",children:t.description||"No description"}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[e.jsxs("span",{children:["v",t.version]}),((ae=t.publisher)==null?void 0:ae.username)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{children:["by ",t.publisher.username]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-auto pt-2",children:[e.jsxs("a",{href:((re=t.links)==null?void 0:re.npm)||`https://www.npmjs.com/package/${t.name}`,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] font-mono text-[#9CA3AF] dark:text-[#71717a] hover:text-[#111827] dark:hover:text-[#E5E5E5] flex items-center gap-1",children:[e.jsx(de,{className:"h-3 w-3"}),"npm"]}),j?e.jsxs("span",{className:"text-[11px] font-mono text-[#16A34A] dark:text-[#22C55E] flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),"Installed"]}):e.jsxs("button",{onClick:()=>J(t),disabled:b,className:"h-6 px-2 rounded-md bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5] text-[10px] font-mono font-semibold flex items-center gap-1 hover:bg-[#D1D5DB] dark:hover:bg-[#32323a] disabled:opacity-50",children:[e.jsx(Ae,{className:A("h-3 w-3",b&&"animate-pulse")}),b?"Installing...":"Install"]})]})]},t.name)})}),M&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ce,{className:"h-5 w-5 text-[#9CA3AF] dark:text-[#71717a] animate-spin"})}),$&&E&&E.list.length>0&&e.jsx("div",{className:"text-center py-4 text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:"No more packages"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-[#E5E7EB] dark:border-[#1f2937] shrink-0",children:[e.jsxs("span",{className:"text-[11px] font-mono text-[#9CA3AF] dark:text-[#71717a]",children:[(E==null?void 0:E.total)??0," packages found"]}),e.jsxs("a",{href:"https://glama.ai/mcp/servers",target:"_blank",rel:"noopener noreferrer",className:"text-[11px] font-mono text-[#3b82f6] hover:underline flex items-center gap-1",children:["Browse more on Glama",e.jsx(de,{className:"h-3 w-3"})]})]})]})]})})]})}),e.jsx(Ue,{open:d,onOpenChange:l,onAdd:I}),C&&e.jsx($e,{pkg:C,onClose:()=>F(null),onInstall:t=>{_(C.name),I(t)}})]})}function fe({active:n,children:a,onClick:r}){return e.jsx("button",{onClick:r,className:A("px-3 py-1 rounded text-[12px] font-mono font-semibold transition-colors",n?"bg-[#E5E7EB] text-[#111827] dark:bg-[#27272a] dark:text-[#E5E5E5]":"text-[#6B7280] dark:text-[#a1a1aa]"),children:a})}function K({label:n,enabled:a,onToggle:r}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] font-mono text-[#6B7280] dark:text-[#a1a1aa]",children:n}),e.jsx(He,{enabled:a,onChange:r})]})}function He({enabled:n,onChange:a}){return e.jsx("button",{onClick:a,className:A("w-9 h-5 rounded-full px-0.5 flex items-center transition-colors",n?"bg-[#16A34A] dark:bg-[#22C55E] justify-end":"bg-[#E5E7EB] dark:bg-[#27272a] justify-start"),children:e.jsx("span",{className:"h-4 w-4 rounded-full bg-white"})})}function Ue({open:n,onOpenChange:a,onAdd:r}){const[c,d]=o.useState("form"),[l,s]=o.useState(""),[m,h]=o.useState(""),[i,k]=o.useState(""),[v,N]=o.useState(`{
|
|
2
2
|
"name": "my-server",
|
|
3
3
|
"command": "npx",
|
|
4
4
|
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|