@deepseekcode/cli 1.0.19 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +3 -3
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1735,7 +1735,7 @@ The reviewer should pay special attention to: **${j}**
1735
1735
  `)){if(!K.trim())continue;const[X,Y,q]=K.split("\t");const Z=Number(X)||0;const G=Number(Y)||0;if(!q)continue;const H=J.get(q)||"M";D.push({path:q,status:H,added:Z,removed:G,staged:H===H.toUpperCase()})}return D}async function c$6(z,J=90000){const D=m$6(lO8(p$6(),"dsc-git-list-"));const K=lO8(D,"repo");try{let X=await p0(D,["clone","--depth","1","--filter=blob:none","--no-checkout","--",z,"repo"],J);if(X.code!==0){try{cO8(K,{recursive:true,force:true})}catch{}X=await p0(D,["clone","--depth","1","--no-checkout","--",z,"repo"],J)}if(X.code!==0){const H=(X.stderr||X.stdout).trim()||`git clone failed (code ${X.code})`;return{code:X.code,files:[],error:H}}const Y=await p0(K,["rev-parse","--abbrev-ref","HEAD"],J);const q=Y.code===0?Y.stdout.trim():undefined;const Z=await p0(K,["ls-tree","-r","--name-only","HEAD"],J);if(Z.code!==0){return{code:Z.code,files:[],branch:q,error:Z.stderr.trim()||"git ls-tree failed"}}const G=Z.stdout.split(`
1736
1736
  `).map((H)=>H.trim()).filter(Boolean);return{code:0,files:G,branch:q}}catch(X){return{code:-1,files:[],error:X instanceof Error?X.message:String(X)}}finally{try{cO8(D,{recursive:true,force:true})}catch{}}}async function l$6(z){const J=await p0(z,["rev-parse","--abbrev-ref","HEAD"]);if(J.code!==0){return{available:false,projectName:dO8(z),error:"Not a git repository"}}const D=await p0(z,["status","--porcelain=v1"]);const K=new Map;for(const C of D.stdout.split(`
1737
1737
  `)){if(!C.trim())continue;const M=C.slice(0,2).trim();const L=C.slice(3).replace(/^"|"$/g,"");K.set(L,M||"M")}const X=await p0(z,["diff","--numstat"]);const Y=await p0(z,["diff","--cached","--numstat"]);const q=[...iO8(Y.stdout,K),...iO8(X.stdout,K)];const Z=new Map;for(const C of q)Z.set(C.path,C);for(const[C,M]of K){if(M.includes("?")&&!Z.has(C)){Z.set(C,{path:C,status:M,added:0,removed:0})}}const G=Array.from(Z.values());const H=G.reduce((C,M)=>C+M.added,0);const V=G.reduce((C,M)=>C+M.removed,0);let O=0,j=0;const Q=await p0(z,["rev-list","--count","@{upstream}..HEAD"]);if(Q.code===0)O=Number(Q.stdout.trim())||0;const B=await p0(z,["rev-list","--count","HEAD..@{upstream}"]);if(B.code===0)j=Number(B.stdout.trim())||0;let A=null;const N=await p0(z,["log","-1","--format=%H%x09%an%x09%at%x09%s"]);if(N.code===0&&N.stdout.trim()){const[C,M,L,...T]=N.stdout.trim().split("\t");A={hash:C,author:M,timestamp:Number(L)*1000,subject:T.join("\t")}}return{available:true,projectName:dO8(z),branch:J.stdout.trim()||undefined,ahead:O,behind:j,changes:G,totalAdded:H,totalRemoved:V,dirty:G.length>0,lastCommit:A}}async function d$6(z){const J=await p0(z,["rev-parse","--abbrev-ref","HEAD"]);if(J.code!==0)return{available:false,error:"Not a git repository",branches:[]};const D=await p0(z,["branch","--format=%(refname:short)"]);const K=D.stdout.split(`
1738
- `).map((X)=>X.trim()).filter(Boolean);return{available:true,current:J.stdout.trim()||undefined,branches:K}}async function i$6(z,J,D=true){const K=D?["add","-A"]:["add","-u"];const X=await p0(z,K,30000);if(X.code!==0)return{ok:false,error:X.stderr.trim()||`git add failed (code ${X.code})`};const Y=await p0(z,["commit","-m",J],30000);if(Y.code!==0){const Z=Y.stderr.trim();if(/nothing to commit|no changes added/.test(Z)){return{ok:false,error:"Nothing to commit — working tree is clean",message:J}}return{ok:false,error:Z||`git commit failed (code ${Y.code})`,message:J}}const q=/\[[^\]]+ ([0-9a-f]+)\]/.exec(Y.stdout);return{ok:true,hash:q?q[1]:undefined,message:Y.stdout.trim()}}async function n$6(z){const J=await p0(z,["push"],60000);if(J.code!==0)return{ok:false,error:J.stderr.trim()||`git push failed (code ${J.code})`};return{ok:true,message:J.stdout.trim()}}async function a$6(z,J){const D=await p0(z,["checkout",J],30000);if(D.code!==0)return{ok:false,error:D.stderr.trim()||`git checkout failed (code ${D.code})`};return{ok:true,message:D.stdout.trim()}}async function o$6(z,J=30000){const D=await p0(z,["status"],5000);if(D.code!==0)return{available:false,error:"Not a git repository"};const K=await new Promise((Y)=>{const q=Pm("gh",["--version"],{cwd:z});let Z="";let G="";const H=setTimeout(()=>{q.kill();Y({code:-1,stdout:Z,stderr:"gh CLI timed out"})},5000);q.stdout.on("data",(V)=>{Z+=String(V)});q.stderr.on("data",(V)=>{G+=String(V)});q.on("close",(V)=>{clearTimeout(H);Y({code:V??-1,stdout:Z,stderr:G})});q.on("error",()=>{clearTimeout(H);Y({code:-1,stdout:Z,stderr:"gh CLI not found"})})});if(K.code!==0){return{available:false,error:"GitHub CLI (gh) is not installed or not on PATH. Install gh to see PR status."}}const X=await new Promise((Y)=>{const q=Pm("gh",["pr","list","--json","number,title,state,headRefName,baseRefName,author,createdAt,updatedAt,url","--limit","50"],{cwd:z});let Z="";let G="";const H=setTimeout(()=>{q.kill();Y({code:-1,stdout:Z,stderr:`gh pr list timed out after ${J}ms`})},J);q.stdout.on("data",(V)=>{Z+=String(V)});q.stderr.on("data",(V)=>{G+=String(V)});q.on("close",(V)=>{clearTimeout(H);Y({code:V??-1,stdout:Z,stderr:G})});q.on("error",(V)=>{clearTimeout(H);Y({code:-1,stdout:Z,stderr:V.message})})});if(X.code!==0){return{available:false,error:X.stderr.trim()||`gh pr list failed (code ${X.code})`}}try{const Y=JSON.parse(X.stdout);const q=Y.map((Z)=>({number:Z.number,title:Z.title,state:Z.state.toLowerCase(),branch:Z.headRefName,base:Z.baseRefName,author:Z.author?.login??"unknown",createdAt:new Date(Z.createdAt).getTime(),updatedAt:new Date(Z.updatedAt).getTime(),url:Z.url||undefined}));return{available:true,prs:q}}catch(Y){return{available:false,error:`Failed to parse gh output: ${Y.message}`}}}fK();var e$6=Number(process.env.DSC_HEAP_LIMIT_MB||4096);var rF8=Number(process.env.DEEPSEEKCODE_HTTP_PORT||8080);var DX1=Number(process.env.DEEPSEEKCODE_WS_PORT||rF8+1);var MC=Number(process.env.DSC_FETCH_TIMEOUT_MS||5000);var zQ6=Number(process.env.DSC_FETCH_LONG_TIMEOUT_MS||1e4);var JQ6=Number(process.env.DSC_MARKET_INSTALL_TIMEOUT_MS||60000);var KX1=Number(process.env.DSC_MAX_LOG_LINE_LENGTH||1e4);var XX1=Number(process.env.DSC_MAX_LOG_FILE_SIZE||10485760);var YX1=Number(process.env.DSC_MAX_TERMINAL_LINES||1000);var qX1=Number(process.env.DSC_MAX_HISTORY_MESSAGES||200);var ZX1=Number(process.env.DSC_TOKEN_WARNING_THRESHOLD||0.8);var GX1=Number(process.env.DSC_TOKEN_ERROR_THRESHOLD||0.95);var HX1=Number(process.env.DSC_AUTO_COMPACT_THRESHOLD||0.7);var VX1=Number(process.env.DSC_STREAM_FLUSH_MS||500);var WX1=Number(process.env.DSC_STREAM_BUFFER_MAX_BYTES||10485760);var OX1=Number(process.env.DSC_MAX_BLOCK_CONTENT_CHARS||51200);var $X1=Number(process.env.DSC_MAX_MESSAGES||2000);var QX1=Number(process.env.DSC_MAX_FILE_READ_SIZE||10485760);var jX1=Number(process.env.DSC_MAX_SEARCH_RESULTS||1000);var AX1=Number(process.env.DSC_MAX_SESSION_FILE_SIZE||52428800);var BX1=Number(process.env.DSC_SESSION_AUTO_SAVE_MS||5000);var aO8="jwcode-ai/jwcode";var oO8="@deepseekcode/cli";var DQ6=3600000;var sF8=Math.min(MC,8000);var Pj=null;function Tm(){if("1.0.19")return"1.0.19";try{const z=s$6(t$6(import.meta.url));const J=[nO8(z,"..","package.json"),nO8(z,"..","..","package.json")];for(const D of J){const K=JSON.parse(r$6(D,"utf8"));if(typeof K?.version==="string"&&K.version)return K.version}}catch{}return"1.0.0"}async function KQ6(z){const J=await fetch(`https://api.github.com/repos/${aO8}/releases/latest`,{headers:{Accept:"application/vnd.github+json","User-Agent":"deepseekcode-update-check"},signal:AbortSignal.timeout(sF8)});if(!J.ok)return null;const D=await J.json();const K=String(D.tag_name??"").replace(/^v/i,"");if(!K)return null;return{version:K,current:z,available:H$8(K,z)>0,channel:"stable",publishedAt:typeof D.published_at==="string"?D.published_at:undefined,notes:typeof D.body==="string"?D.body.slice(0,4000):undefined,url:typeof D.html_url==="string"?D.html_url:`https://github.com/${aO8}/releases`,source:"github"}}async function XQ6(z){const J=await fetch(`https://registry.npmjs.org/${oO8}/latest`,{signal:AbortSignal.timeout(sF8)});if(!J.ok)return null;const D=await J.json();const K=String(D.version??"");if(!K)return null;return{version:K,current:z,available:H$8(K,z)>0,channel:"stable",url:`https://www.npmjs.com/package/${oO8}`,source:"npm"}}async function rO8(z,J=false){const D=z??Tm();if(!J&&Pj&&Date.now()-Pj.at<DQ6)return Pj.info;let K=null;try{K=await KQ6(D)}catch{K=null}if(!K){try{K=await XQ6(D)}catch{K=null}}Pj={at:Date.now(),info:K};return K}function YQ6(){Pj=null}function ZQ6(){if(tF8()==="win32")return"powershell.exe";return process.env.SHELL||"sh"}class eF8{defaultWorkspaceDir;wsPort;sessions=new Map;constructor(z,J){this.defaultWorkspaceDir=z;this.wsPort=J}start(z){const J=`terminal_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;const D=qQ6(z.workspaceDir||this.defaultWorkspaceDir);const K=ZQ6();this.sessions.set(J,{id:J,workspaceDir:D,shell:K,startedAt:Date.now()});return{terminalId:J,port:this.wsPort,ttydPort:this.wsPort,wsUrl:`ws://127.0.0.1:${this.wsPort}/terminal?terminalId=${encodeURIComponent(J)}`,workspaceDir:D,shell:K}}status(z){const J=z?this.sessions.get(z):undefined;const D=[...this.sessions.values()];return{running:z?Boolean(J?.child):D.some((K)=>Boolean(K.child)),terminalAvailable:true,ttydAvailable:true,port:this.wsPort,ttydPort:this.wsPort,uptime:J?Math.floor((Date.now()-J.startedAt)/1000):undefined,workspaceDir:J?.workspaceDir||this.defaultWorkspaceDir,wsUrl:z?`ws://127.0.0.1:${this.wsPort}/terminal?terminalId=${encodeURIComponent(z)}`:`ws://127.0.0.1:${this.wsPort}/terminal`,sessions:D.map((K)=>({id:K.id,workspaceDir:K.workspaceDir,shell:K.shell,uptime:Math.floor((Date.now()-K.startedAt)/1000),cols:K.cols,rows:K.rows,exitCode:K.exitCode,error:K.error}))}}stop(z){const J=z?[this.sessions.get(z)].filter(Boolean):[...this.sessions.values()];for(const D of J){try{D.child?.kill();D.socket?.close?.()}catch{}this.sessions.delete(D.id)}return J.length}openSocket(z,J){let D=J?this.sessions.get(J):undefined;if(!D){const q=this.start({});D=this.sessions.get(q.terminalId)}D.socket=z;let K;try{K=this.spawnShell(D)}catch(q){D.error=q instanceof Error?q.message:String(q);z.send(`Terminal failed to start: ${q instanceof Error?q.message:String(q)}\r
1738
+ `).map((X)=>X.trim()).filter(Boolean);return{available:true,current:J.stdout.trim()||undefined,branches:K}}async function i$6(z,J,D=true){const K=D?["add","-A"]:["add","-u"];const X=await p0(z,K,30000);if(X.code!==0)return{ok:false,error:X.stderr.trim()||`git add failed (code ${X.code})`};const Y=await p0(z,["commit","-m",J],30000);if(Y.code!==0){const Z=Y.stderr.trim();if(/nothing to commit|no changes added/.test(Z)){return{ok:false,error:"Nothing to commit — working tree is clean",message:J}}return{ok:false,error:Z||`git commit failed (code ${Y.code})`,message:J}}const q=/\[[^\]]+ ([0-9a-f]+)\]/.exec(Y.stdout);return{ok:true,hash:q?q[1]:undefined,message:Y.stdout.trim()}}async function n$6(z){const J=await p0(z,["push"],60000);if(J.code!==0)return{ok:false,error:J.stderr.trim()||`git push failed (code ${J.code})`};return{ok:true,message:J.stdout.trim()}}async function a$6(z,J){const D=await p0(z,["checkout",J],30000);if(D.code!==0)return{ok:false,error:D.stderr.trim()||`git checkout failed (code ${D.code})`};return{ok:true,message:D.stdout.trim()}}async function o$6(z,J=30000){const D=await p0(z,["status"],5000);if(D.code!==0)return{available:false,error:"Not a git repository"};const K=await new Promise((Y)=>{const q=Pm("gh",["--version"],{cwd:z});let Z="";let G="";const H=setTimeout(()=>{q.kill();Y({code:-1,stdout:Z,stderr:"gh CLI timed out"})},5000);q.stdout.on("data",(V)=>{Z+=String(V)});q.stderr.on("data",(V)=>{G+=String(V)});q.on("close",(V)=>{clearTimeout(H);Y({code:V??-1,stdout:Z,stderr:G})});q.on("error",()=>{clearTimeout(H);Y({code:-1,stdout:Z,stderr:"gh CLI not found"})})});if(K.code!==0){return{available:false,error:"GitHub CLI (gh) is not installed or not on PATH. Install gh to see PR status."}}const X=await new Promise((Y)=>{const q=Pm("gh",["pr","list","--json","number,title,state,headRefName,baseRefName,author,createdAt,updatedAt,url","--limit","50"],{cwd:z});let Z="";let G="";const H=setTimeout(()=>{q.kill();Y({code:-1,stdout:Z,stderr:`gh pr list timed out after ${J}ms`})},J);q.stdout.on("data",(V)=>{Z+=String(V)});q.stderr.on("data",(V)=>{G+=String(V)});q.on("close",(V)=>{clearTimeout(H);Y({code:V??-1,stdout:Z,stderr:G})});q.on("error",(V)=>{clearTimeout(H);Y({code:-1,stdout:Z,stderr:V.message})})});if(X.code!==0){return{available:false,error:X.stderr.trim()||`gh pr list failed (code ${X.code})`}}try{const Y=JSON.parse(X.stdout);const q=Y.map((Z)=>({number:Z.number,title:Z.title,state:Z.state.toLowerCase(),branch:Z.headRefName,base:Z.baseRefName,author:Z.author?.login??"unknown",createdAt:new Date(Z.createdAt).getTime(),updatedAt:new Date(Z.updatedAt).getTime(),url:Z.url||undefined}));return{available:true,prs:q}}catch(Y){return{available:false,error:`Failed to parse gh output: ${Y.message}`}}}fK();var e$6=Number(process.env.DSC_HEAP_LIMIT_MB||4096);var rF8=Number(process.env.DEEPSEEKCODE_HTTP_PORT||8080);var DX1=Number(process.env.DEEPSEEKCODE_WS_PORT||rF8+1);var MC=Number(process.env.DSC_FETCH_TIMEOUT_MS||5000);var zQ6=Number(process.env.DSC_FETCH_LONG_TIMEOUT_MS||1e4);var JQ6=Number(process.env.DSC_MARKET_INSTALL_TIMEOUT_MS||60000);var KX1=Number(process.env.DSC_MAX_LOG_LINE_LENGTH||1e4);var XX1=Number(process.env.DSC_MAX_LOG_FILE_SIZE||10485760);var YX1=Number(process.env.DSC_MAX_TERMINAL_LINES||1000);var qX1=Number(process.env.DSC_MAX_HISTORY_MESSAGES||200);var ZX1=Number(process.env.DSC_TOKEN_WARNING_THRESHOLD||0.8);var GX1=Number(process.env.DSC_TOKEN_ERROR_THRESHOLD||0.95);var HX1=Number(process.env.DSC_AUTO_COMPACT_THRESHOLD||0.7);var VX1=Number(process.env.DSC_STREAM_FLUSH_MS||500);var WX1=Number(process.env.DSC_STREAM_BUFFER_MAX_BYTES||10485760);var OX1=Number(process.env.DSC_MAX_BLOCK_CONTENT_CHARS||51200);var $X1=Number(process.env.DSC_MAX_MESSAGES||2000);var QX1=Number(process.env.DSC_MAX_FILE_READ_SIZE||10485760);var jX1=Number(process.env.DSC_MAX_SEARCH_RESULTS||1000);var AX1=Number(process.env.DSC_MAX_SESSION_FILE_SIZE||52428800);var BX1=Number(process.env.DSC_SESSION_AUTO_SAVE_MS||5000);var aO8="jwcode-ai/jwcode";var oO8="@deepseekcode/cli";var DQ6=3600000;var sF8=Math.min(MC,8000);var Pj=null;function Tm(){if("1.0.20")return"1.0.20";try{const z=s$6(t$6(import.meta.url));const J=[nO8(z,"..","package.json"),nO8(z,"..","..","package.json")];for(const D of J){const K=JSON.parse(r$6(D,"utf8"));if(typeof K?.version==="string"&&K.version)return K.version}}catch{}return"1.0.0"}async function KQ6(z){const J=await fetch(`https://api.github.com/repos/${aO8}/releases/latest`,{headers:{Accept:"application/vnd.github+json","User-Agent":"deepseekcode-update-check"},signal:AbortSignal.timeout(sF8)});if(!J.ok)return null;const D=await J.json();const K=String(D.tag_name??"").replace(/^v/i,"");if(!K)return null;return{version:K,current:z,available:H$8(K,z)>0,channel:"stable",publishedAt:typeof D.published_at==="string"?D.published_at:undefined,notes:typeof D.body==="string"?D.body.slice(0,4000):undefined,url:typeof D.html_url==="string"?D.html_url:`https://github.com/${aO8}/releases`,source:"github"}}async function XQ6(z){const J=await fetch(`https://registry.npmjs.org/${oO8}/latest`,{signal:AbortSignal.timeout(sF8)});if(!J.ok)return null;const D=await J.json();const K=String(D.version??"");if(!K)return null;return{version:K,current:z,available:H$8(K,z)>0,channel:"stable",url:`https://www.npmjs.com/package/${oO8}`,source:"npm"}}async function rO8(z,J=false){const D=z??Tm();if(!J&&Pj&&Date.now()-Pj.at<DQ6)return Pj.info;let K=null;try{K=await KQ6(D)}catch{K=null}if(!K){try{K=await XQ6(D)}catch{K=null}}Pj={at:Date.now(),info:K};return K}function YQ6(){Pj=null}function ZQ6(){if(tF8()==="win32")return"powershell.exe";return process.env.SHELL||"sh"}class eF8{defaultWorkspaceDir;wsPort;sessions=new Map;constructor(z,J){this.defaultWorkspaceDir=z;this.wsPort=J}start(z){const J=`terminal_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;const D=qQ6(z.workspaceDir||this.defaultWorkspaceDir);const K=ZQ6();this.sessions.set(J,{id:J,workspaceDir:D,shell:K,startedAt:Date.now()});return{terminalId:J,port:this.wsPort,ttydPort:this.wsPort,wsUrl:`ws://127.0.0.1:${this.wsPort}/terminal?terminalId=${encodeURIComponent(J)}`,workspaceDir:D,shell:K}}status(z){const J=z?this.sessions.get(z):undefined;const D=[...this.sessions.values()];return{running:z?Boolean(J?.child):D.some((K)=>Boolean(K.child)),terminalAvailable:true,ttydAvailable:true,port:this.wsPort,ttydPort:this.wsPort,uptime:J?Math.floor((Date.now()-J.startedAt)/1000):undefined,workspaceDir:J?.workspaceDir||this.defaultWorkspaceDir,wsUrl:z?`ws://127.0.0.1:${this.wsPort}/terminal?terminalId=${encodeURIComponent(z)}`:`ws://127.0.0.1:${this.wsPort}/terminal`,sessions:D.map((K)=>({id:K.id,workspaceDir:K.workspaceDir,shell:K.shell,uptime:Math.floor((Date.now()-K.startedAt)/1000),cols:K.cols,rows:K.rows,exitCode:K.exitCode,error:K.error}))}}stop(z){const J=z?[this.sessions.get(z)].filter(Boolean):[...this.sessions.values()];for(const D of J){try{D.child?.kill();D.socket?.close?.()}catch{}this.sessions.delete(D.id)}return J.length}openSocket(z,J){let D=J?this.sessions.get(J):undefined;if(!D){const q=this.start({});D=this.sessions.get(q.terminalId)}D.socket=z;let K;try{K=this.spawnShell(D)}catch(q){D.error=q instanceof Error?q.message:String(q);z.send(`Terminal failed to start: ${q instanceof Error?q.message:String(q)}\r
1739
1739
  `);z.close?.();this.sessions.delete(D.id);return}D.child=K;const X=new tO8("utf-8");const Y=new tO8("utf-8");K.stdout.on("data",(q)=>z.send(X.write(q)));K.stderr.on("data",(q)=>z.send(Y.write(q)));K.on("error",(q)=>{D.error=q.message;try{z.send(`Terminal process error: ${q.message}\r
1740
1740
  `);z.close?.()}catch{}this.sessions.delete(D.id)});K.on("exit",(q)=>{D.exitCode=q;try{z.send(`\r
1741
1741
  [terminal exited ${q??""}]\r
@@ -4380,7 +4380,7 @@ Error: API Key is required for deployment. Process exited with code 1.\r
4380
4380
  `)){const q8=n.trim();if(!q8||q8.startsWith("#"))continue;const x8=q8.indexOf(":");if(x8===-1)continue;const w8=q8.slice(0,x8).trim();let o8=q8.slice(x8+1).trim();if(typeof o8==="string"&&o8.startsWith("[")&&o8.endsWith("]")){o8=o8.slice(1,-1).split(",").map((u)=>u.trim()).filter(Boolean)}else if(o8==="true")o8=true;else if(o8==="false")o8=false;Q8[w8]=o8}return Q8}function w(d){const Q8=d.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!Q8)return null;return{frontmatter:O8(Q8[1]),body:Q8[2].trim()}}function o(d){const Q8=(q8)=>String(q8??"");const n=(q8)=>Array.isArray(q8)?q8.join(", "):q8?String(q8):"";return["---",`id: ${Q8(d.id)}`,`name: ${Q8(d.name||d.id)}`,`description: ${Q8(d.description).replace(/\n/g," ")}`,`enabled: ${d.enabled!==false}`,`category: ${Q8(d.category||"General")}`,`icon: ${Q8(d.icon||"馃幆")}`,`trigger: ${Q8(d.trigger||"")}`,`injection: ${Q8(d.injection||"lazy")}`,`tags: [${n(d.tags)}]`,`tools: [${n(d.requiredTools)}]`,`source: ${Q8(d.source||"user")}`,`editable: ${d.editable!==false}`,"---","",Q8(d.systemPrompt)].join(`
4381
4381
  `)}function i(){z8();const d=new Map;for(const Q8 of tH(X8)){if(!Q8.endsWith(".skill.md"))continue;try{const n=U0(U1(X8,Q8),"utf-8");const q8=w(n);if(!q8)continue;const x8=q8.frontmatter;const w8=String(x8.id??Q8.replace(/\.skill\.md$/,""));d.set(w8,{id:w8,name:String(x8.name??w8),description:String(x8.description??""),enabled:x8.enabled!==false,category:String(x8.category??"General"),icon:String(x8.icon??"star"),tags:Array.isArray(x8.tags)?x8.tags:[],trigger:String(x8.trigger??""),injection:String(x8.injection??"lazy"),systemPrompt:q8.body,requiredTools:Array.isArray(x8.tools)?x8.tools:[],source:String(x8.source??"file"),editable:x8.editable!==false,version:String(x8.version??"1.0"),author:String(x8.author??"user")})}catch(n){e7.warn("skills.load_failed",`Failed to load skill ${Q8}`,String(n))}}return d}function s(d){z8();C2(U1(X8,String(d.id)+".skill.md"),o(d),"utf-8")}function D8(d){const Q8=U1(X8,d+".skill.md");if(u7(Q8))gO8(Q8)}function V8(){z8();if(tH(X8).some((Q8)=>Q8.endsWith(".skill.md")))return;const d=[{id:"code-review",name:"Code Review",description:"Review code changes for correctness, security, and best practices",enabled:true,category:"Development",icon:"馃帗",tags:["review","code-quality"],trigger:"review",injection:"lazy",systemPrompt:"You are a thorough code reviewer. Analyze code for bugs, security issues, performance problems, and adherence to best practices. Provide constructive feedback.",requiredTools:["read","grep"],source:"built-in",editable:false,version:"1.0",author:"system"},{id:"debug",name:"Debug",description:"Analyze and fix bugs in code",enabled:true,category:"Development",icon:"馃攳",tags:["debug","bug-fix"],trigger:"debug",injection:"lazy",systemPrompt:"You are a debugging expert. Systematically analyze code, identify root causes, and propose fixes. Use tools to inspect code and runtime state.",requiredTools:["read","grep","bash"],source:"built-in",editable:false,version:"1.0",author:"system"},{id:"explain",name:"Explain Code",description:"Explain what code does in detail",enabled:true,category:"Learning",icon:"馃摉",tags:["explain","understand"],trigger:"explain",injection:"lazy",systemPrompt:"You are a coding teacher. When asked to explain code, provide a clear, detailed explanation of what it does, how it works, key patterns used, and potential pitfalls.",requiredTools:["read"],source:"built-in",editable:false,version:"1.0",author:"system"},{id:"refactor",name:"Refactor",description:"Refactor code to improve quality and maintainability",enabled:true,category:"Development",icon:"馃敡",tags:["refactor","clean-code"],trigger:"refactor",injection:"lazy",systemPrompt:"You are a refactoring specialist. Improve code structure, readability, and maintainability while preserving functionality. Suggest modern patterns and best practices.",requiredTools:["read","write","grep"],source:"built-in",editable:false,version:"1.0",author:"system"},{id:"test",name:"Write Tests",description:"Generate unit tests for code",enabled:true,category:"Testing",icon:"馃И",tags:["test","unit-test"],trigger:"test",injection:"lazy",systemPrompt:"You are a testing expert. Write comprehensive unit tests covering normal cases, edge cases, and error conditions. Use the appropriate testing framework for the project.",requiredTools:["read","write"],source:"built-in",editable:false,version:"1.0",author:"system"},{id:"document",name:"Document",description:"Generate documentation for code",enabled:true,category:"Documentation",icon:"馃摑",tags:["doc","documentation"],trigger:"doc",injection:"lazy",systemPrompt:"You are a technical writer. Generate clear, comprehensive documentation including API docs, inline comments, and usage examples.",requiredTools:["read","write"],source:"built-in",editable:false,version:"1.0",author:"system"}];for(const Q8 of d)s(Q8)}V8();const Y8=i();const j8=U1(Z,"skill-marketplaces.json");const C8=U1(Z,"skill-market-cache.json");const B8=[{id:"superpowers",name:"Superpowers",url:"https://github.com/obra/superpowers",builtin:true,description:"Claude Code skill collection: brainstorming, systematic debugging, TDD, plan writing, code review and more"},{id:"anthropics-skills",name:"Anthropic Skills",url:"https://github.com/anthropics/skills",builtin:true,description:"Official Anthropic skill library: docx/pdf/pptx/xlsx generation, frontend design, mcp-builder, skill-creator and more"},{id:"agentic-curated",name:"Agentic 精选技能",url:"builtin://agentic-curated",builtin:true,description:"从 agentic-awesome-skills(2000+ 社区技能库)精选的零配置安全技能,随应用离线内置,无需联网"}];const U8=new Map;function d8(){return(process.env.DEEPSEEKCODE_GITHUB_MIRROR||process.env.DSC_GITHUB_MIRROR||"").trim()}function v8(d){const Q8=d8();if(!Q8)return d;return Q8.replace(/\/+$/,"")+"/"+d}function t6(d){try{const Q8=new URL(d);return Q8.hostname==="github.com"||Q8.hostname==="www.github.com"}catch{return/^https?:\/\/github\.com\//i.test(d)}}function H6(d){if(!d)return false;if(/^[a-zA-Z]:[\\/]/.test(d))return true;if(/^\/[^/]/.test(d)||/^\.\.?[\\/]/.test(d))return true;return false}function q6(d){return d.split("/").includes("skills")&&/(^|\/)(SKILL\.md|.+\.skill\.md)$/i.test(d)}function m6(){try{if(u7(C8)){const d=JSON.parse(U0(C8,"utf8"));if(d&&typeof d==="object")return d}}catch(d){e7.warn("market.cache_load_failed","Failed to load marketplace cache",String(d))}return{}}function x6(d,Q8){try{const n=m6();n[d]=Q8;_z(Z,{recursive:true});C2(C8,JSON.stringify(n,null,2),"utf8")}catch(n){e7.warn("market.cache_save_failed","Failed to save marketplace cache",String(n))}}function u1(d){try{const Q8=m6();if(d in Q8){delete Q8[d];_z(Z,{recursive:true});C2(C8,JSON.stringify(Q8,null,2),"utf8")}}catch(Q8){e7.warn("market.cache_clear_failed","Failed to clear marketplace cache",String(Q8))}}function M1(){try{if(!u7(j8))return[];const d=JSON.parse(U0(j8,"utf8"));return Array.isArray(d)?d.filter((Q8)=>Q8&&typeof Q8.url==="string"):[]}catch(d){e7.warn("marketplaces.load_failed","Failed to load skill marketplaces",String(d));return[]}}function A1(d){_z(Z,{recursive:true});C2(j8,JSON.stringify(d,null,2),"utf8")}function B7(){const d=[process.env.DEEPSEEKCODE_SKILLS_LIBRARY||process.env.DSC_SKILLS_LIBRARY||"",U1(mO8(),".agent","skills-library"),"D:/agent/agentic-awesome-skills"];for(const Q8 of d){if(!Q8)continue;try{if(u7(Q8)&&t5(Q8).isDirectory())return Q8}catch{}}return null}function O7(){const d=M1();const Q8=[...B8];const n=B7();if(n){Q8.push({id:"agentic-awesome-local",name:"本地技能库",url:n,builtin:true,description:"本机 agentic-awesome-skills 技能库(自动发现,完全离线)"})}const q8=new Set(Q8.map((w8)=>w8.id));const x8=new Set(Q8.map((w8)=>w8.url.replace(/[\\/]+$/,"")));return[...Q8,...d.filter((w8)=>!q8.has(w8.id)&&!x8.has(w8.url.replace(/[\\/]+$/,"")))]}function c0(d){if(H6(d)){const w8=d.replace(/[\\/]+$/,"").split(/[\\/]/).pop()||"local";const o8=w8.replace(/[^a-zA-Z0-9_-]+/g,"-").toLowerCase();return o8||"local"}const Q8=d.replace(/^https?:\/\//i,"").replace(/[?#].*$/,"").replace(/\/+$/,"");const n=Q8.split("/");const q8=n[n.length-1]||n[n.length-2]||"market";const x8=q8.replace(/\.(json|md)$/i,"").replace(/[^a-zA-Z0-9_-]+/g,"-").toLowerCase();return x8||"market"}function V0(d,Q8){try{return new URL(Q8,d).href}catch{return Q8}}async function Q7(d,Q8=MC){const n=await fetch(d,{headers:{"User-Agent":"deepseekcode-server"},signal:AbortSignal.timeout(Q8)});if(!n.ok)throw new Error(`HTTP ${n.status} for ${d}`);return n.text()}async function e6(d,Q8){return JSON.parse(await Q7(d,Q8))}const Y7=["https://ghfast.top/","https://gh-proxy.com/","https://mirror.ghproxy.com/"];async function j7(d,Q8){const n=[];const q8=[d];if(!d8()&&/^https:\/\/raw\.githubusercontent\.com\//i.test(d)){for(const w8 of Y7)q8.push(w8+d)}let x8;for(let w8=0;w8<q8.length;w8++){const o8=w8===0?Math.min(Q8,MC):Q8;try{return await Q7(q8[w8],o8)}catch(u){x8=u;n.push(`${q8[w8]}: ${u instanceof Error?u.message:String(u)}`)}}throw new Error(n.join(" | ")||(x8 instanceof Error?x8.message:String(x8)))}function K0(d,Q8,n,q8){const x8=(w8)=>w8.split("/").map(encodeURIComponent).join("/");return v8(`https://raw.githubusercontent.com/${x8(d)}/${x8(Q8)}/${x8(n)}/${x8(q8)}`)}async function Y9(d){const Q8=d.url.match(/github\.com\/([^/]+)\/([^/?#]+)/i);if(!Q8)throw new Error("Not a GitHub repository URL: "+d.url);const n=Q8[1];const q8=Q8[2].replace(/\.git$/i,"");let x8="main";let w8=[];let o8="";try{const J8=await e6(v8(`https://api.github.com/repos/${n}/${q8}`));x8=J8.default_branch||"main";const $8=await e6(v8(`https://api.github.com/repos/${n}/${q8}/git/trees/${encodeURIComponent(x8)}?recursive=1`));w8=($8.tree||[]).filter((R8)=>R8.type==="blob"&&R8.path&&q6(R8.path)).map((R8)=>R8.path)}catch(J8){o8=J8 instanceof Error?J8.message:String(J8)}if(w8.length===0){const J8=await c$6(d.url);if(J8.code===0&&J8.files.length>0){w8=J8.files.filter(q6);if(J8.branch)x8=J8.branch}else{const $8=[o8&&`GitHub API: ${o8}`,J8.error&&`git: ${J8.error}`].filter(Boolean).join("; ");throw new Error(`Unable to list repository files (${$8||"empty tree"})`)}}const u=new Map;for(const J8 of w8){const $8=/(^|\/)SKILL\.md$/i.test(J8);const R8=J8.replace(/\/[^/]+$/,"");if(!u.has(R8)||$8)u.set(R8,J8)}const c=[];for(const J8 of u.values()){const $8=J8.split("/").pop()||J8;const R8=J8.replace(/\/[^/]+$/,"");const E8=/^SKILL\.md$/i.test($8)?R8.split("/").pop()||R8:$8.replace(/\.skill\.md$/i,"");const u8=E8.replace(/[^a-zA-Z0-9_-]+/g,"-");c.push({id:u8,name:u8,description:"",category:"GitHub",icon:"⭐",tags:["github"],author:`${n}/${q8}`,version:x8,path:J8,rawUrl:K0(n,q8,x8,J8)})}return{name:d.name,skills:c,fetchedAt:new Date().toISOString()}}async function A4(d){const Q8=await e6(d.url);const n=d.url.split("/").slice(0,-1).join("/")+"/";const q8=(Q8.skills||[]).map((x8)=>{const w8=String(x8.id||x8.name||"skill").replace(/[^a-zA-Z0-9_-]+/g,"-");return{id:w8,name:String(x8.name||w8),description:String(x8.description||""),category:String(x8.category||"Marketplace"),icon:String(x8.icon||"⭐"),tags:Array.isArray(x8.tags)?x8.tags.map(String):[],author:String(x8.author||"unknown"),version:String(x8.version||"1.0"),path:String(x8.file||x8.url||""),rawUrl:x8.content?"":V0(n,String(x8.file||x8.url||"")),content:x8.content}});return{name:String(Q8.name||d.name),skills:q8,fetchedAt:new Date().toISOString()}}async function s4(d){const Q8=E2(String(d.url));if(!u7(Q8))throw new Error(`Directory not found: ${Q8}`);if(!t5(Q8).isDirectory())throw new Error(`Not a directory: ${Q8}`);const n=U1(Q8,"skills_index.json");const q8=U1(Q8,"skills");const x8=[];if(u7(n)){const w8=JSON.parse(U0(n,"utf8"));if(Array.isArray(w8)){for(const o8 of w8){const u=String(o8.path||"");const c=String(o8.id||u.split("/").pop()||"").replace(/[^a-zA-Z0-9_-]+/g,"-");if(!c||!u)continue;x8.push({id:c,name:String(o8.name||c),description:String(o8.description||""),category:String(o8.category||"Uncategorized"),icon:"⭐",tags:Array.isArray(o8.tags)?o8.tags.map(String):[],author:String(o8.source||"community"),version:String(o8.version||"1.0"),path:u.replace(/[\\/]+$/,""),rawUrl:"",risk:o8.risk?String(o8.risk):undefined})}if(x8.length>0){return{name:d.name,skills:x8,fetchedAt:new Date().toISOString()}}}}if(!u7(q8)){if(x8.length===0)throw new Error(`No skills/ directory or skills_index.json under ${Q8}`)}else{for(const w8 of tH(q8,{withFileTypes:true})){if(!w8.isDirectory())continue;const o8=b2(U1(q8,w8.name));if(!o8)continue;const u=w(U0(o8,"utf8"));const c=u?.frontmatter||{};const J8=w8.name.replace(/[^a-zA-Z0-9_-]+/g,"-");x8.push({id:J8,name:String(c.name||J8),description:String(c.description||""),category:String(c.category||"Local"),icon:"⭐",tags:Array.isArray(c.tags)?c.tags.map(String):[],author:String(c.author||"local"),version:String(c.version||"1.0"),path:U1("skills",w8.name).split("\\").join("/"),rawUrl:"",risk:c.risk?String(c.risk):undefined})}}if(x8.length===0)throw new Error(`No skills found under ${Q8}`);return{name:d.name,skills:x8,fetchedAt:new Date().toISOString()}}function b2(d){const Q8=U1(d,"SKILL.md");if(u7(Q8)&&t5(Q8).isFile())return Q8;try{for(const n of tH(d)){if(/\.skill\.md$/i.test(n)&&t5(U1(d,n)).isFile())return U1(d,n)}}catch{}return null}function v2(){const d=jQ6;const Q8=(d.skills||[]).map((n)=>({id:String(n.id||n.name||"skill").replace(/[^a-zA-Z0-9_-]+/g,"-"),name:String(n.name||n.id||"skill"),description:String(n.description||""),category:String(n.category||"Curated"),icon:"⭐",tags:[],author:"community",version:String(d.version||"1.0"),path:String(n.id||""),rawUrl:"",content:String(n.content||""),risk:n.risk?String(n.risk):undefined}));return{name:String(d.name||"Agentic 精选技能"),skills:Q8,fetchedAt:new Date().toISOString()}}async function t4(d){let Q8;if(d.url==="builtin://agentic-curated")Q8=v2();else if(H6(d.url))Q8=await s4(d);else if(t6(d.url))Q8=await Y9(d);else Q8=await A4(d);U8.set(d.id,Q8);x6(d.id,Q8);return Q8}async function x9(d){const Q8=U8.get(d.id);if(Q8)return Q8;const n=m6()[d.id];if(n&&Array.isArray(n.skills)&&n.skills.length>0){U8.set(d.id,n);return n}return t4(d)}async function Tz(d,Q8){const n=await x9(d);const q8=n.skills.find((J8)=>J8.id===Q8);if(!q8)throw new Error(`Skill "${Q8}" not found in marketplace "${d.name}"`);let x8=q8.content;if(!x8&&H6(d.url)&&q8.path){const J8=U1(E2(String(d.url)),q8.path);const $8=b2(J8);if(!$8)throw new Error(`Skill "${Q8}" not found on disk at ${J8}`);x8=U0($8,"utf8")}if(!x8){if(!q8.rawUrl)throw new Error(`Skill "${Q8}" has no downloadable content`);x8=await j7(q8.rawUrl,JQ6)}const w8=w(x8);const o8=w8?.frontmatter||{};const u=String(o8.id||q8.id).replace(/[^a-zA-Z0-9_-]+/g,"-");const c={id:u,name:String(o8.name||q8.name||u),description:String(o8.description||q8.description||""),enabled:o8.enabled!==false,category:String(o8.category||q8.category||"Marketplace"),icon:String(o8.icon||q8.icon||"⭐"),tags:Array.isArray(o8.tags)?o8.tags.map(String):q8.tags,trigger:String(o8.trigger||""),injection:o8.injection==="eager"||o8.injection==="on_demand"?o8.injection:"lazy",systemPrompt:w8?.body||x8,requiredTools:Array.isArray(o8.tools)?o8.tools.map(String):[],source:"marketplace",editable:o8.editable!==false,version:String(o8.version||q8.version||"1.0"),author:String(o8.author||q8.author||d.name),provenance:"marketplace",marketplace:d.id,marketUrl:q8.rawUrl||q8.path};s(c);Y8.set(u,c);try{A.skills.loadAll()}catch{}return c}async function p6(d,Q8){const n=Q8.pathname;const q8=d.method.toUpperCase();if(q8==="OPTIONS")return l(L8({}));const x8={runtime:A,getApiKey:()=>M.load()?.apiKey||null};if(n==="/v1/chat/completions"&&q8==="POST"){const{handleChatCompletions:w8}=await Promise.resolve().then(()=>Em);return w8(d,x8)}if(n==="/v1/models"&&q8==="GET"){const{handleModels:w8}=await Promise.resolve().then(()=>Em);return w8(d,x8)}return null}function h9(){return[{category:"TOOL",events:[{name:"PRE_TOOL_USE",summary:"Intercept before tool execution",hasMatcher:true,matcherField:"toolNamePattern"},{name:"POST_TOOL_USE",summary:"Post tool execution",hasMatcher:true,matcherField:"toolNamePattern"},{name:"POST_TOOL_USE_FAILURE",summary:"Tool execution failed",hasMatcher:true,matcherField:"toolNamePattern"},{name:"PERMISSION_DENIED",summary:"Permission denied",hasMatcher:false},{name:"PERMISSION_REQUEST",summary:"Permission request",hasMatcher:false}]},{category:"SESSION",events:[{name:"SESSION_START",summary:"Session started",hasMatcher:false},{name:"SESSION_END",summary:"Session ended",hasMatcher:false},{name:"STOP",summary:"Generation stopped",hasMatcher:false},{name:"STOP_FAILURE",summary:"Stop failed",hasMatcher:false},{name:"NOTIFICATION",summary:"System notification",hasMatcher:false}]},{category:"CONTEXT",events:[{name:"PRE_COMPACT",summary:"Before context compaction",hasMatcher:false},{name:"POST_COMPACT",summary:"After context compaction",hasMatcher:false},{name:"PRE_CONTEXT_RESET",summary:"Before context reset",hasMatcher:false},{name:"POST_CONTEXT_RESET",summary:"After context reset",hasMatcher:false}]},{category:"STATE_MACHINE",events:[{name:"STATE_TRANSITION",summary:"",hasMatcher:true,matcherField:"fromState"},{name:"STATE_ENTERED",summary:"",hasMatcher:true,matcherField:"fromState"}]},{category:"TASK",events:[{name:"USER_PROMPT_SUBMIT",summary:"User submitted prompt",hasMatcher:false},{name:"SUBAGENT_START",summary:"Subagent started",hasMatcher:false},{name:"SUBAGENT_STOP",summary:"Subagent stopped",hasMatcher:false},{name:"TASK_CREATED",summary:"Task created",hasMatcher:false},{name:"TASK_COMPLETED",summary:"Task completed",hasMatcher:false},{name:"TEAMMATE_IDLE",summary:"Teammate idle",hasMatcher:false}]},{category:"A2A",events:[{name:"TASK_DISPATCH",summary:"Task dispatched",hasMatcher:false},{name:"A2A_REMOTE_INTERCEPT",summary:"Remote intercept",hasMatcher:false}]},{category:"CONFIG",events:[{name:"CONFIG_CHANGE",summary:"Configuration changed",hasMatcher:false},{name:"INSTRUCTIONS_LOADED",summary:"Instructions loaded",hasMatcher:false},{name:"CWD_CHANGED",summary:"Working directory changed",hasMatcher:false},{name:"FILE_CHANGED",summary:"File changed",hasMatcher:false}]}]}function jq(){return[{id:"main",name:"Main",description:"Primary orchestration agent - general task processing"},{id:"code-reviewer",name:"Code Reviewer",description:"Code review specialist agent"},{id:"debugger",name:"Debugger",description:"Debug analysis specialist agent"}]}function l0(d){if(!G)return true;const Q8=d.headers.get("authorization")||"";if(Q8.startsWith("Bearer ")){if(Q8.slice(7).trim()===G)return true}return d.headers.get("x-api-token")===G}async function X0(d,Q8){const n=Q8.pathname;const q8=d.method.toUpperCase();if(q8==="OPTIONS")return l(L8({}));if(n==="/api/health")return l(L8({status:"ok"}));if(n==="/api/stt/status"&&q8==="GET"){return l(L8(await v.status()))}if(n==="/api/stt/transcribe"&&q8==="POST"){const u=await f8(d);const c=String(u.language||"en");const J8=String(u.audio||"");if(c!=="en"&&c!=="zh"){return l(e8(`Unsupported STT language: ${c} (use 'en' or 'zh')`),400)}if(!J8)return l(e8("Missing 'audio' (base64 WAV)"),400);try{const $8=await v.transcribe({language:c,audio:J8,format:u.format==="f32"?"f32":"wav"});return l(L8($8))}catch($8){return l(e8($8 instanceof Error?$8.message:String($8)),500)}}if(n==="/api/stt/install"&&q8==="POST"){const u=await f8(d);const c=String(u.backend||"");if(c!=="en"&&c!=="zh"){return l(e8(`Unsupported backend: ${c} (use 'en' or 'zh')`),400)}const J8=await v.install(c);return J8.started?l(L8(J8)):l(L8({started:false,alreadyRunning:J8.alreadyRunning,manualCommand:J8.manualCommand,error:J8.error}),409)}if(n==="/api/stt/install/status"&&q8==="GET"){return l(L8(v.installStatus()))}if(n==="/api/stt/install/cancel"&&q8==="POST"){return l(L8({cancelled:v.cancelInstall()}))}if(G&&!l0(d)){return l({ok:false,error:"Unauthorized: missing or invalid API token (Authorization: Bearer <token>). Set DEEPSEEKCODE_API_TOKEN on the server."},401)}if(n==="/api/weixin/bind"&&q8==="GET"){try{const{fetchWebQrCode:u}=await Promise.resolve().then(()=>(m0(),Q4));const c=await u();return l(L8(c))}catch(u){return l(e8(`Failed to fetch WeChat QR code: ${u instanceof Error?u.message:String(u)}`),500)}}if(n==="/api/weixin/bind/status"&&q8==="GET"){const u=Q8.searchParams.get("qrcode")||"";if(!u)return l(e8("缺少 qrcode 参数"),400);try{const{checkWebQrStatus:c}=await Promise.resolve().then(()=>(m0(),Q4));const J8=await c({qrcode:u});if(J8.status==="confirmed"&&J8.ilink_bot_id){try{const{saveWeixinAccount:$8,registerWeixinAccountId:R8,clearStaleAccountsForUserId:E8}=await Promise.resolve().then(()=>(m0(),Q4));const u8=String(J8.ilink_bot_id).replace(/@im\.bot$/,"").replace(/@/g,"-");const D6=J8.baseurl||"https://ilinkai.weixin.qq.com";$8(u8,{token:J8.bot_token||"",baseUrl:D6,userId:J8.ilink_user_id});R8(u8);if(J8.ilink_user_id){E8(u8,J8.ilink_user_id)}await f6(u8,D6,J8.ilink_user_id)}catch($8){e7.error("weixin.bind_persist_failed","Failed to persist WeChat bind result",String($8))}}return l(L8(J8))}catch(c){return l(e8(`Failed to check binding status: ${c instanceof Error?c.message:String(c)}`),500)}}if(n==="/api/system/status"){const u=f();return l(L8({status:"running",runtime:"typescript",product:"deepseekcode",uptime:Math.floor((Date.now()-O)/1000),memory:{used:process.memoryUsage().heapUsed,total:process.memoryUsage().heapTotal,max:process.memoryUsage().rss},models:{total:u.length,online:u.filter((c)=>c.status==="online").length,offline:u.filter((c)=>c.status!=="online").length},timestamp:Date.now()}))}if(n==="/api/system/shutdown"){if(z.onShutdown){setImmediate(z.onShutdown);return l(L8({message:"Shutting down..."}))}setImmediate(()=>{try{g9.close()}catch{}try{pJ.close()}catch{}A.dispose();process.exit(0)});return l(L8({message:"Shutting down..."}))}if(n==="/api/system/restart"){try{A.dispose()}catch{}return l(L8({message:"DeepSeekCode TS server restart initiated — please restart the process manually for full lifecycle reset"}))}if(n==="/api/system/version"){const u=Tm();let c=null;try{c=await rO8(u)}catch{c=null}return l(L8({product:"deepseekcode",channel:"stable",current:u,update:c,checkedAt:Date.now(),status:c?c.available?"update-available":"up-to-date":"unknown"}))}if(n==="/api/system/update/check"&&q8==="GET"){const u=Tm();YQ6();let c=null;try{c=await rO8(u,true)}catch{c=null}return l(L8({product:"deepseekcode",channel:"stable",current:u,update:c,checkedAt:Date.now(),status:c?c.available?"update-available":"up-to-date":"unknown"}))}if(n==="/api/config/provider"){if(q8==="GET"){const P7=M.response();const U7=_6();return l(L8({...P7,providers:U7}))}const u=await f8(d);const c=String(u.provider||u.defaultProvider||"");if(!c)return l(e8("provider is required"),400);const J8=Array.isArray(u.apiKeys)?u.apiKeys.map((P7)=>String(P7).trim()).filter(Boolean):("apiKey"in u)||("api_key"in u)?[String(u.apiKey??u.api_key??"")].map((P7)=>P7.trim()).filter(Boolean):undefined;const $8=M.getEntry(c);const R8=String(u.baseUrl||u.base_url||$8?.baseUrl||"");const E8=String(u.apiType||"openai-chat-completions");let u8;if(Array.isArray(u.models)){const P7=[];u.models.forEach((U7,c7)=>{const f1=U7&&typeof U7==="object"?U7:{};const m1=String(f1.id||f1.name||"").trim();if(!m1)return;P7.push({id:m1,provider:c,enabled:f1.enabled!==false,isDefault:Boolean(f1.isDefault)||c7===0,defaultFor:String(f1.defaultFor||""),apiType:String(f1.apiType||u.apiType||"openai-chat-completions"),name:String(f1.name||m1),aliases:Array.isArray(f1.aliases)?f1.aliases.map(String).filter(Boolean):undefined,baseUrl:String(f1.baseUrl||u.baseUrl||""),maxTokens:f1.maxTokens!==undefined?Number(f1.maxTokens):undefined,contextWindow:f1.contextWindow!==undefined?Number(f1.contextWindow):undefined,temperature:f1.temperature!==undefined?Number(f1.temperature):undefined})});u8=P7}const D6=M.saveEntry({key:c,name:String(u.name||$8?.name||c),baseUrl:R8||$8?.baseUrl||"",apiType:E8||$8?.apiType||"openai-chat-completions",apiKeys:J8??$8?.apiKeys,models:u8??$8?.models??[]});const I6=M.load();if(u.setDefault===true||!I6.provider||I6.provider===c){M.setDefaultProvider(c)}const r6=M.response();const B1=_6();H8();return l(L8({...r6,providers:B1}))}if(n==="/api/config/provider/remove"&&q8==="POST"){const u=await f8(d);const c=String(u.provider||"");if(!c)return l(e8("provider is required"),400);let J8=F8();J8=J8.filter((R8)=>R8.provider!==c);y8(J8);K6(c);const $8=M.load();if($8.provider===c){const R8=J8.length>0?J8[0].provider:"deepseek";const E8=J8.length>0?J8[0].id:"";M.save({provider:R8,model:E8})}H8();return l(L8({removed:true}))}if(n==="/api/providers/presets"&&q8==="GET"){const u=!u7(E);if(u){try{const J8=new Promise(($8)=>setTimeout($8,3500));await Promise.race([t(1e4).then(()=>{}),J8])}catch{}}const c=g();t(1e4);return l(L8(c))}if(n==="/api/providers/refresh"&&q8==="POST"){let u=null;try{if(u7(E)){u=JSON.parse(U0(E,"utf-8"))}}catch{}t(1e4);if(u){return l(L8({refreshed:true,source:"cache"}))}return l(L8({refreshed:true,message:"Refresh triggered in background"}))}const x8=Z;const w8=["config.yaml","channels.json","hooks.json","system-prompt.md","history.json","daemon.json","settings.json","provider.json","theme.json","mode.json"];const o8=["history.json"];if(n==="/api/config/files"&&q8==="GET"){const u=w8.filter((c)=>u7(U1(x8,c))).map((c)=>{try{const J8=t5(U1(x8,c));return{name:c,size:J8.size,modified:J8.mtimeMs,editable:!o8.includes(c)}}catch{return null}}).filter(Boolean);return l(L8(u))}if(n==="/api/config/files/read"&&q8==="GET"){const u=String(Q8.searchParams.get("file")||"");if(!u||!w8.includes(u))return l(e8("Invalid config file name"),400);const c=U1(x8,u);if(!u7(c))return l(e8("File not found"),404);try{const J8=U0(c,"utf8");return l(L8({name:u,content:J8,editable:!o8.includes(u)}))}catch(J8){return l(e8(J8.message),500)}}if(n==="/api/config/files/write"&&q8==="PUT"){const u=await f8(d);const c=String(u.file||"");if(!c||!w8.includes(c))return l(e8("Invalid config file name"),400);if(o8.includes(c))return l(e8("File is read-only"),403);try{_z(x8,{recursive:true});C2(U1(x8,c),String(u.content||""),"utf8");return l(L8({message:`${c} saved`}))}catch(J8){return l(e8(J8.message),500)}}if(n==="/api/commands"){const u=Q8.searchParams.get("lang")||undefined;return l(L8(u?A.listCommandsLocalized(u):A.listCommands()))}if(n==="/api/models"&&q8==="GET")return l(L8({models:f(),defaultProvider:M.load().provider}));if(n==="/api/models"&&q8==="POST"){const u=await f8(d);const c=u.model&&typeof u.model==="object"?u.model:{};const J8=c.apiKeys;const $8=Array.isArray(J8)?String(J8[0]||""):String(J8||c.apiKey||"");const R8=String(u.provider||c.provider||M.load().provider);const E8=String(c.id||c.name||c.model||M.load().model);const u8=String(c.apiType||"openai-chat-completions");const D6=M.save({provider:R8,model:E8,baseUrl:c.baseUrl||c.base_url,apiKey:$8||undefined,maxTokens:c.maxTokens||c.max_tokens,contextWindow:c.contextWindow||c.context_window,temperature:c.temperature});const I6=F8();J6(I6,E8,R8,c.enabled!==false,false,undefined);const r6=I6.findIndex((B1)=>B1.id.toLowerCase()===E8.toLowerCase()&&B1.provider===R8);if(r6>=0){I6[r6].apiType=u8;if(c.name)I6[r6].name=String(c.name);if(c.baseUrl)I6[r6].baseUrl=String(c.baseUrl)}y8(I6);P8(R8,{baseUrl:String(c.baseUrl||D6.baseUrl||""),hasApiKey:Boolean($8||D6.apiKey),apiType:u8,modelCount:I6.filter((B1)=>B1.provider===R8).length});H8();return l(L8({model:D6,provider:D6.provider,savedTo:"config.yaml"}))}if(n==="/api/models/update"&&q8==="POST"){const u=await f8(d);const c=M.load();const J8=u.model&&typeof u.model==="object"?u.model:{};const $8=String(u.provider||c.provider);const R8=String(u.modelId||J8.id||J8.model||c.model);const E8=M.getEntry($8);if(E8){const D6=E8.models.find((I6)=>I6.id===R8);if(D6){if(J8.name)D6.name=String(J8.name);if(Array.isArray(J8.aliases)){D6.aliases=J8.aliases.map(String).filter(Boolean)}if(J8.baseUrl)D6.baseUrl=String(J8.baseUrl);if(J8.maxTokens!==undefined)D6.maxTokens=Number(J8.maxTokens);if(J8.contextWindow!==undefined)D6.contextWindow=Number(J8.contextWindow);if(J8.temperature!==undefined)D6.temperature=Number(J8.temperature);const I6=String(u.apiKey??J8.apiKey??"").trim();if(I6){const r6=Array.isArray(E8.apiKeys)?E8.apiKeys.slice():[];if(r6.length===0)r6.push(I6);else r6[0]=I6;E8.apiKeys=r6}M.saveEntry(E8)}}const u8=$8===c.provider?M.save({model:R8,baseUrl:String(J8.baseUrl||J8.base_url||c.baseUrl||""),maxTokens:J8.maxTokens!==undefined?Number(J8.maxTokens):c.maxTokens,contextWindow:J8.contextWindow!==undefined?Number(J8.contextWindow):c.contextWindow,temperature:J8.temperature!==undefined?Number(J8.temperature):c.temperature}):undefined;H8();return l(L8({provider:$8,modelId:R8,model:u8}))}if(n==="/api/models/delete"&&q8==="POST"){const u=await f8(d);const c=String(u.modelId||"");const J8=String(u.provider||"");const $8=M.load();let R8=F8();R8=R8.filter((E8)=>!(E8.id===c&&(!J8||E8.provider===J8)));y8(R8);if(c&&c===$8.model){const E8=R8.find((D6)=>D6.enabled);const u8=E8?.id??"";M.save({model:u8})}H8();return l(L8({provider:J8,modelId:c,removed:true}))}if(n==="/api/models/toggle"&&q8==="POST"){const u=await f8(d);const c=String(u.modelId||"");const J8=String(u.provider||"");let $8=F8();const R8=$8.findIndex((D6)=>D6.id===c&&(!J8||D6.provider===J8));const E8=R8>=0?$8[R8].enabled:true;const u8=u.enabled!==undefined?Boolean(u.enabled):!E8;J6($8,c,J8,u8);y8($8);H8();return l(L8({provider:J8,modelId:c,enabled:u8}))}if(n==="/api/models/defaults"&&q8==="POST"){const u=await f8(d);const c=M.load();let J8=F8();const $8=(u8)=>{if(J8.some((I6)=>I6.id===u8))return u8;const D6=u8.indexOf(":");if(D6>0){const I6=u8.slice(D6+1);if(J8.some((r6)=>r6.id===I6)){for(const r6 of J8){if(r6.id===u8)r6.defaultFor=""}return I6}}return u8};if(u.global){const u8=$8(String(u.global));M.save({model:u8});J6(J8,u8,c.provider,true,true)}for(const u8 of["plan","act","goal"]){const D6=u[u8];if(D6===null){for(const I6 of J8){if(I6.defaultFor===u8)I6.defaultFor=""}}else if(D6){J6(J8,$8(String(D6)),c.provider,true,undefined,u8)}}y8(J8);g8();H8();const R8=$8(String(u.global||c.model));const E8=(u8)=>J8.find((D6)=>D6.defaultFor===u8)?.id;return l(L8({defaults:{global:R8,plan:String(u.plan?$8(String(u.plan)):E8("plan")||R8),act:String(u.act?$8(String(u.act)):E8("act")||R8),goal:String(u.goal?$8(String(u.goal)):E8("goal")||R8)}}))}if(n==="/api/models/fetch"&&q8==="POST"){const u=await f8(d);const c=String(u.baseUrl||"").trim().replace(/\/+$/,"");const J8=String(u.apiKey||"").trim();const $8=J8.replace(/[^\x00-\xFF]/g,"");if(J8&&J8!==$8){console.warn(`[API] API Key contains non-Latin-1 characters (e.g. •). Stripped for fetch request.`)}const R8=$8||(M.load().apiKey||"");if(!c)return l(e8("Base URL is required"),400);const E8=c.endsWith("/v1")||c.endsWith("/v1beta")?c:`${c}/v1`;const u8=[...c.endsWith("/models")?[c]:[`${c}/models`,`${E8}/models`],...c.includes("/anthropic")||c.includes("/coding")||c.includes("/step_plan")||c.includes("/compatible")||c.includes("/claude")?(()=>{const B1=c.replace(/\/+(api\/|apps\/)?(anthropic|coding|step_plan|compatible|claudecode|claude)\/?.*$/,"");return B1&&B1.includes("://")?[`${B1}/v1/models`,`${B1}/models`]:[]})():[]];const D6=new Set;const I6=u8.filter((B1)=>{const P7=B1.toLowerCase();return D6.has(P7)?false:(D6.add(P7),true)});let r6="";for(const B1 of I6){try{const P7={"content-type":"application/json"};if(R8)P7.authorization=`Bearer ${R8}`;const U7=await fetch(B1,{headers:P7,signal:AbortSignal.timeout(MC)});if(!U7.ok){if(U7.status===404||U7.status===405)continue;r6=`HTTP ${U7.status}`;break}const c7=await U7.json();let f1=(Array.isArray(c7.data)?c7.data:[]).filter((m1)=>m1&&typeof m1==="object"&&m1.id).map((m1)=>({id:String(m1.id),name:String(m1.id)}));if(f1.length===0&&Array.isArray(c7.models)){f1=c7.models.filter((m1)=>m1&&typeof m1==="object"&&m1.name).map((m1)=>{const e4=String(m1.name||"").replace(/^models\//,"");return{id:e4,name:e4}})}if(f1.length===0&&Array.isArray(c7)){f1=c7.filter((m1)=>m1&&typeof m1==="object"&&m1.id).map((m1)=>({id:String(m1.id),name:String(m1.id)}))}if(f1.length>0){const m1=new Set;f1=f1.filter((e4)=>{const M0=e4.id;return m1.has(M0)?false:(m1.add(M0),true)});return l(L8({models:f1,url:B1}))}r6=`No models found in response from ${B1}`}catch(P7){r6=P7.message}}return l(e8(r6||"Failed to fetch models"),400)}if(n.startsWith("/api/models/")){const u=n.split("/");const c=decodeURIComponent(u[3]||"");if(u.length>4){if(u[4]==="test"&&q8==="POST"){const J8=await f8(d);const $8=String(J8.baseUrl||"");const R8=String(J8.apiKey||"");const E8=$8||M.load().baseUrl||"";const u8=R8||M.load().apiKey||"";const D6=u8.replace(/[^\x00-\xFF]/g,"");if(!E8)return l(e8("No base URL configured"),400);const I6={"content-type":"application/json"};if(D6)I6.authorization=`Bearer ${D6}`;const r6=_(E8);let B1="";for(const P7 of r6){try{const U7=await fetch(P7,{headers:I6,signal:AbortSignal.timeout(zQ6)});const c7=U7.ok||U7.status===401||U7.status===403;return l(L8({connected:c7,status:U7.status,message:c7?"Connected":`HTTP ${U7.status}`}))}catch(U7){B1=U7.message}}return l(L8({connected:false,message:B1||"All endpoints failed"}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(q8==="GET"){const J8=f().find(($8)=>$8.id===c);return J8?l(L8(J8)):l(e8("Model not found"),404)}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n==="/api/tools")return l(L8(P.listApiTools()));if(n.startsWith("/api/tools/")){const u=n.split("/");const c=decodeURIComponent(u[3]||"");if(u.length>4){if(u[4]==="toggle"&&q8==="POST"){const J8=await f8(d);const $8=J8.enabled!==undefined?Boolean(J8.enabled):true;const R8=P.setToolEnabled(c,$8);if(!R8)return l(e8("Tool not found"),404);return l(L8({id:c,enabled:$8}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(q8==="GET"){const J8=P.listApiTools();const $8=J8.find((R8)=>R8.id===c);return $8?l(L8($8)):l(e8("Tool not found"),404)}if(q8==="PUT"){const J8=await f8(d);const $8=P.listApiTools();const R8=$8.find((E8)=>E8.id===c);if(!R8)return l(e8("Tool not found"),404);if(J8.enabled!==undefined)P.setToolEnabled(c,Boolean(J8.enabled));return l(L8(P.listApiTools().find((E8)=>E8.id===c)))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n==="/api/skills"&&q8==="GET")return l(L8(Array.from(Y8.values())));if(n==="/api/skills"&&q8==="POST"){const u=await f8(d);if(!u.id)return l(e8("Skill ID is required"),400);const c={id:u.id,name:u.name||u.id,description:u.description||"",enabled:u.enabled!==false,category:u.category||"General",icon:u.icon||"star",tags:u.tags||[],trigger:u.trigger||"",injection:u.injection||"lazy",systemPrompt:u.systemPrompt||"",requiredTools:u.requiredTools||[],source:"user",editable:true,version:u.version||"1.0",author:"user",provenance:"manual"};Y8.set(c.id,c);s(c);return l(L8(c))}if(n.startsWith("/api/skills/import")&&q8==="POST"){const u=await f8(d);const c=u.id||u.fileName?.replace(/\.(skill\.md|md|txt)$/i,"")||"imported-"+Date.now();const J8={id:c,name:u.name||c,description:u.description||"Imported skill",enabled:true,category:"Imported",icon:"馃摝",tags:u.tags||[],trigger:u.trigger||"",injection:u.injection||"lazy",systemPrompt:u.content||u.systemPrompt||"",requiredTools:u.requiredTools||[],source:"imported",editable:true,version:u.version||"1.0",author:"user",provenance:"import"};Y8.set(J8.id,J8);s(J8);return l(L8(J8))}if(n==="/api/skills/marketplaces"&&q8==="GET"){const u=O7();const c=Array.from(Y8.values()).filter((R8)=>R8.source==="marketplace"||R8.provenance==="marketplace").map((R8)=>R8.id);const J8=await Promise.all(u.map(async(R8)=>{try{const E8=await x9(R8);return{id:R8.id,entry:{name:E8.name,skills:E8.skills,fetchedAt:E8.fetchedAt}}}catch(E8){return{id:R8.id,entry:{name:R8.name,skills:[],fetchedAt:"",error:E8 instanceof Error?E8.message:String(E8)}}}}));const $8={};for(const{id:R8,entry:E8}of J8)$8[R8]=E8;return l(L8({marketplaces:u,installed:c,indexes:$8}))}if(n==="/api/skills/marketplaces"&&q8==="POST"){const u=await f8(d);const c=String(u.url||"").trim();if(!/^https?:\/\//i.test(c)&&!H6(c)){return l(e8("A valid URL is required (GitHub repo, index.json, or a local skills folder)"),400)}const J8=String(u.id||c0(c));const $8={id:J8,name:String(u.name||J8),url:c,builtin:false,description:String(u.description||""),addedAt:new Date().toISOString()};const R8=M1();const E8=R8.find((u8)=>u8.id===J8);if(E8)E8.url=c;else{R8.push($8);A1(R8)}try{const u8=await t4($8);return l(L8({marketplace:$8,index:{name:u8.name,skills:u8.skills,fetchedAt:u8.fetchedAt}}))}catch(u8){return l(e8("Marketplace unreachable: "+(u8 instanceof Error?u8.message:String(u8))),502)}}if(n.startsWith("/api/skills/marketplaces/")){const u=n.split("/");const c=decodeURIComponent(u[4]||"");const J8=O7().find((R8)=>R8.id===c);if(!J8)return l(e8("Marketplace not found"),404);if(q8==="GET"){try{const R8=await x9(J8);return l(L8({marketplace:J8,index:{name:R8.name,skills:R8.skills,fetchedAt:R8.fetchedAt}}))}catch(R8){return l(e8("Failed to load index: "+(R8 instanceof Error?R8.message:String(R8))),502)}}const $8=u[5];if($8==="refresh"&&q8==="POST"){U8.delete(c);u1(c);try{const R8=await t4(J8);return l(L8({marketplace:J8,index:{name:R8.name,skills:R8.skills,fetchedAt:R8.fetchedAt}}))}catch(R8){return l(e8("Refresh failed: "+(R8 instanceof Error?R8.message:String(R8))),502)}}if($8==="install"&&q8==="POST"){const R8=await f8(d);try{const E8=await Tz(J8,String(R8.skillId||""));return l(L8(E8))}catch(E8){return l(e8("Install failed: "+(E8 instanceof Error?E8.message:String(E8))),502)}}if(q8==="DELETE"){if(J8.builtin)return l(e8("Built-in marketplaces cannot be removed"),400);const R8=M1();A1(R8.filter((E8)=>E8.id!==c));U8.delete(c);u1(c);return l(L8({deleted:true}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/skills/")){const u=n.split("/");const c=decodeURIComponent(u[3]);if(!c)return l(e8("Skill ID is required"),400);if(u[4]==="toggle"&&q8==="POST"){const J8=await f8(d);const $8=Y8.get(c);if(!$8)return l(e8("Skill not found"),404);$8.enabled=J8.enabled!==undefined?J8.enabled:!$8.enabled;Y8.set(c,$8);s($8);return l(L8($8))}if(q8==="GET"){const J8=Y8.get(c);return J8?l(L8(J8)):l(e8("Skill not found"),404)}if(q8==="PUT"){const J8=Y8.get(c);if(!J8)return l(e8("Skill not found"),404);const $8=await f8(d);Object.assign(J8,$8,{id:c});Y8.set(c,J8);s(J8);return l(L8(J8))}if(q8==="DELETE"){if(!Y8.has(c))return l(e8("Skill not found"),404);Y8.delete(c);D8(c);return l(L8({deleted:true}))}return l(L8({message:"Skill endpoint"}))}if(n==="/api/agents"&&q8==="GET")return l(L8(Array.from(a.values())));if(n==="/api/agents"&&q8==="POST"){const u=await f8(d);const c=String(u.id||u.name||`agent-${Date.now()}`).replace(/[^a-zA-Z0-9_-]/g,"-").toLowerCase();const J8={id:c,name:String(u.name||c),description:String(u.description||""),color:String(u.color||"#58a6ff"),active:Boolean(u.active),enabled:u.enabled!==false,instanceCount:Number(u.instanceCount||1),state:u.state==="busy"||u.state==="error"?u.state:"idle",modelBinding:u.modelBinding||{mode:"mode-default"}};a.set(c,J8);return l(L8(J8),201)}if(n.startsWith("/api/agents/")){const u=n.split("/");const c=decodeURIComponent(u[3]||"");const J8=a.get(c);if(!J8)return l(e8("Agent not found"),404);if(u.length===4&&q8==="GET")return l(L8(J8));if(u.length===4&&q8==="PUT"){const $8=await f8(d);const R8={...J8,...$8,id:c};a.set(c,R8);return l(L8(R8))}if(u.length===4&&q8==="DELETE"){if(c==="main")return l(e8("Cannot delete the main agent"),400);a.delete(c);return l(L8({deleted:true}))}if(u[4]==="activate"&&q8==="POST"){for(const[$8,R8]of a)a.set($8,{...R8,active:$8===c});return l(L8({agentId:c,active:true}))}if(u[4]==="toggle"&&q8==="POST"){const $8=await f8(d);const R8=$8.enabled!==undefined?Boolean($8.enabled):!J8.enabled;const E8={...J8,enabled:R8,state:R8?"idle":"idle"};a.set(c,E8);return l(L8({agentId:c,enabled:R8,instanceCount:E8.instanceCount,state:E8.state}))}if(u[4]==="model"&&q8==="POST"){const $8=await f8(d);const R8={mode:$8.mode==="specified"?"specified":"mode-default",...$8.modelRef?{modelRef:String($8.modelRef)}:{}};const E8={...J8,modelBinding:R8};a.set(c,E8);return l(L8({agentId:c,...R8}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n==="/api/sessions"&&q8==="GET")return l(L8(C.list()));if(n==="/api/sessions"&&q8==="POST"){const u=await f8(d);const c=u.sessionId?C.ensure(String(u.sessionId),u.title||"New Session"):C.create(u.title||"New Session");const{messages:J8,...$8}=c;return l(L8($8))}if(n.startsWith("/api/sessions/")){const u=n.split("/");const c=u[3];if(u[4]==="messages")return l(L8(C.getMessages(c)));if(u[4]==="resume"){return l(L8(C.resumeSnapshot(c,{tasks:A.listTasks(),pendingApprovals:L.list()})))}if(q8==="DELETE"){C.delete(c);return l(L8({deleted:true}))}const J8=C.get(c);return J8?l(L8(J8)):l(e8("Session not found"),404)}if(n==="/api/tasks"&&q8==="GET"){const u=Q8.searchParams.get("sessionId")||"";const c=A.listTasks();const J8=u?c.filter(($8)=>$8.sessionId===u):c;return l(L8(J8))}if(n==="/api/tasks"&&q8==="POST")return l(L8(A.createTask(await f8(d))));if(n==="/api/tasks"&&q8==="DELETE"){let u=0;for(const c of A.listTasks()){if(["COMPLETED","FAILED","CANCELLED"].includes(c.status)){A.deleteTask(c.id);u+=1}}return l(L8({deleted:u}))}if(n.startsWith("/api/tasks/")){const u=n.split("/");const c=u[3];const J8=A.getTask(c);if(!J8)return l(e8("Task not found"),404);if(q8==="DELETE"){A.deleteTask(J8.id);return l(L8({deleted:true}))}if(q8==="PUT"||q8==="PATCH"){const $8=await f8(d);A.updateTask(c,{...u[4]==="status"?{status:$8.status}:$8,updatedAt:d6()});return l(L8(A.getTask(c)))}if(u[4]==="stop")return l(L8(A.stopTask(c)));if(u[4]==="output"){if(q8==="POST"){const $8=await f8(d);return l(L8(A.addTaskOutput(c,$8.line||$8.output||"")))}return l(L8(A.getTaskOutput(c)))}return l(L8(J8))}if(n==="/api/plans"&&q8==="GET"){try{const u=A.plans.list();return l(L8(u))}catch(u){return l(e8(u.message),500)}}if(n.startsWith("/api/plans/")&&q8==="GET"){const u=n.split("/");const c=decodeURIComponent(u[3]);const J8=A.plans.read(c);if(!J8)return l(e8("Plan not found"),404);return l(L8({...J8,slug:c}))}if(n.startsWith("/api/plans/")&&q8==="DELETE"){const u=n.split("/");const c=decodeURIComponent(u[3]);const J8=A.plans.delete(c);if(!J8)return l(e8("Plan not found"),404);return l(L8({deleted:true}))}if(n==="/api/files"&&q8==="GET"){try{const u=O6(Q8.searchParams.get("path")||".");return l(L8([T6(u)]))}catch(u){return l(e8(u.message),400)}}if(n==="/api/files/read"&&q8==="GET"){try{return l(L8(U0(O6(Q8.searchParams.get("path")||""),"utf8")))}catch(u){return l(e8(u.message),400)}}if(n==="/api/files/write"&&q8==="PUT"||n==="/api/files"&&q8==="POST"||n==="/api/files/upload"&&q8==="POST"){const u=await f8(d);try{const c=O6(u.path);_z(E2(c,".."),{recursive:true});C2(c,String(u.content||""),u.base64?"base64":"utf8");return l(L8({path:u.path,size:t5(c).size}))}catch(c){return l(e8(c.message),400)}}if(n==="/api/files"&&q8==="DELETE"){try{const u=O6(Q8.searchParams.get("path")||"");gO8(u);return l(L8({deleted:true}))}catch(u){return l(e8(u.message),400)}}if(n==="/api/files/download"&&q8==="GET"){try{return new Response(U0(O6(Q8.searchParams.get("path")||"")))}catch(u){return l(e8(u.message),400)}}if(n.startsWith("/api/files"))return l(e8(`Unhandled endpoint: ${q8} ${n}`),404);if(n==="/api/filejob/parse"&&q8==="POST"){const u=await f8(d);try{const c=[];const J8=Array.isArray(u.files)?u.files:[];const $8=Array.isArray(u.paths)?u.paths:[];if($8.length===0&&J8.length===0){return l(e8("Provide either `files` (base64) or `paths` (workspace file paths)."),400)}for(const R8 of J8){const E8=String(R8?.name||"unnamed");const u8=String(R8?.base64||"");if(!u8)continue;if(u8.length>73400320)throw new Error(`${E8} exceeds the 50MB upload limit`);const D6=Kq(E8,Buffer.from(u8,"base64"));c.push(D6.info)}for(const R8 of $8){const E8=LK(String(R8));const u8=U0(O6(String(R8)));const D6=Kq(E8,u8);c.push(D6.info)}return l(L8(c))}catch(c){return l(e8(c.message),400)}}if(n==="/api/filejob/render"&&q8==="POST"){const u=await f8(d);try{const c=u.data||{};const J8=u.template||{};const $8=String(u.outputFormat||"xlsx");let R8,E8;if(c.path){R8=LK(String(c.path));E8=U0(O6(String(c.path)))}else if(c.base64){R8=String(c.name||"data");E8=Buffer.from(String(c.base64),"base64")}else{return l(e8("`data` must include `path` or `base64`."),400)}let u8,D6;if(J8.path){u8=LK(String(J8.path));D6=U0(O6(String(J8.path)))}else if(J8.base64){u8=String(J8.name||"template.txt");D6=Buffer.from(String(J8.base64),"base64")}else{return l(e8("`template` must include `path` or `base64`."),400)}const I6=Kq(R8,E8);const r6=vK(u8);let B1="";if(r6==="docx"){const{parseDocx:h4}=await Promise.resolve().then(()=>(m0(),Q4));B1=h4(D6)}else if(r6==="xlsx"||r6==="xls"){const{parseXlsx:h4}=await Promise.resolve().then(()=>(m0(),Q4));B1=h4(D6).map((hK)=>hK.headers.join(",")).join(`
4382
4382
  `)}else{B1=D6.toString("utf8")}const{detectPlaceholders:P7,autoMapPlaceholders:U7,renderDataToBuffer:c7}=await Promise.resolve().then(()=>(m0(),Q4));const f1=P7(B1);const m1=Object.keys(I6.rows[0]||{});const e4=Array.isArray(u.mapping)&&u.mapping.length>0?u.mapping.map((h4)=>({placeholder:String(h4.placeholder),field:String(h4.field),fallback:h4.fallback,hitRate:1})):U7(f1.length?f1:m1,m1,I6.rows.length);const M0=c7({data:I6.rows,templateText:f1.length?B1:undefined,outputFormat:$8,outputName:String(u.outputName||"output"),mapping:e4});const bz=U1(".deepseekcode","output",M0.fileName).split("\\").join("/");const I2=O6(bz);_z(Yj(I2),{recursive:true});C2(I2,M0.buffer);const xK={fileName:M0.fileName,format:M0.format,size:t5(I2).size,path:bz,rowCount:M0.rowCount,successCount:M0.successCount,failedRows:M0.failedRows};return l(L8({result:xK,mapping:e4,parsed:I6.info}))}catch(c){return l(e8(c.message),400)}}if(n==="/api/filejob/import"&&q8==="POST"){const u=await f8(d);try{const c=Array.isArray(u.paths)?u.paths.map(($8)=>String($8)).filter(Boolean):[];if(c.length===0)return l(L8([]));const J8=[];for(const $8 of c){const R8=t5($8);if(!R8.isFile())continue;if(R8.size>52428800)continue;const E8=LK($8);let u8=E8;let D6=1;while(u7(O6(U1(j,u8)))){const B1=E8.lastIndexOf(".");u8=B1>0?`${E8.slice(0,B1)} (${D6})${E8.slice(B1)}`:`${E8} (${D6})`;D6++}const I6=U1(j,u8).split("\\").join("/");const r6=O6(I6);_z(Yj(r6),{recursive:true});C2(r6,U0($8));J8.push({name:u8,path:I6,size:R8.size})}return l(L8(J8))}catch(c){return l(e8(c.message),400)}}if(n==="/api/git/status"&&q8==="GET"){try{const u=await l$6(q);return l(L8(u))}catch(u){return l(L8({available:false,error:u.message}))}}if(n==="/api/git/branches"&&q8==="GET"){try{return l(L8(await d$6(q)))}catch(u){return l(L8({available:false,error:u.message}))}}if(n==="/api/git/commit"&&q8==="POST"){const u=await f8(d);try{const c=String(u.message||"").trim();if(!c)return l(e8("commit message is required"),400);return l(L8(await i$6(q,c,u.all!==false)))}catch(c){return l(e8(c.message),400)}}if(n==="/api/git/push"&&q8==="POST"){try{return l(L8(await n$6(q)))}catch(u){return l(e8(u.message),400)}}if(n==="/api/git/checkout"&&q8==="POST"){const u=await f8(d);try{const c=String(u.branch||"").trim();if(!c)return l(e8("branch name is required"),400);return l(L8(await a$6(q,c)))}catch(c){return l(e8(c.message),400)}}if(n==="/api/repos/pr"&&q8==="GET"){try{const u=await o$6(q);return l(L8(u))}catch(u){return l(L8({available:false,error:u.message}))}}if(n==="/api/terminal/status")return l(L8(R.status(Q8.searchParams.get("terminalId")||undefined)));if(n==="/api/terminal/start"){const u=await f8(d);return l(L8(R.start({workspaceDir:u.workspaceDir})))}if(n==="/api/terminal/stop"){const u=await f8(d);return l(L8({stopped:R.stop(u.terminalId)}))}if(n==="/api/mcp/servers"){if(q8==="POST"){y.reload();await $6()}return l(L8(y.listServers()))}if(n==="/api/mcp/health")return l(L8(y.health()));if(n==="/api/mcp/tools"){try{const u=await A.refreshMcpTools((c)=>z6(c));return l(L8(u))}catch(u){return l(e8(u.message),400)}}if(n==="/api/mcp/call"&&q8==="POST"){const u=await f8(d);try{return l(L8(await y.callTool(String(u.server||""),String(u.tool||u.name||""),u.arguments||u.args||{})))}catch(c){return l(e8(c.message),400)}}if(n==="/api/connectors"){if(q8==="GET")return l(L8({connectors:A.connectors.list()}));return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n==="/api/connectors/custom"){if(q8==="POST"){const u=await f8(d);try{const c=A.connectors.addCustom({name:String(u.name||""),command:String(u.command||""),args:Array.isArray(u.args)?u.args.map(String):[],env:u.env&&typeof u.env==="object"?u.env:undefined,cwd:u.cwd?String(u.cwd):undefined,url:u.url?String(u.url):undefined,transport:u.transport?String(u.transport):undefined,headers:u.headers&&typeof u.headers==="object"?u.headers:undefined,description:u.description?String(u.description):undefined});y.reload();await $6();return l(L8(c))}catch(c){return l(e8(c instanceof Error?c.message:String(c)),400)}}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/connectors/custom/")){const u=decodeURIComponent(n.split("/").pop()||"");if(q8==="DELETE"){const c=A.connectors.removeCustom(u);y.reload();await $6();return l(L8({removed:c,id:u}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/connectors/")){const u=n.split("/");const c=decodeURIComponent(u[3]||"");if(u.length>4&&u[4]==="toggle"&&q8==="POST"){const J8=await f8(d);const $8=J8.enabled!==undefined?Boolean(J8.enabled):true;const R8=J8.env&&typeof J8.env==="object"?J8.env:undefined;try{const E8=await A.connectors.toggle(c,$8,R8);if(E8.kind==="mcp"){y.reload();await $6()}return l(L8(E8))}catch(E8){return l(e8(E8 instanceof Error?E8.message:String(E8)),400)}}if(q8==="GET"){const J8=A.connectors.get(c);return J8?l(L8(J8)):l(e8("Connector not found"),404)}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/hooks")){const u=n.split("/").filter(Boolean);const c=u.slice(2).join("/");const J8=q8==="POST"||q8==="PUT"||q8==="PATCH"?await f8(d):{};if(!c&&q8==="GET"){return l(L8({endpoints:["stats","events","agents","export","import","reload","rules","rules/batch-delete","rules/batch-toggle"],stats:T.stats()}))}if(c==="reload"){L.reload();return l(L8({reloaded:true,stats:T.stats()}))}if(c==="stats")return l(L8(T.stats()));if(c==="events")return l(L8(h9()));if(c==="agents")return l(L8(jq()));if(c==="dry-run"){return l(L8(L.dryRun({toolName:String(J8.toolName||J8.tool||""),action:String(J8.action||""),risk:J8.risk==="low"||J8.risk==="medium"||J8.risk==="high"?J8.risk:"medium",payload:J8.payload&&typeof J8.payload==="object"?J8.payload:J8},String(J8.sessionId||""))))}if(c==="export")return l(L8(T.export()));if(c==="import"&&q8==="POST"){const E8=T.import({hooks:Array.isArray(J8.hooks)?J8.hooks:[],mergeMode:String(J8.mergeMode||"replace"),scope:String(J8.scope||"project")});return l(L8(E8))}if(c==="rules/batch-delete"&&q8==="POST"){const E8=Array.isArray(J8.names)?J8.names:[];const u8=T.batchDelete(E8,String(J8.scope||"project"));return l(L8({deleted:u8}))}if(c==="rules/batch-toggle"&&q8==="POST"){const E8=Array.isArray(J8.names)?J8.names:[];const u8=J8.enabled!==false;const D6=T.batchToggle(E8,u8,String(J8.scope||"project"));return l(L8({count:D6,enabled:u8}))}const $8=c.match(/^rules\/(.+)\/toggle$/);if($8&&q8==="PATCH"){const E8=decodeURIComponent($8[1]);const u8=T.toggle(E8,J8.enabled!==false);if(!u8)return l(e8("Rule not found"),404);return l(L8({name:E8,enabled:J8.enabled!==false}))}const R8=c.match(/^rules(?:\/(.+))?$/);if(R8){const E8=R8[1]||null;const u8=E8?decodeURIComponent(E8):null;if(!u8&&q8==="GET"){return l(L8(T.listAll()))}if(u8&&q8==="GET"){const D6=T.get(u8);if(!D6)return l(e8("Rule not found"),404);return l(L8(D6))}if(!u8&&q8==="POST"){const D6=T.create(J8);if(!D6.success)return l(e8(D6.error),400);return l(L8(D6),201)}if(u8&&q8==="PUT"){const D6=T.update(u8,J8);if(!D6.success)return l(e8(D6.error),400);return l(L8(D6))}if(u8&&q8==="DELETE"){const D6=T.delete(u8);if(!D6)return l(e8("Rule not found"),404);return l(L8({deleted:true}))}return l(e8(`Unsupported request: ${q8} /${c}`),400)}return l(e8(`Unsupported endpoint: /${c}`),404)}if(n==="/api/inbox"&&q8==="GET"){const u=new URL(d.url||"","http://localhost").searchParams;const c=u.get("state")||"pending";const J8=u.get("sessionId")||undefined;const $8=u.get("kind")||undefined;const R8=Z8.list({state:c==="all"?undefined:c,sessionId:J8,kind:$8});return l(L8({items:R8,stats:Z8.stats()}))}if(n==="/api/inbox/stats"&&q8==="GET"){return l(L8(Z8.stats()))}if(n.startsWith("/api/inbox/")){const u=n.split("/").filter(Boolean);const c=u[2];if(u[3]==="resolve"&&q8==="POST"&&c){const J8=await f8(d);const $8=String(J8.resolution||"allow");const R8=Z8.resolve(c,$8);if(!R8)return l(e8("Inbox item not found or already resolved"),404);const E8=Z8.get(c);if($8==="always"&&E8?.kind==="approval"){const u8=p.automationForRunSession(E8.sessionId);const D6=String(E8.data?.toolName||"");const I6=E8.data?.payload&&typeof E8.data.payload==="object"?E8.data.payload:{};const r6=D6?Sc(D6,I6):null;if(u8&&D6&&r6){p.addRule(u8.id,D6,r6);z6({type:"automation.update",data:JSON.stringify({action:"permission_added",automation:u8.toJSON()})})}}if(E8)z6({type:"inbox.resolved",sessionId:E8.sessionId,data:JSON.stringify(E8)});return l(L8({resolved:true,item:E8}))}if(q8==="GET"&&c){const J8=Z8.get(c);if(!J8)return l(e8("Inbox item not found"),404);return l(L8(J8))}return l(e8(`Unsupported request: ${q8} ${n}`),400)}if(n==="/api/audit"&&q8==="GET"){const u=new URL(d.url||"","http://localhost").searchParams;const c=Q.query({sessionId:u.get("sessionId")||undefined,tool:u.get("tool")||undefined,decision:u.get("decision"),approvedBy:u.get("approvedBy"),page:Number(u.get("page")||0),pageSize:Number(u.get("pageSize")||50)});return l(L8(c))}if(n==="/api/audit/stats"&&q8==="GET"){return l(L8(Q.stats()))}if(n==="/api/automations"&&q8==="GET"){return l(L8(p.list().map((u)=>u.toJSON())))}if(n==="/api/automations"&&q8==="POST"){const u=await f8(d);const c=u.schedule&&typeof u.schedule==="object"?{kind:u.schedule.kind==="once"?"once":"cron",cron:u.schedule.cron?String(u.schedule.cron):null,fireAt:u.schedule.fireAt?String(u.schedule.fireAt):null,timezone:u.schedule.timezone?String(u.schedule.timezone):"local"}:{kind:"cron",cron:String(u.cron||"0 9 * * *")};if(c.kind==="cron"){const{validateCron:$8}=await Promise.resolve().then(()=>(m0(),Q4));const R8=$8(c.cron||"");if(R8)return l(e8(`Invalid cron: ${R8}`),400)}const J8=p.create({name:String(u.name||"Untitled automation"),instructions:String(u.instructions||""),schedule:c,workspaceDir:String(u.workspaceDir||q),permissions:Array.isArray(u.permissions)?u.permissions.map(String):[],readAutoAllow:u.readAutoAllow!==false});z6({type:"automation.update",data:JSON.stringify({action:"created",automation:J8.toJSON()})});return l(L8(J8.toJSON()),201)}if(n.startsWith("/api/automations/")){const u=n.split("/").filter(Boolean);const c=u[2];if(!c)return l(e8("Missing automation id"),400);const J8=p.get(c);if(u[3]==="toggle"&&q8==="POST"){if(!J8)return l(e8("Automation not found"),404);const $8=await f8(d);const R8=$8.enabled!==false;const E8=p.toggle(c,R8);z6({type:"automation.update",data:JSON.stringify({action:R8?"enabled":"disabled",automation:E8?.toJSON()})});return l(L8(E8?.toJSON()))}if(u[3]==="run"&&q8==="POST"){if(!J8)return l(e8("Automation not found"),404);const $8=A8.startRun(c);z6({type:"automation.run",data:JSON.stringify({action:"started",automationId:c,run:$8?.toJSON()})});return l(L8($8?.toJSON()),202)}if(u[3]==="runs"&&q8==="GET"){if(!J8)return l(e8("Automation not found"),404);return l(L8(p.runsFor(c).map(($8)=>$8.toJSON())))}if(u[3]==="permissions"&&q8==="POST"){if(!J8)return l(e8("Automation not found"),404);const $8=await f8(d);const R8=String($8.tool||"");const E8=String($8.target||"");const u8=p.addRule(c,R8,E8);if(!u8)return l(e8("Invalid rule entry or already present"),400);z6({type:"automation.update",data:JSON.stringify({action:"permission_added",automation:u8.toJSON()})});return l(L8(u8.toJSON()))}if(u[3]==="permissions"&&q8==="DELETE"){if(!J8)return l(e8("Automation not found"),404);const $8=await f8(d);const R8=String($8.entry||"");const E8=p.revokeRule(c,R8);if(!E8)return l(e8("Rule entry not found"),404);z6({type:"automation.update",data:JSON.stringify({action:"permission_revoked",automation:E8.toJSON()})});return l(L8(E8.toJSON()))}if(q8==="GET"){if(!J8)return l(e8("Automation not found"),404);return l(L8(J8.toJSON()))}if(q8==="PUT"){if(!J8)return l(e8("Automation not found"),404);const $8=await f8(d);const R8=p.update(c,{name:$8.name!==undefined?String($8.name):undefined,instructions:$8.instructions!==undefined?String($8.instructions):undefined,schedule:$8.schedule&&typeof $8.schedule==="object"?{kind:$8.schedule.kind==="once"?"once":"cron",cron:$8.schedule.cron?String($8.schedule.cron):null,fireAt:$8.schedule.fireAt?String($8.schedule.fireAt):null,timezone:$8.schedule.timezone?String($8.schedule.timezone):"local"}:undefined,workspaceDir:$8.workspaceDir!==undefined?String($8.workspaceDir):undefined,permissions:Array.isArray($8.permissions)?$8.permissions.map(String):undefined,readAutoAllow:$8.readAutoAllow!==undefined?Boolean($8.readAutoAllow):undefined});z6({type:"automation.update",data:JSON.stringify({action:"updated",automation:R8?.toJSON()})});return l(L8(R8?.toJSON()))}if(q8==="DELETE"){const $8=p.delete(c);if(!$8)return l(e8("Automation not found"),404);z6({type:"automation.update",data:JSON.stringify({action:"deleted",automationId:c})});return l(L8({deleted:true}))}return l(e8(`Unsupported request: ${q8} ${n}`),400)}if(n==="/api/channels"&&q8==="GET"){const u=U1(x8,"channels.json");const c=Y6(u,[]);const J8=Array.isArray(c)?c:c.channels||[];const{decryptConfig:$8}=await Promise.resolve().then(()=>(m0(),Q4));const R8=J8.map((E8)=>$8(E8));return l(L8(R8))}if(n==="/api/channels"&&q8==="POST"){const u=await f8(d);const c=U1(x8,"channels.json");const J8=c6(c);const{encryptConfig:$8,decryptConfig:R8}=await Promise.resolve().then(()=>(m0(),Q4));const E8=String(u.id||u.name||`channel-${Date.now()}`).replace(/[^a-zA-Z0-9_-]/g,"-").toLowerCase();const u8={id:E8,name:String(u.name||"Channel"),type:u.type==="feishu"||u.type==="dingtalk"?u.type:"wechat",appId:String(u.appId||""),appSecret:String(u.appSecret||""),token:String(u.token||""),encodingAESKey:String(u.encodingAESKey||""),enabled:u.enabled!==false,extra:u.extra&&typeof u.extra==="object"?u.extra:{},connected:false};const D6=$8(u8);R6(c,[...J8.filter((I6)=>I6.id!==u8.id),D6]);if(u8.enabled){try{await A.initializeChannels([u8])}catch(I6){e7.error("channels.error","Channel initialization failed",String(I6))}}return l(L8(R8(u8)),201)}if(n.startsWith("/api/channels/")){const u=n.split("/");const c=decodeURIComponent(u[3]||"");const J8=U1(x8,"channels.json");const $8=c6(J8);const R8=$8.find((E8)=>E8.id===c);if(!R8)return l(e8("Channel not found"),404);if(u.length===4&&q8==="PUT"){const{encryptConfig:E8,decryptConfig:u8}=await Promise.resolve().then(()=>(m0(),Q4));const D6=await f8(d);const I6={...R8,...D6,id:c};const r6=E8(I6);R6(J8,$8.map((B1)=>B1.id===c?r6:B1));try{await A.channels.removeAdapter(c);if(I6.enabled!==false){await A.channels.createAdapter(I6)}}catch(B1){e7.error("channels.error","Channel operation failed",String(B1))}return l(L8(u8(I6)))}if(u.length===4&&q8==="DELETE"){R6(J8,$8.filter((E8)=>E8.id!==c));return l(L8({deleted:true}))}if(u[4]==="toggle"&&q8==="PATCH"){const E8=await f8(d);const u8=Boolean(E8.enabled);const D6={...R8,enabled:u8};R6(J8,$8.map((I6)=>I6.id===c?D6:I6));try{if(u8){await A.channels.createAdapter(D6)}else{await A.channels.removeAdapter(c)}}catch(I6){e7.error("channels.error","Channel operation failed",String(I6))}return l(L8({id:c,enabled:u8}))}if(u[4]==="webhook"&&q8==="POST"){const E8=A.channels.getAdapter(c);if(!E8){return l(L8({message:`Channel ${c} not started, cannot process webhook`}),404)}try{const u8=await f8(d);if(E8.type==="dingtalk"){const{DingTalkApiClient:D6}=await Promise.resolve().then(()=>(m0(),Q4));const I6=D6.parseCallbackBody(u8);if(I6){E8.ingestCallbackMessage(I6)}return l({errcode:0,errmsg:"ok"})}if(E8.type==="feishu"){const D6=u8?.event||u8;if(D6?.message){E8.ingestWebhookMessage(D6.message)}return l({code:0})}return l(L8({message:`Webhook received by channel ${c} (${E8.type})`}))}catch(u8){e7.error("channels.webhook_failed","Channel operation failed",String(u8));return l(e8("Webhook processing failed"),500)}}if(u[4]==="test"&&q8==="POST"){const E8=A.channels.getAdapter(c);if(!E8){return l(L8({connected:false,message:`Channel ${c} not started, save config first`}))}const u8=E8.isConnected();return l(L8({connected:u8,message:u8?"Connected":"Disconnected"}))}if(u[4]==="wechat"){const E8=A.channels.getAdapter(c);if(!E8||E8.type!=="wechat"){return l(L8({message:"WeChat adapter not installed or not started"}))}if(u[5]==="qrcode"&&q8==="GET"&&u[6]!=="status"){try{const{fetchWebQrCode:u8}=await Promise.resolve().then(()=>(m0(),Q4));const D6=await u8();return l(L8(D6))}catch(u8){return l(e8(`Failed to fetch WeChat QR code: ${u8 instanceof Error?u8.message:String(u8)}`),500)}}if(u[5]==="qrcode"&&u[6]==="status"&&q8==="GET"){const u8=new URL(d.url||"","http://localhost").searchParams;const D6=u8.get("qrcode")||"";const I6=u8.get("token")||"";if(!D6||!I6){return l(e8("Missing required parameters"),400)}try{const{checkWebQrStatus:r6}=await Promise.resolve().then(()=>(m0(),Q4));const B1=await r6({qrcode:D6});return l(L8(B1))}catch(r6){return l(e8(`Failed to check QR code status: ${r6 instanceof Error?r6.message:String(r6)}`),500)}}return l(e8(`Unhandled WeChat endpoint: ${q8} ${n}`),404)}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/channels"))return l(e8(`Unhandled endpoint: ${q8} ${n}`),404);if(n==="/api/logs"&&q8==="GET"){const u=U1(x8,"logs");if(!u7(u))return l(L8([]));const c=tH(u).filter((J8)=>t5(U1(u,J8)).isFile()).map((J8)=>{const $8=t5(U1(u,J8));return{name:J8,size:$8.size,modified:$8.mtimeMs,previewable:/\.(log|txt|json|ndjson|jsonl|md)$/i.test(J8)}});return l(L8(c))}if(n==="/api/logs/read"&&q8==="GET"){const u=U1(x8,"logs");const c=LK(String(Q8.searchParams.get("file")||""));if(!c)return l(e8("Log file is required"),400);const J8=U1(u,c);if(!u7(J8))return l(e8("Log file not found"),404);const $8=U0(J8,"utf8").split(/\r?\n/);if($8.length>0&&$8[$8.length-1]==="")$8.pop();const R8=Math.max(1,Number(Q8.searchParams.get("maxLines")||500));const E8=Math.max(0,$8.length-R8);const u8=t5(J8);return l(L8({name:c,size:u8.size,modified:u8.mtimeMs,totalLines:$8.length,startLine:E8,content:$8.slice(E8).join(`
4383
- `)}))}if(n==="/api/logs/download"&&q8==="GET"){const u=U1(x8,"logs");const c=LK(String(Q8.searchParams.get("file")||""));const J8=U1(u,c);if(!c||!u7(J8))return l(e8("Log file not found"),404);return new Response(U0(J8),{headers:{"content-type":"application/octet-stream","access-control-allow-origin":"*"}})}if(n.startsWith("/api/logs"))return l(e8(`Unhandled endpoint: ${q8} ${n}`),404);if(n.startsWith("/api/observability")){const u=typeof A.telemetry?.snapshot==="function"?A.telemetry.snapshot():null;const c=typeof A.telemetry?.getMetricSummary==="function"?A.telemetry.getMetricSummary():{};if(n==="/api/observability/summary"&&q8==="GET"){return l(L8({totalRuns:c["trace.run[count]"]||0,totalCost:0,avgCost:0,totalTokens:c["token.usage[count]"]||0,activeSpans:u?.activeSpans?.length||0,recentEvents:u?.events?.length||0}))}if(n==="/api/observability/costs"&&q8==="GET"){return l(L8({daily:[],total:0,metrics:c}))}if(n==="/api/observability/runs"&&q8==="GET"){const J8=typeof A.workflows?.listRuns==="function"?A.workflows.listRuns():[];return l(L8(J8))}if(n.startsWith("/api/observability/runs/")&&q8==="GET"){const J8=n.split("/");const $8=J8[4];if(J8[5]==="events"){const E8=typeof A.workflows?.listEvents==="function"?A.workflows.listEvents($8):[];return l(L8({events:E8,total:Array.isArray(E8)?E8.length:0,page:Number(Q8.searchParams.get("page")||0),size:Number(Q8.searchParams.get("size")||50)}))}const R8=typeof A.workflows?.getRun==="function"?A.workflows.getRun($8):null;return l(L8(R8))}return l(L8({metrics:c,telemetry:true}))}if(n==="/api/workflows"&&q8==="GET")return l(L8(A.workflows.listRuns()));if(n==="/api/workflows"&&q8==="POST"){const u=await f8(d);const c=await A.workflows.start({sessionId:String(u.sessionId||""),runId:String(u.runId||""),goalId:typeof u.goalId==="string"?u.goalId:undefined,checkpointPolicy:String(u.checkpointPolicy||"phase-and-token"),message:String(u.message||u.content||""),script:typeof u.script==="string"?u.script:undefined,workflow:typeof u.workflow==="object"&&u.workflow?u.workflow:undefined});return l(L8(c))}if(n.startsWith("/api/workflows/")){const u=n.split("/");const c=u[3];if(u[4]==="events")return l(L8(A.workflows.listEvents(c)));if(u[4]==="checkpoints")return l(L8(A.workflows.listCheckpoints(c)));if(u[4]==="pause"&&q8==="POST")return l(L8(A.workflows.pause(c)));if(u[4]==="resume"&&q8==="POST")return l(L8(await A.workflows.resume(c)));if(u[4]==="cancel"&&q8==="POST")return l(L8(A.workflows.cancel(c)));const J8=A.workflows.getRun(c);return J8?l(L8(J8)):l(e8("Workflow not found"),404)}if(n==="/workflow/runs"&&q8==="GET")return l(L8(A.workflows.listRuns()));if(n==="/workflow/runs"&&q8==="POST"){const u=await f8(d);const c=await A.workflows.start({sessionId:String(u.sessionId||""),runId:String(u.runId||""),goalId:typeof u.goalId==="string"?u.goalId:undefined,checkpointPolicy:String(u.checkpointPolicy||"phase-and-token"),message:String(u.message||u.content||""),script:typeof u.script==="string"?u.script:undefined,workflow:typeof u.workflow==="object"&&u.workflow?u.workflow:undefined});return l(L8(c))}if(n.startsWith("/workflow/runs/")){const u=n.split("/");const c=u[3];if(u[4]==="trace"&&q8==="GET"){const $8=A.workflows.getTrace(c);return $8?l(L8($8)):l(e8("Workflow trace not found"),404)}if(u[4]==="events"&&q8==="GET")return l(L8(A.workflows.listEvents(c)));if(u[4]==="events"&&q8==="POST"){const $8=await f8(d);const R8=A.workflows.injectEvent(c,String($8.type||"user_event"),$8.data??$8);return R8?l(L8(R8)):l(e8("Workflow not found"),404)}if(u[4]==="pause"&&q8==="POST")return l(L8(A.workflows.pause(c)));if(u[4]==="resume"&&q8==="POST")return l(L8(await A.workflows.resume(c)));if(u[4]==="cancel"&&q8==="POST")return l(L8(A.workflows.cancel(c)));const J8=A.workflows.getRun(c);return J8?l(L8(J8)):l(e8("Workflow not found"),404)}if(n.startsWith("/api/checkpoints"))return l(L8(A.workflows.listCheckpoints()));if(n==="/api/templates"&&q8==="GET"){return l(L8(A.templates.list()))}if(n==="/api/templates"&&q8==="POST"){const u=await f8(d);let c;let J8={type:"handwritten"};let $8;if(typeof u.sourceRunId==="string"&&u.sourceRunId){const D6=A.workflows.getRun(u.sourceRunId);if(!D6)return l(e8("Run not found"),404);const I6=A.workflows.getRunDefinition(u.sourceRunId);if(!I6){if(D6.status==="FAILED"){return l(e8(`Run ${u.sourceRunId} failed before producing a workflow definition${D6.error?`: ${D6.error}`:""}`),400)}return l(e8("Run workflow definition not found"),404)}c=I6;J8={type:"saved",runId:u.sourceRunId};$8=I6.title}else if(typeof u.definition==="object"&&u.definition){c=u.definition;$8=c.title;J8=typeof u.source==="object"&&u.source?u.source:{type:"handwritten"}}let R8=false;let E8;if(u.generalize===true&&c&&J8.type==="saved"){try{const D6=M.load();const I6=new Pl({provider:new y9(D6),model:String(D6.model||""),timeoutMs:120000,maxTokensOverride:8000});const r6=await I6.generalize(c,typeof u.message==="string"&&u.message?u.message:c.title);if(!r6.degraded){c=r6.definition;$8=r6.name;u.description=r6.description;u.category=r6.category;u.inputs=r6.inputs}else{R8=true;E8=r6.reason||"LLM generalize failed";e7.info("templates.generalize_degraded","LLM generalize failed, saved as-is",E8)}}catch(D6){R8=true;E8=D6 instanceof Error?D6.message:String(D6);e7.error("templates.generalize_failed","TemplateGeneralizer threw",E8)}}const u8=typeof u.name==="string"&&u.name?u.name:$8;if(!u8||!c){return l(e8("Template requires a name and either a definition or sourceRunId"),400)}try{const D6=A.templates.create({name:u8,description:u.description!=null?String(u.description):undefined,category:typeof u.category==="string"&&u.category?u.category:"general",inputs:Array.isArray(u.inputs)?u.inputs:undefined,definition:c,source:J8});return R8?l(L8({...D6,degraded:R8,degradeReason:E8})):l(L8(D6))}catch(D6){return l(e8(D6 instanceof Error?D6.message:String(D6)),400)}}if(n.startsWith("/api/templates/")){const u=n.split("/");const c=decodeURIComponent(u[3]);if(!Vc(c))return l(e8("Invalid template id"),400);const J8=u[4];if(J8==="versions"){if(q8==="GET"&&u[5]){const $8=A.templates.getVersion(c,Number(u[5]));return $8?l(L8($8)):l(e8("Template version not found"),404)}if(q8==="GET")return l(L8(A.templates.listVersions(c)));return l(e8(`Unhandled template endpoint: ${q8} ${n}`),404)}if(J8==="render"&&q8==="POST"){const $8=await f8(d);const R8=$8&&typeof $8==="object"&&$8.inputs&&typeof $8.inputs==="object"&&!Array.isArray($8.inputs)?$8.inputs:$8;const E8=A.templates.render(c,R8);if(!E8.ok)return l(e8((E8.errors||[]).join("; ")),400);return l(L8(E8.definition))}if(q8==="GET"&&!J8){const $8=A.templates.get(c);return $8?l(L8($8)):l(e8("Template not found"),404)}if(q8==="PUT"&&!J8){const $8=await f8(d);const R8=A.templates.update(c,{name:typeof $8?.name==="string"?$8.name:undefined,description:typeof $8?.description==="string"?$8.description:undefined,category:typeof $8?.category==="string"?$8.category:undefined,inputs:Array.isArray($8?.inputs)?$8.inputs:undefined,definition:typeof $8?.definition==="object"&&$8?.definition?$8.definition:undefined,source:typeof $8?.source==="object"&&$8?.source?$8.source:undefined});return R8?l(L8(R8)):l(e8("Template not found"),404)}if(q8==="DELETE"&&!J8){return l(L8({removed:A.templates.remove(c)}))}return l(e8(`Unhandled template endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/speech")){return l(L8({available:false,text:"",supported:false,engines:[]}))}if(n.startsWith("/api/metrics")){const u=process.memoryUsage();const c=Math.floor((Date.now()-O)/1000);const J8=typeof A.sessions?.list==="function"?A.sessions.list().length:0;const $8=typeof A.telemetry?.getMetricSummary==="function"?A.telemetry.getMetricSummary():{};return l(L8({uptime:c,memory:{heapUsed:u.heapUsed,heapTotal:u.heapTotal,rss:u.rss},sessions:J8,clients:N.size,workspace:q,version:"1.0.19",metrics:$8}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}function Sz(d){const Q8=d.pathname==="/"?"/index.html":d.pathname;const n=v$6(U1(V,Q8));if(!n.startsWith(V)||!u7(n)||t5(n).isDirectory()){const o8=U1(V,"index.html");return u7(o8)?new Response(U0(o8),{headers:{"content-type":"text/html; charset=utf-8"}}):L6("DeepSeekCode server is running")}const q8=b$6(n);const x8={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8"};const w8=x8[q8]||"application/octet-stream";return new Response(U0(n),{headers:{"content-type":w8}})}function _7(d){const Q8=new URL(d.url||"/",`http://${d.headers.host||`localhost:${K}`}`);const n={method:d.method,headers:d.headers};if(d.method!=="GET"&&d.method!=="HEAD"){n.body=d;n.duplex="half"}return{request:new Request(Q8,n),url:Q8}}async function q9(d,Q8){d.statusCode=Q8.status;Q8.headers.forEach((q8,x8)=>d.setHeader(x8,q8));const n=Buffer.from(await Q8.arrayBuffer());d.end(n)}function M5(d){if(Array.isArray(d))return Buffer.concat(d);if(d instanceof ArrayBuffer)return Buffer.from(d);return d}async function mJ(d,Q8){if(d.data?.path==="/terminal"){R.handleSocketMessage(String(d.data?.terminalId??""),M5(Q8));return}if(G&&d.data?.authenticated!==true){let w8;try{w8=JSON.parse(String(M5(Q8)))}catch{w8={}}if(w8.type==="auth"){if(w8.token===G){d.data=d.data||{};d.data.authenticated=true;d.send(JSON.stringify({type:"auth_success",message:"Authenticated"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));e7.info("ws.authenticated","WebSocket client authenticated");return}d.send(JSON.stringify({type:"auth_failed",message:"Invalid API token"}));d.close(4401,"Invalid API token");return}d.send(JSON.stringify({type:"auth_required",message:"Authentication required: send {type:'auth', token}"}));return}let n;try{n=JSON.parse(String(M5(Q8)))}catch{d.send(JSON.stringify({type:"error",data:JSON.stringify({error:"Invalid JSON"})}));return}const q8=d.data?.clientId;const x8=n;if(q8){x8.clientId=q8}if(n.type==="auth"){d.data=d.data||{};d.data.authenticated=true;d.send(JSON.stringify({type:"auth_success",message:"Authenticated"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));return}if(n.type==="workspace"){d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));return}if(n.type==="ping"){d.send(JSON.stringify({type:"pong",sessionId:n.sessionId||null}));return}if(n.type==="message_ack")return;if(n.type==="hook_allow"||n.type==="hook_deny"){const w8=Mz(n.data);const o8=String(n.approvalId||w8.approvalId||"");const u=n.type==="hook_allow";const c=typeof w8.sessionId==="string"?w8.sessionId:undefined;const J8=o8?L.decide(o8,u,{sessionId:n.sessionId||c,remember:Boolean(w8.remember||w8.sessionAllow)}):false;d.send(JSON.stringify({type:"hook_response_ack",sessionId:n.sessionId||null,data:JSON.stringify({approvalId:o8,allowed:u,resolved:J8})}));return}if(n.type==="create_session"){const w8=Mz(n.data);const o8=w8.sessionId?C.ensure(String(w8.sessionId)):M6();const u="messages"in o8?(({messages:c,...J8})=>J8)(o8):o8;d.send(JSON.stringify({type:"session_created",sessionId:u.id,data:JSON.stringify(u)}));return}if(n.type==="chat"||n.type==="plan"){if(!n.traceId)n.traceId=XC();const w8=n.traceId;await A.run(n,(o8)=>{o8.traceId=w8;d.send(JSON.stringify(o8))});return}if(n.type==="workflow_start"||n.type==="workflow_pause"||n.type==="workflow_resume"||n.type==="workflow_cancel"){if(!n.traceId)n.traceId=XC();const w8=n.traceId;await A.handleControlMessage(n,(o8)=>{o8.traceId=w8;d.send(JSON.stringify(o8))});return}if(n.type==="plan_confirm"){d.send(JSON.stringify({type:"plan_complete",sessionId:n.sessionId,data:JSON.stringify({status:"confirmed"})}));return}if(n.type==="user_exit_plan_mode"){const w8=Mz(n.data)||{};const o8=String(w8.planContent||"");const u=String(w8.planSlug||"");if(o8){try{A.plans.write(u||"user-exit-plan",o8)}catch(c){e7.warn("plan.save_failed","Failed to save plan on user exit",String(c))}}try{A.modeManager.exitPlanMode("User exited plan mode");z6({type:"plan_mode_change",sessionId:n.sessionId,data:JSON.stringify({previousMode:"plan",newMode:"act",reason:"User exited plan mode",timestamp:Date.now()})});d.send(JSON.stringify({type:"plan_complete",sessionId:n.sessionId,data:JSON.stringify({status:"user_exited",planSaved:!!o8})}))}catch(c){e7.warn("plan.exit_failed","Failed to exit plan mode",String(c))}return}if(["stop","pause","resume","get_commands"].includes(n.type)){await A.handleControlMessage(n,(w8)=>d.send(JSON.stringify(w8)));return}if(n.type==="reset"){const w8=n.sessionId||"";if(w8){const o8=C.reset(w8);d.send(JSON.stringify({type:"log",sessionId:w8,data:JSON.stringify({level:"info",message:o8?"Context cleared":"Session not found"})}))}else{d.send(JSON.stringify({type:"log",sessionId:w8,data:JSON.stringify({level:"warn",message:"Reset skipped: no sessionId"})}))}return}if(n.type==="resume_session"){const w8=Mz(n.data);const o8=String(n.sessionId||w8.sessionId||"");const u=o8?C.ensure(o8):C.create();d.send(JSON.stringify({type:"session_resumed",sessionId:u.id,data:JSON.stringify(C.resumeSnapshot(u.id,{tasks:A.listTasks(),pendingApprovals:L.list()}))}));return}if(n.type==="mcp"){const w8=Mz(n.data);const o8=String(w8.action||"list");try{const u=o8==="reload"?(y.reload(),await $6(),y.listServers()):o8==="tools"?(await $6(),await y.listTools(String(w8.server||"")||undefined)):y.listServers();d.send(JSON.stringify({type:"notification",sessionId:n.sessionId,data:JSON.stringify({kind:"mcp",action:o8,result:u})}))}catch(u){d.send(JSON.stringify({type:"error",sessionId:n.sessionId,data:u.message}))}return}if(n.type==="question_answer"){const w8=Mz(n.data);const o8=String(w8.questionId||"");const u=String(w8.answer||"");const c=Array.isArray(w8.selectedOptions)?w8.selectedOptions.map(String):undefined;const J8=Array.isArray(w8.answers)?w8.answers.map(($8)=>({question:$8.question?String($8.question):undefined,answer:String($8.answer||"(user did not answer)"),selectedOptions:Array.isArray($8.selectedOptions)?$8.selectedOptions.map(String):undefined})):undefined;if(o8){const $8=J8?{answers:J8}:{answer:u,selectedOptions:c};const R8=xp(o8,$8);d.send(JSON.stringify({type:"question_answer_ack",sessionId:n.sessionId||null,data:JSON.stringify({questionId:o8,resolved:R8,ok:R8})}))}else{d.send(JSON.stringify({type:"error",sessionId:n.sessionId||null,data:JSON.stringify({error:"Missing questionId"})}))}return}if(n.type==="plan_mode_change"){const w8=Mz(n.data);const o8=String(n.mode||w8.frontendMode||w8.newMode||w8.mode||"");const u=A.modeManager.getMode();let c;let J8;if(o8==="auto"){c=u==="normal"?"act":u;J8=!L.isAutoMode()}else if($46(o8)){c=O46(o8);J8=true}else if(o8==="plan"||o8==="act"||o8==="goal"||o8==="normal"){c=o8;J8=false}else{d.send(JSON.stringify({type:"log",sessionId:n.sessionId,data:JSON.stringify({level:"warn",message:`plan_mode_change ignored: unknown mode "${o8}"`})}));return}const $8=A.modeManager.setMode(c,`Client mode change: ${o8}`);await A.handleControlMessage({type:"hook_auto",sessionId:n.sessionId,data:JSON.stringify({enabled:J8})},(R8)=>z6(R8));if(!$8)g8();d.send(JSON.stringify({type:"plan_mode_change_ack",sessionId:n.sessionId,data:JSON.stringify({mode:qV(A.modeManager.getMode()),auto:J8})}));return}if(n.type==="select_model"||n.type==="model_change"){const w8=Mz(n.data);const o8=String(w8.model||"");if(o8){M.save({model:o8});const u=qV(A.modeManager.getMode());if(u==="plan"||u==="act"||u==="goal"){const c=F8();J6(c,o8,M.load().provider,true,u==="act",u);y8(c)}d.send(JSON.stringify({type:"token_update",sessionId:n.sessionId,data:JSON.stringify({model:o8})}));g8()}return}if(await A.handleControlMessage(n,(w8)=>d.send(JSON.stringify(w8))))return;d.send(JSON.stringify({type:"log",sessionId:n.sessionId,data:JSON.stringify({level:"info",message:`Unhandled WS message: ${n.type}`})}))}const g9=uO8(async(d,Q8)=>{try{const{request:n,url:q8}=_7(d);const x8=q8.pathname.startsWith("/v1/")?await p6(n,q8):null;const w8=x8||(q8.pathname.startsWith("/api/")?await X0(n,q8):Sz(q8));await q9(Q8,w8)}catch(n){await q9(Q8,l(e8(n.message||String(n)),500))}});g9.on("close",()=>{v.shutdown()});const pJ=uO8((d,Q8)=>{q9(Q8,L6("DeepSeekCode WebSocket endpoint"))});const Z9=new k$6.default({noServer:true});pJ.on("upgrade",(d,Q8,n)=>{const q8=new URL(d.url||"/",`http://${d.headers.host||`localhost:${X}`}`);Z9.handleUpgrade(d,Q8,n,(x8)=>{x8.data={path:q8.pathname,sessionId:q8.searchParams.get("sessionId"),terminalId:q8.searchParams.get("terminalId"),clientId:q8.searchParams.get("clientId")||undefined};Z9.emit("connection",x8,d)})});let wz=false;Z9.on("connection",(d)=>{if(d.data?.path==="/terminal"){R.openSocket(d,String(d.data?.terminalId??""))}else{N.add(d);e7.debug("ws.connected","New WebSocket connection");d.send(JSON.stringify({type:"auth_required",message:"Authentication required"}));d.send(JSON.stringify({type:"connected",message:"Connected to DeepSeekCode TypeScript runtime"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));g8(d);const Q8=M.load();if(!Q8.apiKey||!Q8.baseUrl){d.send(JSON.stringify({type:"notification",data:JSON.stringify({severity:"warn",message:"Provider not configured - run /config to set up your API provider."})}));d.send(JSON.stringify({type:"status",data:JSON.stringify({configured:false})}));if(!wz){wz=true;e7.warn("provider.not_configured","Provider not configured on client connect")}}}d.on("message",(Q8)=>{mJ(d,Q8).catch((n)=>{let q8;try{const x8=JSON.parse(String(M5(Q8)));if(x8.traceId)q8=x8.traceId}catch{}e7.error("ws.message_error","Error handling WS message",String(n),undefined,q8);d.send(JSON.stringify({type:"error",data:JSON.stringify({error:n.message||String(n)})}))})});d.on("close",()=>{if(d.data?.path==="/terminal"){R.closeSocket(String(d.data?.terminalId??""));return}N.delete(d)})});t(15000);return{runtime:A,httpServer:g9,wsHttpServer:pJ,webSocketServer:Z9,handleApi:X0,handleSocketMessage:mJ,httpPort:K,wsPort:X,host:Y||undefined,workspaceDir:q,configDir:Z,inboxStore:Z8,auditStore:Q,automationStore:p,automationScheduler:A8,cronScheduler:N8,sttManager:v}}var AQ6=process.argv[1]&&(process.argv[1].endsWith("index.js")||process.argv[1].endsWith("index.ts"));if(AQ6){const z=process.execArgv.find((K)=>K.startsWith("--max-old-space-size="))?.split("=")[1]||"0";const J=Number(z)||0;if(J>0&&J<2048){console.warn(`[deepseekcode] WARNING: --max-old-space-size=${J}MB may be too low for large sessions. Set DSC_HEAP_LIMIT_MB=4096 or higher.`)}else if(J===0){console.warn(`[deepseekcode] WARNING: No --max-old-space-size set. Default Node.js heap limit (~2GB) may cause OOM with large sessions. Set DSC_HEAP_LIMIT_MB=4096 or use --max-old-space-size=4096.`)}console.log(`[deepseekcode] Heap limit: ${J||"default (~2GB)"} (DSC_HEAP_LIMIT_MB env default: ${e$6}MB — set --max-old-space-size to apply a different value at startup)`);const D=al();D.httpServer.listen(D.httpPort,D.host);D.wsHttpServer.listen(D.wsPort,D.host);console.log(`[deepseekcode] HTTP API: http://localhost:${D.httpPort}`);console.log(`[deepseekcode] WebSocket: ws://localhost:${D.wsPort}/ws`);console.log(`[deepseekcode] Workspace: ${D.workspaceDir}`)}import{join as w2}from"node:path";import{homedir as hA}from"node:os";import{createServer as zj6}from"node:net";u4();import{execFile as oE}from"node:child_process";import{homedir as BQ6}from"node:os";import{join as _Q6}from"node:path";import{existsSync as JL8,readFileSync as UQ6,unlinkSync as MQ6,writeFileSync as NQ6}from"node:fs";var yA=_Q6(BQ6(),".agent","logs","dscode-cli.pid");function kA(){return process.env.DEEPSEEKCODE_QUIET==="1"}function DL8(z){return new Promise((J)=>{if(process.platform==="win32"){oE("netstat",["-ano"],{timeout:5000,windowsHide:true,maxBuffer:16*1024*1024},(D,K)=>{if(D){J([]);return}const X=new Set;for(const Y of K.split(/\r?\n/)){const q=Y.trim().split(/\s+/);if(q.length<5)continue;const Z=q[1];const G=q[3].toUpperCase();const H=q[4];const V=Z.includes("]")?Z.split("]:").pop():Z.split(":").pop();if(V===String(z)&&(G==="LISTENING"||G==="ESTABLISHED")){const O=parseInt(H,10);if(Number.isFinite(O)&&O>0)X.add(O)}}J([...X])});return}oE("lsof",["-ti",`:${z}`],{timeout:5000},(D,K)=>{if(D){J([]);return}J(K.trim().split(/\r?\n/).map((X)=>parseInt(X.trim(),10)).filter((X)=>Number.isFinite(X)&&X>0))})})}function FQ6(z){return new Promise((J)=>{if(process.platform==="win32"){oE("taskkill",["/F","/T","/PID",String(z)],{timeout:5000,windowsHide:true},(D)=>J(!D));return}oE("kill",["-KILL",String(z)],{timeout:5000},(D)=>J(!D))})}function LQ6(z){try{process.kill(z,0);return true}catch(J){return J.code==="EPERM"}}function KL8(){try{if(!JL8(yA))return null;const z=UQ6(yA,"utf8").trim();if(!z)return null;return JSON.parse(z)}catch{return null}}function XL8(z){try{NQ6(yA,JSON.stringify(z),"utf8")}catch{}}function rE(){try{const z=KL8();if(z&&z.pid===process.pid&&JL8(yA)){MQ6(yA)}}catch{}}async function YL8(){const z=new Set;const J=KL8();if(J&&J.pid!==process.pid){if(LQ6(J.pid)){z.add(J.pid);try{const X=`pid=${J.pid} started=${J.startedAt}`+(J.port?` port=${J.port}`:"")+(J.workspace?` workspace=${J.workspace}`:"");D1.warn(`Previous instance still running (${X}) — use --force to take over its port`)}catch{}}}const D=Number(process.env.DEEPSEEKCODE_HTTP_PORT||8080);let K=[];try{K=await DL8(D);for(const X of K){if(X!==process.pid)z.add(X)}}catch{}return{stalePids:[...z],holdersOnDefaultPort:K}}async function qL8(z,J){const D=new Set([...J]);try{for(const X of await DL8(z)){if(X!==process.pid)D.add(X)}}catch{}let K=true;for(const X of D){try{const Y=await FQ6(X);if(!Y){process.stderr.write(`[dscode] ⚠ Failed to kill PID ${X}.
4383
+ `)}))}if(n==="/api/logs/download"&&q8==="GET"){const u=U1(x8,"logs");const c=LK(String(Q8.searchParams.get("file")||""));const J8=U1(u,c);if(!c||!u7(J8))return l(e8("Log file not found"),404);return new Response(U0(J8),{headers:{"content-type":"application/octet-stream","access-control-allow-origin":"*"}})}if(n.startsWith("/api/logs"))return l(e8(`Unhandled endpoint: ${q8} ${n}`),404);if(n.startsWith("/api/observability")){const u=typeof A.telemetry?.snapshot==="function"?A.telemetry.snapshot():null;const c=typeof A.telemetry?.getMetricSummary==="function"?A.telemetry.getMetricSummary():{};if(n==="/api/observability/summary"&&q8==="GET"){return l(L8({totalRuns:c["trace.run[count]"]||0,totalCost:0,avgCost:0,totalTokens:c["token.usage[count]"]||0,activeSpans:u?.activeSpans?.length||0,recentEvents:u?.events?.length||0}))}if(n==="/api/observability/costs"&&q8==="GET"){return l(L8({daily:[],total:0,metrics:c}))}if(n==="/api/observability/runs"&&q8==="GET"){const J8=typeof A.workflows?.listRuns==="function"?A.workflows.listRuns():[];return l(L8(J8))}if(n.startsWith("/api/observability/runs/")&&q8==="GET"){const J8=n.split("/");const $8=J8[4];if(J8[5]==="events"){const E8=typeof A.workflows?.listEvents==="function"?A.workflows.listEvents($8):[];return l(L8({events:E8,total:Array.isArray(E8)?E8.length:0,page:Number(Q8.searchParams.get("page")||0),size:Number(Q8.searchParams.get("size")||50)}))}const R8=typeof A.workflows?.getRun==="function"?A.workflows.getRun($8):null;return l(L8(R8))}return l(L8({metrics:c,telemetry:true}))}if(n==="/api/workflows"&&q8==="GET")return l(L8(A.workflows.listRuns()));if(n==="/api/workflows"&&q8==="POST"){const u=await f8(d);const c=await A.workflows.start({sessionId:String(u.sessionId||""),runId:String(u.runId||""),goalId:typeof u.goalId==="string"?u.goalId:undefined,checkpointPolicy:String(u.checkpointPolicy||"phase-and-token"),message:String(u.message||u.content||""),script:typeof u.script==="string"?u.script:undefined,workflow:typeof u.workflow==="object"&&u.workflow?u.workflow:undefined});return l(L8(c))}if(n.startsWith("/api/workflows/")){const u=n.split("/");const c=u[3];if(u[4]==="events")return l(L8(A.workflows.listEvents(c)));if(u[4]==="checkpoints")return l(L8(A.workflows.listCheckpoints(c)));if(u[4]==="pause"&&q8==="POST")return l(L8(A.workflows.pause(c)));if(u[4]==="resume"&&q8==="POST")return l(L8(await A.workflows.resume(c)));if(u[4]==="cancel"&&q8==="POST")return l(L8(A.workflows.cancel(c)));const J8=A.workflows.getRun(c);return J8?l(L8(J8)):l(e8("Workflow not found"),404)}if(n==="/workflow/runs"&&q8==="GET")return l(L8(A.workflows.listRuns()));if(n==="/workflow/runs"&&q8==="POST"){const u=await f8(d);const c=await A.workflows.start({sessionId:String(u.sessionId||""),runId:String(u.runId||""),goalId:typeof u.goalId==="string"?u.goalId:undefined,checkpointPolicy:String(u.checkpointPolicy||"phase-and-token"),message:String(u.message||u.content||""),script:typeof u.script==="string"?u.script:undefined,workflow:typeof u.workflow==="object"&&u.workflow?u.workflow:undefined});return l(L8(c))}if(n.startsWith("/workflow/runs/")){const u=n.split("/");const c=u[3];if(u[4]==="trace"&&q8==="GET"){const $8=A.workflows.getTrace(c);return $8?l(L8($8)):l(e8("Workflow trace not found"),404)}if(u[4]==="events"&&q8==="GET")return l(L8(A.workflows.listEvents(c)));if(u[4]==="events"&&q8==="POST"){const $8=await f8(d);const R8=A.workflows.injectEvent(c,String($8.type||"user_event"),$8.data??$8);return R8?l(L8(R8)):l(e8("Workflow not found"),404)}if(u[4]==="pause"&&q8==="POST")return l(L8(A.workflows.pause(c)));if(u[4]==="resume"&&q8==="POST")return l(L8(await A.workflows.resume(c)));if(u[4]==="cancel"&&q8==="POST")return l(L8(A.workflows.cancel(c)));const J8=A.workflows.getRun(c);return J8?l(L8(J8)):l(e8("Workflow not found"),404)}if(n.startsWith("/api/checkpoints"))return l(L8(A.workflows.listCheckpoints()));if(n==="/api/templates"&&q8==="GET"){return l(L8(A.templates.list()))}if(n==="/api/templates"&&q8==="POST"){const u=await f8(d);let c;let J8={type:"handwritten"};let $8;if(typeof u.sourceRunId==="string"&&u.sourceRunId){const D6=A.workflows.getRun(u.sourceRunId);if(!D6)return l(e8("Run not found"),404);const I6=A.workflows.getRunDefinition(u.sourceRunId);if(!I6){if(D6.status==="FAILED"){return l(e8(`Run ${u.sourceRunId} failed before producing a workflow definition${D6.error?`: ${D6.error}`:""}`),400)}return l(e8("Run workflow definition not found"),404)}c=I6;J8={type:"saved",runId:u.sourceRunId};$8=I6.title}else if(typeof u.definition==="object"&&u.definition){c=u.definition;$8=c.title;J8=typeof u.source==="object"&&u.source?u.source:{type:"handwritten"}}let R8=false;let E8;if(u.generalize===true&&c&&J8.type==="saved"){try{const D6=M.load();const I6=new Pl({provider:new y9(D6),model:String(D6.model||""),timeoutMs:120000,maxTokensOverride:8000});const r6=await I6.generalize(c,typeof u.message==="string"&&u.message?u.message:c.title);if(!r6.degraded){c=r6.definition;$8=r6.name;u.description=r6.description;u.category=r6.category;u.inputs=r6.inputs}else{R8=true;E8=r6.reason||"LLM generalize failed";e7.info("templates.generalize_degraded","LLM generalize failed, saved as-is",E8)}}catch(D6){R8=true;E8=D6 instanceof Error?D6.message:String(D6);e7.error("templates.generalize_failed","TemplateGeneralizer threw",E8)}}const u8=typeof u.name==="string"&&u.name?u.name:$8;if(!u8||!c){return l(e8("Template requires a name and either a definition or sourceRunId"),400)}try{const D6=A.templates.create({name:u8,description:u.description!=null?String(u.description):undefined,category:typeof u.category==="string"&&u.category?u.category:"general",inputs:Array.isArray(u.inputs)?u.inputs:undefined,definition:c,source:J8});return R8?l(L8({...D6,degraded:R8,degradeReason:E8})):l(L8(D6))}catch(D6){return l(e8(D6 instanceof Error?D6.message:String(D6)),400)}}if(n.startsWith("/api/templates/")){const u=n.split("/");const c=decodeURIComponent(u[3]);if(!Vc(c))return l(e8("Invalid template id"),400);const J8=u[4];if(J8==="versions"){if(q8==="GET"&&u[5]){const $8=A.templates.getVersion(c,Number(u[5]));return $8?l(L8($8)):l(e8("Template version not found"),404)}if(q8==="GET")return l(L8(A.templates.listVersions(c)));return l(e8(`Unhandled template endpoint: ${q8} ${n}`),404)}if(J8==="render"&&q8==="POST"){const $8=await f8(d);const R8=$8&&typeof $8==="object"&&$8.inputs&&typeof $8.inputs==="object"&&!Array.isArray($8.inputs)?$8.inputs:$8;const E8=A.templates.render(c,R8);if(!E8.ok)return l(e8((E8.errors||[]).join("; ")),400);return l(L8(E8.definition))}if(q8==="GET"&&!J8){const $8=A.templates.get(c);return $8?l(L8($8)):l(e8("Template not found"),404)}if(q8==="PUT"&&!J8){const $8=await f8(d);const R8=A.templates.update(c,{name:typeof $8?.name==="string"?$8.name:undefined,description:typeof $8?.description==="string"?$8.description:undefined,category:typeof $8?.category==="string"?$8.category:undefined,inputs:Array.isArray($8?.inputs)?$8.inputs:undefined,definition:typeof $8?.definition==="object"&&$8?.definition?$8.definition:undefined,source:typeof $8?.source==="object"&&$8?.source?$8.source:undefined});return R8?l(L8(R8)):l(e8("Template not found"),404)}if(q8==="DELETE"&&!J8){return l(L8({removed:A.templates.remove(c)}))}return l(e8(`Unhandled template endpoint: ${q8} ${n}`),404)}if(n.startsWith("/api/speech")){return l(L8({available:false,text:"",supported:false,engines:[]}))}if(n.startsWith("/api/metrics")){const u=process.memoryUsage();const c=Math.floor((Date.now()-O)/1000);const J8=typeof A.sessions?.list==="function"?A.sessions.list().length:0;const $8=typeof A.telemetry?.getMetricSummary==="function"?A.telemetry.getMetricSummary():{};return l(L8({uptime:c,memory:{heapUsed:u.heapUsed,heapTotal:u.heapTotal,rss:u.rss},sessions:J8,clients:N.size,workspace:q,version:"1.0.20",metrics:$8}))}return l(e8(`Unhandled endpoint: ${q8} ${n}`),404)}function Sz(d){const Q8=d.pathname==="/"?"/index.html":d.pathname;const n=v$6(U1(V,Q8));if(!n.startsWith(V)||!u7(n)||t5(n).isDirectory()){const o8=U1(V,"index.html");return u7(o8)?new Response(U0(o8),{headers:{"content-type":"text/html; charset=utf-8"}}):L6("DeepSeekCode server is running")}const q8=b$6(n);const x8={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8"};const w8=x8[q8]||"application/octet-stream";return new Response(U0(n),{headers:{"content-type":w8}})}function _7(d){const Q8=new URL(d.url||"/",`http://${d.headers.host||`localhost:${K}`}`);const n={method:d.method,headers:d.headers};if(d.method!=="GET"&&d.method!=="HEAD"){n.body=d;n.duplex="half"}return{request:new Request(Q8,n),url:Q8}}async function q9(d,Q8){d.statusCode=Q8.status;Q8.headers.forEach((q8,x8)=>d.setHeader(x8,q8));const n=Buffer.from(await Q8.arrayBuffer());d.end(n)}function M5(d){if(Array.isArray(d))return Buffer.concat(d);if(d instanceof ArrayBuffer)return Buffer.from(d);return d}async function mJ(d,Q8){if(d.data?.path==="/terminal"){R.handleSocketMessage(String(d.data?.terminalId??""),M5(Q8));return}if(G&&d.data?.authenticated!==true){let w8;try{w8=JSON.parse(String(M5(Q8)))}catch{w8={}}if(w8.type==="auth"){if(w8.token===G){d.data=d.data||{};d.data.authenticated=true;d.send(JSON.stringify({type:"auth_success",message:"Authenticated"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));e7.info("ws.authenticated","WebSocket client authenticated");return}d.send(JSON.stringify({type:"auth_failed",message:"Invalid API token"}));d.close(4401,"Invalid API token");return}d.send(JSON.stringify({type:"auth_required",message:"Authentication required: send {type:'auth', token}"}));return}let n;try{n=JSON.parse(String(M5(Q8)))}catch{d.send(JSON.stringify({type:"error",data:JSON.stringify({error:"Invalid JSON"})}));return}const q8=d.data?.clientId;const x8=n;if(q8){x8.clientId=q8}if(n.type==="auth"){d.data=d.data||{};d.data.authenticated=true;d.send(JSON.stringify({type:"auth_success",message:"Authenticated"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));return}if(n.type==="workspace"){d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));return}if(n.type==="ping"){d.send(JSON.stringify({type:"pong",sessionId:n.sessionId||null}));return}if(n.type==="message_ack")return;if(n.type==="hook_allow"||n.type==="hook_deny"){const w8=Mz(n.data);const o8=String(n.approvalId||w8.approvalId||"");const u=n.type==="hook_allow";const c=typeof w8.sessionId==="string"?w8.sessionId:undefined;const J8=o8?L.decide(o8,u,{sessionId:n.sessionId||c,remember:Boolean(w8.remember||w8.sessionAllow)}):false;d.send(JSON.stringify({type:"hook_response_ack",sessionId:n.sessionId||null,data:JSON.stringify({approvalId:o8,allowed:u,resolved:J8})}));return}if(n.type==="create_session"){const w8=Mz(n.data);const o8=w8.sessionId?C.ensure(String(w8.sessionId)):M6();const u="messages"in o8?(({messages:c,...J8})=>J8)(o8):o8;d.send(JSON.stringify({type:"session_created",sessionId:u.id,data:JSON.stringify(u)}));return}if(n.type==="chat"||n.type==="plan"){if(!n.traceId)n.traceId=XC();const w8=n.traceId;await A.run(n,(o8)=>{o8.traceId=w8;d.send(JSON.stringify(o8))});return}if(n.type==="workflow_start"||n.type==="workflow_pause"||n.type==="workflow_resume"||n.type==="workflow_cancel"){if(!n.traceId)n.traceId=XC();const w8=n.traceId;await A.handleControlMessage(n,(o8)=>{o8.traceId=w8;d.send(JSON.stringify(o8))});return}if(n.type==="plan_confirm"){d.send(JSON.stringify({type:"plan_complete",sessionId:n.sessionId,data:JSON.stringify({status:"confirmed"})}));return}if(n.type==="user_exit_plan_mode"){const w8=Mz(n.data)||{};const o8=String(w8.planContent||"");const u=String(w8.planSlug||"");if(o8){try{A.plans.write(u||"user-exit-plan",o8)}catch(c){e7.warn("plan.save_failed","Failed to save plan on user exit",String(c))}}try{A.modeManager.exitPlanMode("User exited plan mode");z6({type:"plan_mode_change",sessionId:n.sessionId,data:JSON.stringify({previousMode:"plan",newMode:"act",reason:"User exited plan mode",timestamp:Date.now()})});d.send(JSON.stringify({type:"plan_complete",sessionId:n.sessionId,data:JSON.stringify({status:"user_exited",planSaved:!!o8})}))}catch(c){e7.warn("plan.exit_failed","Failed to exit plan mode",String(c))}return}if(["stop","pause","resume","get_commands"].includes(n.type)){await A.handleControlMessage(n,(w8)=>d.send(JSON.stringify(w8)));return}if(n.type==="reset"){const w8=n.sessionId||"";if(w8){const o8=C.reset(w8);d.send(JSON.stringify({type:"log",sessionId:w8,data:JSON.stringify({level:"info",message:o8?"Context cleared":"Session not found"})}))}else{d.send(JSON.stringify({type:"log",sessionId:w8,data:JSON.stringify({level:"warn",message:"Reset skipped: no sessionId"})}))}return}if(n.type==="resume_session"){const w8=Mz(n.data);const o8=String(n.sessionId||w8.sessionId||"");const u=o8?C.ensure(o8):C.create();d.send(JSON.stringify({type:"session_resumed",sessionId:u.id,data:JSON.stringify(C.resumeSnapshot(u.id,{tasks:A.listTasks(),pendingApprovals:L.list()}))}));return}if(n.type==="mcp"){const w8=Mz(n.data);const o8=String(w8.action||"list");try{const u=o8==="reload"?(y.reload(),await $6(),y.listServers()):o8==="tools"?(await $6(),await y.listTools(String(w8.server||"")||undefined)):y.listServers();d.send(JSON.stringify({type:"notification",sessionId:n.sessionId,data:JSON.stringify({kind:"mcp",action:o8,result:u})}))}catch(u){d.send(JSON.stringify({type:"error",sessionId:n.sessionId,data:u.message}))}return}if(n.type==="question_answer"){const w8=Mz(n.data);const o8=String(w8.questionId||"");const u=String(w8.answer||"");const c=Array.isArray(w8.selectedOptions)?w8.selectedOptions.map(String):undefined;const J8=Array.isArray(w8.answers)?w8.answers.map(($8)=>({question:$8.question?String($8.question):undefined,answer:String($8.answer||"(user did not answer)"),selectedOptions:Array.isArray($8.selectedOptions)?$8.selectedOptions.map(String):undefined})):undefined;if(o8){const $8=J8?{answers:J8}:{answer:u,selectedOptions:c};const R8=xp(o8,$8);d.send(JSON.stringify({type:"question_answer_ack",sessionId:n.sessionId||null,data:JSON.stringify({questionId:o8,resolved:R8,ok:R8})}))}else{d.send(JSON.stringify({type:"error",sessionId:n.sessionId||null,data:JSON.stringify({error:"Missing questionId"})}))}return}if(n.type==="plan_mode_change"){const w8=Mz(n.data);const o8=String(n.mode||w8.frontendMode||w8.newMode||w8.mode||"");const u=A.modeManager.getMode();let c;let J8;if(o8==="auto"){c=u==="normal"?"act":u;J8=!L.isAutoMode()}else if($46(o8)){c=O46(o8);J8=true}else if(o8==="plan"||o8==="act"||o8==="goal"||o8==="normal"){c=o8;J8=false}else{d.send(JSON.stringify({type:"log",sessionId:n.sessionId,data:JSON.stringify({level:"warn",message:`plan_mode_change ignored: unknown mode "${o8}"`})}));return}const $8=A.modeManager.setMode(c,`Client mode change: ${o8}`);await A.handleControlMessage({type:"hook_auto",sessionId:n.sessionId,data:JSON.stringify({enabled:J8})},(R8)=>z6(R8));if(!$8)g8();d.send(JSON.stringify({type:"plan_mode_change_ack",sessionId:n.sessionId,data:JSON.stringify({mode:qV(A.modeManager.getMode()),auto:J8})}));return}if(n.type==="select_model"||n.type==="model_change"){const w8=Mz(n.data);const o8=String(w8.model||"");if(o8){M.save({model:o8});const u=qV(A.modeManager.getMode());if(u==="plan"||u==="act"||u==="goal"){const c=F8();J6(c,o8,M.load().provider,true,u==="act",u);y8(c)}d.send(JSON.stringify({type:"token_update",sessionId:n.sessionId,data:JSON.stringify({model:o8})}));g8()}return}if(await A.handleControlMessage(n,(w8)=>d.send(JSON.stringify(w8))))return;d.send(JSON.stringify({type:"log",sessionId:n.sessionId,data:JSON.stringify({level:"info",message:`Unhandled WS message: ${n.type}`})}))}const g9=uO8(async(d,Q8)=>{try{const{request:n,url:q8}=_7(d);const x8=q8.pathname.startsWith("/v1/")?await p6(n,q8):null;const w8=x8||(q8.pathname.startsWith("/api/")?await X0(n,q8):Sz(q8));await q9(Q8,w8)}catch(n){await q9(Q8,l(e8(n.message||String(n)),500))}});g9.on("close",()=>{v.shutdown()});const pJ=uO8((d,Q8)=>{q9(Q8,L6("DeepSeekCode WebSocket endpoint"))});const Z9=new k$6.default({noServer:true});pJ.on("upgrade",(d,Q8,n)=>{const q8=new URL(d.url||"/",`http://${d.headers.host||`localhost:${X}`}`);Z9.handleUpgrade(d,Q8,n,(x8)=>{x8.data={path:q8.pathname,sessionId:q8.searchParams.get("sessionId"),terminalId:q8.searchParams.get("terminalId"),clientId:q8.searchParams.get("clientId")||undefined};Z9.emit("connection",x8,d)})});let wz=false;Z9.on("connection",(d)=>{if(d.data?.path==="/terminal"){R.openSocket(d,String(d.data?.terminalId??""))}else{N.add(d);e7.debug("ws.connected","New WebSocket connection");d.send(JSON.stringify({type:"auth_required",message:"Authentication required"}));d.send(JSON.stringify({type:"connected",message:"Connected to DeepSeekCode TypeScript runtime"}));d.send(JSON.stringify({type:"workspace_changed",data:JSON.stringify({newDir:q})}));g8(d);const Q8=M.load();if(!Q8.apiKey||!Q8.baseUrl){d.send(JSON.stringify({type:"notification",data:JSON.stringify({severity:"warn",message:"Provider not configured - run /config to set up your API provider."})}));d.send(JSON.stringify({type:"status",data:JSON.stringify({configured:false})}));if(!wz){wz=true;e7.warn("provider.not_configured","Provider not configured on client connect")}}}d.on("message",(Q8)=>{mJ(d,Q8).catch((n)=>{let q8;try{const x8=JSON.parse(String(M5(Q8)));if(x8.traceId)q8=x8.traceId}catch{}e7.error("ws.message_error","Error handling WS message",String(n),undefined,q8);d.send(JSON.stringify({type:"error",data:JSON.stringify({error:n.message||String(n)})}))})});d.on("close",()=>{if(d.data?.path==="/terminal"){R.closeSocket(String(d.data?.terminalId??""));return}N.delete(d)})});t(15000);return{runtime:A,httpServer:g9,wsHttpServer:pJ,webSocketServer:Z9,handleApi:X0,handleSocketMessage:mJ,httpPort:K,wsPort:X,host:Y||undefined,workspaceDir:q,configDir:Z,inboxStore:Z8,auditStore:Q,automationStore:p,automationScheduler:A8,cronScheduler:N8,sttManager:v}}var AQ6=process.argv[1]&&(process.argv[1].endsWith("index.js")||process.argv[1].endsWith("index.ts"));if(AQ6){const z=process.execArgv.find((K)=>K.startsWith("--max-old-space-size="))?.split("=")[1]||"0";const J=Number(z)||0;if(J>0&&J<2048){console.warn(`[deepseekcode] WARNING: --max-old-space-size=${J}MB may be too low for large sessions. Set DSC_HEAP_LIMIT_MB=4096 or higher.`)}else if(J===0){console.warn(`[deepseekcode] WARNING: No --max-old-space-size set. Default Node.js heap limit (~2GB) may cause OOM with large sessions. Set DSC_HEAP_LIMIT_MB=4096 or use --max-old-space-size=4096.`)}console.log(`[deepseekcode] Heap limit: ${J||"default (~2GB)"} (DSC_HEAP_LIMIT_MB env default: ${e$6}MB — set --max-old-space-size to apply a different value at startup)`);const D=al();D.httpServer.listen(D.httpPort,D.host);D.wsHttpServer.listen(D.wsPort,D.host);console.log(`[deepseekcode] HTTP API: http://localhost:${D.httpPort}`);console.log(`[deepseekcode] WebSocket: ws://localhost:${D.wsPort}/ws`);console.log(`[deepseekcode] Workspace: ${D.workspaceDir}`)}import{join as w2}from"node:path";import{homedir as hA}from"node:os";import{createServer as zj6}from"node:net";u4();import{execFile as oE}from"node:child_process";import{homedir as BQ6}from"node:os";import{join as _Q6}from"node:path";import{existsSync as JL8,readFileSync as UQ6,unlinkSync as MQ6,writeFileSync as NQ6}from"node:fs";var yA=_Q6(BQ6(),".agent","logs","dscode-cli.pid");function kA(){return process.env.DEEPSEEKCODE_QUIET==="1"}function DL8(z){return new Promise((J)=>{if(process.platform==="win32"){oE("netstat",["-ano"],{timeout:5000,windowsHide:true,maxBuffer:16*1024*1024},(D,K)=>{if(D){J([]);return}const X=new Set;for(const Y of K.split(/\r?\n/)){const q=Y.trim().split(/\s+/);if(q.length<5)continue;const Z=q[1];const G=q[3].toUpperCase();const H=q[4];const V=Z.includes("]")?Z.split("]:").pop():Z.split(":").pop();if(V===String(z)&&(G==="LISTENING"||G==="ESTABLISHED")){const O=parseInt(H,10);if(Number.isFinite(O)&&O>0)X.add(O)}}J([...X])});return}oE("lsof",["-ti",`:${z}`],{timeout:5000},(D,K)=>{if(D){J([]);return}J(K.trim().split(/\r?\n/).map((X)=>parseInt(X.trim(),10)).filter((X)=>Number.isFinite(X)&&X>0))})})}function FQ6(z){return new Promise((J)=>{if(process.platform==="win32"){oE("taskkill",["/F","/T","/PID",String(z)],{timeout:5000,windowsHide:true},(D)=>J(!D));return}oE("kill",["-KILL",String(z)],{timeout:5000},(D)=>J(!D))})}function LQ6(z){try{process.kill(z,0);return true}catch(J){return J.code==="EPERM"}}function KL8(){try{if(!JL8(yA))return null;const z=UQ6(yA,"utf8").trim();if(!z)return null;return JSON.parse(z)}catch{return null}}function XL8(z){try{NQ6(yA,JSON.stringify(z),"utf8")}catch{}}function rE(){try{const z=KL8();if(z&&z.pid===process.pid&&JL8(yA)){MQ6(yA)}}catch{}}async function YL8(){const z=new Set;const J=KL8();if(J&&J.pid!==process.pid){if(LQ6(J.pid)){z.add(J.pid);try{const X=`pid=${J.pid} started=${J.startedAt}`+(J.port?` port=${J.port}`:"")+(J.workspace?` workspace=${J.workspace}`:"");D1.warn(`Previous instance still running (${X}) — use --force to take over its port`)}catch{}}}const D=Number(process.env.DEEPSEEKCODE_HTTP_PORT||8080);let K=[];try{K=await DL8(D);for(const X of K){if(X!==process.pid)z.add(X)}}catch{}return{stalePids:[...z],holdersOnDefaultPort:K}}async function qL8(z,J){const D=new Set([...J]);try{for(const X of await DL8(z)){if(X!==process.pid)D.add(X)}}catch{}let K=true;for(const X of D){try{const Y=await FQ6(X);if(!Y){process.stderr.write(`[dscode] ⚠ Failed to kill PID ${X}.
4384
4384
  `);K=false}else{process.stderr.write(`[dscode] ✅ Killed stale instance PID ${X} (--force)
4385
4385
  `)}}catch{K=false}}if(!K)return false;await new Promise((X)=>setTimeout(X,400));return true}var rQ6=process.execArgv.some(function(z){return z.includes("max-old-space-size")});var sQ6=process.env.NODE_OPTIONS?.includes("max-old-space-size");var tQ6=process.env.DSC_HEAP_LIMIT_MB||"8192";if(!rQ6&&!sQ6&&process.env.DEEPSEEKCODE_QUIET!=="1"&&process.argv[1]&&!process.argv[1].includes("--version")&&!process.argv[1].includes("-v")){try{process.stderr.write("[DSC] Tip: Run with --max-old-space-size="+tQ6+` to prevent OOM.
4386
4386
  `);process.stderr.write(`[DSC] Set env DSC_HEAP_LIMIT_MB to change limit.
@@ -4390,7 +4390,7 @@ Error: API Key is required for deployment. Process exited with code 1.\r
4390
4390
  ${z.stack||z.message}`)}catch(J){}LL8("Fatal error:",z);process.exit(1)});process.on("unhandledRejection",(z)=>{const J=z instanceof Error?z:new Error(String(z));if(J.code==="EPIPE"||J.code==="ECONNRESET")return;try{D1.error(`FATAL UNHANDLED REJECTION: ${J.stack||J.message}`);D1.error(`Node.js ${process.version}, heapUsed: ${(process.memoryUsage().heapUsed/1024/1024).toFixed(1)}MB`);const D=w2(hA(),".agent","logs");const K=w2(D,".last-crash");Dd(K,`${new Date().toISOString()}
4391
4391
  UNHANDLED REJECTION
4392
4392
  ${J.stack||J.message}`)}catch(D){}LL8("Fatal unhandled rejection:",J);process.exit(1)});process.on("exit",(z)=>{try{const J=w2(hA(),".agent","logs");Dd(w2(J,".last-exit"),`${new Date().toISOString()} code=${z}
4393
- `)}catch{}try{rE()}catch{}try{dS()}catch{}});function CL8(){const z=process.stdin;if(z.isTTY===undefined&&typeof z.setRawMode==="function"){z.isTTY=true}return z}var sV="1.0.19";var zd=null;function EL8(z){if(zd)return;zd=Rh(z)?Promise.resolve(null):nG8(sV)}async function RL8(z,J=1200){const D=JH8();if(D&&!kA()){try{process.stderr.write(DH8(D))}catch{}}if(Rh(z)||kA())return;EL8(z);const K=await Promise.race([zd,new Promise((X)=>setTimeout(()=>X(null),J))]);if(!K)return;try{if(tG8(z)||!eG8(sV)){process.stderr.write(aG8(K))}else{process.stderr.write(KH8(K));zH8(K.latest)}}catch{}}function NL8(){console.log(`DeepSeekCode CLI v${sV}`);console.log("");console.log("Usage:");console.log(" dscode [options] Start local core + interactive terminal");console.log(" dscode start [options] Start local core + interactive terminal");console.log(" dscode start --auto Start with auto mode enabled");console.log(" dscode run --backend URL Connect to existing backend");console.log(" dscode exec <command> Execute command non-interactively (JSONL output)");console.log(" dscode exec --file <path> Execute command from file");console.log(" dscode exec --text Output plain text instead of JSONL");console.log(" dscode --no-update-check Disable the startup new-version notice");console.log(" dscode --no-auto-update Disable background auto-update (notice still shown)");console.log(" dscode --resume Resume last session");console.log(" dscode --resume <id> Resume an existing session");console.log(" dscode codeview [options] AI code review: bugs + unwired features (JSON output)");console.log(" dscode review Review current code changes (legacy)");console.log(" dscode test-fix Run auto-fix test loop");console.log(" dscode auto Enable auto mode (auto-approve all hooks)");console.log(" dscode version Print version");console.log("");console.log("Interactive commands (inside TUI):");console.log(" /auto Toggle auto mode on/off");console.log(" /plan Toggle plan mode");console.log(" /clear Clear conversation");console.log(" /help Show help");console.log(" /context Show current context info");console.log("");console.log("Options:");console.log(" -p, --port <port> HTTP port (default: first available from 8080)");console.log(" --ws-port <port> WebSocket port (default: HTTP port + 1)");console.log(" -w, --workspace <dir> Workspace directory (default: current directory)");console.log(" -F, --force Kill existing process on target port before starting");console.log(" -b, --backend <url> Backend URL for run mode");console.log(" --ws <url> Override WebSocket URL");console.log(" --file <path> Read command from file (for exec)");console.log(" --text Output plain text (for exec/review)");console.log(" --brief Output brief results (for exec/review)");console.log(" --provider <name> Provider to use (for exec/review)");console.log(" --model <name> Model to use (for exec/review)");console.log(" --packages <list> Comma-separated packages (for test-fix)");console.log(" --retries <n> Max retry count (for test-fix, default 5)");console.log(" --skip <list> Comma-separated validations to skip (for test-fix)");console.log(" --dry-run Analyze only, no fixes applied (for test-fix)");console.log(" --focus <text> Focus area for codeview (e.g. security, performance)");console.log(" --no-fix Skip interactive fix prompt in codeview");console.log(" --output <file> Write codeview JSON report to file");console.log(" --resume [session-id] Resume a session (omit ID to resume last session)");console.log(" --theme <name|path> Theme name or JSON file path (e.g. nord, /path/to/t.json)");console.log(" --prompt-version <ver> Prompt template version (e.g. v1.0)");console.log(" --timeout <ms> Per-attempt LLM timeout (default: 300000 = 5min)");console.log(" --stall-threshold <ms> Stream stall detection threshold (default: 240000 = 4min)");console.log("");console.log("Environment:");console.log(" DEEPSEEKCODE_QUIET=1 Suppress non-fatal startup warnings (stale instance, port conflict, tips)");console.log(" DEEPSEEKCODE_NO_AUTO_UPDATE=1 Disable background auto-update (version notice still shown)");console.log(" DEEPSEEKCODE_HTTP_PORT=<n> HTTP port (default: 8080)");console.log(" DEEPSEEKCODE_WS_PORT=<n> WebSocket port (default: HTTP port + 1)");console.log(" DEEPSEEKCODE_TUI=1 Log to file instead of terminal (auto-set in start mode)")}function Dj6(){const z={};const J=process.argv.slice(2);for(let D=0;D<J.length;D+=1){const K=J[D];if(K==="--force"||K==="-F")z.force=true;else if(K==="--port"||K==="-p")z.port=J[++D];else if(K==="--ws-port")z.wsPort=J[++D];else if(K==="--workspace"||K==="-w")z.workspace=J[++D];else if(K==="--backend"||K==="-b")z.backend=J[++D];else if(K==="--ws")z.ws=J[++D];else if(K==="--file")z.file=J[++D];else if(K==="--json")z.json=true;else if(K==="--text")z.text=true;else if(K==="--brief")z.brief=true;else if(K==="--provider")z.provider=J[++D];else if(K==="--model")z.model=J[++D];else if(K==="--timeout")z.timeout=J[++D];else if(K==="--stall-threshold")z.stallThreshold=J[++D];else if(K==="--packages")z.packages=J[++D];else if(K==="--retries")z.retries=J[++D];else if(K==="--skip")z.skip=J[++D];else if(K==="--dry-run")z.dryRun=true;else if(K==="--focus")z.focus=J[++D];else if(K==="--no-fix")z.noFix=true;else if(K==="--no-update-check")z.noUpdateCheck=true;else if(K==="--output")z.output=J[++D];else if(K==="--theme")z.theme=J[++D];else if(K==="--prompt-version")z.promptVersion=J[++D];else if(K==="--auto")z.auto=true;else if(K==="--resume"){const X=D+1<J.length&&!J[D+1].startsWith("-")?J[++D]:undefined;z.resume=X||true}else if(!K.startsWith("-")){if(!z._cmd)z._cmd=K;else(z._args??=[]).push(K)}}return z}async function Kj6(z){return new Promise((J)=>{const D=zj6();let K=false;const X=(Y)=>{if(K)return;K=true;J(Y)};D.once("error",()=>X(false));D.once("listening",()=>{D.close(()=>X(true))});D.listen(z,"::")})}async function el(z,J=20){const D=Number.isFinite(z)&&z>0?Math.floor(z):8080;for(let K=D;K<D+J;K+=1){if(await Kj6(K))return K}throw new Error(`No available port found in range ${D}-${D+J-1}`)}async function FL8(z,J,D){return new Promise((K,X)=>{const Y=(Z)=>{z.off("listening",q);X(new Error(`${D} failed to listen on port ${J}: ${Z.code||Z.message}`))};const q=()=>{z.off("error",Y);K()};z.once("error",Y);z.once("listening",q);z.listen(J)})}function PL8(){if(process.env.DEEPSEEKCODE_FRAME_TIMING!=="1")return;let z=0;let J=0,D=0,K=0,X=0,Y=0,q=0;let Z=Date.now();return(G)=>{z++;const H=G.phases;if(H){if(H.renderer>J)J=H.renderer;if(H.diff>D)D=H.diff;if(H.write>K)K=H.write;if(H.optimize>X)X=H.optimize;if(H.patches>q)q=H.patches}if(G.durationMs>Y)Y=G.durationMs;if(G.durationMs>50){D1.info(`[frame-timing] SPIKE ${G.durationMs.toFixed(1)}ms renderer=${H?.renderer?.toFixed(1)} diff=${H?.diff?.toFixed(1)} write=${H?.write?.toFixed(1)} patches=${H?.patches} yogaVisited=${H?.yogaVisited} yogaMeasured=${H?.yogaMeasured} yogaLive=${H?.yogaLive}`)}if(Date.now()-Z>=1000){D1.info(`[frame-timing] ${z}fps maxTot=${Y.toFixed(1)}ms renderer=${J.toFixed(1)} diff=${D.toFixed(1)} write=${K.toFixed(1)} optimize=${X.toFixed(1)} maxPatches=${q}`);z=0;J=0;D=0;K=0;X=0;Y=0;q=0;Z=Date.now()}}}async function Xj6(z,J,D,K,X,Y){D1.debug("Rendering App UI");const q=CL8();let Z=null;const{waitUntilExit:G,unmount:H}=await oS(Jd.createElement(Eh,{backendUrl:z,wsUrl:J,onExit:()=>{try{Z?.()}catch{}},clientFactory:K,version:sV,workspaceDir:X,resumeSessionId:Y}),{stdin:q,exitOnCtrlC:false,onFrame:PL8()});Z=H;Kd=H;await G();D1.warn("[exit] App UI exited");D()}async function Yj6(z){process.env.DEEPSEEKCODE_TUI="1";const J=String(z.workspace||process.cwd());const D=Number(z.port||process.env.DEEPSEEKCODE_HTTP_PORT||8080);EL8(z);const K=Boolean(z.force);let X=[];try{const L=await YL8();X=L.stalePids}catch{}let Y=await el(D);if(K){const L=await qL8(D,X);if(L)Y=await el(D)}const q=Number(z.wsPort||process.env.DEEPSEEKCODE_WS_PORT||Y+1);const Z=q===Y?Y+1:q;const G=await el(Z);const H=w2(hA(),".agent","logs");D1.debug(`Starting local core runtime, workspace: ${J}`);D1.debug(`AI trace file: ${w2(H,"ai-trace-*.ndjson")} (DEEPSEEKCODE_TRACE_AI=1 enables full request/response tracing)`);if(Y!==D){D1.warn(`HTTP port ${D} is already in use; using ${Y}`)}if(G!==Z){D1.warn(`WebSocket port ${Z} is already in use; using ${G}`)}XL8({pid:process.pid,startedAt:new Date().toISOString(),port:Y,workspace:J});const V=new Th(J);let O=false;let j=null;function Q(L="unknown"){if(O)return;O=true;D1.warn(`[exit] Shutting down... (trigger: ${L})`);const T=setTimeout(()=>{try{process.exit(0)}catch{}},3000);try{T.unref?.()}catch{}try{B.httpServer.close()}catch{}try{B.wsHttpServer.close()}catch{}try{V.close()}catch{}try{j?.()}catch{}rE();process.exit(0)}const B=al({runtime:V.runtime,workspaceDir:J,httpPort:Y,wsPort:G,onShutdown:()=>Q("web-ui")});await FL8(B.httpServer,B.httpPort,"HTTP API");await FL8(B.wsHttpServer,B.wsPort,"WebSocket");await RL8(z);process.on("SIGINT",()=>Q("SIGINT"));process.on("SIGTERM",()=>Q("SIGTERM"));process.on("SIGBREAK",()=>Q("SIGBREAK"));if(!await V.providerConfigured()){D1.info("Provider not configured; directing user to the web config UI");if(!kA()){try{const L=`http://localhost:${B.httpPort}/#models`;const T=yQ()?`\x1B]8;;${L}\x07${L}\x1B]8;;\x07`:L;process.stderr.write(`[dscode] ⚠ 尚未配置模型/Provider,请在网页端完成配置:
4393
+ `)}catch{}try{rE()}catch{}try{dS()}catch{}});function CL8(){const z=process.stdin;if(z.isTTY===undefined&&typeof z.setRawMode==="function"){z.isTTY=true}return z}var sV="1.0.20";var zd=null;function EL8(z){if(zd)return;zd=Rh(z)?Promise.resolve(null):nG8(sV)}async function RL8(z,J=1200){const D=JH8();if(D&&!kA()){try{process.stderr.write(DH8(D))}catch{}}if(Rh(z)||kA())return;EL8(z);const K=await Promise.race([zd,new Promise((X)=>setTimeout(()=>X(null),J))]);if(!K)return;try{if(tG8(z)||!eG8(sV)){process.stderr.write(aG8(K))}else{process.stderr.write(KH8(K));zH8(K.latest)}}catch{}}function NL8(){console.log(`DeepSeekCode CLI v${sV}`);console.log("");console.log("Usage:");console.log(" dscode [options] Start local core + interactive terminal");console.log(" dscode start [options] Start local core + interactive terminal");console.log(" dscode start --auto Start with auto mode enabled");console.log(" dscode run --backend URL Connect to existing backend");console.log(" dscode exec <command> Execute command non-interactively (JSONL output)");console.log(" dscode exec --file <path> Execute command from file");console.log(" dscode exec --text Output plain text instead of JSONL");console.log(" dscode --no-update-check Disable the startup new-version notice");console.log(" dscode --no-auto-update Disable background auto-update (notice still shown)");console.log(" dscode --resume Resume last session");console.log(" dscode --resume <id> Resume an existing session");console.log(" dscode codeview [options] AI code review: bugs + unwired features (JSON output)");console.log(" dscode review Review current code changes (legacy)");console.log(" dscode test-fix Run auto-fix test loop");console.log(" dscode auto Enable auto mode (auto-approve all hooks)");console.log(" dscode version Print version");console.log("");console.log("Interactive commands (inside TUI):");console.log(" /auto Toggle auto mode on/off");console.log(" /plan Toggle plan mode");console.log(" /clear Clear conversation");console.log(" /help Show help");console.log(" /context Show current context info");console.log("");console.log("Options:");console.log(" -p, --port <port> HTTP port (default: first available from 8080)");console.log(" --ws-port <port> WebSocket port (default: HTTP port + 1)");console.log(" -w, --workspace <dir> Workspace directory (default: current directory)");console.log(" -F, --force Kill existing process on target port before starting");console.log(" -b, --backend <url> Backend URL for run mode");console.log(" --ws <url> Override WebSocket URL");console.log(" --file <path> Read command from file (for exec)");console.log(" --text Output plain text (for exec/review)");console.log(" --brief Output brief results (for exec/review)");console.log(" --provider <name> Provider to use (for exec/review)");console.log(" --model <name> Model to use (for exec/review)");console.log(" --packages <list> Comma-separated packages (for test-fix)");console.log(" --retries <n> Max retry count (for test-fix, default 5)");console.log(" --skip <list> Comma-separated validations to skip (for test-fix)");console.log(" --dry-run Analyze only, no fixes applied (for test-fix)");console.log(" --focus <text> Focus area for codeview (e.g. security, performance)");console.log(" --no-fix Skip interactive fix prompt in codeview");console.log(" --output <file> Write codeview JSON report to file");console.log(" --resume [session-id] Resume a session (omit ID to resume last session)");console.log(" --theme <name|path> Theme name or JSON file path (e.g. nord, /path/to/t.json)");console.log(" --prompt-version <ver> Prompt template version (e.g. v1.0)");console.log(" --timeout <ms> Per-attempt LLM timeout (default: 300000 = 5min)");console.log(" --stall-threshold <ms> Stream stall detection threshold (default: 240000 = 4min)");console.log("");console.log("Environment:");console.log(" DEEPSEEKCODE_QUIET=1 Suppress non-fatal startup warnings (stale instance, port conflict, tips)");console.log(" DEEPSEEKCODE_NO_AUTO_UPDATE=1 Disable background auto-update (version notice still shown)");console.log(" DEEPSEEKCODE_HTTP_PORT=<n> HTTP port (default: 8080)");console.log(" DEEPSEEKCODE_WS_PORT=<n> WebSocket port (default: HTTP port + 1)");console.log(" DEEPSEEKCODE_TUI=1 Log to file instead of terminal (auto-set in start mode)")}function Dj6(){const z={};const J=process.argv.slice(2);for(let D=0;D<J.length;D+=1){const K=J[D];if(K==="--force"||K==="-F")z.force=true;else if(K==="--port"||K==="-p")z.port=J[++D];else if(K==="--ws-port")z.wsPort=J[++D];else if(K==="--workspace"||K==="-w")z.workspace=J[++D];else if(K==="--backend"||K==="-b")z.backend=J[++D];else if(K==="--ws")z.ws=J[++D];else if(K==="--file")z.file=J[++D];else if(K==="--json")z.json=true;else if(K==="--text")z.text=true;else if(K==="--brief")z.brief=true;else if(K==="--provider")z.provider=J[++D];else if(K==="--model")z.model=J[++D];else if(K==="--timeout")z.timeout=J[++D];else if(K==="--stall-threshold")z.stallThreshold=J[++D];else if(K==="--packages")z.packages=J[++D];else if(K==="--retries")z.retries=J[++D];else if(K==="--skip")z.skip=J[++D];else if(K==="--dry-run")z.dryRun=true;else if(K==="--focus")z.focus=J[++D];else if(K==="--no-fix")z.noFix=true;else if(K==="--no-update-check")z.noUpdateCheck=true;else if(K==="--output")z.output=J[++D];else if(K==="--theme")z.theme=J[++D];else if(K==="--prompt-version")z.promptVersion=J[++D];else if(K==="--auto")z.auto=true;else if(K==="--resume"){const X=D+1<J.length&&!J[D+1].startsWith("-")?J[++D]:undefined;z.resume=X||true}else if(!K.startsWith("-")){if(!z._cmd)z._cmd=K;else(z._args??=[]).push(K)}}return z}async function Kj6(z){return new Promise((J)=>{const D=zj6();let K=false;const X=(Y)=>{if(K)return;K=true;J(Y)};D.once("error",()=>X(false));D.once("listening",()=>{D.close(()=>X(true))});D.listen(z,"::")})}async function el(z,J=20){const D=Number.isFinite(z)&&z>0?Math.floor(z):8080;for(let K=D;K<D+J;K+=1){if(await Kj6(K))return K}throw new Error(`No available port found in range ${D}-${D+J-1}`)}async function FL8(z,J,D){return new Promise((K,X)=>{const Y=(Z)=>{z.off("listening",q);X(new Error(`${D} failed to listen on port ${J}: ${Z.code||Z.message}`))};const q=()=>{z.off("error",Y);K()};z.once("error",Y);z.once("listening",q);z.listen(J)})}function PL8(){if(process.env.DEEPSEEKCODE_FRAME_TIMING!=="1")return;let z=0;let J=0,D=0,K=0,X=0,Y=0,q=0;let Z=Date.now();return(G)=>{z++;const H=G.phases;if(H){if(H.renderer>J)J=H.renderer;if(H.diff>D)D=H.diff;if(H.write>K)K=H.write;if(H.optimize>X)X=H.optimize;if(H.patches>q)q=H.patches}if(G.durationMs>Y)Y=G.durationMs;if(G.durationMs>50){D1.info(`[frame-timing] SPIKE ${G.durationMs.toFixed(1)}ms renderer=${H?.renderer?.toFixed(1)} diff=${H?.diff?.toFixed(1)} write=${H?.write?.toFixed(1)} patches=${H?.patches} yogaVisited=${H?.yogaVisited} yogaMeasured=${H?.yogaMeasured} yogaLive=${H?.yogaLive}`)}if(Date.now()-Z>=1000){D1.info(`[frame-timing] ${z}fps maxTot=${Y.toFixed(1)}ms renderer=${J.toFixed(1)} diff=${D.toFixed(1)} write=${K.toFixed(1)} optimize=${X.toFixed(1)} maxPatches=${q}`);z=0;J=0;D=0;K=0;X=0;Y=0;q=0;Z=Date.now()}}}async function Xj6(z,J,D,K,X,Y){D1.debug("Rendering App UI");const q=CL8();let Z=null;const{waitUntilExit:G,unmount:H}=await oS(Jd.createElement(Eh,{backendUrl:z,wsUrl:J,onExit:()=>{try{Z?.()}catch{}},clientFactory:K,version:sV,workspaceDir:X,resumeSessionId:Y}),{stdin:q,exitOnCtrlC:false,onFrame:PL8()});Z=H;Kd=H;await G();D1.warn("[exit] App UI exited");D()}async function Yj6(z){process.env.DEEPSEEKCODE_TUI="1";const J=String(z.workspace||process.cwd());const D=Number(z.port||process.env.DEEPSEEKCODE_HTTP_PORT||8080);EL8(z);const K=Boolean(z.force);let X=[];try{const L=await YL8();X=L.stalePids}catch{}let Y=await el(D);if(K){const L=await qL8(D,X);if(L)Y=await el(D)}const q=Number(z.wsPort||process.env.DEEPSEEKCODE_WS_PORT||Y+1);const Z=q===Y?Y+1:q;const G=await el(Z);const H=w2(hA(),".agent","logs");D1.debug(`Starting local core runtime, workspace: ${J}`);D1.debug(`AI trace file: ${w2(H,"ai-trace-*.ndjson")} (DEEPSEEKCODE_TRACE_AI=1 enables full request/response tracing)`);if(Y!==D){D1.warn(`HTTP port ${D} is already in use; using ${Y}`)}if(G!==Z){D1.warn(`WebSocket port ${Z} is already in use; using ${G}`)}XL8({pid:process.pid,startedAt:new Date().toISOString(),port:Y,workspace:J});const V=new Th(J);let O=false;let j=null;function Q(L="unknown"){if(O)return;O=true;D1.warn(`[exit] Shutting down... (trigger: ${L})`);const T=setTimeout(()=>{try{process.exit(0)}catch{}},3000);try{T.unref?.()}catch{}try{B.httpServer.close()}catch{}try{B.wsHttpServer.close()}catch{}try{V.close()}catch{}try{j?.()}catch{}rE();process.exit(0)}const B=al({runtime:V.runtime,workspaceDir:J,httpPort:Y,wsPort:G,onShutdown:()=>Q("web-ui")});await FL8(B.httpServer,B.httpPort,"HTTP API");await FL8(B.wsHttpServer,B.wsPort,"WebSocket");await RL8(z);process.on("SIGINT",()=>Q("SIGINT"));process.on("SIGTERM",()=>Q("SIGTERM"));process.on("SIGBREAK",()=>Q("SIGBREAK"));if(!await V.providerConfigured()){D1.info("Provider not configured; directing user to the web config UI");if(!kA()){try{const L=`http://localhost:${B.httpPort}/#models`;const T=yQ()?`\x1B]8;;${L}\x07${L}\x1B]8;;\x07`:L;process.stderr.write(`[dscode] ⚠ 尚未配置模型/Provider,请在网页端完成配置:
4394
4394
  `+` ${T}
4395
4395
  `+` (配置完成后回到这里即可继续,提示会自动消失)
4396
4396
  `)}catch{}}}if(!process.stdin.isTTY){D1.warn("Non-TTY stdin detected; TUI skipped, running headless (Web UI only)");if(!kA()){try{const L=`http://localhost:${B.httpPort}`;const T=yQ()?`\x1B]8;;${L}\x07${L}\x1B]8;;\x07`:L;process.stderr.write(`[dscode] Non-interactive stdin detected — TUI skipped, running headless.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepseekcode/cli",
3
- "version": "1.0.19",
3
+ "version": "1.0.20",
4
4
  "description": "DeepSeekCode TypeScript CLI",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",