blade-code 0.7.7 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-0b3m5qn6.js → chunk-06h100e2.js} +1 -1
  3. package/dist/chunk-07jvw0kn.js +1 -0
  4. package/dist/chunk-0dj326ms.js +5 -0
  5. package/dist/chunk-14erxdhd.js +1 -0
  6. package/dist/chunk-1pt090dg.js +615 -0
  7. package/dist/{chunk-2qckpa16.js → chunk-1smf2dj3.js} +2 -2
  8. package/dist/chunk-34pdtz4q.js +3 -0
  9. package/dist/chunk-3gw66r7a.js +2 -0
  10. package/dist/chunk-49g067ek.js +41 -0
  11. package/dist/chunk-6es6av6j.js +2 -0
  12. package/dist/{chunk-6y58y4rx.js → chunk-9xkjb87h.js} +1 -1
  13. package/dist/chunk-a12tmmfr.js +1 -0
  14. package/dist/chunk-bggvft3z.js +1 -0
  15. package/dist/{chunk-60se4kxq.js → chunk-bm8vwfez.js} +1 -1
  16. package/dist/chunk-bxbagv76.js +9 -0
  17. package/dist/chunk-ctqf59q1.js +2 -0
  18. package/dist/chunk-d08wbxjr.js +1 -0
  19. package/dist/chunk-d4ex0qvs.js +2 -0
  20. package/dist/{chunk-zet4zjc3.js → chunk-dr06x0cw.js} +1 -1
  21. package/dist/chunk-e4a240t7.js +34 -0
  22. package/dist/{chunk-v61bja34.js → chunk-gsfkrr25.js} +1 -1
  23. package/dist/chunk-gytwh5y1.js +6 -0
  24. package/dist/chunk-hjx5n3dw.js +3 -0
  25. package/dist/chunk-hrnd3wjg.js +6 -0
  26. package/dist/chunk-j39q2kx7.js +1 -0
  27. package/dist/chunk-jakzknh3.js +1570 -0
  28. package/dist/chunk-jqr2pknb.js +151 -0
  29. package/dist/{chunk-2n8a87ds.js → chunk-jt62ctz7.js} +1 -1
  30. package/dist/{chunk-5xjj88wd.js → chunk-kawv31m3.js} +1 -1
  31. package/dist/chunk-n8ymp6nd.js +1 -0
  32. package/dist/{chunk-yyw9bbfd.js → chunk-nned222j.js} +1 -1
  33. package/dist/chunk-qwdbqjh7.js +22 -0
  34. package/dist/chunk-syj3anec.js +6 -0
  35. package/dist/chunk-tv4r86ez.js +24 -0
  36. package/dist/chunk-twem6p0g.js +2 -0
  37. package/dist/chunk-v3ctg84r.js +1 -0
  38. package/dist/chunk-v5rn5r1h.js +1 -0
  39. package/dist/{chunk-w1m1ehs1.js → chunk-wmes2tt9.js} +1 -1
  40. package/dist/chunk-xhnyy54e.js +2 -0
  41. package/dist/{chunk-6087cgst.js → chunk-ychj0e5q.js} +1 -1
  42. package/dist/{chunk-7e5hzpmp.js → chunk-ydb9myhe.js} +1 -1
  43. package/dist/{chunk-p7rf3zp8.js → chunk-yhpm9azy.js} +1 -1
  44. package/dist/{chunk-c6rtexw1.js → chunk-yqxw7zz4.js} +1 -1
  45. package/dist/web/assets/{FilePreview-B2anY2d1.js → FilePreview-DvgnEspB.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-BVfRG88x.js → MarkdownRenderer-e1ZUy6jV.js} +1 -1
  47. package/dist/web/assets/{McpModal-BVvb-dzr.js → McpModal-Raois2g1.js} +1 -1
  48. package/dist/web/assets/SettingsModal-Dzuatoea.js +1 -0
  49. package/dist/web/assets/{SettingsStore-B87y64B4.js → SettingsStore-BxDA0Usw.js} +1 -1
  50. package/dist/web/assets/{SkillsModal-BXYaF2KK.js → SkillsModal-Cg2-befH.js} +1 -1
  51. package/dist/web/assets/{TerminalPanel-B-NRhOXN.js → TerminalPanel-CEoQI9Lu.js} +1 -1
  52. package/dist/web/assets/index-BvGeIa_-.js +16 -0
  53. package/dist/web/assets/index-DDJnZJcp.css +1 -0
  54. package/dist/web/index.html +2 -2
  55. package/package.json +4 -11
  56. package/dist/chunk-0y895nft.js +0 -9
  57. package/dist/chunk-2j3tb2dm.js +0 -1
  58. package/dist/chunk-3fcze972.js +0 -1
  59. package/dist/chunk-4n7fsts0.js +0 -2
  60. package/dist/chunk-54vk4tw8.js +0 -615
  61. package/dist/chunk-6cry51vb.js +0 -9
  62. package/dist/chunk-778h8815.js +0 -26
  63. package/dist/chunk-89j9pm90.js +0 -24
  64. package/dist/chunk-8e0rv3j5.js +0 -41
  65. package/dist/chunk-8p98nt9v.js +0 -151
  66. package/dist/chunk-94vj1hjp.js +0 -1
  67. package/dist/chunk-c8cxeve8.js +0 -1
  68. package/dist/chunk-d61d6m07.js +0 -2
  69. package/dist/chunk-ebcmqx1k.js +0 -2
  70. package/dist/chunk-gsn659hw.js +0 -1
  71. package/dist/chunk-h79044h0.js +0 -3
  72. package/dist/chunk-kppxkh33.js +0 -1
  73. package/dist/chunk-ptt8s7nd.js +0 -6
  74. package/dist/chunk-qnh7np1s.js +0 -6
  75. package/dist/chunk-ran4gsmy.js +0 -1
  76. package/dist/chunk-swyvd7hd.js +0 -1
  77. package/dist/chunk-t9zdypqp.js +0 -2
  78. package/dist/chunk-x1khkevy.js +0 -1563
  79. package/dist/chunk-x24ddbhs.js +0 -6
  80. package/dist/chunk-x466sb8s.js +0 -34
  81. package/dist/web/assets/SettingsModal-aseVv-gp.js +0 -1
  82. package/dist/web/assets/index-9kl44E8k.js +0 -9
  83. package/dist/web/assets/index-CUVe9dGs.css +0 -1
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-2qckpa16.js";import"./chunk-zet4zjc3.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{Ha as a,Ia as b,Ja as c,Ka as d,La as e,Ma as f}from"./chunk-d61d6m07.js";import"./chunk-zet4zjc3.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,2 +0,0 @@
1
- var s={name:"blade-code",version:"0.7.7",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@anthropic-ai/sandbox-runtime":"0.0.67","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:s.name,version:s.version,description:s.description}}function n(){return s.version}function o(){return s.name}function c(){return s.description}function a(){return`v${s.version}`}function d(){return`v${s.version} © 2025 Blade Code`}
2
- export{r as Ha,n as Ia,o as Ja,c as Ka,a as La,d as Ma};
@@ -1,2 +0,0 @@
1
- import{aa as V}from"./chunk-9ad7tt9s.js";import{Bb as Q}from"./chunk-v61bja34.js";import{z as k}from"zod";var Y=k.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),K=k.array(k.string().trim().min(1).max(200)).max(128).transform((F)=>[...new Set(F)]),Z=k.object({description:k.string().trim().min(1).max(4096),prompt:k.string().trim().min(1).max(1e5),tools:K.optional(),disallowedTools:K.optional(),model:k.string().trim().min(1).max(200).optional(),permissionMode:k.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"]).optional(),maxTurns:k.number().int().positive().max(Q).optional(),isolation:k.enum(["none","worktree"]).optional()}).strict();function y(F){let w;try{w=JSON.parse(F)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([B,W])=>{if(!Y.safeParse(B).success)throw Error(`Invalid --agents name "${B}": use letters, numbers, hyphens, or underscores`);let I=Z.safeParse(W);if(!I.success)throw Error(`Invalid --agents definition for "${B}"`);let q=I.data;return{name:B,description:q.description,systemPrompt:q.prompt,tools:q.tools,disallowedTools:q.disallowedTools,model:q.model,permissionMode:q.permissionMode===void 0?void 0:V(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{y};
@@ -1 +0,0 @@
1
- import{v as a,w as b,x as c}from"./chunk-x24ddbhs.js";import"./chunk-ebcmqx1k.js";import"./chunk-9ad7tt9s.js";import"./chunk-89j9pm90.js";import"./chunk-778h8815.js";import"./chunk-2n8a87ds.js";import"./chunk-v61bja34.js";import"./chunk-h79044h0.js";import"./chunk-zet4zjc3.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,3 +0,0 @@
1
- import{_b as F}from"./chunk-zet4zjc3.js";import{appendFileSync as R,existsSync as x,mkdirSync as m,readdirSync as C,statSync as z,unlinkSync as V}from"node:fs";import $ from"node:path";import{execSync as A}from"node:child_process";import*as _ from"node:os";import*as M from"node:path";function B(q){return M.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function f(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function X(q){let G=B(q);return M.join(W(),"projects",G)}function N(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function Y(q){if(!N(q))throw Error(`Invalid session ID: ${q}`)}function u(q,G){return Y(G),M.join(X(q),`${G}.jsonl`)}function P(q,G){return Y(G),M.join(X(q),`${G}.inbox.json`)}function h(q,G){return Y(G),M.join(X(q),`${G}.goal.json`)}function y(q){try{return A("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function W(){return process.env.BLADE_STORAGE_ROOT||M.join(_.homedir(),".blade")}async function p(){let{readdir:q}=await import("node:fs/promises");try{let G=M.join(W(),"projects");return(await q(G,{withFileTypes:!0})).filter((H)=>H.isDirectory()).map((H)=>H.name)}catch{return[]}}var E;((J)=>{J[J.DEBUG=0]="DEBUG";J[J.INFO=1]="INFO";J[J.WARN=2]="WARN";J[J.ERROR=3]="ERROR"})(E||={});var Z=null,k=null,w=!1;function n(q){if(Z!==q)Z=q}async function l(){}function b(){if(w)return k;w=!0;try{let q=$.join(W(),"logs");if(!x(q))m(q,{recursive:!0,mode:493});if(z(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return j(q,30),k=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function j(q,G){try{let K=C(q),H=Date.now(),J=G*24*60*60*1000;for(let T of K){if(!T.startsWith("blade-")||!T.endsWith(".log")&&!T.endsWith(".jsonl"))continue;let O=$.join(q,T);try{let U=z(O);if(H-U.mtimeMs>J)V(O)}catch(U){}}}catch(K){}}function D(){let q=b();if(!q)return null;let G=Z||"default";return $.join(q,`blade-${G}.jsonl`)}function v(q,G,K){let H=D();if(!H)return;try{let J={timestamp:new Date().toISOString(),level:E[G],category:q,message:K};R(H,JSON.stringify(J)+`
2
- `)}catch(J){}}class Q{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(Q.globalDebugConfig!==null)this.enabled=Boolean(Q.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){Q.globalDebugConfig=q}static clearGlobalDebug(){Q.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((J)=>J.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((H)=>H.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((K)=>G.includes(K.toLowerCase()));return!q.categories.some((K)=>G.includes(K.toLowerCase()))}shouldLogToConsole(q){if(Q.globalDebugConfig!==null){let{enabled:G,filter:K}=this.parseDebugFilter(Q.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(K)}return this.enabled&&q>=this.minLevel}log(q,...G){let K=G.map((H)=>typeof H==="object"?JSON.stringify(H):String(H)).join(" ");if(v(this.category,q,K),this.shouldLogToConsole(q)){let H=E[q],J=`[${this.category}] [${H}]`;console.error(J,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function i(q,G){return new Q({...G,category:q})}var a=new Q({category:"General"});
3
- export{f as Lb,X as Mb,N as Nb,Y as Ob,u as Pb,P as Qb,h as Rb,y as Sb,W as Tb,p as Ub,n as Vb,l as Wb,Q as Xb,i as Yb,a as Zb};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-yyw9bbfd.js";import"./chunk-d61d6m07.js";import"./chunk-zet4zjc3.js";export{a as globalOptions,b as cliConfig};
@@ -1,6 +0,0 @@
1
- import{p as A,q as E,r as N,s as f}from"./chunk-c6rtexw1.js";import{t as D}from"./chunk-yyw9bbfd.js";import{v as L,w as _,x}from"./chunk-x24ddbhs.js";import{y as B}from"./chunk-ebcmqx1k.js";import{K as $,S as b}from"./chunk-x1khkevy.js";import"./chunk-9ad7tt9s.js";import"./chunk-x466sb8s.js";import"./chunk-60se4kxq.js";import"./chunk-89j9pm90.js";import"./chunk-778h8815.js";import"./chunk-d61d6m07.js";import{_a as Z}from"./chunk-54vk4tw8.js";import"./chunk-6y58y4rx.js";import"./chunk-8e0rv3j5.js";import"./chunk-2n8a87ds.js";import{Ab as T,zb as Y}from"./chunk-v61bja34.js";import"./chunk-0y895nft.js";import"./chunk-h79044h0.js";import"./chunk-zet4zjc3.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
- `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
- `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
- `);else F.stdout.write(`${H}
5
- `);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
6
- `),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
@@ -1,6 +0,0 @@
1
- import{p as d,q as u,r as m,s as l}from"./chunk-c6rtexw1.js";import{t as c}from"./chunk-yyw9bbfd.js";import{v as g,w as v,x as p}from"./chunk-x24ddbhs.js";import{y as z}from"./chunk-ebcmqx1k.js";import{K as C,O as E,P as S,R as W,S as h}from"./chunk-x1khkevy.js";import"./chunk-9ad7tt9s.js";import"./chunk-x466sb8s.js";import"./chunk-60se4kxq.js";import"./chunk-89j9pm90.js";import"./chunk-778h8815.js";import"./chunk-d61d6m07.js";import{_a as y}from"./chunk-54vk4tw8.js";import"./chunk-6y58y4rx.js";import"./chunk-8e0rv3j5.js";import"./chunk-2n8a87ds.js";import{Ab as x,Bb as F,zb as w}from"./chunk-v61bja34.js";import"./chunk-0y895nft.js";import"./chunk-h79044h0.js";import"./chunk-zet4zjc3.js";import Aq from"yargs";import{hideBin as Mq}from"yargs/helpers";import{z as X}from"zod";import{z as Y}from"zod";var k=1,_=Y.object({event_version:Y.literal(k)}),e=_.extend({type:Y.literal("content_delta"),delta:Y.string()}),t=_.extend({type:Y.literal("thinking_delta"),delta:Y.string()}),qq=_.extend({type:Y.literal("thinking"),content:Y.string()}),Qq=_.extend({type:Y.literal("stream_end")}),Yq=_.extend({type:Y.literal("content"),content:Y.string()}),Zq=_.extend({type:Y.literal("tool_start"),tool_name:Y.string(),summary:Y.string(),target:Y.string().optional(),tool_kind:Y.enum(["readonly","write","execute"]).optional()}),$q=_.extend({type:Y.literal("tool_result"),tool_name:Y.string(),summary:Y.string(),target:Y.string().optional(),tool_kind:Y.enum(["readonly","write","execute"]).optional(),success:Y.boolean().optional(),error_type:Y.string().optional(),error_message:Y.string().optional()}),Gq=_.extend({type:Y.literal("phase"),phase:Y.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y.enum(["ongoing","hit","done"]),message:Y.string(),turn:Y.number().optional(),tool_name:Y.string().optional(),target:Y.string().optional()}),Xq=_.extend({type:Y.literal("tool_detail"),tool_name:Y.string(),detail:Y.string()}),Uq=_.extend({type:Y.literal("task_update"),tasks:Y.array(W)}),Kq=_.extend({type:Y.literal("token_usage"),input_tokens:Y.number(),output_tokens:Y.number(),total_tokens:Y.number(),max_context_tokens:Y.number()}),Vq=_.extend({type:Y.literal("compacting"),state:Y.enum(["started","completed"])}),bq=_.extend({type:Y.literal("turn_limit"),turns_count:Y.number(),action:Y.literal("continue")}),Dq=_.extend({type:Y.literal("output"),content:Y.string(),exit_code:Y.number()}),_q=_.extend({type:Y.literal("error"),message:Y.string()}),wq=Y.discriminatedUnion("type",[e,t,qq,Qq,Yq,Zq,$q,Gq,Xq,Uq,Kq,Vq,bq,Dq,_q]);function H(Q,$){return{event_version:k,type:Q,...$}}function Rq(Q){if(Q?.signal)return{signal:Q.signal,dispose:()=>{return}};let $=new AbortController,G=()=>$.abort("interrupt");return process.once("SIGINT",G),process.once("SIGTERM",G),{signal:$.signal,dispose:()=>{process.removeListener("SIGINT",G),process.removeListener("SIGTERM",G)}}}var jq=X.enum(["text","jsonl"]),fq=X.object({headless:X.boolean().optional(),message:X.string().optional(),_:X.array(X.union([X.string(),X.number()])).optional(),model:X.string().optional(),systemPrompt:X.string().optional(),appendSystemPrompt:X.string().optional(),maxTurns:X.number().int().max(F).refine((Q)=>Q===-1||Q>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:X.nativeEnum(w).optional(),mcpConfig:X.array(X.string()).optional(),strictMcpConfig:X.boolean().optional(),sessionId:X.string().optional(),allowedTools:X.array(X.string()).optional(),disallowedTools:X.array(X.string()).optional(),agents:X.string().optional(),continue:X.boolean().optional(),resume:X.union([X.string(),X.boolean()]).optional(),forkSession:X.boolean().optional(),outputFormat:jq.optional()});class i{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Q){this.openedThinking=Q}hasOpenThinking(){return this.openedThinking}completeStream(){let Q={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Q}}function Bq(Q){return Q.issues.map(($)=>`${$.path.join(".")||"options"}: ${$.message}`).join("; ")}function Iq(Q){let $=fq.safeParse(Q);if(!$.success)throw Error(`Invalid headless options: ${Bq($.error)}`);return $.data}function Jq(Q){return Q.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",($)=>$.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async($)=>{if(!$.headless)return;let G=await kq($);process.exit(G)})}function A(Q,$=""){Q.write(`${$}
2
- `)}function Pq(Q){return`[task] [${Q.status}] ${Q.subject}`}function Lq(){return{requestConfirmation:async(Q)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function xq(Q){if(!(Q instanceof Error))return"Unknown error";let q=Q.lastError??Q;if(q.responseBody)try{let V=JSON.parse(q.responseBody)?.error?.message;if(V)return q.statusCode?`${V} (HTTP ${q.statusCode})`:V}catch{}let Z=Q.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return Q.message}function Nq(Q){return Q==="jsonl"?"jsonl":"text"}function T(Q,$){let G=(...q)=>{for(let Z of q){let b=$[Z];if(typeof b==="string"&&b.trim()!=="")return b}return};switch(Q){case"Read":case"Edit":case"Write":case"UndoEdit":return G("file_path");case"NotebookEdit":return G("notebook_path");case"Grep":return G("path","pattern");case"Glob":return G("pattern");case"WebFetch":return G("url");case"WebSearch":return G("query");case"Bash":return G("command","description");case"Task":return G("description");case"LSP":return G("filePath","operation");case"EnterWorktree":return G("name");case"ExitWorktree":return G("action");default:return}}function Wq(Q,$,G,q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),b=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Q)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${$}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:G?`Working within target: ${$}`:`Executing: ${$}`,shouldLockTarget:!1};if(Z.has(Q))return{phase:"searching",status:"ongoing",message:`Still searching: ${$}`,shouldLockTarget:!1};if(b.has(Q))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${$}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${$}`,shouldLockTarget:!1}}function O(Q,$){let G=(q,Z)=>{Q.stdout.write(`${JSON.stringify(H(q,Z))}
3
- `)};return{contentDelta(q){if($==="jsonl"){G("content_delta",{delta:q});return}Q.stdout.write(q)},thinkingDelta(q,Z){if($==="jsonl")return G("thinking_delta",{delta:q}),Z;if(!Z)Q.stderr.write("[thinking] ");return Q.stderr.write(q),!0},thinking(q){if($==="jsonl"){G("thinking",{content:q});return}A(Q.stderr,`[thinking] ${q}`)},streamEnd(q,Z){if($==="jsonl"){G("stream_end",{});return}if(Z)Q.stderr.write(`
4
- `);if(q)Q.stdout.write(`
5
- `)},content(q){if($==="jsonl"){G("content",{content:q});return}A(Q.stdout,q)},toolStart(q,Z,b,V){if($==="jsonl"){G("tool_start",{tool_name:q,summary:Z,target:b,tool_kind:V});return}A(Q.stderr,`[tool:start] ${Z}`)},toolResult(q,Z,b,V,M){if($==="jsonl"){G("tool_result",{tool_name:q,summary:Z,target:b,tool_kind:V,success:M?.success,error_type:M?.errorType,error_message:M?.errorMessage});return}A(Q.stderr,`[tool:result] ${Z}`)},phase(q,Z,b,V={}){if($==="jsonl"){G("phase",{phase:q,status:Z,message:b,turn:V.turn,tool_name:V.toolName,target:V.target});return}A(Q.stderr,`[phase:${q}] ${b}`)},toolDetail(q,Z){if($==="jsonl"){G("tool_detail",{tool_name:q,detail:Z});return}A(Q.stderr,Z)},taskUpdate(q){if($==="jsonl"){G("task_update",{tasks:q});return}for(let Z of q)A(Q.stderr,Pq(Z))},tokenUsage(q){if($==="jsonl"){G("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens});return}A(Q.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){if($==="jsonl"){G("compacting",{state:q?"started":"completed"});return}A(Q.stderr,q?"[context] compacting started":"[context] compacting completed")},turnLimit(q){if($==="jsonl"){G("turn_limit",{turns_count:q,action:"continue"});return}A(Q.stderr,`[turn-limit] continuing after ${q} turns`)},output(q,Z=0){if($==="jsonl"){G("output",{content:q,exit_code:Z});return}A(Z===0?Q.stdout:Q.stderr,q)},error(q){if($==="jsonl"){G("error",{message:q});return}A(Q.stderr,q)}}}async function kq(Q,$={stdout:process.stdout,stderr:process.stderr},G){let q="text",Z=O($,q),b=new i,V={targetLocked:!1},M,R=Rq(G);try{let K=Iq(Q);q=Nq(K.outputFormat),Z=O($,q),await d();let n=await u(K),j=await m(n);if(j.mode==="output"){if(j.content)Z.output(j.content,j.exitCode??0);return j.exitCode??0}let N=K.permissionMode??"yolo",{sessionId:P,messages:r}=await l({sessionId:K.sessionId,continue:K.continue,resume:K.resume,forkSession:K.forkSession,fallbackSessionPrefix:"headless"}),s={messages:[...r],userId:"cli-user",sessionId:P,workspaceRoot:x(),permissionMode:N,signal:R.signal,confirmationHandler:Lq()};M=await C.create({sessionId:P,workspaceRoot:x(),modelId:K.model,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig,agents:K.agents?z(K.agents):void 0});let o=K.maxTurns??M.getConfig().maxTurns,a=await h.createWithRuntime(M,{sessionId:P,systemPrompt:K.systemPrompt,appendSystemPrompt:K.appendSystemPrompt,maxTurns:K.maxTurns,modelId:K.model,permissionMode:N,toolWhitelist:K.allowedTools,toolBlacklist:K.disallowedTools,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig}),L=await y(a.chatStream(j.content,s,{stream:!0,signal:R.signal,maxTurns:K.maxTurns,...o===-1?{onTurnLimitReached:async(D)=>{return Z.turnLimit(D.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(D)=>{switch(D.kind){case"content_delta":b.markAssistantContent(),Z.contentDelta(D.delta);break;case"thinking_delta":b.setThinkingOpened(Z.thinkingDelta(D.delta,b.hasOpenThinking()));break;case"stream_end":{let U=b.completeStream();Z.streamEnd(U.wroteAssistantContent,U.openedThinking);break}case"tool_start":{let U=D.toolCall;if(!("function"in U))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(U.function.name))break;try{let f=JSON.parse(U.function.arguments),B=E(U.function.name,f),I=T(U.function.name,f),J=Wq(U.function.name,B,I,V);if(J.shouldLockTarget)V.targetLocked=!0;Z.phase(J.phase,J.status,J.message,{toolName:U.function.name,target:I}),Z.toolStart(U.function.name,B,I,D.toolKind)}catch{Z.phase(V.targetLocked?"executing":"searching",V.targetLocked?"hit":"ongoing",V.targetLocked?`Working within target: ${U.function.name}`:`Still searching: ${U.function.name}`,{toolName:U.function.name}),Z.toolStart(U.function.name,U.function.name,void 0,D.toolKind)}break}case"tool_result":{let U=D.toolCall;if(!("function"in U))break;let f;try{let I=JSON.parse(U.function.arguments);f=T(U.function.name,I)}catch{f=void 0}let B=S(U.function.name,D.result);if(Z.toolResult(U.function.name,B.summary,f,void 0,{success:D.result.success,errorType:D.result.error?.type,errorMessage:D.result.error?.message}),B.detail)Z.toolDetail(U.function.name,B.detail);break}case"token_usage":Z.tokenUsage(D.usage);break;case"compaction":Z.compacting(D.phase==="start");break;case"task_update":Z.taskUpdate(D.tasks);break;case"steering_applied":case"follow_up_started":case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":break;case"model_fallback":break;case"turn_start":if(D.turn===1)V.targetLocked=!1;Z.phase("turn",V.targetLocked?"hit":"ongoing",`Turn ${D.turn} started`,{turn:D.turn});break;default:{let U=D}}});if(L.metadata?.outputTruncated)Z.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!L.success)return Z.error(`Error: ${L.error?.message??"Agent execution failed"}`),1;return Z.phase("completed","done","Headless run completed"),0}catch(K){if(b.hasOpenThinking()&&q==="text")$.stderr.write(`
6
- `);return Z.error(`Error: ${xq(K)}`),1}finally{try{await M?.dispose()}finally{R.dispose()}}}async function rq(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:G,"output-format":q,"system-prompt":Z,"append-system-prompt":b,"max-turns":V,...M}=c,R=Aq(Mq(process.argv)).scriptName("blade").strict(!1).options(M).middleware([v,g,p]);return Jq(R),await R.parse(),!0}export{kq as runHeadless,rq as handleHeadlessMode,fq as HeadlessOptionsSchema};
@@ -1 +0,0 @@
1
- import{Kb as a}from"./chunk-0y895nft.js";import"./chunk-h79044h0.js";import"./chunk-zet4zjc3.js";export{a as createChatServiceAsync};
@@ -1 +0,0 @@
1
- import{Aa as k,Ba as l,Ca as m,qa as a,ra as b,sa as c,ta as d,ua as e,va as f,wa as g,xa as h,ya as i,za as j}from"./chunk-89j9pm90.js";import"./chunk-778h8815.js";import"./chunk-2n8a87ds.js";import"./chunk-v61bja34.js";import"./chunk-h79044h0.js";import"./chunk-zet4zjc3.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
@@ -1,2 +0,0 @@
1
- import{j as Z0,k as U0}from"./chunk-4n7fsts0.js";import{$ as _0,A as b0,C as sx,D as wx,E as mx,G as ex,H as P,K as x0,L as Qx,M as q,N as l,P as $0,Q as V0,S as M0}from"./chunk-x1khkevy.js";import{ca as a}from"./chunk-x466sb8s.js";import{Ca as t,va as Vx,xa as Ix,ya as gx}from"./chunk-89j9pm90.js";import{Ia as Mx}from"./chunk-d61d6m07.js";import{Oa as X0,Qa as Nx,_a as Bx}from"./chunk-54vk4tw8.js";import{qb as rx}from"./chunk-6y58y4rx.js";import{ub as nx}from"./chunk-2n8a87ds.js";import{Ab as E}from"./chunk-v61bja34.js";import{Ob as ix,Yb as D}from"./chunk-h79044h0.js";import{_b as Lx}from"./chunk-zet4zjc3.js";var E$={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function m$($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{Hono as w$}from"hono";import{cors as y$}from"hono/cors";import{existsSync as D0,readFileSync as yx}from"node:fs";import{createServer as K$}from"node:http";import{networkInterfaces as z$}from"node:os";import{dirname as W$,extname as H$,join as s}from"node:path";import{fileURLToPath as C$}from"node:url";import{WebSocketServer as A$}from"ws";import{z as Ox}from"zod";class k extends Error{code;statusCode;constructor($,V,x=500){super(V);this.code=$;this.statusCode=x;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class L extends k{constructor($,V){super("NOT_FOUND",V?`${$} not found: ${V}`:`${$} not found`,404)}}class C extends k{constructor($){super("BAD_REQUEST",$,400)}}class xx extends k{constructor($){super("CONFLICT",$,409)}}class v extends k{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class c extends k{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var p$=Ox.object({error:Ox.object({code:Ox.string(),message:Ox.string()})});import{Hono as E0}from"hono";import{z as $x}from"zod";var Wx=D("Service"),m0=$x.object({updates:$x.record($x.any()),options:$x.object({scope:$x.enum(["local","project","global"]).optional(),immediate:$x.boolean().optional()}).optional()}),Sx=()=>{let $=new E0;return $.get("/",async(V)=>{try{let x=Vx();return V.json(x||{})}catch(x){return Wx.error("[ConfigRoutes] Failed to get config:",x),V.json({})}}),$.put("/",async(V)=>{try{let x=await V.req.json(),M=m0.safeParse(x);if(!M.success)throw new C("Invalid config update format");let{updates:G,options:U}=M.data;return await t().updateConfig(G,U),V.json({success:!0,updates:G})}catch(x){throw Wx.error("[ConfigRoutes] Failed to update config:",x),x}}),$.get("/permissions",async(V)=>{try{let x=Vx();return V.json(x?.permissions||{})}catch(x){return Wx.error("[ConfigRoutes] Failed to get permissions:",x),V.json({})}}),$};import{Hono as L0}from"hono";var kx=()=>{let $=new L0;return $.get("/health",(V)=>{return V.json({healthy:!0,version:Mx()})}),$.get("/info",(V)=>{return V.json({version:Mx(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:E()})}),$};import{Hono as h0}from"hono";var Jx=D("Service"),Rx=()=>{let $=new h0;return $.get("/",async(V)=>{try{let M=a.getInstance().getAllServers(),G=Array.from(M.entries()).map(([U,J])=>({id:U,name:U,status:J.status==="connected"?"connected":J.status==="connecting"?"connecting":J.lastError?"error":"offline",endpoint:J.config.command?`${J.config.command} ${(J.config.args||[]).join(" ")}`.trim():J.config.url||"Unknown",description:`MCP server: ${U}`,tools:J.tools.map((b)=>b.name),connectedAt:J.connectedAt?.toISOString(),error:J.lastError?.message}));return V.json(G)}catch(x){return Jx.error("[McpRoutes] Failed to get MCP servers:",x),V.json([])}}),$.post("/:name/connect",async(V)=>{try{let x=V.req.param("name");return await a.getInstance().connectServer(x),V.json({success:!0})}catch(x){return Jx.error("[McpRoutes] Failed to connect MCP server:",x),V.json({success:!1,error:x.message},500)}}),$.post("/:name/disconnect",async(V)=>{try{let x=V.req.param("name");return await a.getInstance().disconnectServer(x),V.json({success:!0})}catch(x){return Jx.error("[McpRoutes] Failed to disconnect MCP server:",x),V.json({success:!1,error:x.message},500)}}),$.delete("/:name",async(V)=>{try{let x=V.req.param("name");await a.getInstance().unregisterServer(x);let G=Vx();if(G?.mcpServers){let{[x]:U,...J}=G.mcpServers;await t().updateConfig({mcpServers:J})}return V.json({success:!0})}catch(x){return Jx.error("[McpRoutes] Failed to delete MCP server:",x),V.json({success:!1,error:x.message},500)}}),$.post("/",async(V)=>{try{let x=await V.req.json(),{name:M,config:G}=x;if(!M||!G)return V.json({success:!1,error:"Missing name or config"},400);await a.getInstance().registerServer(M,G);let J=Vx();return await t().updateConfig({mcpServers:{...J?.mcpServers,[M]:G}}),V.json({success:!0})}catch(x){return Jx.error("[McpRoutes] Failed to add MCP server:",x),V.json({success:!1,error:x.message},500)}}),$};import{Hono as p0}from"hono";var Xx=D("Service"),vx=()=>{let $=new p0;return $.get("/",async(V)=>{try{let x=Ix(),M=gx();return V.json({configured:x,current:M})}catch(x){return Xx.error("[ModelsRoutes] Failed to get models:",x),V.json({configured:[],current:null})}}),$.post("/",async(V)=>{try{let x=await V.req.json(),{provider:M,name:G,model:U,baseUrl:J,apiKey:b}=x;if(!U)throw new C("model is required");let _=await t().addModel({provider:M||"openai-compatible",name:G||U,model:U,baseUrl:J||void 0,apiKey:b||void 0});return V.json({success:!0,model:_})}catch(x){throw Xx.error("[ModelsRoutes] Failed to add model:",x),x}}),$.put("/:modelId",async(V)=>{try{let x=V.req.param("modelId"),M=await V.req.json(),{baseUrl:G,apiKey:U,model:J}=M;return await t().updateModel(x,{baseUrl:G||void 0,apiKey:U||void 0,model:J||void 0}),V.json({success:!0})}catch(x){throw Xx.error("[ModelsRoutes] Failed to update model:",x),x}}),$.delete("/:modelId",async(V)=>{try{let x=V.req.param("modelId");return await t().removeModel(x),V.json({success:!0})}catch(x){throw Xx.error("[ModelsRoutes] Failed to delete model:",x),x}}),$};import{Hono as x$}from"hono";import{z as g}from"zod";import ax from"node:path";import{Mutex as I0}from"async-mutex";import{Hono as g0}from"hono";import{streamSSE as v0}from"hono/streaming";import{LRUCache as u0}from"lru-cache";import{nanoid as jx}from"nanoid";import{z as F}from"zod";import{z as f}from"zod";var ux=f.enum(["default","autoEdit","yolo","plan"]);var Hx=f.enum(["user","assistant","system","tool"]),lx=f.union([f.object({type:f.literal("text"),text:f.string()}),f.object({type:f.literal("image_url"),image_url:f.object({url:f.string()})})]),fV=f.object({id:f.string(),role:Hx,content:f.union([f.string(),f.array(lx)]),timestamp:f.number(),metadata:f.record(f.unknown()).optional(),thinkingContent:f.string().optional(),tool_call_id:f.string().optional(),name:f.string().optional(),tool_calls:f.unknown().optional()}),P0=f.object({sessionId:f.string(),projectPath:f.string(),title:f.string().optional(),gitBranch:f.string().optional(),rootId:f.string(),parentId:f.string().optional(),relationType:f.enum(["subagent","fork"]).optional(),messageCount:f.number(),firstMessageTime:f.string(),lastMessageTime:f.string(),hasErrors:f.boolean()}),GV=f.object({version:f.literal(1),sessionId:f.string(),goalId:f.string(),objective:f.string(),status:f.enum(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:f.number().optional(),tokensUsed:f.number(),timeUsedSeconds:f.number(),continuationCount:f.number(),statusReason:f.string().optional(),createdAt:f.string(),updatedAt:f.string()}),dx=f.object({role:Hx,content:f.union([f.string(),f.array(lx)]),metadata:f.unknown().optional(),reasoningContent:f.string().optional(),thinkingContent:f.string().optional(),tool_call_id:f.string().optional(),name:f.string().optional(),tool_calls:f.unknown().optional()}),YV=f.object({session:P0,messages:f.array(dx)}),cx=f.enum(["conversation","code","both"]),S0=f.object({messageId:f.string(),preview:f.string(),createdAt:f.string(),fileCount:f.number().int().nonnegative()}),ox=f.object({targetMessageId:f.string().min(1),mode:cx.default("conversation")}),JV=f.object({checkpoint:S0,mode:cx,removedTurns:f.number().int().positive(),restoredFiles:f.array(f.string()),messages:f.array(dx)}),QV=f.object({sessionId:f.string(),projectPath:f.string()}),ZV=f.object({type:f.string(),properties:f.record(f.unknown())}),tx=f.object({content:f.string(),projectPath:f.string().optional(),permissionMode:ux.optional(),attachments:f.array(f.object({type:f.enum(["file","image","url"]),path:f.string().optional(),url:f.string().optional(),content:f.string().optional(),mimeType:f.string().optional(),name:f.string().optional()})).optional()}),UV=f.object({messageId:f.string(),role:Hx,content:f.string(),timestamp:f.string()}),OV=f.object({approved:f.boolean(),remember:f.boolean().optional(),scope:f.enum(["once","session","project"]).optional(),targetMode:ux.optional(),feedback:f.string().optional(),answers:f.record(f.union([f.string(),f.array(f.string())])).optional()}),XV=f.object({id:f.string(),name:f.string(),provider:f.string(),model:f.string(),baseUrl:f.string().optional(),apiKey:f.string().optional(),maxContextTokens:f.number().optional()}),TV=f.enum(["vs-dark","vs-light","hc-black"]),k0=f.enum(["light","dark","system"]),R0=f.object({language:f.string(),theme:f.string(),uiTheme:k0,autoSaveSessions:f.boolean(),notifyBuild:f.boolean(),notifyErrors:f.boolean(),notifySounds:f.boolean(),privacyTelemetry:f.boolean(),privacyCrash:f.boolean()}),NV=R0.partial();var B=D("Service"),l0=F.object({title:F.string().optional(),projectPath:F.string().optional()}),d0=tx,c0=F.object({title:F.string().optional(),projectPath:F.string().optional()}),o0=F.object({projectPath:F.string()}),t0=F.object({objective:F.string().min(1),tokenBudget:F.number().int().positive().optional(),permissionMode:F.enum(["default","autoEdit","plan","yolo"]).optional()}),a0=F.discriminatedUnion("action",[F.object({action:F.literal("pause")}),F.object({action:F.literal("resume")}),F.object({action:F.literal("edit"),objective:F.string().min(1)})]),p=new Map,h=new u0({max:100,ttl:1800000,dispose:($,V)=>{if($.status==="running"||$.status==="waiting_permission")$.abortController.abort(),B.debug(`[SessionRoutes] Run ${V} disposed due to cache eviction`)}});function i0($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function Tx($,V="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let x=$.pendingPermission;return $.pendingPermission=void 0,x?.resolve({approved:!1,reason:rx}),$.abortController.abort(V),$.status="cancelled",l.publish(i0($),"run.cancelled",{runId:$.id}),!0}function j0($,V=!1){let{permissionId:x,details:M}=$;if(M.type==="askUserQuestion"&&M.questions)return{type:"question.required",properties:{requestId:x,toolCallId:x,questions:M.questions,details:M,...V?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:M.toolName,description:M.message,args:M.args,details:M,...V?{replayed:!0}:{}}}}function n0(){for(let $ of h.values())Tx($,"route-reset");h.clear(),p.clear()}var r0=($)=>{if(!$||typeof $!=="object")return $;let V={...$},x=200000;if(typeof V.oldContent==="string"&&V.oldContent.length>x)delete V.oldContent;if(typeof V.newContent==="string"&&V.newContent.length>x)delete V.newContent;return V};function Dx($,V="projectPath"){if(!ax.isAbsolute($))throw new C(`${V} must be absolute`);return ax.resolve($)}function f0($){try{ix($)}catch(V){throw new C(V instanceof Error?V.message:`Invalid session ID: ${$}`)}}function I($){return{sessionId:$.id,projectPath:$.projectPath}}function Cx($,V){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,messages:V}}function Ax($){return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function u($,V){if(f0($),V!==void 0){let M=Qx({sessionId:$,projectPath:Dx(V)});if(p.has(q(M)))return M;let G=await P.findSessionMetadata(M.sessionId,M.projectPath);if(!G)throw new L("Session",$);return Qx({sessionId:G.sessionId,projectPath:G.projectPath})}let x=new Map;for(let M of p.values()){if(M.id!==$)continue;let G=I(M);x.set(q(G),G)}for(let M of await P.listSessions()){if(M.sessionId!==$)continue;let G=Qx({sessionId:M.sessionId,projectPath:M.projectPath});x.set(q(G),G)}if(x.size===0)try{let M=await P.findSessionMetadata($);if(!M)throw new L("Session",$);return Qx({sessionId:M.sessionId,projectPath:M.projectPath})}catch(M){if(M instanceof L)throw M;if(M instanceof Error&&M.message.startsWith("Ambiguous session ID:"))throw new v;throw M}if(x.size>1)throw new v;return x.values().next().value}function qx($){if(typeof $==="string")return $;return $.filter((V)=>V.type==="text").map((V)=>V.text).join(`
2
- `)}function s0($,V){let x=(V??[]).filter((G)=>G.type==="image"&&typeof G.content==="string").map((G)=>({type:"image_url",image_url:{url:G.content}}));if(x.length===0)return $;let M=[];if($.trim())M.push({type:"text",text:$});return M.push(...x),M}var G0=()=>{n0();let $=new g0;$.onError((j,Z)=>{if(j instanceof k)return Z.json(j.toObject(),j.statusCode);return B.error("[SessionRoutes] Unhandled route error:",j),Z.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let V=new Map,x=new Map,M=new Map,G=new Map,U=(j)=>{let Z=q(j),Y=G.get(Z);if(!Y)Y=new I0,G.set(Z,Y);return Y},J=async(j)=>{let Z=q(I(j)),Y=V.get(Z);if(Y)return Y;let Q=x.get(Z);if(!Q)Q=x0.create({sessionId:j.id,workspaceRoot:j.projectPath}),x.set(Z,Q);try{let O=await Q;return V.set(Z,O),O}finally{if(x.get(Z)===Q)x.delete(Z)}},b=async(j)=>{let Z=q(j),Y=p.get(Z);if(Y)return Y;let Q=M.get(Z);if(!Q)Q=(async()=>{let O=await P.findSessionMetadata(j.sessionId,j.projectPath);if(!O)throw new L("Session",j.sessionId);let T=Cx(O,await P.loadSession(j.sessionId,j.projectPath));return p.set(Z,T),T})(),M.set(Z,Q);try{return await Q}finally{if(M.get(Z)===Q)M.delete(Z)}},_=async(j,Z)=>{return b(await u(j,Z))},X=(j,Z,Y,Q={})=>{let O=jx(12),T={id:O,sessionId:j.id,projectPath:j.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return h.set(O,T),j.currentRunId=O,T.completion=e0(T,j,Z,Y,J,{pendingInputOnly:Q.pendingInputOnly,preparedInputTurn:Q.preparedInputTurn,goalContinuationOnly:Q.goalContinuationOnly}).catch((N)=>{B.error(`[SessionRoutes] Run ${O} failed:`,N)}),T},y=async(j)=>{let Z=j.currentRunId?h.get(j.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return;let Y=await J(j),Q=j.currentRunId?h.get(j.currentRunId):void 0;if(Q&&(Q.status==="running"||Q.status==="waiting_permission"))return;let O=Y.getPendingSteeringCount()>0,N=(O?null:await Y.getGoal())?.status==="active";if(!O&&!N||Y.hasTurnOwner())return;X(j,"","default",{pendingInputOnly:O,goalContinuationOnly:N})};return $.get("/",async(j)=>{try{let Z=await P.listSessions(),Y=new Set(Z.filter((H)=>H.relationType==="subagent").map((H)=>q({sessionId:H.sessionId,projectPath:H.projectPath}))),Q=Array.from(p.values()).filter((H)=>!Y.has(q(I(H)))&&H.relationType!=="subagent").map((H)=>Ax(H)),O=new Set(Q.map((H)=>q({sessionId:H.sessionId,projectPath:H.projectPath}))),T=Z.filter((H)=>{if(H.relationType==="subagent")return!1;return!O.has(q({sessionId:H.sessionId,projectPath:H.projectPath}))}),N=new Set(O),K=T.filter((H)=>{let A=q({sessionId:H.sessionId,projectPath:H.projectPath});if(N.has(A))return!1;return N.add(A),!0}),W=[...Q,...K];return j.json(W)}catch(Z){throw B.error("[SessionRoutes] Failed to list sessions:",Z),new c("Failed to list sessions")}}),$.post("/",async(j)=>{try{let Z=await j.req.json(),Y=l0.safeParse(Z);if(!Y.success)throw new C("Invalid request body");let{title:Q,projectPath:O}=Y.data,T=nx("web",12),N=Dx(O||j.get("directory")||E(),O?"projectPath":"directory"),K=await P.createSessionMetadata(T,N,{title:Q}),W=Cx(K,[]);return p.set(q(I(W)),W),j.json({...Ax(W),status:void 0,agentType:void 0,model:void 0})}catch(Z){if(B.error("[SessionRoutes] Failed to create session:",Z),Z instanceof C)throw Z;throw new c("Failed to create session")}}),$.post("/:sessionId/fork",async(j)=>{let Z=j.req.param("sessionId");try{f0(Z);let Y=await j.req.json(),Q=o0.safeParse(Y);if(!Q.success)throw new C("Invalid request body");let O=Dx(Q.data.projectPath),T=await P.findSessionMetadata(Z,O);if(!T)throw new L("Session",Z);let N=await P.forkSession(Z,{sourceProjectPath:T.projectPath,targetProjectPath:T.projectPath}),K=Cx(N.metadata,N.messages);return p.set(q(I(K)),K),j.json({session:N.metadata,messages:N.messages},201)}catch(Y){if(Y instanceof C||Y instanceof L||Y instanceof xx)throw Y;if(Y instanceof ex)throw new xx("Session has no durable creation record");throw B.error("[SessionRoutes] Failed to fork session:",Y),new c("Failed to fork session")}}),$.get("/:sessionId",async(j)=>{let Z=j.req.param("sessionId");try{let Y=await u(Z,j.req.query("projectPath")),Q=p.get(q(Y));if(Q)return j.json(Ax(Q));let O=await P.findSessionMetadata(Y.sessionId,Y.projectPath);if(!O)throw new L("Session",Z);return j.json(O)}catch(Y){if(Y instanceof C||Y instanceof L||Y instanceof v)throw Y;throw B.error("[SessionRoutes] Failed to get session:",Y),new c("Failed to get session")}}),$.patch("/:sessionId",async(j)=>{let Z=j.req.param("sessionId");try{let Y=await j.req.json(),Q=c0.safeParse(Y);if(!Q.success)throw new C("Invalid request body");if(Q.data.title===void 0)throw new C("title is required");let O=await u(Z,Q.data.projectPath),T=await P.updateSessionMetadata(O.sessionId,O.projectPath,{title:Q.data.title}),N=p.get(q(O));if(N)N.title=T.title??N.title,N.updatedAt=new Date(T.lastMessageTime);return j.json({success:!0,title:T.title})}catch(Y){if(B.error("[SessionRoutes] Failed to update session:",Y),Y instanceof C||Y instanceof L||Y instanceof v)throw Y;throw new c("Failed to update session")}}),$.get("/:sessionId/rewind",async(j)=>{let Z=await _(j.req.param("sessionId"),j.req.query("projectPath")),Y=await J(Z);return j.json({checkpoints:await Y.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(j)=>{let Z=ox.safeParse(await j.req.json());if(!Z.success)throw new C("Invalid rewind request");let Y=await _(j.req.param("sessionId"),j.req.query("projectPath")),Q=I(Y);return U(Q).runExclusive(async()=>{let O=Y.currentRunId?h.get(Y.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))throw new xx("Cannot rewind while a run is active");let T=await J(Y),N;try{N=await T.rewindSession(Z.data)}catch(K){if(K instanceof Error&&K.message.startsWith("Cannot rewind while"))throw new xx(K.message);throw K}return Y.messages=[...N.messages],Y.updatedAt=new Date,l.publish(Q,"session.rewound",{targetMessageId:N.checkpoint.messageId,mode:N.mode,removedTurns:N.removedTurns,restoredFiles:N.restoredFiles,messages:N.messages}),j.json(N)})}),$.get("/:sessionId/goal",async(j)=>{let Z=await _(j.req.param("sessionId"),j.req.query("projectPath"));return j.json({goal:await new sx(Z.projectPath,Z.id).get()})}),$.put("/:sessionId/goal",async(j)=>{let Z=t0.safeParse(await j.req.json());if(!Z.success)throw new C("Invalid goal request");let Y=await _(j.req.param("sessionId"),j.req.query("projectPath")),Q=I(Y);return U(Q).runExclusive(async()=>{let O=Y.currentRunId?h.get(Y.currentRunId):void 0;if(O&&(O.status==="running"||O.status==="waiting_permission"))return j.json({status:"rejected",reason:"run_active"},409);let N=await(await J(Y)).createGoal(Z.data);l.publish(Q,"goal.updated",{goal:N});let K=Z.data.permissionMode??"default",W=X(Y,"",K,{goalContinuationOnly:!0});return j.json({status:"running",runId:W.id,goal:N},202)})}),$.patch("/:sessionId/goal",async(j)=>{let Z=a0.safeParse(await j.req.json());if(!Z.success)throw new C("Invalid goal update");let Y=await _(j.req.param("sessionId"),j.req.query("projectPath")),Q=I(Y);return U(Q).runExclusive(async()=>{let O=await J(Y),T;if(Z.data.action==="pause")T=await O.pauseGoal();else if(Z.data.action==="edit")T=await O.editGoal(Z.data.objective);else T=await O.resumeGoal();if(l.publish(Q,"goal.updated",{goal:T}),T.status==="active"&&(!Y.currentRunId||!["running","waiting_permission"].includes(h.get(Y.currentRunId)?.status??""))){let N=X(Y,"","default",{goalContinuationOnly:!0});return j.json({status:"running",runId:N.id,goal:T},202)}return j.json({status:T.status,goal:T})})}),$.delete("/:sessionId/goal",async(j)=>{let Z=await _(j.req.param("sessionId"),j.req.query("projectPath")),Y=I(Z),O=await(await J(Z)).clearGoal();if(O)l.publish(Y,"goal.cleared",{});return j.json({cleared:O})}),$.delete("/:sessionId",async(j)=>{let Z=j.req.param("sessionId"),Y=j.req.query("projectPath");try{let Q=await u(Z,Y),O=q(Q),T=p.get(O),N=V.get(O),K;if(T?.currentRunId){let W=h.get(T.currentRunId);if(W)Tx(W),await W.completion,K=W.id}if(N)await N.clearGoal().catch((W)=>{B.warn("[SessionRoutes] Failed to clear session goal:",W)});if(await P.deleteSession(Q.sessionId,Q.projectPath),K)h.delete(K);if(p.delete(O),M.delete(O),x.delete(O),G.delete(O),N){if(await N.dispose(),V.delete(O),V.size===0)await a.getInstance().disconnectAll()}return j.json({success:!0})}catch(Q){if(B.error("[SessionRoutes] Failed to delete session:",Q),Q instanceof C||Q instanceof L||Q instanceof v)throw Q;throw new c("Failed to delete session")}}),$.get("/:sessionId/message",async(j)=>{let Z=j.req.param("sessionId");try{let Y=await u(Z,j.req.query("projectPath")),Q=p.get(q(Y)),O=Q?.messages?Q.messages:await P.loadSession(Y.sessionId,Y.projectPath);return j.json(O)}catch(Y){if(B.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof C||Y instanceof L||Y instanceof v)throw Y;throw new c("Failed to get messages")}}),$.get("/:sessionId/events",async(j)=>{let Z=j.req.param("sessionId"),Y=await u(Z,j.req.query("projectPath")),Q=await b(Y);return v0(j,async(O)=>{let N,K,W=!1,H=()=>{if(K!==void 0)clearInterval(K),K=void 0;N?.(),N=void 0},A=()=>{if(W)return;W=!0,H()},w=new Set;O.onAbort(A),N=l.subscribe((z)=>{if(z.sessionId!==Y.sessionId||z.projectPath!==Y.projectPath)return;let d=z.properties.requestId;if((z.type==="permission.asked"||z.type==="question.required")&&typeof d==="string"){if(w.has(d))return;w.add(d)}O.writeSSE({data:JSON.stringify({type:z.type,properties:{...z.properties,sessionId:z.sessionId,projectPath:z.projectPath}})}).catch(A)});try{if(O.aborted||W)return;if(await O.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now()}})}).catch((m)=>{throw A(),m}),O.aborted||W)return;let d=(Q.currentRunId?h.get(Q.currentRunId):void 0)?.pendingPermission;if(d){w.add(d.permissionId);let m=j0(d,!0);await O.writeSSE({data:JSON.stringify({type:m.type,properties:{...m.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}y(Q).catch((m)=>{B.error(`[SessionRoutes] Failed to resume pending input for ${Z}:`,m)}),K=setInterval(()=>{if(!O.aborted)O.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(A)},15000);while(!O.aborted&&!W)await new Promise((m)=>setTimeout(m,1000))}finally{A()}})}),$.post("/:sessionId/message",async(j)=>{let Z=j.req.param("sessionId"),Y=await j.req.json(),Q=d0.safeParse(Y);if(!Q.success)throw new C("Invalid message format");let{content:O,attachments:T,permissionMode:N,projectPath:K}=Q.data,W=N||"default",H=s0(O,T),A=await _(Z,K??j.req.query("projectPath")),w=I(A);return U(w).runExclusive(async()=>{let z=A.currentRunId?h.get(A.currentRunId):void 0;if(z&&(z.status==="running"||z.status==="waiting_permission")){let R=await(await J(A)).enqueueSteering(H,{allowBeforeTurn:!0});if(!R.accepted)return j.json({status:"rejected",reason:R.reason??"turn_unavailable"},409);let e=R.messageId??jx(12),Ux=R.queued;l.publish(w,"message.created",{messageId:e,role:"user",content:qx(H)});let zx=R.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(l.publish(w,zx,{runId:z.id,messageId:e,queued:Ux}),R.delivery==="next_turn"&&z.status!=="running"&&z.status!=="waiting_permission")y(A).catch((F0)=>{B.error(`[SessionRoutes] Failed to wake queued follow-up for ${Z}:`,F0)});if(R.delivery==="next_turn")z.pendingFollowUpRequested=!0;return j.json({runId:z.id,messageId:e,status:R.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:Ux},202)}let m=await(await J(A)).prepareInputTurn(H);if(!m.accepted)return j.json({status:"rejected",reason:m.reason},m.reason==="queue_full"?429:409);let Yx=X(A,H,W,{preparedInputTurn:m});return j.json({runId:Yx.id,messageId:m.messageId,status:"running"},202)})}),$.post("/:sessionId/abort",async(j)=>{let Z=j.req.param("sessionId"),Y=await u(Z,j.req.query("projectPath")),Q=p.get(q(Y));if(Q?.currentRunId){let O=h.get(Q.currentRunId);if(O)Tx(O),await O.completion}return j.json({success:!0})}),$.get("/:sessionId/status",async(j)=>{let Z=j.req.param("sessionId"),Y=await u(Z,j.req.query("projectPath")),Q=p.get(q(Y));if(!Q?.currentRunId)return j.json({sessionId:Z,projectPath:Y.projectPath,status:"idle"});let O=h.get(Q.currentRunId);return j.json({sessionId:Z,projectPath:Y.projectPath,runId:Q.currentRunId,status:O?.status||"idle"})}),$};async function e0($,V,x,M,G,U={}){let{abortController:J,sessionId:b,id:_}=$,X=U.preparedInputTurn?.messageId??jx(12),j=U.pendingInputOnly===!0||U.preparedInputTurn?.mode==="pending"||U.goalContinuationOnly===!0?void 0:jx(12),Z,Y=I(V),Q=(O,T)=>{l.publish(Y,O,T)};try{if(!U.pendingInputOnly&&!U.goalContinuationOnly)Q("message.created",{messageId:X,role:"user",content:qx(x)});if(Q("session.status",{status:"running"}),j)Q("message.created",{messageId:j,role:"assistant",content:""});Z=await G(V);let O=Z,T=await M0.createWithRuntime(O,{sessionId:b}),N=async(w)=>{let z=jx(12),d=300000;$.status="waiting_permission";let m=new Promise((e)=>{let Ux=setTimeout(()=>{B.warn(`[SessionRoutes] Permission ${z} timed out after 300000ms`),Q("permission.timeout",{requestId:z}),e({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:z,resolve:(zx)=>{clearTimeout(Ux),e(zx)},details:w}}),Yx=$.pendingPermission;if(!Yx)throw Error("Permission request was not registered");let Kx=j0(Yx);Q(Kx.type,Kx.properties),B.info(`[SessionRoutes] Permission request created: ${z}, runId: ${_}`);let R=await m;if(B.info(`[SessionRoutes] Permission response received: ${z}, approved: ${R.approved}`),!J.signal.aborted)$.status="running";if($.pendingPermission===Yx)$.pendingPermission=void 0;return R},K={messages:[...V.messages],userId:"web-user",sessionId:b,workspaceRoot:V.projectPath,signal:J.signal,permissionMode:M,confirmationHandler:{requestConfirmation:N}},W=()=>{if(!j)j=jx(12),Q("message.created",{messageId:j,role:"assistant",content:""});return j},H=async(w)=>{switch(w.kind){case"content_delta":Q("message.delta",{messageId:W(),delta:w.delta});break;case"thinking_delta":Q("thinking.delta",{delta:w.delta});break;case"tool_start":if("function"in w.toolCall)Q("tool.start",{messageId:W(),toolName:w.toolCall.function.name,toolCallId:w.toolCall.id,arguments:w.toolCall.function.arguments,toolKind:w.toolKind});break;case"tool_result":if("function"in w.toolCall)Q("tool.result",{messageId:W(),toolName:w.toolCall.function.name,toolCallId:w.toolCall.id,success:w.result.success,summary:w.result.metadata?.summary,output:V0($0(w.toolCall.function.name,w.result)),metadata:r0(w.result.metadata)});break;case"token_usage":Q("token.usage",{...w.usage});break;case"turn_start":Q("turn.started",{turn:w.turn,maxTurns:w.maxTurns});break;case"steering_applied":Q("steering.applied",{runId:_,messageIds:w.messageIds,count:w.count,recovered:w.recovered,delivery:w.delivery,queued:O.getPendingSteeringCount()});break;case"follow_up_started":{if(j)Q("message.complete",{messageId:j}),j=void 0;for(let z of w.messages){if(!z.recovered||z.persisted)continue;Q("message.created",{messageId:z.id,role:"user",content:qx(z.content),recovered:!0})}Q("follow_up.started",{runId:_,queued:w.queued,recovered:w.recovered}),W();break}case"goal_updated":Q("goal.updated",{goal:w.goal});break;case"goal_continuation_started":Q("goal.continuation.started",{goal:w.goal,continuation:w.continuation}),W();break;case"compaction":Q(w.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":Q("model.fallback",{});break;case"task_update":Q("task.updated",{tasks:w.tasks});break;default:break}},A=await Bx(T.chatStream(x,K,{stream:!0,pendingInputOnly:U.pendingInputOnly,preparedInputTurn:U.preparedInputTurn,goalContinuationOnly:U.goalContinuationOnly}),H);if(!A.success)throw Error(A.error?.message??"Agent run failed");for(let w=0;w<20;w++){let z=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,O.getPendingSteeringCount()===0){if(!z)break;continue}if(J.signal.aborted)break;if(A=await Bx(T.chatStream("",K,{stream:!0,pendingInputOnly:!0}),H),!A.success)throw Error(A.error?.message??"Agent follow-up failed")}if(V.messages=[...K.messages],V.updatedAt=new Date,J.signal.aborted||$.status==="cancelled"){Q("session.status",{status:"idle"});return}if(j)Q("message.complete",{messageId:j});Q("thinking.completed",{}),$.status="completed",Q("session.completed",{runId:_,outputTruncated:A.metadata?.outputTruncated??!1}),Q("session.status",{status:"idle"})}catch(O){if(Z&&U.preparedInputTurn)await Z.finishTurn(U.preparedInputTurn.handle).catch(()=>{return});if(J.signal.aborted||$.status==="cancelled"){Tx($,"runtime-abort"),Q("session.status",{status:"idle"});return}B.error("[SessionRoutes] Agent execution error:",O),$.status="failed",Q("session.error",{error:O instanceof Error?O.message:"Unknown error"}),Q("session.status",{status:"error"})}}function Y0($,V,x){B.info(`[SessionRoutes] Looking for permission ${V} in session ${$.sessionId}`),B.info(`[SessionRoutes] Active runs: ${h.size}`);for(let[M,G]of h.entries())if(B.info(`[SessionRoutes] Checking run ${M}: sessionId=${G.sessionId}, projectPath=${G.projectPath}, pendingPermission=${G.pendingPermission?.permissionId}`),G.sessionId===$.sessionId&&G.projectPath===$.projectPath&&G.pendingPermission?.permissionId===V)return G.pendingPermission.resolve(x),B.info(`[SessionRoutes] Permission ${V} responded, runId: ${G.id}`),!0;return B.error(`[SessionRoutes] Permission not found: ${V}`),!1}var Fx=D("Service"),$$=g.object({approved:g.boolean(),remember:g.boolean().optional(),scope:g.enum(["once","session","project"]).optional(),targetMode:g.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:g.string().optional(),answers:g.record(g.union([g.string(),g.array(g.string())])).optional()}),J0=()=>{let $=new x$;return $.post("/:permissionId",async(V)=>{let x=V.req.param("permissionId"),M=V.req.query("sessionId"),G=V.req.query("projectPath");Fx.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${M}`);try{let U=await V.req.json(),J=$$.safeParse(U);if(!J.success)throw new C("Invalid permission response format");let{approved:b,remember:_,scope:X,targetMode:y,feedback:j,answers:Z}=J.data;if(!M)throw new C("sessionId query parameter is required");let Y=await u(M,G);if(!Y0(Y,x,{approved:b,reason:j,scope:X,targetMode:y,feedback:j,answers:Z}))throw new L("Permission request",x);return Fx.info(`[PermissionRoutes] Permission ${x} ${b?"approved":"denied"}`),V.json({success:!0,approved:b,remember:_})}catch(U){if(Fx.error("[PermissionRoutes] Failed to respond to permission:",U),U instanceof C||U instanceof v||U instanceof L||U instanceof k)throw U;throw U}}),$};import{Hono as V$}from"hono";var Q0=D("Service"),O0=()=>{let $=new V$;return $.get("/",async(V)=>{try{let x=await Z0();return V.json(x)}catch(x){return Q0.error("[ProviderRoutes] Failed to list providers:",x),V.json([])}}),$.get("/:provider/models",async(V)=>{let x=V.req.param("provider");try{let M=await U0(x);return V.json(M)}catch(M){return Q0.error("[ProviderRoutes] Failed to list models:",M),V.json([])}}),$};import{Hono as M$}from"hono";import*as i from"node:fs/promises";import{homedir as j$}from"node:os";import*as bx from"node:path";var r=D("Service"),Ex=bx.join(j$(),".blade","skills-config.json");async function T0(){try{let $=await i.readFile(Ex,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function f$($){await i.mkdir(bx.dirname(Ex),{recursive:!0}),await i.writeFile(Ex,JSON.stringify($,null,2))}async function G$($,V){let x=await T0();if(V)x.disabled=x.disabled.filter((M)=>M!==$);else if(!x.disabled.includes($))x.disabled.push($);await f$(x)}var fx=null,Y$=300000;async function J$(){if(fx&&Date.now()-fx.timestamp<Y$)return fx.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok)return r.warn(`GitHub API returned ${$.status}`),fx?.data||[];let V=await $.json(),x=[];for(let M of V){if(M.type!=="dir")continue;let G=`Official ${M.name} skill`;try{let U=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${M.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(U.ok){let b=(await U.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(b)G=b[1].trim().slice(0,100)}}catch{}x.push({name:M.name,description:G,tag:"Official",author:"Anthropic"})}return fx={data:x,timestamp:Date.now()},x}catch($){return r.warn("Failed to fetch skills catalog from GitHub:",$),fx?.data||[]}}var N0=()=>{let $=new M$;return $.get("/",async(V)=>{try{let x=Nx();await x.initialize();let M=x.getAll(),G=await T0(),U=M.map((J)=>({id:J.name,name:J.name,enabled:!G.disabled.includes(J.name),description:J.description||"",version:J.version||"1.0.0",provider:"Local",location:J.source==="builtin"?"Built-in":J.basePath,capabilities:["prompts"],allowedTools:J.allowedTools||[]}));return V.json(U)}catch(x){return r.error("[SkillsRoutes] Failed to get skills:",x),V.json([])}}),$.post("/:name/toggle",async(V)=>{try{let x=V.req.param("name"),M=await V.req.json();return await G$(x,M.enabled),V.json({success:!0,enabled:M.enabled})}catch(x){return r.error("[SkillsRoutes] Failed to toggle skill:",x),V.json({success:!1,error:x.message},500)}}),$.delete("/:name",async(V)=>{try{let x=V.req.param("name"),M=`${process.env.HOME}/.blade/skills/${x}`;return await i.rm(M,{recursive:!0,force:!0}),await Nx().refresh(),V.json({success:!0})}catch(x){return r.error("[SkillsRoutes] Failed to uninstall skill:",x),V.json({success:!1,error:x.message},500)}}),$.post("/install",async(V)=>{try{let x=await V.req.json(),M=X0(),G=Nx(),U=!1;if(x.source==="catalog"&&x.name){if(U=await M.installOfficialSkill(x.name),!U)return V.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(U=await M.installFromRepo(x.url,x.name),!U)return V.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(U=await M.installFromLocal(x.path,x.name),!U)return V.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return V.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await G.refresh(),V.json({success:!0})}catch(x){return r.error("[SkillsRoutes] Failed to install skill:",x),V.json({success:!1,error:x.message},500)}}),$.get("/catalog",async(V)=>{try{let x=await J$();return V.json(x)}catch(x){return r.error("[SkillsRoutes] Failed to get catalog:",x),V.json([])}}),$};import Q$ from"fast-glob";import{Hono as Z$}from"hono";import{execSync as U$}from"node:child_process";import{readdir as O$}from"node:fs/promises";import _x from"node:path";var Zx=D("Service"),X$=($)=>{try{return U$("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},T$=[...wx.map(($)=>`${$}/**`),...wx,...mx.map(($)=>`**/${$}`)],N$=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),w0=()=>{let $=new Z$;return $.get("/commands",async(V)=>{try{let x=V.req.query("q")||"",M=_0(x).filter((G)=>!N$.has(G.command));return V.json(M)}catch(x){return Zx.error("[SuggestionsRoutes] Failed to get command suggestions:",x),V.json([])}}),$.get("/files",async(V)=>{try{let x=V.req.query("q")||"",M=V.get("directory")||E(),G=Math.min(Number(V.req.query("limit"))||100,1000),J=(await Q$("**/*",{cwd:M,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:T$})).map((X)=>X.replace(/\\/g,"/"));if(!x)return V.json(J.slice(0,G));let b=x.toLowerCase(),_=J.filter((X)=>X.toLowerCase().includes(b)).slice(0,G);return V.json(_)}catch(x){return Zx.error("[SuggestionsRoutes] Failed to get file suggestions:",x),V.json([])}}),$.get("/files/tree",async(V)=>{try{let x=V.get("directory")||E(),M=V.req.query("path")||"",G=M?_x.join(x,M):x,J=(await O$(G,{withFileTypes:!0})).map((X)=>({name:X.name,path:M?`${M}/${X.name}`:X.name,type:X.isDirectory()?"dir":"file"}));J.sort((X,y)=>{if(X.type!==y.type)return X.type==="dir"?-1:1;return X.name.localeCompare(y.name)});let b=new Set(wx),_=J.filter((X)=>{let y=X.name;if(y.startsWith("."))return!1;if(b.has(y))return!1;for(let j of mx)if(y.match(new RegExp(j.replace("*",".*"))))return!1;return!0});return V.json(_)}catch(x){return Zx.error("[SuggestionsRoutes] Failed to get file tree:",x),V.json([])}}),$.get("/files/content",async(V)=>{try{let x=V.req.query("path");if(!x)return V.json({error:"Missing file path"},400);let M=V.get("directory")||E(),G=_x.resolve(M,x),U=_x.relative(M,G);if(U.startsWith("..")||_x.isAbsolute(U))return V.json({error:"Invalid file path"},400);let J=b0(),b=await J.stat(G);if(!b?.isFile)return V.json({error:"File not found"},404);let _=200000,X=await J.readTextFile(G),y=X.length>_;return V.json({path:x,content:y?X.slice(0,_):X,truncated:y,size:b.size})}catch(x){return Zx.error("[SuggestionsRoutes] Failed to get file content:",x),V.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(V)=>{try{let x=V.get("directory")||E(),M=X$(x);return V.json({branch:M})}catch(x){return Zx.error("[SuggestionsRoutes] Failed to get git info:",x),V.json({branch:null})}}),$};import{Hono as b$}from"hono";var n=D("Service"),Gx=new Map,y0=2097152,K0=65536;function z0(){return typeof globalThis.Bun<"u"}async function _$($,V,x){if(z0()){let{spawn:U}=await import("bun-pty"),J=U($,V,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:J.pid,write:(b)=>J.write(b),resize:(b,_)=>J.resize(b,_),kill:()=>J.kill(),onData:(b)=>J.onData(b),onExit:(b)=>J.onExit(b)}}let G=(await import("node-pty")).spawn($,V,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:G.pid,write:(U)=>G.write(U),resize:(U,J)=>G.resize(U,J),kill:()=>G.kill(),onData:(U)=>{G.onData(U)},onExit:(U)=>{G.onExit(U)}}}var px=void 0,hx;if(z0())try{let{createBunWebSocket:$}=await import("hono/bun"),V=$();hx=V.upgradeWebSocket,px=V.websocket}catch($){n.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function W0($,V){let x=`term-${Date.now()}`;n.info(`[Terminal] New connection: ${x}, cwd: ${$}`);let M=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",G=M.endsWith("sh")?["-l"]:[],U=await _$(M,G,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),J={id:x,process:U,cwd:$,buffer:"",subscribers:new Set};if(Gx.set(x,J),J.subscribers.add(V),U.onData((b)=>{let _=!1;for(let X of J.subscribers)try{X.send(b),_=!0}catch{J.subscribers.delete(X)}if(_)return;if(J.buffer+=b,J.buffer.length>y0)J.buffer=J.buffer.slice(-y0)}),U.onExit(({exitCode:b})=>{n.info(`[Terminal] Process exited: ${x}, code: ${b}`);for(let _ of J.subscribers)try{_.close()}catch{}Gx.delete(x)}),J.buffer){let b=J.buffer;J.buffer="";for(let _=0;_<b.length;_+=K0)V.send(b.slice(_,_+K0))}return{session:J,cleanup:()=>{if(n.info(`[Terminal] Connection closed: ${x}`),J.subscribers.delete(V),J.subscribers.size===0){try{J.process.kill()}catch{}Gx.delete(x)}}}}function H0($,V){$.on("connection",async(x,M)=>{let G=new URL(M.url||"/",`http://${M.headers.host}`);if(!G.pathname.endsWith("/terminal/ws")){x.close();return}let U=G.searchParams.get("cwd")||V()||E();try{let{session:J,cleanup:b}=await W0(U,{send:(_)=>x.send(_),close:()=>x.close()});x.on("message",(_)=>{try{J.process.write(String(_))}catch(X){n.error("[Terminal] Failed to write to PTY:",X)}}),x.on("close",b),x.on("error",b)}catch(J){n.error("[Terminal] Failed to spawn PTY:",J),x.close()}})}var C0=()=>{let $=new b$;if($.get("/status",(V)=>{let x=Array.from(Gx.values()).map((M)=>({id:M.id,cwd:M.cwd}));return V.json({active:x.length,terminals:x})}),$.post("/kill/:terminalId",(V)=>{let x=V.req.param("terminalId"),M=Gx.get(x);if(M){try{M.process.kill()}catch{}for(let G of M.subscribers)G.close();return Gx.delete(x),V.json({success:!0})}return V.json({success:!1,error:"Terminal not found"},404)}),hx)$.get("/ws",hx((V)=>{let x=V.req.query("cwd")||V.get("directory")||E(),M;return{async onOpen(G,U){try{M=await W0(x,{send:(J)=>U.send(J),close:()=>U.close()})}catch(J){n.error("[Terminal] Failed to spawn PTY:",J),U.close()}},onMessage(G){if(!M)return;try{M.session.process.write(String(G.data))}catch(U){n.error("[Terminal] Failed to write to PTY:",U)}},onClose(){M?.cleanup()}}}));else $.get("/ws",(V)=>{return V.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};var S=D("Service"),Px=[];function B$(){let $=W$(C$(import.meta.url)),V=[s($,"web"),s(E(),"dist/web"),s(E(),"packages/cli/dist/web")];for(let x of V){let M=s(x,"index.html");if(D0(M)){if(yx(M,"utf-8").includes("/assets/"))return S.debug(`[Server] Found web dist at: ${x}`),x}}return null}function D$(){let $=new w$;$.onError((x,M)=>{if(S.error("[Server] Request error:",x),x instanceof k)return M.json(x.toObject(),x.statusCode);let G=x instanceof Error?x.message:String(x);return M.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),$.use(async(x,M)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return M();let U=x.req.path;if(U==="/"||U.startsWith("/assets/")||U.endsWith(".html")||U.endsWith(".js")||U.endsWith(".css"))return M();let J=x.req.header("Authorization");if(!J?.startsWith("Basic "))return x.header("WWW-Authenticate",'Basic realm="Blade Server"'),x.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let b=Buffer.from(J.slice(6),"base64").toString(),[_,X]=b.split(":"),y=process.env.BLADE_SERVER_USERNAME??"blade";if(_!==y||X!==G)return x.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return M()}),$.use(async(x,M)=>{let G=x.req.path==="/health"||x.req.path==="/global/health"||x.req.path.startsWith("/assets/");if(!G)S.debug(`[Server] ${x.req.method} ${x.req.path}`);let U=Date.now();if(await M(),!G){let J=Date.now()-U;S.debug(`[Server] ${x.req.method} ${x.req.path} - ${x.res.status} (${J}ms)`)}}),$.use(y$({origin(x){if(!x)return;if(x.startsWith("http://localhost:"))return x;if(x.startsWith("http://127.0.0.1:"))return x;if(x==="tauri://localhost"||x==="http://tauri.localhost")return x;if(Px.includes(x))return x;return}})),$.use(async(x,M)=>{let G=x.req.query("directory")||x.req.header("x-blade-directory")||E();try{G=decodeURIComponent(G)}catch{}return x.set("directory",G),M()}),$.route("/global",kx()),$.route("/sessions",G0()),$.route("/configs",Sx()),$.route("/permissions",J0()),$.route("/providers",O0()),$.route("/models",vx()),$.route("/suggestions",w0()),$.route("/terminal",C0()),$.route("/mcp",Rx()),$.route("/skills",N0()),$.get("/health",(x)=>{return x.json({healthy:!0,version:Mx()})});let V=B$();if(V)S.info(`[Server] Serving static files from ${V}`),$.get("/assets/*",(x)=>{let M=s(V,x.req.path);if(!D0(M))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${x.req.path}`}},404);let G=yx(M),U=H$(M).toLowerCase(),b={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[U]||"application/octet-stream";return new Response(G,{headers:{"Content-Type":b,"Cache-Control":"public, max-age=31536000, immutable"}})}),$.get("/",(x)=>{let M=s(V,"index.html"),G=yx(M,"utf-8");return x.html(G)}),$.get("*",(x)=>{let M=x.req.path;if(M.includes("."))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${M}`}},404);let G=s(V,"index.html"),U=yx(G,"utf-8");return x.html(U)});else S.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(x)=>{return x.json({message:"Blade API Server",version:Mx(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),$.all("*",(x)=>{return x.json({error:{code:"NOT_FOUND",message:`Route not found: ${x.req.path}`}},404)});return $}function q$(){let $=z$(),V=[];for(let x of Object.keys($)){let M=$[x];if(!M)continue;for(let G of M){if(G.internal||G.family!=="IPv4")continue;if(G.address.startsWith("172."))continue;V.push(G.address)}}return V}function A0(){return typeof globalThis.Bun<"u"}function B0($,V){let x=globalThis.Bun,M=(U)=>{try{return x.serve({hostname:V.hostname,port:U,fetch:$.fetch,idleTimeout:0,websocket:px})}catch(J){S.error("Failed to start Bun server:",J);return}},G=V.port===0?M(4096)??M(0):M(V.port);if(!G)throw Error(`Failed to start Bun server on port ${V.port}`);return{url:G.url,port:G.port,hostname:G.hostname,stop:async()=>{G.stop(!0)}}}function F$($,V){return new Promise((x,M)=>{let G=K$(async(X,y)=>{let j=new URL(X.url||"/",`http://${X.headers.host}`),Z=new Headers;for(let[O,T]of Object.entries(X.headers))if(T)if(Array.isArray(T))for(let N of T)Z.append(O,N);else Z.set(O,T);let Y;if(X.method!=="GET"&&X.method!=="HEAD")Y=(await new Promise((T)=>{let N=[];X.on("data",(K)=>N.push(K)),X.on("end",()=>T(Buffer.concat(N)))})).toString();let Q=new Request(j.toString(),{method:X.method,headers:Z,body:Y});try{let O=await $.fetch(Q);if(y.statusCode=O.status,O.headers.forEach((T,N)=>{y.setHeader(N,T)}),O.body){let T=O.body.getReader(),N=async()=>{let{done:K,value:W}=await T.read();if(K){y.end();return}return y.write(W),N()};await N()}else{let T=await O.text();y.end(T)}}catch(O){S.error("[Server] Node request error:",O),y.statusCode=500,y.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),U=new A$({noServer:!0}),J=E();H0(U,()=>J),G.on("upgrade",(X,y,j)=>{if(new URL(X.url||"/",`http://${X.headers.host}`).pathname==="/terminal/ws")U.handleUpgrade(X,y,j,(Y)=>{U.emit("connection",Y,X)});else y.destroy()});let b=(X)=>{return new Promise((y,j)=>{G.once("error",(Z)=>{if(Z.code==="EADDRINUSE")j(Z);else j(Z)}),G.listen(X,V.hostname,()=>{let Z=G.address();if(Z&&typeof Z==="object")y(Z.port);else y(X)})})};(async()=>{let X;if(V.port===0)try{X=await b(4096)}catch{X=await b(0)}else X=await b(V.port);let y=new URL(`http://${V.hostname==="0.0.0.0"?"localhost":V.hostname}:${X}`);x({url:y,port:X,hostname:V.hostname,stop:async()=>{return new Promise((j)=>{U.close(()=>{G.close(()=>j())})})}})})().catch(M)})}var q0;((u1)=>{let $,V;function x(){if(!V)V=D$();return V}u1.getApp=x;function M(J){Px=J.cors??[];let b=x();if(A0())$=B0(b,J),S.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let _=$;return{url:_.url,port:_.port,hostname:_.hostname,stop:async()=>{if($)await $.stop(),$=void 0,V=void 0,S.info("[Server] Blade server stopped")}}}u1.listen=M;async function G(J){Px=J.cors??[];let b=x();if(A0())$=B0(b,J),S.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await F$(b,J),S.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);let _=$;return{url:_.url,port:_.port,hostname:_.hostname,stop:async()=>{if($)await $.stop(),$=void 0,V=void 0,S.info("[Server] Blade server stopped")}}}u1.listenAsync=G;function U(){return $!==void 0}u1.isRunning=U})(q0||={});export{E$ as f,m$ as g,q$ as h,q0 as i};