dskcode 0.1.51 → 0.1.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,7 +79,9 @@
79
79
 
80
80
  ### 🔌 扩展性
81
81
 
82
- - **MCP 插件** — 通过 Model Context Protocol 扩展任意外部工具(数据库 / 浏览器 / Notion 等)
82
+ - **MCP 服务器** — 通过 [Model Context Protocol](https://modelcontextprotocol.io) 扩展任意外部工具(数据库 / 浏览器 / Notion / GitHub / Figma 等),本地 stdio 与远程 HTTP 均支持
83
+ - **`/mcp` 命令** — 查看所有 MCP server 状态、重启、重载
84
+ - **自动重试** — 启动失败的 server 会按 2/4/8/16/30 秒指数退避重试
83
85
  - **Tool 抽象** — 自定义工具只需实现 `AgentTool` 接口
84
86
 
85
87
  ---
@@ -157,6 +159,7 @@ dskcode init
157
159
  | `/toolchoice` | 切换工具调用策略(auto / required / none) |
158
160
  | `/model` | 切换模型(DeepSeek-V4-Flash / DeepSeek-V4-Pro) |
159
161
  | `/permissions` | 查看当前权限规则、会话 grants、配置文件加载来源 |
162
+ | `/mcp` | 列出所有 MCP server 状态;`/mcp restart <name>` 重启;`/mcp reload` 重载 |
160
163
  | `/clear` | 清空当前对话历史 |
161
164
  | `/help` | 查看所有可用命令 |
162
165
  | `/version` | 显示版本信息 |
@@ -284,6 +287,29 @@ Chrome 扩展启动后会自动连这个 URL,无需在 popup 粘贴。
284
287
  **关闭后台 server**:传 `--no-config-ui` 或设置 `DSKCODE_CONFIG_UI=0`。
285
288
  如果 54006 已被另一个 `dskcode` 占用,本进程会跳过 ws 并打出一行提示,扩展连不到。
286
289
 
290
+ ### MCP 服务器(v0.8+)
291
+
292
+ 在 `~/.dskcode/settings.json` 的 `mcpServers` 段声明 MCP server,启动 dskcode 后会自动
293
+ spawn 子进程并把 server 暴露的工具注册到 `ToolRegistry`。详见 `docs/接入MCP服务.md`。
294
+
295
+ ```jsonc
296
+ {
297
+ "mcpServers": {
298
+ "filesystem": {
299
+ "command": "npx",
300
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
301
+ },
302
+ "github": {
303
+ "command": "npx",
304
+ "args": ["-y", "@modelcontextprotocol/server-github"],
305
+ "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "<your-token>" }
306
+ }
307
+ },
308
+ "mcpServerTimeout": 60
309
+ }
310
+ ```
311
+
312
+ 旧配置 `plugins: PluginConfig[]` 仍兼容 1 个版本,会被自动迁移到 `mcpServers`。
287
313
 
288
314
  ---
289
315
 
@@ -0,0 +1,2 @@
1
+ import{d as a}from"./chunk-LPD7BHH5.js";a();function c(r){let e="^",n=0;for(;n<r.length;){let t=r[n];if(t==="*")r[n+1]==="*"?(e+=".*",n+=2,r[n]==="/"&&n++):(e+="[^/]*",n++);else if(t==="?")e+="[^/]",n++;else if(t==="["){let s=r.indexOf("]",n);s<0?(e+="\\[",n++):(e+=r.slice(n,s+1),n=s+1)}else t==="."||t==="("||t===")"||t==="+"||t==="|"||t==="^"||t==="$"||t==="{"||t==="}"||t==="\\"?(e+="\\"+t,n++):(e+=t,n++)}return e+="$",new RegExp(e)}var l=class{#e;constructor(e){this.#e=e}get rules(){return[...this.#e]}evaluate(e,n){for(let t of this.#e)if(p(t.tool,e)&&this.#t(t.match,n))return t.action;return null}#t(e,n){if(!e)return!0;if(e.pathGlob&&(!n.targetPath||!R(e.pathGlob,n.targetPath)))return!1;if(e.commandRegex){let t=g(n.args);if(t===null)return!1;let s;try{s=new RegExp(e.commandRegex)}catch{return!1}if(!s.test(t))return!1}if(e.argValueRegex){let t=n.args;if(typeof t!="object"||t===null)return!1;let s=t;for(let[u,f]of Object.entries(e.argValueRegex)){let i=s[u];if(typeof i!="string")return!1;let o;try{o=new RegExp(f)}catch{return!1}if(!o.test(i))return!1}}return!0}};function g(r){if(typeof r!="object"||r===null)return null;let n=r.command;return typeof n!="string"?null:n}function R(r,e){if(!r||!e)return!1;try{return c(r).test(e)}catch{return!1}}function p(r,e){if(r===e)return!0;if(r.endsWith("_"))return e.startsWith(r);if(/[.*+?()[\]{}|\\^$]/.test(r))try{return new RegExp(r).test(e)}catch{return!1}return!1}export{l as a};
2
+ //# sourceMappingURL=chunk-5NFOBNG6.js.map
@@ -0,0 +1,13 @@
1
+ import{d as h}from"./chunk-LPD7BHH5.js";h();import{existsSync as _e,watch as Me}from"fs";import{mkdir as U,readFile as A,writeFile as F}from"fs/promises";import{join as S}from"path";var De=60,$e=/^[a-z0-9_-]+$/,Ne=new Set(["read_file","write_file","edit_file","multi_edit","delete_range","bash","glob","grep","ls","fetch","skill"]),I={defaultProvider:"deepseek",maxTokens:8192,temperature:.7,maxToolRounds:20,providers:[{name:"deepseek",baseUrl:"https://api.deepseek.com",model:"deepseek-v4-flash"}],tools:[{name:"read_file",enabled:!0},{name:"write_file",enabled:!0},{name:"edit_file",enabled:!0},{name:"bash",enabled:!0},{name:"glob",enabled:!0},{name:"grep",enabled:!0},{name:"ls",enabled:!0},{name:"fetch",enabled:!0}],mcpServers:{},mcpServerTimeout:De,plugins:[],stock:{symbols:[{code:"sh000001"},{code:"sz399300"},{code:"sh601899"}]},thinking:{enabled:!1,effort:"high"}};function ue(t){if(t)return[t];let e=process.env.HOME??process.env.USERPROFILE??"~";return[S(e,".dskcode","settings.json"),S(process.cwd(),".dskcode","settings.json")]}function Ue(t,e){let n={...t};return e.defaultProvider!==void 0&&(n.defaultProvider=e.defaultProvider),e.verbose!==void 0&&(n.verbose=e.verbose),e.maxTokens!==void 0&&(n.maxTokens=e.maxTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.maxToolRounds!==void 0&&(n.maxToolRounds=e.maxToolRounds),e.budgetLimit!==void 0&&(n.budgetLimit=e.budgetLimit),e.tokenBudgetLimit!==void 0&&(n.tokenBudgetLimit=e.tokenBudgetLimit),e.providers!==void 0&&(n.providers=e.providers),e.tools!==void 0&&(n.tools=e.tools),e.mcpServers!==void 0?n.mcpServers={...n.mcpServers??{},...e.mcpServers}:n.mcpServers===void 0&&(n.mcpServers={}),e.mcpServerTimeout!==void 0&&(n.mcpServerTimeout=e.mcpServerTimeout),e.plugins!==void 0&&(n.plugins=e.plugins),e.stock!==void 0&&(n.stock=e.stock),e.voice!==void 0&&(n.voice=e.voice),e.permissions!==void 0&&(n.permissions=e.permissions),e.thinking!==void 0&&(n.thinking=e.thinking),n}var E="DSKCODE_",Fe={[`${E}DEFAULT_PROVIDER`]:"defaultProvider",[`${E}VERBOSE`]:"verbose",[`${E}MAX_TOKENS`]:"maxTokens",[`${E}TEMPERATURE`]:"temperature",[`${E}MAX_TOOL_ROUNDS`]:"maxToolRounds",[`${E}BUDGET_LIMIT`]:"budgetLimit",[`${E}TOKEN_BUDGET_LIMIT`]:"tokenBudgetLimit",[`${E}THINKING`]:"thinking.enabled",[`${E}THINKING_EFFORT`]:"thinking.effort"};function We(t){let e={...t,providers:[...t.providers]};for(let[s,o]of Object.entries(Fe)){let r=process.env[s];if(r!==void 0){if(o.startsWith("thinking.")){let i=o.slice(9),d=e.thinking??{enabled:!1,effort:"high"};i==="enabled"?e.thinking={...d,enabled:r==="1"||r.toLowerCase()==="true"}:i==="effort"&&(r==="high"||r==="max")&&(e.thinking={...d,effort:r});continue}switch(o){case"verbose":case"defaultProvider":{e[o]=r;break}case"maxTokens":case"maxToolRounds":case"budgetLimit":case"tokenBudgetLimit":{let i=Number(r);Number.isFinite(i)&&i>=0&&(e[o]=i);break}case"temperature":{let i=Number(r);Number.isFinite(i)&&i>=0&&i<=2&&(e[o]=i);break}}}}let n=process.env.DEEPSEEK_API_KEY;if(n){let s=e.providers.findIndex(o=>o.name==="deepseek");if(s!==-1){let o=e.providers[s];o.apiKey||(e.providers[s]={...o,apiKey:n})}else e.providers.unshift({name:"deepseek",baseUrl:"https://api.deepseek.com",model:"deepseek-v4-flash",apiKey:n})}return e}function $t(t,e){let n={...t,providers:[...t.providers]};if(e.verbose!==void 0&&(n.verbose=e.verbose),e.model!==void 0){let s=n.providers.findIndex(o=>o.name===n.defaultProvider);s!==-1&&(n.providers[s]={...n.providers[s],model:e.model})}return e.maxTokens!==void 0&&e.maxTokens>0&&(n.maxTokens=e.maxTokens),e.temperature!==void 0&&e.temperature>=0&&e.temperature<=2&&(n.temperature=e.temperature),e.budgetLimit!==void 0&&e.budgetLimit>=0&&(n.budgetLimit=e.budgetLimit),e.tokenBudgetLimit!==void 0&&e.tokenBudgetLimit>=0&&(n.tokenBudgetLimit=e.tokenBudgetLimit),n}function Be(t){let e=[];(!t.providers||t.providers.length===0)&&e.push({field:"providers",message:"\u81F3\u5C11\u9700\u8981\u914D\u7F6E\u4E00\u4E2A Provider\u3002\u8BF7\u901A\u8FC7\u914D\u7F6E\u6587\u4EF6\u6216 DEEPSEEK_API_KEY \u73AF\u5883\u53D8\u91CF\u8BBE\u7F6E\u3002"});let n=["deepseek-v4-flash","deepseek-v4-pro"];for(let s=0;s<t.providers.length;s++){let o=t.providers[s];o.name||e.push({field:`providers[${s}].name`,message:`\u7B2C ${s+1} \u4E2A Provider \u7F3A\u5C11 name \u5B57\u6BB5\u3002`}),o.model?n.includes(o.model)||e.push({field:`providers[${s}].model`,message:`Provider "${o.name||s}" \u7684 model "${o.model}" \u4E0D\u53D7\u652F\u6301\u3002dskcode \u4EC5\u652F\u6301: ${n.join(", ")}`}):e.push({field:`providers[${s}].model`,message:`Provider "${o.name||s}" \u7F3A\u5C11 model \u5B57\u6BB5\u3002`})}if(t.defaultProvider&&(t.providers.some(o=>o.name===t.defaultProvider)||e.push({field:"defaultProvider",message:`\u9ED8\u8BA4 Provider "${t.defaultProvider}" \u672A\u5728 providers \u4E2D\u5B9A\u4E49\u3002`})),t.temperature!==void 0&&(t.temperature<0||t.temperature>2)&&e.push({field:"temperature",message:"temperature \u5FC5\u987B\u5728 0.0 ~ 2.0 \u4E4B\u95F4\u3002"}),t.maxTokens!==void 0&&t.maxTokens<1&&e.push({field:"maxTokens",message:"maxTokens \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E 1\u3002"}),t.maxToolRounds!==void 0&&t.maxToolRounds<1&&e.push({field:"maxToolRounds",message:"maxToolRounds \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E 1\u3002"}),t.budgetLimit!==void 0&&t.budgetLimit<0&&e.push({field:"budgetLimit",message:"budgetLimit \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E 0\uFF080 \u8868\u793A\u4E0D\u9650\u5236\uFF09\u3002"}),t.tokenBudgetLimit!==void 0&&t.tokenBudgetLimit<0&&e.push({field:"tokenBudgetLimit",message:"tokenBudgetLimit \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E 0\uFF080 \u8868\u793A\u4E0D\u9650\u5236\uFF09\u3002"}),t.mcpServerTimeout!==void 0&&(t.mcpServerTimeout<1||t.mcpServerTimeout>3600)&&e.push({field:"mcpServerTimeout",message:"mcpServerTimeout \u5FC5\u987B\u5728 1 ~ 3600 \u4E4B\u95F4\u3002"}),t.mcpServers!==void 0)if(t.mcpServers===null||typeof t.mcpServers!="object"||Array.isArray(t.mcpServers))e.push({field:"mcpServers",message:"mcpServers \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08key \u4E3A server id\uFF09\u3002"});else for(let[s,o]of Object.entries(t.mcpServers)){if($e.test(s)||e.push({field:`mcpServers.${s}`,message:"server id \u4EC5\u5141\u8BB8\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u3001\u4E0B\u5212\u7EBF\u3002"}),Ne.has(s)&&e.push({field:`mcpServers.${s}`,message:`server id "${s}" \u4E0E dskcode \u5185\u7F6E\u5DE5\u5177\u91CD\u540D\uFF0C\u8BF7\u6362\u4E00\u4E2A\u3002`}),o===null||typeof o!="object"||Array.isArray(o)){e.push({field:`mcpServers.${s}`,message:"server value \u5FC5\u987B\u662F\u5BF9\u8C61\u3002"});continue}let r=o,i="command"in r&&typeof r.command=="string",d="url"in r&&typeof r.url=="string";if(i&&d){e.push({field:`mcpServers.${s}`,message:"MCP server \u4E0D\u80FD\u540C\u65F6\u4E3A stdio \u4E0E http\uFF1B\u8BF7\u4E8C\u9009\u4E00\uFF08\u79FB\u9664 command \u6216 url \u5B57\u6BB5\uFF09\u3002"});continue}if(!i&&!d){e.push({field:`mcpServers.${s}`,message:"MCP server \u914D\u7F6E\u7F3A\u5C11 command\uFF08stdio\uFF09\u6216 url\uFF08http\uFF09\u5B57\u6BB5\u3002"});continue}if(i){let c=r;if(c.command.trim()===""&&e.push({field:`mcpServers.${s}.command`,message:"command \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\u3002"}),c.args!==void 0&&!Array.isArray(c.args))e.push({field:`mcpServers.${s}.args`,message:"args \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u6570\u7EC4\u3002"});else if(Array.isArray(c.args))for(let g=0;g<c.args.length;g++)typeof c.args[g]!="string"&&e.push({field:`mcpServers.${s}.args[${g}]`,message:"args \u5143\u7D20\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u3002"});if(c.env!==void 0)if(c.env===null||typeof c.env!="object"||Array.isArray(c.env))e.push({field:`mcpServers.${s}.env`,message:"env \u5FC5\u987B\u662F\u666E\u901A\u5BF9\u8C61\u3002"});else for(let[g,v]of Object.entries(c.env))typeof v!="string"&&e.push({field:`mcpServers.${s}.env.${g}`,message:"env \u7684 value \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u3002"});c.timeout!==void 0&&(typeof c.timeout!="number"||!Number.isInteger(c.timeout)||c.timeout<1)&&e.push({field:`mcpServers.${s}.timeout`,message:"timeout \u5FC5\u987B\u4E3A\u6B63\u6574\u6570\u79D2\u3002"})}else if(d){let c=r;if(c.url.trim()==="")e.push({field:`mcpServers.${s}.url`,message:"url \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\u3002"});else{let g;try{g=new URL(c.url)}catch{e.push({field:`mcpServers.${s}.url`,message:`url \u89E3\u6790\u5931\u8D25\uFF1A${c.url}`}),g=new URL("http://invalid")}let v=g.protocol.toLowerCase();if(v!=="https:")if(v==="http:"){let f=g.hostname.toLowerCase();f!=="localhost"&&f!=="127.0.0.1"&&f!=="::1"&&e.push({field:`mcpServers.${s}.url`,message:`\u4E0D\u5141\u8BB8\u7684 http URL "${c.url}"\uFF1A\u4EC5\u5141\u8BB8 https:// \u6216 http://localhost/127.0.0.1\uFF08\u9632 SSRF\uFF09\u3002`})}else e.push({field:`mcpServers.${s}.url`,message:`\u4E0D\u652F\u6301\u7684 URL scheme "${v}"\uFF1A\u4EC5\u5141\u8BB8 http(s)://\u3002`})}if(c.headers!==void 0)if(c.headers===null||typeof c.headers!="object"||Array.isArray(c.headers))e.push({field:`mcpServers.${s}.headers`,message:"headers \u5FC5\u987B\u662F\u666E\u901A\u5BF9\u8C61\u3002"});else for(let[g,v]of Object.entries(c.headers))typeof v!="string"&&e.push({field:`mcpServers.${s}.headers.${g}`,message:"headers \u7684 value \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u3002"});c.timeout!==void 0&&(typeof c.timeout!="number"||!Number.isInteger(c.timeout)||c.timeout<1)&&e.push({field:`mcpServers.${s}.timeout`,message:"timeout \u5FC5\u987B\u4E3A\u6B63\u6574\u6570\u79D2\u3002"}),c.oauth!==void 0&&(c.oauth===null||typeof c.oauth!="object"||Array.isArray(c.oauth)?e.push({field:`mcpServers.${s}.oauth`,message:"oauth \u5FC5\u987B\u662F\u666E\u901A\u5BF9\u8C61\u3002"}):(typeof c.oauth.clientId!="string"||c.oauth.clientId==="")&&e.push({field:`mcpServers.${s}.oauth.clientId`,message:"oauth.clientId \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\u3002"}))}}return e}async function me(t){let e=ue(t),n=structuredClone(I);for(let o of e)try{let r=await A(o,"utf-8"),i=JSON.parse(r);n=Ue(n,i)}catch{}n=We(n);let s=He(n);return s.hadLegacyPlugins&&process.stderr.write(`[mcp] "plugins" \u5B57\u6BB5\u5DF2\u91CD\u547D\u540D\u4E3A "mcpServers"\uFF0C\u4E0B\u6B21\u5347\u7EA7\u5C06\u5220\u9664\u3002\u8BF7\u6539\u7528 "mcpServers"\u3002
2
+ `),s.config}async function z(t){let e=await me(t),n=Be(e);return{config:e,errors:n}}function Nt(t){return typeof t.command=="string"}function Ut(t){return typeof t.url=="string"}function He(t){if(!(Array.isArray(t.plugins)&&t.plugins.length>0))return t.mcpServers===void 0?{config:{...t,mcpServers:{}},hadLegacyPlugins:!1}:{config:t,hadLegacyPlugins:!1};let n={...t.mcpServers??{}};for(let s of t.plugins??[]){if(!s.name||n[s.name]!==void 0)continue;let o={command:s.command,...s.args?{args:s.args}:{},...s.env?{env:s.env}:{}};n[s.name]=o}return{config:{...t,mcpServers:n},hadLegacyPlugins:!0}}function ge(t,e){let n=ue(e).filter(r=>_e(r));n.length===0&&n.push(S(process.cwd(),".dskcode","settings.json"));let s=[],o;for(let r of n)try{let i=Me(r,d=>{d==="change"&&(o&&clearTimeout(o),o=setTimeout(()=>{(async()=>{try{let c=await me(e);t(c)}catch{}})()},300))});s.push(i)}catch{}return()=>{o&&clearTimeout(o);for(let r of s)r.close()}}async function Ft(t){let e=process.env.HOME??process.env.USERPROFILE??"~",n=S(e,".dskcode"),s=S(n,"settings.json");await U(n,{recursive:!0});let o;try{let d=await A(s,"utf-8");o=JSON.parse(d)}catch{o=structuredClone(I)}let r=o.providers??[],i=r.find(d=>d.name==="deepseek");return i?i.apiKey=t:r.push({name:"deepseek",apiKey:t,baseUrl:"https://api.deepseek.com",model:"deepseek-v4-flash"}),o.providers=r,await F(s,JSON.stringify(o,null,2),"utf-8"),s}async function Wt(t){let e=process.env.HOME??process.env.USERPROFILE??"~",n=S(e,".dskcode"),s=S(n,"settings.json");await U(n,{recursive:!0});let o;try{let c=await A(s,"utf-8");o=JSON.parse(c)}catch{o=structuredClone(I)}let r=o.providers??[],i=o.defaultProvider??"deepseek",d=r.find(c=>c.name===i);return d?d.model=t:r.push({name:i,baseUrl:"https://api.deepseek.com",model:t}),o.providers=r,await F(s,JSON.stringify(o,null,2),"utf-8"),s}async function Bt(t){let e=process.env.HOME??process.env.USERPROFILE??"~",n=S(e,".dskcode"),s=S(n,"settings.json");await U(n,{recursive:!0});let o;try{let r=await A(s,"utf-8");o=JSON.parse(r)}catch{o=structuredClone(I)}return o.stock={symbols:t},await F(s,JSON.stringify(o,null,2),"utf-8"),s}async function Ht(){let t=process.env.HOME??process.env.USERPROFILE??"~",e=S(t,".dskcode"),n=S(e,"settings.json");await U(e,{recursive:!0});let s;try{let o=await A(n,"utf-8");s=JSON.parse(o)}catch{return null}return s.permissions!==void 0?null:(s.permissions={tools:{}},await F(n,JSON.stringify(s,null,2),"utf-8"),n)}h();var Vt="ws://127.0.0.1:54006";h();import{mkdir as qe,appendFile as Je}from"fs/promises";import{fileURLToPath as Ve}from"url";import{join as G,basename as Y,sep as T}from"path";var pe="logger",fe=2e3,Ke=500;function k(){let t=process.env.HOME??process.env.USERPROFILE??"~";return G(t,".dskcode","logs")}function ze(t){return Y(t)||"_root"}var Q=class t{static#n=new Set;static async flushAll(){let e=[];for(let n of t.#n)e.push(n.flush());await Promise.allSettled(e)}static async endAllAndFlush(){let e=[];for(let n of t.#n)e.push(n.#c());await Promise.allSettled(e)}#s;#o;#t;#e=Promise.resolve();#r=0;#i=!1;#a=!1;constructor(e,n,s){if(this.#o=s?.enabled??!0,this.#t=Date.now(),!this.#o){this.#s="";return}let o=s?.logsDir??k(),r=ze(n);this.#s=G(o,r,`${e}.jsonl`),t.#n.add(this)}get logPath(){return this.#s}get enabled(){return this.#o}log(e){if(!this.#o||this.#i||this.#r>=Ke)return;let n={...e,time:e.time??Ye(e.ts),loc:e.loc??he()};this.#r++,this.#e=this.#e.then(()=>this.#d(n)).catch(()=>{}).finally(()=>this.#r--)}async flush(){this.#i=!0,await this.#e.catch(()=>{}),t.#n.delete(this)}async drain(){await this.#e.catch(()=>{})}async#c(){this.#o&&(this.#i||(this.#a||(this.logSessionEnd(Date.now()-this.#t),this.#a=!0),await this.flush()))}async#d(e){let n=G(this.#s,"..");await qe(n,{recursive:!0});let s=tt(e);await Je(this.#s,s,"utf-8")}logSessionStart(e,n,s,o){this.log({ts:Date.now(),type:"session_start",sessionId:e,cwd:n,model:s,mode:o})}logUserMessage(e){this.log({ts:Date.now(),type:"user_message",content:e})}logAssistantText(e,n){this.log({ts:Date.now(),type:"assistant_text",content:e,round:n})}logReasoning(e,n){this.log({ts:Date.now(),type:"reasoning",content:e,round:n})}logToolCall(e,n,s,o,r){this.log({ts:Date.now(),type:"tool_call",name:e,callId:n,arguments:s,...r!==void 0?{parsedArgs:r}:{},round:o})}logToolResult(e,n,s,o,r,i,d,c){this.log({ts:Date.now(),type:"tool_result",name:e,callId:n,success:s,data:Ge(o),...r?{error:r}:{},...i!==void 0?{elapsed:i}:{},...c?{schemaIssues:c}:{},round:d})}logUsage(e,n,s,o,r,i){this.log({ts:Date.now(),type:"usage",model:e,promptTokens:n,completionTokens:s,...o!==void 0?{cachedPromptTokens:o}:{},cost:r,round:i})}logError(e,n){this.log({ts:Date.now(),type:"error",message:e,...n?{stack:n}:{}})}logTurnDone(e,n){this.log({ts:Date.now(),type:"turn_done",elapsed:e,toolRounds:n})}logSessionEnd(e){this.log({ts:Date.now(),type:"session_end",elapsed:e})}logReflections(e){this.log({ts:Date.now(),type:"reflection",items:e})}};function Ge(t){return t.length<=fe?t:t.slice(0,fe)+`...[\u5DF2\u622A\u65AD\uFF0C\u539F\u59CB\u957F\u5EA6 ${t.length}]`}function Ye(t){let e=new Date(t),n=(s,o=2)=>String(s).padStart(o,"0");return`${e.getFullYear()}-${n(e.getMonth()+1)}-${n(e.getDate())} ${n(e.getHours())}:${n(e.getMinutes())}:${n(e.getSeconds())}.${n(e.getMilliseconds(),3)}`}var _=null;function Qe(){if(_!==null)return _;try{let t=Ve(import.meta.url),e=t.split(T),n=e.lastIndexOf("src");_=n>0?e.slice(0,n).join(T):t}catch{_=""}return _}var Xe=/\s+at\s+.+?\((.+):(\d+):\d+\)|\s+at\s+(.+):(\d+):\d+/;function he(){let t;try{let s=new Error;Error.captureStackTrace?.(s,he),t=s.stack}catch{return{file:"<unknown>",line:0}}if(!t)return{file:"<unknown>",line:0};let e=Qe(),n=t.split(`
3
+ `);for(let s of n){let o=Xe.exec(s);if(!o)continue;let r=o[1]??o[3]??"",i=Number(o[2]??o[4]??"0");if(!r)continue;let d=r.replace(/^file:\/\/\//,"").replace(/^file:\/\//,"");if(d.includes(`${T}${pe}${T}`)||d.endsWith(`${T}${pe}`)||d.includes(`${T}node_modules${T}`))continue;let c=d;return e&&d.startsWith(e)&&(c=d.slice(e.length).replace(/^[/\\]/,"")||Y(d)),{file:c||Y(d),line:i}}return{file:"<unknown>",line:0}}var Ze=80,et="\u2500".repeat(Ze);function tt(t){let e=`[${t.time}] [${t.type}] @ ${t.loc.file}:${t.loc.line}`,n=JSON.stringify(t,null,2);return`${et}
4
+ ${e}
5
+ ${n}
6
+
7
+ `}h();h();var nt="\u2500".repeat(80);function ve(t){return t.split(nt).map(e=>e.trim()).filter(e=>e.length>0)}function st(t){let e=t.split(`
8
+ `),n=e.findIndex(s=>s.trimStart().startsWith("{"));if(n<0)throw new Error("log block: \u627E\u4E0D\u5230 JSON \u8D77\u59CB\u884C");return e.slice(n).join(`
9
+ `)}function ye(t){let e;try{e=st(t)}catch(n){let s=t.slice(0,200);throw new Error(`parseBlock \u5931\u8D25: ${n.message}; block \u9884\u89C8: ${s}`)}return JSON.parse(e)}function X(t){let e=ve(t),n=[];for(let s of e)try{n.push(ye(s))}catch{}return n}h();import{readdir as Re,readFile as ot,stat as rt}from"fs/promises";import{join as Z,basename as rn,sep as an}from"path";function it(t){for(let e of t)if(e.type==="session_start")return{startedAt:e.ts,cwd:e.cwd??"",model:e.model??""};return{startedAt:0,cwd:"",model:""}}async function W(t,e,n){let s=Z(t,e,`${n}.jsonl`);try{let[o,r]=await Promise.all([rt(s),ot(s,"utf-8")]);return{events:X(r),size:o.size,mtime:o.mtimeMs}}catch(o){if(o.code==="ENOENT")return{events:[],size:0,mtime:0};throw o}}function O(t,e){if(!/^[A-Za-z0-9._-]+$/.test(t))throw new Error(`${e} \u5305\u542B\u975E\u6CD5\u5B57\u7B26: ${t}`)}async function ee(t,e=k()){let n;try{n=await Re(e)}catch(r){if(r.code==="ENOENT")return{projects:[],sessions:[]};throw r}let s=[],o=[];for(let r of n){if(!/^[A-Za-z0-9._-]+$/.test(r)||t.projectName&&r!==t.projectName)continue;let i=Z(e,r),d;try{d=await Re(i)}catch{continue}let c=!1;for(let g of d){if(!g.endsWith(".jsonl"))continue;let v=g.slice(0,-6);if(/^[A-Za-z0-9._-]+$/.test(v))try{let{events:f,size:L,mtime:q}=await W(e,r,v);if(t.activeOnly){if(f.some(x=>x.type==="session_end"))continue;let $=t.activeStaleMs??10*6e4;if($>0&&f.length>0){let x=f[f.length-1];if(x&&Date.now()-x.ts>$)continue}}let R=it(f);o.push({project:r,sessionId:v,size:L,mtime:q,startedAt:R.startedAt,cwd:R.cwd,model:R.model}),c=!0}catch{}}c&&s.push(r)}return s.sort((r,i)=>r.localeCompare(i)),o.sort((r,i)=>i.startedAt-r.startedAt),{projects:s,sessions:o}}async function B(t,e=k()){O(t.project,"project"),O(t.sessionId,"sessionId");let{events:n,size:s,mtime:o}=await W(e,t.project,t.sessionId),r=n.length,i=Math.max(0,t.fromIndex??0),d=Math.max(1,Math.min(t.limit??200,2e3)),c=n.slice(i,i+d);return{project:t.project,sessionId:t.sessionId,total:r,events:c,hasMore:i+c.length<r,size:s,mtime:o}}async function te(t,e=k(),n){O(t.project,"project"),O(t.sessionId,"sessionId");let s=Z(e,t.project,`${t.sessionId}.jsonl`),o=Math.max(100,Math.min(t.timeoutMs??3e4,12e4)),r=Math.max(50,Math.min(t.pollIntervalMs??300,2e3)),i=Math.max(0,t.fromIndex??0),c=Date.now()+o,g=await W(e,t.project,t.sessionId);if(g.events.length>i)return{project:t.project,sessionId:t.sessionId,events:g.events.slice(i),total:g.events.length,timedOut:!1};for(;;){if(n?.aborted)return{project:t.project,sessionId:t.sessionId,events:[],total:g.events.length,timedOut:!0};if(Date.now()>=c)return{project:t.project,sessionId:t.sessionId,events:[],total:g.events.length,timedOut:!0};if(await new Promise(f=>setTimeout(f,r)),n?.aborted)return{project:t.project,sessionId:t.sessionId,events:[],total:g.events.length,timedOut:!0};let v;try{v=await W(e,t.project,t.sessionId)}catch{continue}if(v.events.length>i)return{project:t.project,sessionId:t.sessionId,events:v.events.slice(i),total:v.events.length,timedOut:!1}}}async function ne(t,e=k()){if(!t.content||!t.content.trim())throw new Error("EMPTY_CONTENT: content \u4E0D\u80FD\u4E3A\u7A7A");O(t.project,"project"),O(t.sessionId,"sessionId");let{SessionRegistry:n}=await import("./session-registry-HSCHBXFO.js"),s=n.get(t.project,t.sessionId);if(!s)throw new Error(`SESSION_NOT_FOUND: \u8FDB\u7A0B\u5185\u6CA1\u6709\u627E\u5230 sessionId=${t.sessionId} (project=${t.project})\u3002\u53EF\u80FD\u8BE5 dskcode \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u6216 model \u5207\u6362\u5BFC\u81F4 session \u88AB\u91CD\u5EFA\u3002`);if(s.remoteInput)try{await s.remoteInput.onRemoteUserInput(t.content,"chrome")}catch(r){let i=r instanceof Error?r:new Error(String(r));throw new Error(`REMOTE_REJECTED: ${i.message}`,{cause:i})}else try{for await(let r of s.session.chat(t.content));}catch(r){let i=r instanceof Error?r:new Error(String(r));throw new Error(`CHAT_FAILED: ${i.message}`,{cause:i})}if(s.flushLogger)try{await s.flushLogger()}catch{}else await new Promise(r=>setTimeout(r,50));return{ok:!0,accepted:!0,totalEvents:(await B({project:t.project,sessionId:t.sessionId,fromIndex:0,limit:1},e)).total}}h();import{WebSocketServer as bt}from"ws";import{EventEmitter as Et}from"events";import{copyFile as kt,mkdir as Lt,readFile as xt,writeFile as Tt}from"fs/promises";import{existsSync as ce}from"fs";import{join as de}from"path";import{randomUUID as Ct}from"crypto";import{readFileSync as It}from"fs";import{fileURLToPath as Ot}from"url";h();h();import{EventEmitter as at}from"events";var se="permission.request",oe="permission.resolved",H=class{#n;#s;#o;#t=new Map;#e=new at;constructor(e){this.#n=e.broadcast,this.#s=e.timeoutMs??1800*1e3,this.#o=e.uuid??(()=>globalThis.crypto.randomUUID())}onRequest(e){return this.#e.on(se,e),()=>{this.#e.off(se,e)}}onResolved(e){return this.#e.on(oe,e),()=>{this.#e.off(oe,e)}}register(e){let n=this.#o(),s=new Promise(r=>{let i={resolve:r,createdAt:Date.now(),timer:null};i.timer=setTimeout(()=>{this.#r(n,"no","timeout")},this.#s),typeof i.timer.unref=="function"&&i.timer.unref(),this.#t.set(n,i)}),o={requestId:n,toolName:e.toolName,args:e.args,reason:e.reason,ruleAction:e.ruleAction,createdAt:Date.now()};return this.#n({kind:"event",method:"event.permission.request",payload:o}),this.#e.emit(se,o),{requestId:n,promise:s}}respond(e,n,s){return this.#r(e,n,s)}handleRpc(e){return!e||typeof e.requestId!="string"||e.requestId.length===0?{ok:!1,code:"BAD_REQUEST",message:"requestId missing"}:e.response!=="yes"&&e.response!=="no"&&e.response!=="always"?{ok:!1,code:"BAD_REQUEST",message:"invalid response"}:this.respond(e.requestId,e.response,"chrome")?{ok:!0,result:{accepted:!0}}:{ok:!1,code:"ALREADY_RESOLVED",message:"prompt already resolved"}}get pendingCount(){return this.#t.size}reset(){for(let e of this.#t.values())e.timer&&clearTimeout(e.timer);this.#t.clear()}#r(e,n,s){let o=this.#t.get(e);if(!o)return!1;this.#t.delete(e),o.timer&&clearTimeout(o.timer),o.resolve(n);let r={requestId:e,response:n,resolvedBy:s};return this.#n({kind:"event",method:"event.permission.resolved",payload:r}),this.#e.emit(oe,r),!0}};function Se(t,e){return n=>e(t,n)}h();import{mkdir as ct,readFile as Ln,writeFile as dt,unlink as lt}from"fs/promises";import{randomUUID as ut}from"crypto";import{existsSync as mt}from"fs";import{join as gt,dirname as pt}from"path";import{rename as ft}from"fs";function Pe(t){let e=t??process.env.HOME??process.env.USERPROFILE??"";return gt(e,".dskcode","config-ui.json")}async function we(t,e){let n=Pe(e);await ct(pt(n),{recursive:!0});let s={version:1,token:ut(),endpoints:{ws:t},pid:process.pid,startedAt:new Date().toISOString()},o=n+".tmp";return await dt(o,JSON.stringify(s,null,2)+`
10
+ `,"utf8"),await ht(o,n),n}async function be(t){let e=Pe(t);if(mt(e))try{await lt(e)}catch{}}async function ht(t,e){await new Promise((n,s)=>{ft(t,e,o=>o?s(o):n())})}h();import{appendFile as vt,mkdir as yt,truncate as Rt}from"fs/promises";import{existsSync as St}from"fs";import{join as Ee}from"path";function ke(t){let e=t??process.env.HOME??process.env.USERPROFILE??"";return Ee(e,".dskcode","wslog.jsonl")}async function Le(t={}){if(t.disabled)return{path:"",log:()=>{},close:async()=>{}};let e=ke(t.home);try{await yt(Ee(e,".."),{recursive:!0})}catch{return{path:"",log:()=>{},close:async()=>{}}}let n=()=>new Date().toISOString();return{path:e,log(s){let o={ts:n(),pid:process.pid,...s},r;try{r=JSON.stringify(o)+`
11
+ `}catch{return}vt(e,r,"utf8").catch(()=>{})},async close(){}}}function xe(t){return!t||typeof t!="object"?[]:Object.keys(t)}async function Te(t){let e=ke(t);if(e&&St(e))try{await Rt(e,0)}catch{}}function M(t,e=1024){return t?t.length<=e?t:t.slice(0,e)+"\u2026(truncated)":""}var C=null;function re(){if(C!==null)return C;try{let t=[new URL("../../package.json",import.meta.url),new URL("../../../package.json",import.meta.url)];for(let e of t)try{let n=Ot(e),s=It(n,"utf8");return C=JSON.parse(s).version??"0.0.0",C}catch{}C="unknown"}catch{C="unknown"}return C}var le=class extends Error{constructor(n,s){super(`\u7AEF\u53E3 ${s} \u5DF2\u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\uFF08\u591A\u534A\u662F\u53E6\u4E00\u4E2A dskcode\uFF09\u3002\u5982\u679C\u662F\u53E6\u4E00\u4EFD dskcode \u5148\u542F\u7684 ws\uFF0C\u8981\u4E48\u5148\u5173\u6389\u5B83\uFF0C\u8981\u4E48\u6539\u672C\u4FA7 host:port\u3002`);this.host=n;this.port=s;this.name="PortInUseError"}host;port};function j(t){if(t)return t;let e=process.env.HOME??process.env.USERPROFILE??"",n=de(e,".dskcode","settings.json");if(ce(n))return n;let s=de(process.cwd(),".dskcode","settings.json");return ce(s)?s:n}async function jt(t,e){let n=j(e);await Lt(de(n,".."),{recursive:!0});let s={};try{let r=await xt(n,"utf8"),i=JSON.parse(r);i&&typeof i=="object"&&(s=i)}catch{s=structuredClone(I)}for(let[r,i]of Object.entries(t))i!==void 0&&(s[r]=i);let o=JSON.stringify(s,null,2)+`
12
+ `;if(ce(n))try{await kt(n,n+".bak")}catch{}return await At(n,o),n}async function At(t,e){let n=[0,200,500,1500,3e3],s;for(let o of n){o>0&&await new Promise(r=>setTimeout(r,o));try{await Tt(t,e,"utf8");return}catch(r){if(s=r,process.platform!=="win32")throw r;let i=r.code;if(i!=="EPERM"&&i!=="EACCES"&&i!=="EBUSY")throw r}}throw s}async function Zn(t={}){let e=t.host??"127.0.0.1",n=t.port??54006,s=Ct(),o=t.logsDir??k();t.disableWsLog!==!0&&t.truncateWsLogOnStart!==!1&&await Te(t.home);let r=await Le({home:t.home,disabled:t.disableWsLog===!0}),i=new bt({host:e,port:n}),d=new Et,c="config.reloaded",g=0,v=a=>{let p=j(t.configPath),u={configPath:p,source:a},l=ie(R,{kind:"event",method:"event.runtime.reload",payload:u});return d.emit(c,u),r.log({kind:"reload.emit",source:a,configPath:p,subscribers:R.size}),l};function f(a,p,u){ae(a,{id:p,ok:!0,result:u});let y=a._socket;r.log({kind:"rpc.out",clientIp:y?.remoteAddress,id:p,ok:!0,resultKeys:u&&typeof u=="object"?Object.keys(u):[]})}function L(a,p,u){ae(a,{id:p,ok:!1,error:u});let y=a._socket;r.log({kind:"rpc.err",clientIp:y?.remoteAddress,id:p,code:u?.code,message:M(u?.message,200)})}let q=new Promise((a,p)=>{i.once("listening",()=>{let u=i.address();a({port:u.port})}),i.once("error",u=>{u&&u.code==="EADDRINUSE"?p(new le(e,n)):p(u instanceof Error?u:new Error(String(u)))})});t.autoStart;let R=new Set,D=new H({broadcast:Se(R,ie)});i.on("connection",a=>{let p=a._socket,u=p?.remoteAddress??"unknown",l=p?.remotePort??0,y=Date.now();r.log({kind:"client.connect",clientIp:u,clientPort:l});let m={kind:"hello",version:1,configPath:j(t.configPath),authToken:s,dskcodeVersion:re()};ae(a,m),r.log({kind:"client.hello",clientIp:u,clientPort:l}),a.on("message",P=>{Ce(a,P.toString())}),a.on("close",(P,N)=>{R.delete(a);let Ae=N?N.toString():"";r.log({kind:"client.disconnect",clientIp:u,clientPort:l,code:P,reason:M(Ae,200),durationMs:Date.now()-y})}),a.on("error",P=>{R.delete(a),r.log({kind:"client.error",clientIp:u,clientPort:l,message:M(P?.message,200)})}),R.add(a)});let $=ge(async a=>{if(Date.now()<g){r.log({kind:"config.changed",suppressed:!0});return}await ie(R,{kind:"event",method:"event.config.changed",payload:{config:a,configPath:j(t.configPath),source:"file"}});let p=j(t.configPath);d.emit(c,{configPath:p,source:"file"}),r.log({kind:"config.changed",source:"file",configPath:p,keyCount:a&&typeof a=="object"?Object.keys(a).length:0,subscribers:R.size})},t.configPath),{port:x}=await q,J=`ws://${e}:${x}`,V="";t.persistConnectionInfo!==!1&&(t.home&&(process.env.HOME=t.home,process.env.USERPROFILE=t.home),V=await we(J,t.home)),r.log({kind:"server.start",host:e,port:x,url:J,pid:process.pid,dskcodeVersion:re(),connectionInfoPath:V||null,logPath:r.path||null,truncated:t.disableWsLog!==!0&&t.truncateWsLogOnStart!==!1});let K={ws:i,host:e,port:x,url:J,connectionInfoPath:V,authToken:s,dskcodeVersion:re(),onConfigChanged:a=>(d.on(c,a),()=>d.off(c,a)),notifyReload:a=>v(a),permissionBroker:D,close:async()=>{D.reset(),r.log({kind:"server.close",reason:"explicit"}),$(),d.removeAllListeners(c);for(let a of R)try{a.close()}catch{}await new Promise(a=>i.close(()=>a())),t.persistConnectionInfo!==!1&&await be(t.home),await r.close()}};return K.__suppressEchoUntil=a=>{g=a},K;async function Ce(a,p){let u=a._socket,l;try{l=JSON.parse(p)}catch{return r.log({kind:"rpc.in",clientIp:u?.remoteAddress,parseError:!0,preview:M(p,200)}),L(a,0,{code:"BAD_JSON",message:"invalid JSON"})}if(typeof l.id!="number"||typeof l.method!="string")return r.log({kind:"rpc.in",clientIp:u?.remoteAddress,method:l?.method,badShape:!0}),L(a,0,{code:"BAD_REQUEST",message:"id/method missing"});r.log({kind:"rpc.in",clientIp:u?.remoteAddress,id:l.id,method:l.method});let y=l.params??{};if(y.token!==s){let m=y.token;return r.log({kind:"rpc.auth_fail",clientIp:u?.remoteAddress,id:l.id,method:l.method,tokenProvided:typeof m=="string"&&m.length>0,tokenLen:typeof m=="string"?m.length:0}),L(a,l.id,{code:"UNAUTHORIZED",message:"bad token"})}try{switch(l.method){case"config.get":return await f(a,l.id,await Ie(t.configPath));case"config.set":{let m=await Oe(y.patch??{},t.configPath,K.__suppressEchoUntil);f(a,l.id,m),await v("api");return}case"config.schema":return f(a,l.id,je());case"config.watch.subscribe":return f(a,l.id,{subscribed:!0});case"logs.list":{let m=await ee(y??{},o);return f(a,l.id,m)}case"logs.read":{let m=await B(y,o);return f(a,l.id,m)}case"logs.tail":{let m=new AbortController,P=()=>m.abort();a.once("close",P);try{let N=await te(y,o,m.signal);return f(a,l.id,N)}finally{a.off("close",P)}}case"chat.send":{let m=await ne(y,o);return f(a,l.id,m)}case"permission.respond":{let m=D.handleRpc(y);return m.ok?f(a,l.id,m.result):L(a,l.id,{code:m.code,message:m.message})}case"ping":return f(a,l.id,{pong:Date.now()});default:return L(a,l.id,{code:"UNKNOWN_METHOD",message:`unknown method: ${l.method}`})}}catch(m){let P=m;return L(a,l.id,{code:"INTERNAL",message:P.message??String(m)})}}async function Ie(a){let{config:p,errors:u}=await z(a);return{config:p,errors:u,configPath:j(a)}}async function Oe(a,p,u){u(Date.now()+3e3);let l=await jt(a,p),{config:y,errors:m}=await z(p);return r.log({kind:"config.set",configPath:l,keys:xe(a),keyCount:Object.keys(y).length,errorCount:m.length}),{config:y,errors:m,configPath:l}}function je(){return{fields:{defaultProvider:{label:"\u9ED8\u8BA4 Provider",type:"string",help:"providers \u5217\u8868\u4E2D\u67D0\u4E2A name"},verbose:{label:"\u8BE6\u7EC6\u65E5\u5FD7",type:"boolean"},maxTokens:{label:"\u6700\u5927 Token \u6570",type:"number",min:1,max:32768},temperature:{label:"\u6E29\u5EA6 (0~2)",type:"number",min:0,max:2,help:"\u8D8A\u9AD8\u8D8A\u53D1\u6563"},maxToolRounds:{label:"\u5355\u4F1A\u8BDD\u6700\u5927\u5DE5\u5177\u8F6E\u6B21",type:"number",min:1,max:100},budgetLimit:{label:"\u6BCF\u65E5\u9884\u7B97 (\u5143, 0=\u4E0D\u9650)",type:"number",min:0},tokenBudgetLimit:{label:"\u6BCF\u65E5 Token \u9884\u7B97 (0=\u4E0D\u9650)",type:"number",min:0},providers:{label:"Provider \u5217\u8868 (\u9AD8\u7EA7)",type:"list-string",help:"\u5EFA\u8BAE\u6539\u7528\u7EC8\u7AEF chat"},tools:{label:"\u5185\u7F6E\u5DE5\u5177 (\u9AD8\u7EA7)",type:"list-string"},mcpServers:{label:"MCP \u670D\u52A1\u5668 (\u9AD8\u7EA7)",type:"object-map",help:"\u952E\u4E3A server id\uFF0C\u503C\u4E3A stdio (\u542B command) \u6216 http (\u542B url) \u914D\u7F6E\u3002"},mcpServerTimeout:{label:"MCP \u5168\u5C40\u8D85\u65F6 (\u79D2)",type:"number",min:1,max:3600,help:"\u5404 server \u672A\u6307\u5B9A timeout \u65F6\u53D6\u8BE5\u503C\uFF0C\u9ED8\u8BA4 60\u3002"},legacyPlugins:{label:"\u65E7 plugins \u5B57\u6BB5 (\u5DF2\u5E9F\u5F03)",type:"list-string",help:"\u4EC5\u5411\u540E\u517C\u5BB9 1 \u4E2A\u7248\u672C\uFF1B\u8BF7\u6539\u7528 mcpServers\u3002"},"stock.symbols":{label:"\u81EA\u9009\u80A1\u4EE3\u7801\u5217\u8868",type:"list-string",help:"\u5982 sh513090 / sz000001"},"voice.appId":{label:"\u8BED\u97F3 App ID",type:"string"},"voice.accessKey":{label:"\u8BED\u97F3 Access Key",type:"string"},"thinking.enabled":{label:"\u6DF1\u5EA6\u601D\u8003",type:"boolean",help:"\u542F\u7528\u540E\u6A21\u578B\u56DE\u7B54\u524D\u4F1A\u8FDB\u884C\u66F4\u957F\u7684\u63A8\u7406\uFF08\u4EC5\u90E8\u5206\u6A21\u578B\u652F\u6301\uFF09"},"thinking.effort":{label:"\u601D\u8003\u5F3A\u5EA6",type:"select",enum:["high","max"],help:"high = \u6807\u51C6\u6DF1\u5EA6, max = \u6700\u5927\u52AA\u529B"},"permissions.default":{label:"\u6743\u9650\u5BA1\u6279\u9ED8\u8BA4\u7B56\u7565",type:"select",enum:["confirm","allow","deny"],help:"\u672A\u547D\u4E2D\u6B63\u5219\u89C4\u5219\u65F6\u7684\u9ED8\u8BA4\u884C\u4E3A"}}}}}async function ie(t,e){let n=JSON.stringify(e);for(let s of t)if(s.readyState===s.OPEN)try{s.send(n)}catch{}}function ae(t,e){t.readyState===t.OPEN&&t.send(JSON.stringify(e))}export{I as a,$t as b,z as c,Nt as d,Ut as e,Ft as f,Wt as g,Bt as h,Ht as i,Vt as j,Q as k,Zn as l};
13
+ //# sourceMappingURL=chunk-EEH2ZJA5.js.map
@@ -0,0 +1,11 @@
1
+ import{d as v,e as y}from"./chunk-EEH2ZJA5.js";import{d as p}from"./chunk-LPD7BHH5.js";p();p();p();import{mkdir as H,readFile as K,writeFile as q}from"fs/promises";import{dirname as F}from"path";function U(o){let e=process.env.VOLC_ASR_APP_ID?.trim(),t=process.env.VOLC_ASR_ACCESS_KEY?.trim(),r=e||o?.appId||"",s=t||o?.accessKey||"",i={appId:e?"env":o?.appId?"settings":"missing",accessKey:t?"env":o?.accessKey?"settings":"missing"},n=[];return r||n.push("appId"),s||n.push("accessKey"),{resolved:n.length===0,missing:n.length>0?n:void 0,source:i,config:{appId:r,accessKey:s,resourceId:o?.resourceId??"volc.bigasr.sauc.duration",language:o?.language??"zh-CN",sampleRate:o?.sampleRate??16e3,enabled:o?.enabled??!0}}}async function B(o,e,t,r){let s={};try{let n=await K(o,"utf8"),c=JSON.parse(n);c&&typeof c=="object"&&(s=c)}catch(n){if(n.code!=="ENOENT")throw n}let i=s.voice??{appId:"",accessKey:""};s.voice={...i,appId:e,accessKey:t,resourceId:r?.resourceId??i.resourceId??"volc.bigasr.sauc.duration",language:r?.language??i.language??"zh-CN",enabled:i.enabled??!0},await H(F(o),{recursive:!0}),await q(o,JSON.stringify(s,null,2)+`
2
+ `,"utf8")}p();p();var a=class extends Error{constructor(t,r,s){super(t,s);this.kind=r;this.name="TransportError"}kind},u=class extends Error{constructor(t,r,s){super(`MCP server "${t}" \u542F\u52A8\u5931\u8D25\uFF1A${r}`,s);this.serverId=t;this.name="McpStartupError"}serverId};var w=class extends Error{constructor(e,t){super(e,t),this.name="McpProtocolError"}};p();import{spawn as G}from"child_process";import{existsSync as W}from"fs";import{isAbsolute as k}from"path";import{createInterface as O}from"readline";var z=3e3;function Y(o){return!(process.platform!=="win32"||k(o)||o.includes("/")||o.includes("\\")||/\.(exe|cmd|bat|com)$/i.test(o))}var M=class{#e=null;#n=null;#t=null;#s=!1;#r=null;constructor(e){if(!e.command||typeof e.command!="string")throw new a("stdio transport: command \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32","spawn_failed");if(k(e.command)&&!W(e.command))throw new a(`stdio transport: \u547D\u4EE4\u4E0D\u5B58\u5728 "${e.command}"`,"spawn_failed");try{this.#e=G(e.command,e.args??[],{env:{...process.env,...e.env??{}},cwd:e.cwd,stdio:["pipe","pipe","pipe"],windowsHide:!0,shell:Y(e.command)})}catch(n){throw new a(`stdio transport: \u65E0\u6CD5\u542F\u52A8\u547D\u4EE4 "${e.command}"\uFF1A${n.message}`,"spawn_failed",{cause:n})}let t=new Promise(n=>{let c=!1,d=()=>{c||(c=!0,n(null))};this.#e.once("error",l=>{c||(c=!0,n(l))}),this.#e.once("spawn",()=>d())});this.#e.once("exit",(n,c)=>{this.#s||n!==0&&(this.#r||(this.#r=new Error(`stdio transport: \u5B50\u8FDB\u7A0B\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08exit code=${n}, signal=${c??"null"}\uFF09`)))}),(async()=>{let n=await Promise.race([t,new Promise(c=>setTimeout(()=>c(null),50))]);n&&(this.#s=!0,this.#r=n)})();let r=this.#e.stdout;if(!r)throw new a("stdio transport: \u7F3A\u5C11 stdout pipe","spawn_failed");let s=O({input:r,crlfDelay:1/0});this.#n=s[Symbol.asyncIterator]();let i=this.#e.stderr;if(i){let n=O({input:i,crlfDelay:1/0});this.#t=n[Symbol.asyncIterator]()}else this.#t=(async function*(){})()}async send(e){if(this.#r)throw new a(`stdio transport: \u5B50\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25\uFF08${this.#r.message}\uFF09`,"spawn_failed",{cause:this.#r});if(this.#s||!this.#e?.stdin?.writable)throw new a("stdio transport: \u8FDE\u63A5\u5DF2\u5173\u95ED","closed");return new Promise((t,r)=>{let s=this.#e.stdin;s.write(`${e}
3
+ `,n=>{n&&r(new a(`stdio write \u5931\u8D25\uFF1A${n.message}`,"io_error",{cause:n}))})?t():(s.once("drain",()=>t()),s.once("error",n=>{r(new a(`stdio write \u5931\u8D25\uFF1A${n.message}`,"io_error",{cause:n}))}))})}async*receive(){if(!this.#n)throw new a("stdio transport: \u672A\u521D\u59CB\u5316","io_error");if(this.#r)throw new a(`stdio transport: \u5B50\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25\uFF08${this.#r.message}\uFF09`,"spawn_failed",{cause:this.#r});try{for(;;){let{value:e,done:t}=await this.#n.next();if(t){if(this.#r){let r=this.#r;throw new a(`stdio transport: \u5B50\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25\uFF08${r.message}\uFF09`,"spawn_failed",{cause:r})}return}typeof e=="string"&&e.length>0&&(yield e)}}catch(e){if(this.#s)return;throw e instanceof a?e:new a(`stdio read \u5931\u8D25\uFF1A${e.message}`,"io_error",{cause:e})}}async*receiveErr(){if(this.#t)try{for(;;){let{value:e,done:t}=await this.#t.next();if(t)return;typeof e=="string"&&(yield e)}}catch{return}}isAlive(){return!this.#s&&this.#e?.exitCode===null}async dispose(){if(this.#s)return;this.#s=!0;let e=this.#e;if(this.#e=null,!e||e.exitCode!==null)return;try{e.kill("SIGTERM")}catch{}if(!await Promise.race([new Promise(r=>{if(e.exitCode!==null)return r(!0);e.once("exit",()=>r(!0)),setTimeout(()=>r(!1),z)})]))try{e.kill("SIGKILL")}catch{}}};p();var A="Mcp-Session-Id",Q="MCP-Protocol-Version",E="application/json",L="text/event-stream",R=class{#e;#n=null;#t=null;#s=!1;#r=[];#o=null;#a=null;constructor(e){if(!e.url||!/^https?:\/\//i.test(e.url))throw new a(`http transport: url \u5FC5\u987B\u662F http(s) \u534F\u8BAE\uFF0C\u5F53\u524D\u4E3A "${e.url}"`,"spawn_failed");this.#e=e}setProtocolVersion(e){this.#t=e}isAlive(){return!this.#s}async send(e){if(this.#s)throw new a("http transport: \u8FDE\u63A5\u5DF2\u5173\u95ED","closed");let t={"Content-Type":E,Accept:`${E}, ${L}`,...this.#e.headers??{}};this.#n&&(t[A]=this.#n),this.#t&&(t[Q]=this.#t);let r;try{r=await fetch(this.#e.url,{method:"POST",headers:t,body:e})}catch(n){throw new a(`http transport: \u8BF7\u6C42\u5931\u8D25\uFF1A${n.message}`,"io_error",{cause:n})}let s=r.headers.get(A);if(s&&(this.#n=s),r.status===202)return;if(!r.ok){let n=await r.text().catch(()=>"");throw new a(`http transport: HTTP ${r.status}\uFF1A${n||r.statusText}`,r.status===401?"auth_required":"http_status")}let i=r.headers.get("content-type")??"";if(i.includes(L)){let n=r.body?.getReader();if(!n)throw new a("http transport: SSE \u54CD\u5E94\u7F3A\u5C11 body","io_error");let c=new TextDecoder,d="";(async()=>{try{for(;;){let{value:l,done:S}=await n.read();if(S)break;d+=c.decode(l,{stream:!0});let f;for(;(f=X(d))!==-1;){let h=d.slice(0,f),V=d.slice(f,f+4)===`\r
4
+ \r
5
+ `?4:2;d=d.slice(f+V);let _=N(h);_&&this.#c(_)}}}catch(l){this.#i(new a(`http SSE \u9519\u8BEF\uFF1A${l.message}`,"io_error",{cause:l}))}finally{let l=N(d);l&&this.#c(l)}})();return}if(i.includes(E)){let n=await r.text();n.length>0&&this.#c(n);return}throw new a(`http transport: \u610F\u5916\u7684 Content-Type "${i}"`,"io_error")}async*receive(){for(;!this.#s;){if(this.#a){let t=this.#a;throw this.#a=null,t}if(this.#r.length>0){yield this.#r.shift();continue}let e=await new Promise(t=>{this.#o=t});if(this.#o=null,e.done)return;yield e.value}}async*receiveErr(){}async dispose(){this.#s||(this.#s=!0,this.#i(new a("http transport: disposed","closed")))}#c(e){if(this.#o){let t=this.#o;this.#o=null,t({value:e,done:!1})}else this.#r.push(e)}#i(e){if(this.#o){let t=this.#o;this.#o=null,t({value:void 0,done:!0}),this.#a=e}else this.#a=e}};function X(o){let e=o.indexOf(`
6
+
7
+ `),t=o.indexOf(`\r
8
+ \r
9
+ `),r=o.indexOf("\r\r"),s=-1;return e!==-1&&(s=e),t!==-1&&(s===-1||t<s)&&(s=t),r!==-1&&(s===-1||r<s)&&(s=r),s}function N(o){let e=o.split(/\r\n|\n|\r/),t=[];for(let s of e)if(!s.startsWith(":")&&s.startsWith("data:")){let i=s.replace(/^data:\s?/,"");t.push(i)}if(t.length===0)return null;let r=t.join(`
10
+ `);return r==="ping"?null:r}function $(o){let{serverId:e,settings:t}=o,r=t.timeout??o.globalTimeoutSeconds??60;if(v(t)&&y(t))throw new u(e,"MCP server \u4E0D\u80FD\u540C\u65F6\u4E3A stdio \u4E0E http\uFF1B\u8BF7\u4E8C\u9009\u4E00\uFF08\u79FB\u9664 command \u6216 url \u5B57\u6BB5\uFF09");if(!v(t)&&!y(t))throw new u(e,"MCP server \u914D\u7F6E\u7F3A\u5C11 command\uFF08stdio\uFF09\u6216 url\uFF08http\uFF09\u5B57\u6BB5");return v(t)?Z(e,t,r):ee(e,t,r)}function Z(o,e,t){try{return new M({command:e.command,args:e.args,env:e.env})}catch(r){throw r instanceof a?new u(o,r.message,{cause:r}):r}}function ee(o,e,t){te(o,e.url);try{return new R({url:e.url,headers:e.headers})}catch(r){throw r instanceof a?new u(o,r.message,{cause:r}):r}}function te(o,e){let t;try{t=new URL(e)}catch{throw new u(o,`url \u89E3\u6790\u5931\u8D25\uFF1A${e}`)}let r=t.protocol.toLowerCase();if(r!=="https:"){if(r==="http:"){let s=t.hostname.toLowerCase();if(s==="localhost"||s==="127.0.0.1"||s==="::1")return;throw new u(o,`\u4E0D\u5141\u8BB8\u7684 http URL "${e}"\uFF1A\u4EC5\u5141\u8BB8 https:// \u6216 http://localhost/127.0.0.1\uFF08\u9632 SSRF\uFF09`)}throw new u(o,`\u4E0D\u652F\u6301\u7684 URL scheme "${r}"\uFF1A\u4EC5\u5141\u8BB8 http(s)://`)}}p();p();var I=class extends Error{constructor(t,r,s){super(`JSON-RPC "${t}" \u8D85\u65F6\uFF08${r}ms\uFF09`);this.method=t;this.timeoutMs=r;this.serverId=s;this.name="JsonRpcTimeoutError"}method;timeoutMs;serverId},x=class extends Error{constructor(t,r){super(`JSON-RPC "${t}" \u5DF2\u53D6\u6D88`);this.method=t;this.serverId=r;this.name="JsonRpcCanceledError"}method;serverId},P=class extends Error{constructor(t,r,s){super(`JSON-RPC "${t}" \u8FD4\u56DE\u9519\u8BEF [${r.code}]\uFF1A${r.message}`);this.method=t;this.payload=r;this.serverId=s;this.name="JsonRpcRemoteError"}method;payload;serverId},b=class{#e;#n;#t;#s;#r=new Map;#o=new Map;#a=null;#c=null;#i=!1;constructor(e,t={}){this.#e=e,this.#n=t.defaultTimeoutMs??3e4,this.#t=t.serverId;try{this.#s=new Int32Array(new SharedArrayBuffer(4))}catch{let r=new ArrayBuffer(4);this.#s=new Int32Array(r)}this.#f(),this.#u()}async request(e,t,r={}){if(this.#i)throw new a("jsonrpc: client \u5DF2 closed","closed");let s=this.#p(),i=JSON.stringify({jsonrpc:"2.0",id:s,method:e,params:t}),n=r.timeoutMs??this.#n;return new Promise((c,d)=>{let l=!1,S=setTimeout(()=>{l||(l=!0,this.#r.delete(s),d(new I(e,n,this.#t)))},n),f=()=>{l||(l=!0,clearTimeout(S),this.#r.delete(s),this.notify("notifications/cancelled",{requestId:s,reason:"client cancelled"}).catch(()=>{}),d(new x(e,this.#t)))};if(r.signal){if(r.signal.aborted){f();return}r.signal.addEventListener("abort",f,{once:!0})}this.#r.set(s,h=>{if(!l){if(l=!0,clearTimeout(S),r.signal&&r.signal.removeEventListener("abort",f),h.error){d(new P(e,h.error,this.#t));return}c(h.result)}}),this.#e.send(i).catch(h=>{l||(l=!0,clearTimeout(S),this.#r.delete(s),d(h instanceof Error?h:new Error(String(h))))})})}async notify(e,t){if(this.#i)throw new a("jsonrpc: client \u5DF2\u5173\u95ED","closed");let r=JSON.stringify({jsonrpc:"2.0",method:e,params:t});await this.#e.send(r)}onNotification(e,t){let r=this.#o.get(e);return r||(r=new Set,this.#o.set(e,r)),r.add(t),{close:()=>{r.delete(t),r.size===0&&this.#o.delete(e)}}}async close(){if(!this.#i){this.#i=!0;for(let[,e]of this.#r)e({jsonrpc:"2.0",id:-1,error:{code:-32603,message:"client closed"}});this.#r.clear(),this.#o.clear(),this.#a&&await Promise.race([this.#a.catch(()=>{}),new Promise(e=>setTimeout(e,100))]),this.#c&&await Promise.race([this.#c.catch(()=>{}),new Promise(e=>setTimeout(e,100))])}}get isClosed(){return this.#i}getEffectiveDefaultTimeoutMs(){return this.#n}#p(){return Atomics.add(this.#s,0,1)+1}#f(){this.#a=(async()=>{try{for await(let e of this.#e.receive()){if(this.#i)return;let t;try{t=JSON.parse(e)}catch(r){process.env.DSKCODE_MCP_DEBUG&&console.error(`[mcp:${this.#t??"?"}] jsonrpc parse error:`,r.message,"raw=",e.slice(0,200));continue}this.#d(t)}}catch(e){if(!this.#i){for(let[,t]of this.#r)t({jsonrpc:"2.0",id:-1,error:{code:-32603,message:`transport closed: ${e.message}`}});this.#r.clear()}}})()}#u(){this.#c=(async()=>{try{for await(let e of this.#e.receiveErr()){if(this.#i)return;process.env.DSKCODE_MCP_DEBUG&&console.error(`[mcp:${this.#t??"?"}] stderr: ${e}`)}}catch{}})()}#d(e){if(!e||typeof e!="object")return;let t=e;if(t.id!==void 0&&typeof t.id!="object"&&!t.method){let r=this.#r.get(Number(t.id));r&&(this.#r.delete(Number(t.id)),r(e));return}if(typeof t.method=="string"&&t.id===void 0){let r=this.#o.get(t.method);if(r)for(let s of r)try{s(t.params)}catch(i){process.env.DSKCODE_MCP_DEBUG&&console.error(`[mcp:${this.#t??"?"}] notification handler error:`,i.message)}}}};p();var T=["2025-06-18","2025-03-26","2024-11-05"],re=T[0];async function D(o,e){let t=e??await se(),r=await o.request("initialize",{protocolVersion:re,capabilities:{roots:{},sampling:{}},clientInfo:t}),s=r.protocolVersion;if(!T.includes(s))throw new w(`MCP server \u534F\u8BAE\u7248\u672C "${r.protocolVersion}" \u4E0D\u53D7\u652F\u6301\uFF08\u671F\u671B ${T.join(", ")}\uFF09`);let i=r.capabilities??{};return await o.notify("notifications/initialized",{}),{protocolVersion:r.protocolVersion,capabilities:i,name:r.serverInfo?.name,version:r.serverInfo?.version}}async function se(){let o="0.0.0";try{let{readFileSync:e}=await import("fs"),{join:t}=await import("path"),r=t(process.cwd(),"package.json"),s=e(r,"utf-8");o=JSON.parse(s).version??"0.0.0"}catch{}return{name:"dskcode",version:o}}var C=class{#e;#n;#t;#s="created";#r=null;#o=new Set;#a=null;#c=null;constructor(e){this.#e=e.serverId,this.#n=e.transport,this.#t=new b(e.transport,{serverId:e.serverId,defaultTimeoutMs:e.defaultRequestTimeoutMs??3e4}),e.onEvent&&this.#o.add(e.onEvent)}get id(){return this.#e}get state(){return this.#s}get serverInfo(){return this.#r}get capabilities(){return this.#r?.capabilities??null}getEffectiveTimeoutMs(){return this.#t.getEffectiveDefaultTimeoutMs()}async start(){if(this.#s!=="created")throw new u(this.#e,`\u65E0\u6CD5\u542F\u52A8\uFF1A\u5F53\u524D state=${this.#s}`);this.#s="starting";try{this.#r=await D(this.#t),this.#n.setProtocolVersion?.(this.#r.protocolVersion),this.#a=this.#t.onNotification("notifications/tools/list_changed",()=>{this.#p({type:"toolsChanged",serverId:this.#e})}),this.#c=this.#t.onNotification("notifications/prompts/list_changed",()=>{this.#p({type:"promptsChanged",serverId:this.#e})}),this.#s="ready",this.#p({type:"started",serverId:this.#e})}catch(e){this.#s="failed";let t=e instanceof Error?e:new Error(String(e));try{await this.#t.close()}catch{}try{await this.#n.dispose()}catch{}throw this.#p({type:"failed",serverId:this.#e,error:t}),e instanceof u?e:new u(this.#e,t.message,{cause:t})}}async dispose(){if(this.#s==="stopped")return;let e=this.#s;this.#s="stopped";try{this.#a?.close(),this.#c?.close(),this.#a=null,this.#c=null,this.#o.clear(),await this.#t.close()}catch{}try{await this.#n.dispose()}catch{}e==="ready"&&this.#p({type:"stopped",serverId:this.#e})}on(e){return this.#o.add(e),{close:()=>{this.#o.delete(e)}}}tools={list:async()=>(this.#i(),(await this.#t.request("tools/list",{})).tools),call:async(e,t={},r={})=>(this.#i(),await this.#t.request("tools/call",{name:e,arguments:t},{timeoutMs:r.timeoutMs,signal:r.signal}))};prompts={list:async()=>(this.#i(),this.capabilities?.prompts?(await this.#t.request("prompts/list",{})).prompts:[]),get:async(e,t={},r={})=>(this.#i(),await this.#t.request("prompts/get",{name:e,arguments:t},{timeoutMs:r.timeoutMs,signal:r.signal}))};resources={list:async()=>(this.#i(),this.capabilities?.resources?(await this.#t.request("resources/list",{})).resources??[]:[]),read:async(e,t={})=>(this.#i(),await this.#t.request("resources/read",{uri:e},{timeoutMs:t.timeoutMs,signal:t.signal}))};#i(){if(this.#s!=="ready")throw new u(this.#e,`\u64CD\u4F5C\u5931\u8D25\uFF1Aserver \u672A\u5C31\u7EEA\uFF08state=${this.#s}\uFF09`)}#p(e){for(let t of this.#o)try{t(e)}catch{}}};var J=[2e3,4e3,8e3,16e3,3e4],ne=J.length-1,j=class o{#e=new Map;#n=new Map;#t=new Map;#s=new Set;#r;#o;static#a=null;static sharedInstance(e){return o.#a||(o.#a=new o(e??{})),o.#a}static resetSharedInstanceForTests(){o.#a=null}constructor(e={}){this.#r=e.globalTimeoutSeconds??60,this.#o=e.onRetryScheduled}onEvent(e){return this.#s.add(e),{close:()=>{this.#s.delete(e)}}}status(){let e={};for(let[t,r]of this.#n){let s=this.#e.get(t),i=this.#t.get(t);e[t]={id:t,state:s?.state??"stopped",...i?.lastError?.message?{lastError:i.lastError.message}:{},settings:r,retryPending:i?.timer!=null,retryAttempts:i?.attempts??0}}return e}async reconcile(e){let t=new Set;for(let[i,n]of Object.entries(e))n.enabled!==!1&&t.add(i);let r=[];for(let i of this.#e.keys())t.has(i)||r.push(i);for(let i of r)await this.#p(i);let s=[];for(let[i,n]of Object.entries(e)){if(!t.has(i))continue;let c=this.#n.get(i);c&&oe(c,n)&&this.#e.has(i)||s.push(this.#c(i,n))}await Promise.allSettled(s)}async restart(e){let t=this.#n.get(e);t&&await this.#c(e,t)}getServer(e){return this.#e.get(e)??null}async shutdown(){for(let t of this.#t.values())t.timer&&clearTimeout(t.timer),t.timer=null;this.#t.clear();let e=[];for(let t of[...this.#e.keys()])e.push(this.#p(t));await Promise.allSettled(e)}async#c(e,t){this.#e.has(e)&&await this.#p(e);let r=this.#t.get(e);r?.timer&&clearTimeout(r.timer),this.#t.set(e,{attempts:0,timer:null,lastError:null}),await this.#i(e,t)}async#i(e,t){if(!v(t)&&!y(t)){let n=new u(e,"MCP server \u914D\u7F6E\u7F3A\u5C11 command\uFF08stdio\uFF09\u6216 url\uFF08http\uFF09\u5B57\u6BB5");this.#u(e,n);return}let r;try{r=$({serverId:e,settings:t,globalTimeoutSeconds:this.#r})}catch(n){let c=n instanceof Error?n:new Error(String(n));this.#n.set(e,t),this.#u(e,c),this.#d(e,t);return}let s=new C({transport:r,serverId:e,defaultRequestTimeoutMs:(t.timeout??this.#r)*1e3}),i=s.on(n=>this.#f(e,n));this.#e.set(e,s),this.#n.set(e,t),this.#l({type:"statusChanged",serverId:e,state:s.state});try{await s.start()}catch(n){let c=n instanceof Error?n:new Error(String(n));i.close(),this.#e.delete(e),this.#d(e,t)}}async#p(e){let t=this.#e.get(e);if(!t)return;try{await t.dispose()}catch{}this.#e.delete(e),this.#n.delete(e);let r=this.#t.get(e);r?.timer&&clearTimeout(r.timer),r&&(r.timer=null),this.#l({type:"stopped",serverId:e})}#f(e,t){switch(t.type){case"started":this.#l({type:"started",serverId:e});break;case"failed":this.#u(e,t.error);break;case"stopped":this.#l({type:"stopped",serverId:e});break;case"toolsChanged":this.#l({type:"toolsChanged",serverId:e});break;case"promptsChanged":this.#l({type:"promptsChanged",serverId:e});break}}#u(e,t){let r=this.#t.get(e)??{attempts:0,timer:null,lastError:null};r.lastError=t,this.#t.set(e,r),this.#l({type:"failed",serverId:e,error:t})}#d(e,t){let r=this.#t.get(e)??{attempts:0,timer:null,lastError:null},s=Math.min(r.attempts,ne),i=J[s];r.attempts+=1,this.#t.set(e,r),this.#o?.(e,i,r.attempts),r.timer&&clearTimeout(r.timer),r.timer=setTimeout(()=>{r.timer=null,this.#n.has(e)&&this.#i(e,t)},i)}#l(e){for(let t of this.#s)try{t(e)}catch{}}};function oe(o,e){if(o===e)return!0;try{return JSON.stringify(o)===JSON.stringify(e)}catch{return!1}}export{U as a,B as b,j as c};
11
+ //# sourceMappingURL=chunk-FJL5WURJ.js.map
@@ -1,5 +1,5 @@
1
- import{a as p}from"./chunk-MDFCAIOB.js";import{d as a}from"./chunk-LPD7BHH5.js";a();a();import{createHash as x}from"crypto";function f(t){let n=l(t),e=x("sha256");return e.update(n),e.digest("hex").slice(0,16)}function l(t){if(t===null)return"null";if(t===void 0)return"";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number")return Number.isFinite(t)?String(t):"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="bigint")return t.toString();if(typeof t=="function")return'"[function]"';if(Array.isArray(t))return"["+t.map(n=>l(n)).join(",")+"]";if(typeof t=="object"){let n=t,e=Object.keys(n).sort(),s=[];for(let i of e){let r=n[i];r!==void 0&&s.push(JSON.stringify(i)+":"+l(r))}return"{"+s.join(",")+"}"}return JSON.stringify(t)}var u=class{#n=new Map;add(n,e){this.#n.set(this.#t(n,e),!0)}has(n,e){return this.#n.has(this.#t(n,e))}revoke(n,e){return this.#n.delete(this.#t(n,e))}addByKey(n){n&&this.#n.set(n,!0)}hasByKey(n){return n?this.#n.has(n):!1}clear(){this.#n.clear()}get size(){return this.#n.size}#t(n,e){return`${n}:${e}`}};var h=class{#n;#t;#s;#i;#o;#a;#e=void 0;constructor(n={}){this.#n=n.engine??new p([]),this.#t=n.grants??new u,this.#s=n.prompt??$,this.#i=n.defaultDecision??"confirm",this.#o=n.grantKeyFor??k,this.#a=n.onDecision}get grants(){return this.#t}get engine(){return this.#n}async check(n,e){let s=f(e),i={args:e,targetPath:m(e)},r=this.#n.evaluate(n,i);if(r==="allow")return this.#e=void 0,this.#r(n,s,"allow","allow","rule"),!0;if(r==="deny")return this.#e={source:"permission_rule",reason:y(n,"deny",this.#n,i),hint:"\u53EF\u5728 ~/.dskcode/permissions.json \u6216 .dskcode/permissions.json \u4E2D\u8C03\u6574\u6216\u5220\u9664\u8BE5 deny \u89C4\u5219\u3002"},this.#r(n,s,"deny","deny","rule"),!1;let w=r==="confirm"||r===null&&this.#i==="confirm",o=this.#o(n,e);if(w&&o&&this.#t.hasByKey(o))return this.#e=void 0,this.#r(n,s,r,"allow","grant"),!0;let c=r??this.#i;if(c==="allow"&&r===null)return this.#e=void 0,this.#r(n,s,null,"allow","default"),!0;if(c==="deny"&&r===null)return this.#e={source:"permission_rule",reason:`\u9ED8\u8BA4\u51B3\u7B56\u662F deny\uFF08\u672A\u5339\u914D\u4EFB\u4F55\u89C4\u5219\u7684 ${n} \u8C03\u7528\uFF09`,hint:"\u53EF\u5728 ~/.dskcode/permissions.json \u52A0\u4E00\u6761 allow \u89C4\u5219\u53D6\u6D88\u62D2\u7EDD\u3002"},this.#r(n,s,null,"deny","default"),!1;let d=y(n,r,this.#n,i),g=await this.#s({toolName:n,args:e,reason:d,ruleAction:r??void 0});return g==="no"?(this.#e={source:"user_prompt",reason:`\u7528\u6237\u624B\u52A8\u62D2\u7EDD\uFF1A${d}`},this.#r(n,s,r,"deny","prompt"),!1):(g==="always"&&o&&this.#t.addByKey(o),this.#e=void 0,this.#r(n,s,r,"allow","prompt"),!0)}get lastDenial(){return this.#e}#r(n,e,s,i,r){this.#a?.({toolName:n,argsHash:e,ruleAction:s,finalAction:i,via:r})}},$=t=>(console.warn(`[InteractiveGate] \u672A\u4F20\u8BE2\u95EE\u56DE\u8C03\uFF0C\u9ED8\u8BA4\u62D2\u7EDD\u786E\u8BA4\u8BF7\u6C42\u3002
1
+ import{a as p}from"./chunk-5NFOBNG6.js";import{d as a}from"./chunk-LPD7BHH5.js";a();a();import{createHash as x}from"crypto";function f(t){let n=l(t),e=x("sha256");return e.update(n),e.digest("hex").slice(0,16)}function l(t){if(t===null)return"null";if(t===void 0)return"";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number")return Number.isFinite(t)?String(t):"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="bigint")return t.toString();if(typeof t=="function")return'"[function]"';if(Array.isArray(t))return"["+t.map(n=>l(n)).join(",")+"]";if(typeof t=="object"){let n=t,e=Object.keys(n).sort(),s=[];for(let i of e){let r=n[i];r!==void 0&&s.push(JSON.stringify(i)+":"+l(r))}return"{"+s.join(",")+"}"}return JSON.stringify(t)}var u=class{#n=new Map;add(n,e){this.#n.set(this.#t(n,e),!0)}has(n,e){return this.#n.has(this.#t(n,e))}revoke(n,e){return this.#n.delete(this.#t(n,e))}addByKey(n){n&&this.#n.set(n,!0)}hasByKey(n){return n?this.#n.has(n):!1}clear(){this.#n.clear()}get size(){return this.#n.size}#t(n,e){return`${n}:${e}`}};var h=class{#n;#t;#s;#i;#o;#a;#e=void 0;constructor(n={}){this.#n=n.engine??new p([]),this.#t=n.grants??new u,this.#s=n.prompt??$,this.#i=n.defaultDecision??"confirm",this.#o=n.grantKeyFor??k,this.#a=n.onDecision}get grants(){return this.#t}get engine(){return this.#n}async check(n,e){let s=f(e),i={args:e,targetPath:m(e)},r=this.#n.evaluate(n,i);if(r==="allow")return this.#e=void 0,this.#r(n,s,"allow","allow","rule"),!0;if(r==="deny")return this.#e={source:"permission_rule",reason:y(n,"deny",this.#n,i),hint:"\u53EF\u5728 ~/.dskcode/permissions.json \u6216 .dskcode/permissions.json \u4E2D\u8C03\u6574\u6216\u5220\u9664\u8BE5 deny \u89C4\u5219\u3002"},this.#r(n,s,"deny","deny","rule"),!1;let w=r==="confirm"||r===null&&this.#i==="confirm",o=this.#o(n,e);if(w&&o&&this.#t.hasByKey(o))return this.#e=void 0,this.#r(n,s,r,"allow","grant"),!0;let c=r??this.#i;if(c==="allow"&&r===null)return this.#e=void 0,this.#r(n,s,null,"allow","default"),!0;if(c==="deny"&&r===null)return this.#e={source:"permission_rule",reason:`\u9ED8\u8BA4\u51B3\u7B56\u662F deny\uFF08\u672A\u5339\u914D\u4EFB\u4F55\u89C4\u5219\u7684 ${n} \u8C03\u7528\uFF09`,hint:"\u53EF\u5728 ~/.dskcode/permissions.json \u52A0\u4E00\u6761 allow \u89C4\u5219\u53D6\u6D88\u62D2\u7EDD\u3002"},this.#r(n,s,null,"deny","default"),!1;let d=y(n,r,this.#n,i),g=await this.#s({toolName:n,args:e,reason:d,ruleAction:r??void 0});return g==="no"?(this.#e={source:"user_prompt",reason:`\u7528\u6237\u624B\u52A8\u62D2\u7EDD\uFF1A${d}`},this.#r(n,s,r,"deny","prompt"),!1):(g==="always"&&o&&this.#t.addByKey(o),this.#e=void 0,this.#r(n,s,r,"allow","prompt"),!0)}get lastDenial(){return this.#e}#r(n,e,s,i,r){this.#a?.({toolName:n,argsHash:e,ruleAction:s,finalAction:i,via:r})}},$=t=>(console.warn(`[InteractiveGate] \u672A\u4F20\u8BE2\u95EE\u56DE\u8C03\uFF0C\u9ED8\u8BA4\u62D2\u7EDD\u786E\u8BA4\u8BF7\u6C42\u3002
2
2
  \u5DE5\u5177: ${t.toolName}
3
3
  \u539F\u56E0: ${t.reason}
4
4
  \u5982\u9700\u4EA4\u4E92\u5F0F\u5BA1\u6279\uFF0C\u8BF7\u5728\u521B\u5EFA InteractiveGate \u65F6\u4F20 prompt \u9009\u9879\u3002`),"no");function m(t){if(typeof t!="object"||t===null)return;let n=t,e=["path","file_path","filePath","filepath","target"];for(let s of e){let i=n[s];if(typeof i=="string"&&i.length>0)return i}}function k(t,n){let e=m(n);return e?`${t}:${e}`:`${t}:${f(n)}`}function y(t,n,e,s){if(n==="confirm"){let i=e.rules.find(r=>r.tool===t&&r.action==="confirm");if(i){if(i.reason)return i.reason;let r=j(i.match);return`\u89C4\u5219\u547D\u4E2D\uFF1A${t}${r?`\uFF08${r}\uFF09`:""}\u3002\u672C\u6B21\u8C03\u7528\u9700\u8981\u786E\u8BA4\u662F\u5426\u653E\u884C\u3002`}return`\u5DE5\u5177 \`${t}\` \u88AB\u89C4\u5219\u6807\u8BB0\u4E3A\u9700\u8981\u786E\u8BA4\uFF0C\u662F\u5426\u653E\u884C\uFF1F`}return`\u5DE5\u5177 \`${t}\` \u6CA1\u6709\u5339\u914D\u7684\u89C4\u5219\uFF0C\u9ED8\u8BA4\u9700\u8981\u4F60\u786E\u8BA4\u662F\u5426\u653E\u884C\u3002`}function j(t){if(!t)return"";let n=[];if(t.commandRegex&&n.push(`\u547D\u4EE4\u6B63\u5219=${t.commandRegex}`),t.pathGlob&&n.push(`\u8DEF\u5F84 glob=${t.pathGlob}`),t.argValueRegex){let e=Object.entries(t.argValueRegex).map(([s,i])=>`${s}=${i}`).join(", ");n.push(`\u53C2\u6570\u89C4\u5219=${e}`)}return n.join("; ")}export{h as a};
5
- //# sourceMappingURL=chunk-XADXUHKL.js.map
5
+ //# sourceMappingURL=chunk-XW3DXEJJ.js.map
@@ -1,4 +1,4 @@
1
- import{h as f,j as a}from"./chunk-QASDDP3K.js";import"./chunk-XAWVLVWL.js";import{d}from"./chunk-LPD7BHH5.js";d();import{useEffect as h,useState as S}from"react";import{render as x,Box as c,Text as o}from"ink";import l from"chalk";import{jsx as e,jsxs as t}from"react/jsx-runtime";function p({url:n,token:r,infoPath:i,port:s}){return t(c,{flexDirection:"column",paddingX:1,paddingY:1,children:[e(o,{bold:!0,color:"cyan",children:"dskcode config-ui"}),e(o,{dimColor:!0,children:"\u672C\u5730 WebSocket \u670D\u52A1\u5DF2\u542F\u52A8\uFF0C\u7B49\u5F85 Chrome \u6269\u5C55\u8FDE\u63A5"}),t(c,{marginTop:1,flexDirection:"column",children:[t(o,{children:[e(o,{dimColor:!0,children:"endpoint : "}),e(o,{color:"green",children:n})]}),t(o,{children:[e(o,{dimColor:!0,children:"token : "}),e(o,{color:"yellow",children:r})]}),t(o,{children:[e(o,{dimColor:!0,children:"port : "}),e(o,{children:s})]}),t(o,{children:[e(o,{dimColor:!0,children:"info file : "}),e(o,{children:i})]})]}),t(c,{marginTop:1,flexDirection:"column",children:[e(o,{dimColor:!0,children:"\u64CD\u4F5C\u63D0\u793A\uFF1A"}),e(o,{dimColor:!0,children:` \xB7 Chrome \u6269\u5C55\u9ED8\u8BA4\u8FDE\u63A5 ${f}`}),e(o,{dimColor:!0,children:" \xB7 \u6309 Ctrl+C \u9000\u51FA"})]}),t(c,{marginTop:1,children:[e(o,{color:"gray",children:"[dskcode] "}),e(o,{dimColor:!0,children:"listening..."})]})]})}async function y(n){let r=await a({host:n.host??"127.0.0.1",port:n.port??54006,autoStart:!0});console.error(l.cyan(`
1
+ import{j as f,l as a}from"./chunk-EEH2ZJA5.js";import"./chunk-XAWVLVWL.js";import{d}from"./chunk-LPD7BHH5.js";d();import{useEffect as h,useState as S}from"react";import{render as x,Box as c,Text as o}from"ink";import l from"chalk";import{jsx as e,jsxs as t}from"react/jsx-runtime";function p({url:n,token:r,infoPath:i,port:s}){return t(c,{flexDirection:"column",paddingX:1,paddingY:1,children:[e(o,{bold:!0,color:"cyan",children:"dskcode config-ui"}),e(o,{dimColor:!0,children:"\u672C\u5730 WebSocket \u670D\u52A1\u5DF2\u542F\u52A8\uFF0C\u7B49\u5F85 Chrome \u6269\u5C55\u8FDE\u63A5"}),t(c,{marginTop:1,flexDirection:"column",children:[t(o,{children:[e(o,{dimColor:!0,children:"endpoint : "}),e(o,{color:"green",children:n})]}),t(o,{children:[e(o,{dimColor:!0,children:"token : "}),e(o,{color:"yellow",children:r})]}),t(o,{children:[e(o,{dimColor:!0,children:"port : "}),e(o,{children:s})]}),t(o,{children:[e(o,{dimColor:!0,children:"info file : "}),e(o,{children:i})]})]}),t(c,{marginTop:1,flexDirection:"column",children:[e(o,{dimColor:!0,children:"\u64CD\u4F5C\u63D0\u793A\uFF1A"}),e(o,{dimColor:!0,children:` \xB7 Chrome \u6269\u5C55\u9ED8\u8BA4\u8FDE\u63A5 ${f}`}),e(o,{dimColor:!0,children:" \xB7 \u6309 Ctrl+C \u9000\u51FA"})]}),t(c,{marginTop:1,children:[e(o,{color:"gray",children:"[dskcode] "}),e(o,{dimColor:!0,children:"listening..."})]})]})}async function y(n){let r=await a({host:n.host??"127.0.0.1",port:n.port??54006,autoStart:!0});console.error(l.cyan(`
2
2
  dskcode config-ui`)),console.error(l.dim(` endpoint : ${r.url}`)),console.error(l.dim(` token : ${r.authToken}`)),console.error(l.dim(` info file: ${r.connectionInfoPath}
3
3
  `));let{unmount:i}=x(e(p,{url:r.url,token:r.authToken,infoPath:r.connectionInfoPath,port:r.port}),{exitOnCtrlC:!1});await new Promise(s=>{let m=async()=>{i(),await r.close(),s(),process.exit(0)};process.once("SIGINT",()=>{m()}),process.once("SIGTERM",()=>{m()})})}async function U(n={}){let r=await a({host:n.host??"127.0.0.1",port:n.port??54006,autoStart:!0}).catch(i=>{if(i.name==="PortInUseError")return console.error(l.yellow(` \u26A0 ${i.message} Chrome \u6269\u5C55\u65E0\u6CD5\u8FDE\u63A5\u5230\u672C\u8FDB\u7A0B\uFF08\u8FDE\u4E0D\u5230\u5176\u4ED6 dskcode\uFF09\u3002`)),null;throw i});return r?(console.error(l.dim(` [config-ui] ws server listening on ${r.url} (token: ${r.authToken.slice(0,8)}\u2026)`)),r):null}export{p as ConfigUiPanel,U as startConfigServerBackground,y as startConfigUi};
4
- //# sourceMappingURL=config-ui-ESM4R7PB.js.map
4
+ //# sourceMappingURL=config-ui-W3XDQASQ.js.map