blade-code 0.10.72 → 0.10.73

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 (117) hide show
  1. package/README.md +1 -1
  2. package/dist/blade.js +2 -2
  3. package/dist/{chunk-zf96d5we.js → chunk-0hrj06t7.js} +1 -1
  4. package/dist/chunk-0qqzd0hq.js +1 -0
  5. package/dist/{chunk-eh4h7fmr.js → chunk-1ava19kd.js} +2 -2
  6. package/dist/chunk-1cyy8wqj.js +10 -0
  7. package/dist/{chunk-mhyat4mq.js → chunk-2wdxpdz3.js} +2 -2
  8. package/dist/chunk-3fzy7q6x.js +1 -0
  9. package/dist/chunk-3hv57n95.js +1635 -0
  10. package/dist/{chunk-yhnr8vdb.js → chunk-3r0x2p7z.js} +2 -2
  11. package/dist/chunk-4cpgcm7q.js +44 -0
  12. package/dist/{chunk-jyds9m8p.js → chunk-4ehgjdm0.js} +1 -1
  13. package/dist/{chunk-4wvsg8cc.js → chunk-4khtsmrf.js} +1 -1
  14. package/dist/{chunk-hhk5ecpv.js → chunk-5d1gbm41.js} +2 -2
  15. package/dist/chunk-64jq6jcr.js +2 -0
  16. package/dist/{chunk-z7vj2xrg.js → chunk-67ddp3ns.js} +3 -3
  17. package/dist/{chunk-ss1znmv0.js → chunk-77hn7hf6.js} +1 -1
  18. package/dist/{chunk-11gdqmbm.js → chunk-8fm3xamc.js} +1 -1
  19. package/dist/chunk-8h35w91f.js +1 -0
  20. package/dist/{chunk-hwjmm2br.js → chunk-948efzyp.js} +2 -2
  21. package/dist/{chunk-mp4bfn57.js → chunk-9cgsheg0.js} +2 -2
  22. package/dist/chunk-9e6dcbqq.js +160 -0
  23. package/dist/{chunk-hhvkzn6m.js → chunk-a0ns74mh.js} +1 -1
  24. package/dist/{chunk-zac26wwd.js → chunk-a37mn58w.js} +1 -1
  25. package/dist/{chunk-tms0pr01.js → chunk-a5e4sy4q.js} +2 -2
  26. package/dist/{chunk-0kat01bw.js → chunk-ah12xhh6.js} +1 -1
  27. package/dist/{chunk-7am1z065.js → chunk-ax610gqh.js} +1 -1
  28. package/dist/{chunk-6v7f2cv9.js → chunk-b28zsp1t.js} +4 -4
  29. package/dist/{chunk-2d2bcyn1.js → chunk-b3413dtc.js} +1 -1
  30. package/dist/{chunk-a38chc6z.js → chunk-bhhdvqe7.js} +2 -2
  31. package/dist/{chunk-q6daf441.js → chunk-c9e0fbyh.js} +1 -1
  32. package/dist/{chunk-06y3rada.js → chunk-cvvtrvk6.js} +2 -2
  33. package/dist/{chunk-brm24s69.js → chunk-fdmcef2p.js} +2 -2
  34. package/dist/{chunk-x4hh8yqg.js → chunk-fgh6mjdp.js} +1 -1
  35. package/dist/chunk-hswyrd88.js +1 -0
  36. package/dist/chunk-jeazjp08.js +8 -0
  37. package/dist/{chunk-18atvz38.js → chunk-jkh9s1ht.js} +1 -1
  38. package/dist/{chunk-6j3k4v08.js → chunk-js4vqnds.js} +1 -1
  39. package/dist/chunk-jsg7vmxp.js +1 -0
  40. package/dist/{chunk-m6qgme8k.js → chunk-k82ff14t.js} +1 -1
  41. package/dist/chunk-kka51s0k.js +2 -0
  42. package/dist/{chunk-yjj7q7hy.js → chunk-meee1cbq.js} +1 -1
  43. package/dist/{chunk-bs77d8hn.js → chunk-mefb27ch.js} +1 -1
  44. package/dist/{chunk-awj9aqjy.js → chunk-n1w40gq2.js} +2 -2
  45. package/dist/{chunk-wvg81sd9.js → chunk-ne7vres8.js} +1 -1
  46. package/dist/{chunk-e6ezndyf.js → chunk-p0qjjyex.js} +11 -11
  47. package/dist/{chunk-g8425xh4.js → chunk-p7y79y6c.js} +1 -1
  48. package/dist/{chunk-2fd5trh8.js → chunk-q6ak67n8.js} +2 -2
  49. package/dist/{chunk-5va3hhfp.js → chunk-r5bpvfym.js} +1 -1
  50. package/dist/{chunk-0qj8jfj1.js → chunk-r8wbvxn7.js} +1 -1
  51. package/dist/{chunk-s9brgcgs.js → chunk-skw3b17a.js} +1 -1
  52. package/dist/{chunk-xahapj98.js → chunk-sxjs66h6.js} +1 -1
  53. package/dist/{chunk-xszsveq1.js → chunk-tmvg7taj.js} +1 -1
  54. package/dist/{chunk-e0hf1317.js → chunk-traa01dd.js} +1 -1
  55. package/dist/{chunk-28wsyv32.js → chunk-tvv3syt3.js} +1 -1
  56. package/dist/{chunk-gv3ed5gw.js → chunk-tzytnhbp.js} +2 -2
  57. package/dist/chunk-vhadycw2.js +2 -0
  58. package/dist/{chunk-6j9t1xbh.js → chunk-vw0gg08s.js} +2 -2
  59. package/dist/chunk-vxd30mnx.js +1 -0
  60. package/dist/chunk-wbzvy99s.js +1 -0
  61. package/dist/chunk-wg3z2epq.js +1 -0
  62. package/dist/{chunk-c4j2anbm.js → chunk-wp0794r2.js} +2 -2
  63. package/dist/{chunk-y858e8pb.js → chunk-xjc0bthz.js} +2 -2
  64. package/dist/chunk-xkc6v9nb.js +1 -0
  65. package/dist/{chunk-cqeqjtxn.js → chunk-xv92c582.js} +1 -1
  66. package/dist/chunk-y36rdy4v.js +5 -0
  67. package/dist/chunk-yg6c4xrs.js +1 -0
  68. package/dist/{chunk-2sdnmxts.js → chunk-yvnm25nb.js} +1 -1
  69. package/dist/chunk-yx82ang3.js +6 -0
  70. package/dist/chunk-z8a5ebep.js +1 -0
  71. package/dist/chunk-z95pw8nb.js +1 -0
  72. package/dist/chunk-zh2x0tcm.js +1 -0
  73. package/dist/chunk-zr1mg5kq.js +1 -0
  74. package/dist/{chunk-j0yvwrd7.js → chunk-zxn7f308.js} +2 -2
  75. package/dist/web/assets/ChatView-Dm-DMbOV.js +18 -0
  76. package/dist/web/assets/{CodeBlockHighlighter-B5DRAEhB.js → CodeBlockHighlighter-XaY8h0vd.js} +1 -1
  77. package/dist/web/assets/{FilePreview-DSpvLsjW.js → FilePreview-CVHV6oga.js} +1 -1
  78. package/dist/web/assets/{KanbanBoard-6K7IeCXi.js → KanbanBoard-D1_61uZi.js} +1 -1
  79. package/dist/web/assets/{MarkdownRenderer-D6LiW9kF.js → MarkdownRenderer-DUPwAzs4.js} +3 -3
  80. package/dist/web/assets/{SettingsModal-CFHxLfuL.js → SettingsModal-DHnU7uMN.js} +2 -2
  81. package/dist/web/assets/{TaskSwitcher-Bng9nDed.js → TaskSwitcher-CpXhLtO5.js} +1 -1
  82. package/dist/web/assets/{TerminalPanel-BnyQZwkN.js → TerminalPanel-eYsA-A62.js} +1 -1
  83. package/dist/web/assets/index-8G4ejlcH.css +1 -0
  84. package/dist/web/assets/index-gjBOFzd1.js +11 -0
  85. package/dist/web/assets/{session-events-BvtUOaNG.js → session-events-Bgir_Gl_.js} +6 -6
  86. package/dist/web/assets/team-QZ9byb3E.js +1 -0
  87. package/dist/web/assets/teamService-Bb2kW8Hh.js +1 -0
  88. package/dist/web/assets/{vendor-icons-C927DZlr.js → vendor-icons-DovdPN7M.js} +25 -20
  89. package/dist/web/index.html +4 -4
  90. package/package.json +1 -1
  91. package/dist/chunk-139s7p91.js +0 -1
  92. package/dist/chunk-2vkzwqv0.js +0 -1
  93. package/dist/chunk-41smvqs8.js +0 -1
  94. package/dist/chunk-4xpj0d6y.js +0 -2
  95. package/dist/chunk-61arrvhp.js +0 -1
  96. package/dist/chunk-7hf1k2c9.js +0 -6
  97. package/dist/chunk-8geywf8q.js +0 -1
  98. package/dist/chunk-91qsjpm6.js +0 -2
  99. package/dist/chunk-bqz8wera.js +0 -1
  100. package/dist/chunk-ccgq8nrm.js +0 -44
  101. package/dist/chunk-cyjnza5n.js +0 -8
  102. package/dist/chunk-d9a0g85f.js +0 -1
  103. package/dist/chunk-e4ynb9qf.js +0 -1
  104. package/dist/chunk-eh9gdzk5.js +0 -160
  105. package/dist/chunk-emqbb5xh.js +0 -1
  106. package/dist/chunk-gzysna9c.js +0 -1
  107. package/dist/chunk-hryhnmwv.js +0 -1635
  108. package/dist/chunk-mrh3vs01.js +0 -2
  109. package/dist/chunk-ph5rn44j.js +0 -1
  110. package/dist/chunk-pqhjrdnq.js +0 -10
  111. package/dist/chunk-v7phc78b.js +0 -1
  112. package/dist/chunk-ypwjzw5x.js +0 -5
  113. package/dist/chunk-zqxj65xc.js +0 -1
  114. package/dist/chunk-zssys78z.js +0 -1
  115. package/dist/web/assets/ChatView-CgUC5rxo.js +0 -18
  116. package/dist/web/assets/index-CDdYV8kB.css +0 -1
  117. package/dist/web/assets/index-DId2GJVO.js +0 -11
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.72",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 --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","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","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","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",prepack:"node scripts/run-bun.js run build",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",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",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.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
- export{y as nh,p as oh,v as ph,g as qh,f as rh,w as sh};
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.73",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 --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","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","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","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",prepack:"node scripts/run-bun.js run build",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",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",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.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
+ export{y as rh,p as sh,v as th,g as uh,f as vh,w as wh};
@@ -0,0 +1 @@
1
+ import{td as a,ud as b,vd as c}from"./chunk-yx82ang3.js";import"./chunk-vw0gg08s.js";import"./chunk-bhhdvqe7.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-jkh9s1ht.js";import"./chunk-4cpgcm7q.js";import"./chunk-p7y79y6c.js";import"./chunk-k82ff14t.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-kka51s0k.js";import"./chunk-tzytnhbp.js";import"./chunk-948efzyp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-1ava19kd.js";import"./chunk-mefb27ch.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,2 +1,2 @@
1
- import{oh as S}from"./chunk-y858e8pb.js";import{Ih as f}from"./chunk-zf96d5we.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{sh as S}from"./chunk-xjc0bthz.js";import{Mh as f}from"./chunk-0hrj06t7.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as a,u as b,g as c,C as d,V as e};
@@ -0,0 +1,5 @@
1
+ import{Ig as E_,Jg as qf,Kg as gf,Lg as __,Mg as Wf,Og as $f,Qg as If,Sg as q,Tg as Kf,Vg as Df,Wg as Cf,Yg as s}from"./chunk-kka51s0k.js";import{eh as l}from"./chunk-tzytnhbp.js";import{ih as AE,kh as Xf}from"./chunk-948efzyp.js";import{nh as lE}from"./chunk-ne7vres8.js";var I_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},hE=(f)=>I_[f]||{};var D_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&D_.has(f)}function XT(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function WT(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function xE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let S=()=>{T.abort(x.reason);for(let[A,t]of h)A.removeEventListener("abort",t)};h.set(x,S)}for(let[x,S]of h)x.addEventListener("abort",S,{once:!0});return T.signal}function ff(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let S,A=setTimeout(()=>{if(E&&S)E.removeEventListener("abort",S);h()},f);if(E)S=()=>{if(clearTimeout(A),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",S,{once:!0})})}var H_=l("Chat"),U_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function jf(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
2
+ `)}function Y_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return H_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function B_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function b_(f,E){let _=B_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function RE(f,E,_,T,h){let x=f.filter((t)=>t.role==="system").map((t)=>jf(t.content)).filter(Boolean).join(`
3
+
4
+ `),S=[];for(let t of f){if(t.role==="system")continue;if(t.role==="user"){let N=E.input.includes("image"),R=typeof t.content==="string"?t.content:await Promise.all(t.content.map((M)=>M.type==="text"?Promise.resolve({type:"text",text:M.text}):N?b_(M.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:R,timestamp:Date.now()});continue}if(t.role==="assistant"){let N=[];if(t.reasoningContent?.trim())N.push({type:"thinking",thinking:t.reasoningContent});let R=jf(t.content);if(R)N.push({type:"text",text:R});for(let M of t.tool_calls??[]){if(!("function"in M))continue;N.push({type:"toolCall",id:M.id,name:M.function.name,arguments:Y_(M.function.arguments)})}S.push({role:"assistant",content:N,api:E.api,provider:E.provider,model:E.id,usage:U_,stopReason:t.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:t.tool_call_id??"",toolName:t.name??"unknown",content:[{type:"text",text:jf(t.content)}],isError:!1,timestamp:Date.now()})}let A=_?.filter((t)=>!h||t.name===h).map((t)=>({name:t.name,description:t.description,parameters:t.parameters,constrainedSampling:t.constrainedSampling})).sort((t,N)=>t.name<N.name?-1:t.name>N.name?1:0);return{...x?{systemPrompt:x}:{},messages:S,...A?.length?{tools:A}:{}}}function ME(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],S=_+1;while(S<f.length&&f[S].role==="tool")x.push(f[S++]);let A=new Set(h.map((R)=>R.id)),t=x.filter((R)=>R.tool_call_id&&A.has(R.tool_call_id)),N=new Set(t.map((R)=>R.tool_call_id));if(A.size===h.length&&t.length===A.size&&N.size===A.size)E.push(T,...t);_=S-1}return E}function PE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function SE(f,E){return{...f,...E.baseUrl?{baseUrl:AE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function zf(f){let E=f.modelCatalog??Xf();return{models:E.models,model:SE(E.getModel(f.provider,f.model),f)}}function NE(f,E){let _=f.modelCatalog??Xf();return SE(_.getModel(E.provider,E.model),f)}import{createHash as O_}from"node:crypto";var c_=32,V_=1000,j_=512,X_=2000,z_=0.1,J_=0.05,W_=0.9,$_=300000,k_=3600000;class Jf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=L_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<V_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(X_,Math.max(j_,T.cacheReadTokens*z_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-J_))return;let S=_.modelIdentity!==T.modelIdentity,A=_.systemHash!==T.systemHash,t=_.toolsHash!==T.toolsHash,N=_.policyHash!==T.policyHash;if(!(S||A||t||N)&&_.promptTokens<T.promptTokens*W_)return;let M=Math.max(0,E-T.recordedAt),I=T.retention==="long"?k_:$_,Y=S?"model_changed":A?"system_prompt_changed":t?"tools_changed":N?"request_policy_changed":M>=I?"ttl_expired":"server_side",$=G_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:M,callNumber:_.callCount,systemPromptChanged:A,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:t,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:S,requestPolicyChanged:N}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>c_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function L_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Ef(T.name),contractHash:Ef(_f(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Ef(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Ef(_f(_)),toolFingerprints:_,policyHash:Ef(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function G_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${_f(E[_])}`).join(",")}}`}function Ef(f){return O_("sha256").update(f).digest("hex")}import{randomBytes as C_}from"node:crypto";import{createHmac as Z_}from"node:crypto";function Q_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function K_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function Sf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),Q_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",K_(f.customHeaders),_]);return Z_("sha256",Buffer.from(E)).update(T).digest("hex")}var F_=60000,o_=4,s_=0.8;var uf=300000,kf=600000;var uE=128,IE=256,v_=1800000,Nf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Lf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function a(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function w_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function p_(f,E){return Sf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function Tf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function DE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function HE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),$f)}class YE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):C_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(a(f.maxEntries,uE),uE),maxWindowEntries:Math.min(a(f.maxWindowEntries,IE),IE),windowMs:a(f.windowMs,F_),minSamples:a(f.minSamples,o_),errorRateThreshold:w_(f.errorRateThreshold,s_),idleTtlMs:a(f.idleTtlMs,v_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#M();let E=this.#_();this.#B(E);let _=p_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#D();if(this.#x.size>=this.#T.maxEntries)return this.#M();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(uf,Math.min(a(E,uf),kf));return{preflight:()=>_.#P(f),check:()=>_.#b(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#N(h),snapshot:()=>_.#j(f)}}#M(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#S(E),recordFailure:(E)=>f.#S(E),recordNeutral:(E)=>f.#S(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#P(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#u(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Nf)-E);return this.#U(f,Math.min(Nf,_))}#U(f,E){let{allowed:_,...T}=this.#A(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#M().check();if(f.lastTouchedAt=_,this.#u(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#A(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#O(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Nf)-_);return this.#A(f,Math.min(Nf,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#O(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#A(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#I(h,_,x,"reopened");return this.#c(h)}if(E==="neutral")return;if(this.#V(h,E==="failure",x),E!=="failure"||!_)return;let S=Tf(h.samples),A=h.samples.length===0?0:S/h.samples.length;if(h.samples.length>=this.#T.minSamples&&A>=this.#T.errorRateThreshold)return this.#I(h,_,x,"opened");return}#I(f,E,_,T){let h={reason:E.reason,...DE(E.statusCode)!==void 0?{statusCode:DE(E.statusCode)}:{},...HE(E.retryAfterMs)!==void 0?{retryAfterMs:HE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=_+S,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#h()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#c(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#V(f,E,_){if(this.#u(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#u(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#j(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:Tf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#B(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#D(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var UE;function BE(){return UE??=new YE,UE}import{randomBytes as m_}from"node:crypto";var q_=16,bE=128,OE=32,g_=3,cE=16,VE=96,jE=24,XE=12,zE=16,JE=4,WE=4,$E=67108864,kE=33554432,l_=12,a_=2,LE=2,GE=1,FE=15000,ZE=30000;function Gf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:Gf(),queued:Gf(),pendingBytes:Gf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function QE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class xf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,S,A){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=S;this.maxWaitMs=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function tf(f){return f instanceof xf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function y_(f){let E=z(f.globalMaxInFlight,q_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,bE,bE),T=z(f.domainMaxPending,OE,OE),h=Math.min(z(f.ownerMaxInFlight,g_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,cE,cE),_),S=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(VE,Math.max(1,Math.floor(_*3/4))),VE),_),A=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(jE,Math.max(1,Math.floor(T*3/4))),jE),T),t=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(XE,Math.max(1,Math.floor(x*3/4))),XE),x),N=Math.min(z(f.internalGlobalMaxPending,Math.min(zE,Math.max(1,Math.floor(_/8))),zE),S),R=Math.min(z(f.internalDomainMaxPending,Math.min(JE,Math.max(1,Math.floor(T/8))),JE),A),M=Math.min(z(f.internalOwnerMaxPending,Math.min(WE,Math.max(1,Math.floor(x/4))),WE),t),I=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,$E,$E),I),$=Math.min(z(f.ownerMaxPendingBytes,kE,kE),I),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(l_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(a_,h),h),h),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(LE,E),LE),E),Uf=z(f.internalDomainMaxInFlight,GE,GE),Rf=z(f.agingMs,ZE,ZE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:t,internalGlobalMaxPending:N,internalDomainMaxPending:R,internalOwnerMaxPending:M,globalMaxPendingBytes:I,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:Rf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function KE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function e_(f){if(KE(f.sessionId,"sessionId"),KE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>q)throw Error(`maxConcurrent must be between ${If} and ${q}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Qf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function d_(f,E){return Sf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class oE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Zf();#M=1;#S=0;#P=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):m_(32),this.#t=f.now??(()=>performance.now()),this.#f=y_(f)}admit(f){if(e_(f),this.#P)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Qf(f.signal);let E=d_(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#O();if(this.#_.length===0&&this.#A(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#M++;let I=this.#I(E,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(I),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let S=this.#U(f,h,x);if(S)throw this.#X("queue_full",f,S,this.#_.length);let A=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,A,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#M++;let t,N,R=new Promise((I,Y)=>{t=I,N=Y});R.catch(()=>{return});let M={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:t,reject:N,settled:!1,admitted:!1};if(f.signal)M.abortListener=()=>this.#B(M,Qf(f.signal)),f.signal.addEventListener("abort",M.abortListener,{once:!0});return M.timer=setTimeout(()=>this.#j(M),f.maxWaitMs),M.timer.unref?.(),this.#_.push(M),this.#b(h,x,M),this.#N(),{ready:R,getSnapshot:()=>this.#$(M),cancel:(I)=>this.#B(M,Qf(f.signal,I))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:W(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:W(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:W(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#P}}#U(f,E,_){let T=(R,M,I)=>M>=I?{scope:R,resource:"pending_count",inFlight:M,limit:I}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let R=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(R)return R}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let R=T("class",W(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",W(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",W(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(R)return R}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(x,this.#f.domainMaxPendingBytes),A=Math.min(x,this.#f.ownerMaxPendingBytes),t=(R,M)=>f.pendingBytes>M-R,N=(R)=>{if(R==="owner")return{scope:R,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(R==="domain")return{scope:R,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:R,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let R=Math.max(1,Math.floor(x/8)),M=Math.max(1,Math.floor(S/4)),I=Math.max(1,Math.floor(A/4));if(t(this.#E.pendingBytes.internal,R)||t(_.counters.pendingBytes.internal,I)||t(E.counters.pendingBytes.internal,M))return N("class")}if(f.requestClass!=="foreground"){let R=Math.max(1,Math.floor(x*3/4)),M=Math.max(1,Math.floor(S*3/4)),I=Math.max(1,Math.floor(A/2));if(t(W(this.#E.pendingBytes),R)||t(W(_.counters.pendingBytes),I)||t(W(E.counters.pendingBytes),M))return N("class")}if(t(U(this.#E.pendingBytes),x))return N("global");if(t(U(_.counters.pendingBytes),A))return N("owner");if(t(U(E.counters.pendingBytes),S))return N("domain");return}#b(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Zf()}}#O(){return{order:this.#M,counters:Zf()}}#A(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#I(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#c(f,E,_)}}}#c(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#P)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[A,t]of this.#_.entries()){let N=this.#h.get(t.domainKey),R=this.#T.get(t.ownerId);if(N===void 0||R===void 0||!this.#A(N,R,t.requestClass))continue;let M=this.#V(t,f),I=E.get(t.ownerId);if(!I||M<I.rank||M===I.rank&&A<I.index)E.set(t.ownerId,{pending:t,rank:M,index:A})}let _=[...E.values()].filter(({pending:A})=>{let t=this.#h.get(A.domainKey),N=this.#T.get(A.ownerId);return t!==void 0&&N!==void 0&&this.#A(t,N,A.requestClass)}).map(({pending:A,rank:t})=>({pending:A,rank:t,order:this.#T.get(A.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((A)=>A.rank)),h=_.filter((A)=>A.rank===T),S=h.filter((A)=>A.order>this.#S).sort((A,t)=>A.order-t.order)[0]??h.sort((A,t)=>A.order-t.order)[0];this.#u(S.pending,S.order)}}#V(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=E;let _=this.#I(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#j(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#D(f,E)}#D(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#N()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#J(T,h,f);if(this.#W(f),E)this.#z(f.domainKey,f.ownerId);return!0}#J(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,E){let _=this.#h.get(f);if(_&&QE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&QE(T.counters))this.#T.delete(E)}#$(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#L(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#k(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#X(f,E,_,T){return new xf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var CE;function sE(f={}){return CE??=new oE(f),CE}function vE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,S=0,A=!1,t=(R)=>{if(A||R<=0)return;if(!Number.isSafeInteger(R)||R>_-x){x=_+1,A=!0;return}x+=R},N=(R)=>{if(A)return;if(S+=1,S>T){t(_+1);return}if(R===null){t(4);return}switch(typeof R){case"string":t(Buffer.byteLength(R,"utf8"));return;case"number":case"bigint":t(8);return;case"boolean":t(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(R))return;if(h.add(R),ArrayBuffer.isView(R)){t(32+R.byteLength);return}if(R instanceof ArrayBuffer){t(32+R.byteLength);return}if(R instanceof Date){t(40);return}if(R instanceof RegExp){t(32+Buffer.byteLength(R.source,"utf8"));return}if(R instanceof Map){t(32);for(let[M,I]of R)if(N(M),N(I),A)return;return}if(R instanceof Set){t(32);for(let M of R)if(N(M),A)return;return}if(R instanceof WeakMap||R instanceof WeakSet){t(32);return}if(Array.isArray(R)){t(16);for(let M of R)if(N(M),A)return;return}t(32);for(let M of Reflect.ownKeys(R)){if(typeof M!=="string")continue;let I=Object.getOwnPropertyDescriptor(R,M);if(!I?.enumerable||!("value"in I))continue;if(t(8+Buffer.byteLength(M,"utf8")),N(I.value),A)return}};return N(f),x}function wE(f){return vE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var pE=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class Ff extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var n_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],r_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],i_=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function mE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function fT(f){let E=mE(f);return r_.some((_)=>E.includes(_))}function of(f){if(f!==null&&typeof f==="object")pE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&pE.has(f)}function ET(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function _T(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function TT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function e(f,E){let _=mE(f),T=ET(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(n_.some((x)=>_.includes(x))||fT(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??_T(f)??TT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(i_.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function sf(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function qE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=sf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let S=Math.max(0,f-1),A=_.maxExponentialDelayMs??8000,t=Math.min(500*2**S,A),N=Math.max(0,Math.min(1,_.random??Math.random())),R=t*(0.75+N*0.25);return Math.min(Math.round(R),h)}function aE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function hT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function vf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function xT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function tT(f,E,_,T){let h=T?void 0:hT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:xT(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function RT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function MT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;aE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function PT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(lE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}aE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function yE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:vf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(tT(x,E,f,h),RT(x,E.api,T?.toolChoice?.toolName),MT(x,E,f),PT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function gE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var AT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function eE(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,S)=>{let A=new Headers(x.headers);_(gE(x.status,A)),await T?.(x,S)},!AT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,S)=>{let A=await h(x,S);return _(gE(A.status,A.headers)),A}}function dE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,ST=30000;class nE extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class rE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function wf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function NT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function uT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:ST;return Math.max(1,Math.min(_,Math.floor(f/2)))}function IT(f,E,_){if(_?.aborted)return Promise.reject(wf(_));return new Promise((T,h)=>{let x=!1,S=()=>{clearTimeout(R),_?.removeEventListener("abort",N)},A=(M)=>{if(x)return;x=!0,S(),T(M)},t=(M)=>{if(x)return;x=!0,S(),h(M instanceof Error?M:Error(String(M)))},N=()=>{if(_)t(wf(_))},R=setTimeout(()=>A({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",N,{once:!0}),_?.aborted){N();return}f.then((M)=>A({kind:"next",result:M}),t)})}async function*DT(f,E,_){let T=NT(E),h=uT(T,E.stallWarningMs);if(E.signal?.aborted)throw wf(E.signal);let x=Date.now(),S=Promise.resolve().then(()=>f.next()),A;for(;;){let N=await IT(S,(A?T:h??T)-(Date.now()-x),E.signal);if(N.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-x)};return N.result}if(!A&&h!==void 0){_.stallCount++,A={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield A;continue}let R=new nE(T);throw E.abort?.(R),R}}async function*iE(f,E,_,T,h={}){let S=f.stream(E,_,T)[Symbol.asyncIterator](),A=0,t=!1,N={stallCount:0,outputStarted:!1};try{while(!0){let R=DT(S,h,N),M=await R.next();while(!M.done)yield{providerStall:M.value},M=await R.next();let I=M.value;if(I.done)throw new rE;let Y=I.value;switch(Y.type){case"text_delta":N.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":N.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":N.outputStarted=!0,yield{toolCalls:[{index:A++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":t=!0,yield{finishReason:Y.reason,usage:dE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!t)Promise.resolve(S.return?.()).catch(()=>{return})}}var pf=l("Chat"),HT=1;function UT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function YT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function BT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function bT(f,E){let _=e(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=sf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function mf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class lf{config;models;model;promptCacheBreakMonitor=new Jf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${HT++}`;constructor(f){let E=zf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=f_(this.config),pf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",S=[],A,t;for await(let N of this.streamChat(f,E,_,T)){h+=N.content??"",x+=N.reasoningContent??"";for(let R of N.toolCalls??[])if(R.id&&R.type==="function"&&R.function?.name)S.push(R);A=N.usage??A,t=N.finishReason??t}return{content:h,...x?{reasoningContent:x}:{},...S.length>0?{toolCalls:S}:{},usage:A,finishReason:t}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((P)=>P.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=ME(f);if(x.some((P)=>YT(P))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(h)||PE(x),A=await RE(x,this.model,E,_,h),t=(P,u)=>{let c=T?.providerSessionId;if(!c||!P.usage)return P;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(c),P;let B=vf(this.config,u,c),H=this.promptCacheBreakMonitor.observe({sessionId:c,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:A,retention:B,contextEpoch:BT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:B,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:P.usage});if(!H)return P;return pf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...P,usage:{...P.usage,promptCacheBreak:H}}},N=wE({messages:x,context:A,tools:E,requestOptions:T}),R=T?.providerRecovery;if(R&&!__(R.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=R?.mode==="bounded_foreground"&&R.budgetMs>0?{budgetMs:R.budgetMs,startedAt:void 0}:void 0,I=M?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(M?E_:2),Q=M!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??BE(),Rf=this.config.providerCircuitBreakerOpenMs??Wf,T_=Math.max(uf,Math.min(this.config.streamIdleTimeout??Hf,kf)),af=this.providerAdmissionScheduler,h_=this.config.providerRequestConcurrency??q,yf=this.config.providerRequestAdmissionMs??Kf,x_=this.config.providerRequestPendingBytes??Cf,Yf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},t_=(P,u)=>Uf.get({provider:P.provider,api:P.api,baseUrl:P.baseUrl??u.baseUrl??"",model:P.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Rf,probeLeaseMs:T_}),R_=(P,u)=>({provider:P.provider,api:P.api,baseUrl:P.baseUrl??u.baseUrl??"",model:P.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:h_,maxPendingBytes:x_}),j=(P=Date.now())=>{if(!M)return;let u=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,P-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,M.budgetMs-u)}},v=()=>({mode:I,...j()??{}}),ef=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},w=()=>{let P=j();return new y(M?.budgetMs??0,P?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,Bf=(P,u)=>{let{state:c,...B}=u;return{phase:P,...B,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},df=(P)=>({phase:"rejected",requestClass:P.requestClass,resource:P.resource,scope:P.scope,reason:P.reason,queuePosition:0,queueDepth:Math.max(0,P.queued),inFlight:Math.max(0,P.inFlight),limit:Math.max(0,P.limit),waitMs:P.reason==="wait_timeout"?P.maxWaitMs:0,maxWaitMs:P.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),M_=async function*(P,u){if(!af)return{release:()=>{return}};let c=j()?.recoveryRemainingMs,B=c!==void 0&&M?.startedAt!==void 0?Math.min(yf,c):yf,H;try{H=af.admit({scope:R_(P,u),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:B,pendingBytes:N,signal:_})}catch(b){if(tf(b)){if(b.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:df(b)}}throw b}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:Bf("queued",L)};let F=H.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=H.getSnapshot(),O=Math.max(1,Math.min(FE,Math.max(1,B-b.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),O),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:Bf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(tf(G.error)){if(G.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:df(G.error)}}throw G.error}return yield{providerAdmission:Bf("admitted",H.getSnapshot())},G.permit}},P_=(P,u)=>{if(!d())throw w();if(Q)K++;o=void 0;let c=new AbortController,B=_?xE(_,c.signal):c.signal,H=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,L;if(M?.startedAt!==void 0){let O=j()?.recoveryRemainingMs??0;if(O<=0)throw w();L={remainingMs:O,error:new y(M.budgetMs,M.budgetMs)}}let F=yE(u,P,B,T,S);eE(F,P,(O)=>{o=O});let b=iE(this.models,P,A,F,{idleTimeoutMs:u.streamIdleTimeout??Hf,signal:B,abort:(O)=>c.abort(O)});return async function*(){let O,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new Ff(H);O=setTimeout(()=>c.abort(X),H),O.unref?.()}if(L){let X=L;J=setTimeout(()=>c.abort(X.error),X.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},nf=this,g=(P)=>({phase:P.phase,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},...P.retryAfterMs!==void 0?{retryAfterMs:P.retryAfterMs}:{},...P.nextProbeAt!==void 0?{nextProbeAt:P.nextProbeAt}:{},openDurationMs:P.openDurationMs,sampleCount:P.sampleCount,failureCount:P.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),rf=(P,u)=>({phase:P,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),A_=(P)=>({phase:"probe",reason:P.reason??"server_error",...P.statusCode!==void 0?{statusCode:P.statusCode}:{},openDurationMs:P.openDurationMs??Rf,...P.sampleCount!==void 0?{sampleCount:P.sampleCount}:{},...P.failureCount!==void 0?{failureCount:P.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),bf=(P,u,c)=>({providerRetry:{phase:"exhausted",attempt:P,maxRetries:$,reason:u,...c!==void 0?{statusCode:c}:{},...v(),exhaustedBy:"recovery_budget"}}),fE=async function*(P,u,c,B,H){let L,F=!1,b,O,J=t_(P,u);for(let X=0;X<=B;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(b=D.reason,O=D.statusCode,!M||!H){let C=rf("rejected",D);throw yield{providerCircuit:C},new hf(C)}ef();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:rf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),qf,V);if(await ff(m,_,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*M_(P,u)}catch(Z){if(Z instanceof y)yield bf(Q?Math.max(0,K-1):X,b??"timeout",O);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let n=G.token;if(G.probe)yield{providerCircuit:A_(G)};try{let D=!1,k=!1;for await(let Z of P_(P,u)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&b&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(n);if(m)yield{providerCircuit:g(m)}}F=!0,c(),yield t(Z,P)}if(!k){let Z=J.recordSuccess(n);if(Z)yield{providerCircuit:g(Z)}}return}catch(D){if(p?.release(),L=D,nf.logIdleTimeout(D,F,P),await nf.handleAbort(_),D instanceof y){if(F)throw of(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=e(D,o);if(F)throw of(D),D;let Z=bT(D,o),V=Z?J.recordFailure(n,Z):o&&!mf(D)?J.recordNeutral(n):void 0;if(V)yield{providerCircuit:g(V)};if(!k.retryable||!k.reason){if(X>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};throw D}b=k.reason,O=k.statusCode;let m=X<B&&d();if(V&&V.phase!=="closed"&&m&&(!M||!H)){let C={...g(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){ef();let C=Q?K:X+1,N_=qE(C,o,M?{maxDelayMs:gf,maxExponentialDelayMs:gf}:void 0),_E=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(M&&_E>0&&V)yield{providerCircuit:{...g(V),phase:"waiting"}};let u_=j(),cf=Math.max(N_,_E),r=M?Math.min(cf,u_?.recoveryRemainingMs??cf):cf,Pf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Pf,delayMs:r,nextRetryAt:Date.now()+r,...v()}},M){let i=r;while(i>0){let TE=Math.min(i,qf);if(await ff(TE,_,{throwOnAbort:!0}),i-=TE,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Pf,...v(),exhaustedBy:"recovery_budget"}},Af}if(i>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...g(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Pf,delayMs:r,nextRetryAt:Date.now()+i,...v()}}}}}else await ff(r,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Pf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...M&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(n),p?.release()}}throw L},Of,EE=!1,Mf=this.config.fallbackModels??[],S_=M&&Mf.length>0?Math.min(Y,$):$;try{for await(let P of fE(this.model,this.config,()=>{EE=!0},S_,Mf.length===0))yield P;return}catch(P){if(Of=P,EE||!tf(P)&&!Lf(P)&&!mf(P)&&!e(P,o).retryable)throw P}for(let[P,u]of Mf.entries()){if(!d())break;yield{modelFallback:!0};let c=!1;try{let B=UT(this.config,u),H=NE(B,u),L=P===Mf.length-1,F=M&&!L?Math.min(Y,$):$;for await(let b of fE(H,B,()=>{c=!0},F,L))yield b;return}catch(B){if(Of=B,c||!tf(B)&&!Lf(B)&&!mf(B)&&!e(B,o).retryable)throw B}}throw Of}async handleAbort(f){if(f?.aborted)await ff(0,f,{throwOnAbort:!0})}logIdleTimeout(f,E,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;pf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=zf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=f_(this.config)}}function f_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return sE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??q,classLimitsEnabled:!1})}var OT=l("Service");async function Gh(f){let E=f;if(E.provider){let _=hE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},OT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return cT(E)}function cT(f){return new lf(f)}
5
+ export{XT as ee,WT as fe,xE as ge,tf as he,vE as ie,fT as je,Rh as ke,lf as le,Gh as me};
@@ -0,0 +1 @@
1
+ import{se as a,te as b,ue as c}from"./chunk-cvvtrvk6.js";import"./chunk-4cpgcm7q.js";import"./chunk-p7y79y6c.js";import"./chunk-k82ff14t.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-kka51s0k.js";import"./chunk-tzytnhbp.js";import"./chunk-948efzyp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-1ava19kd.js";import"./chunk-mefb27ch.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as Ye,z as Ze,H as _e,W as $e,Z as af};
18
+ export{R as $e,z as af,H as bf,W as cf,Z as df};
@@ -0,0 +1,6 @@
1
+ import{wd as s}from"./chunk-vw0gg08s.js";import{Pd as o}from"./chunk-bhhdvqe7.js";import{$f as E,Pf as y,Qf as D,Sf as N,Uf as j,Vf as F,Xf as R,ag as _,bg as f,cg as C,eg as S,fg as m,jg as c,og as l,pg as n}from"./chunk-4cpgcm7q.js";import{qg as Y}from"./chunk-p7y79y6c.js";import{sg as x,ug as k,xg as Z}from"./chunk-k82ff14t.js";import{Cg as X}from"./chunk-ah12xhh6.js";import{Gg as h,Hg as A,Ng as P,Og as T,Qg as $,Rg as U,Sg as G,Ug as L,Vg as M,Xg as O,Yg as I}from"./chunk-kka51s0k.js";import{eh as d}from"./chunk-tzytnhbp.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
+ [FAIL] 配置初始化失败
3
+ `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
+ 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
+ `),process.exit(1)}};function r(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Ak=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
+ export{Dk as td,hk as ud,Ak as vd};
@@ -0,0 +1 @@
1
+ import{jd as a,kd as b,ld as c,md as d,nd as e,od as f,pd as g,qd as h}from"./chunk-wp0794r2.js";import"./chunk-tzytnhbp.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -0,0 +1 @@
1
+ import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-b28zsp1t.js";import"./chunk-r8wbvxn7.js";import"./chunk-2wdxpdz3.js";import"./chunk-skw3b17a.js";import"./chunk-wp0794r2.js";import"./chunk-c9e0fbyh.js";import"./chunk-y36rdy4v.js";import"./chunk-js4vqnds.js";import"./chunk-4khtsmrf.js";import"./chunk-yvnm25nb.js";import"./chunk-67ddp3ns.js";import"./chunk-4ehgjdm0.js";import"./chunk-p7y79y6c.js";import"./chunk-k82ff14t.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-kka51s0k.js";import"./chunk-tzytnhbp.js";import"./chunk-948efzyp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-mefb27ch.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -0,0 +1 @@
1
+ import{Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g}from"./chunk-2wdxpdz3.js";import"./chunk-skw3b17a.js";import"./chunk-wp0794r2.js";import"./chunk-js4vqnds.js";import"./chunk-yvnm25nb.js";import"./chunk-4ehgjdm0.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-tzytnhbp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -0,0 +1 @@
1
+ import{f as a,g as i,h as l,i as m}from"./chunk-jeazjp08.js";import"./chunk-tvv3syt3.js";import"./chunk-b3413dtc.js";import"./chunk-tmvg7taj.js";import"./chunk-8fm3xamc.js";import"./chunk-r5bpvfym.js";import"./chunk-3hv57n95.js";import"./chunk-9cgsheg0.js";import"./chunk-fdmcef2p.js";import"./chunk-b28zsp1t.js";import"./chunk-r8wbvxn7.js";import"./chunk-2wdxpdz3.js";import"./chunk-skw3b17a.js";import"./chunk-wp0794r2.js";import{yd as n}from"./chunk-n1w40gq2.js";import"./chunk-3r0x2p7z.js";import{Ud as s}from"./chunk-bhhdvqe7.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-y36rdy4v.js";import"./chunk-vhadycw2.js";import"./chunk-js4vqnds.js";import"./chunk-cvvtrvk6.js";import"./chunk-5d1gbm41.js";import"./chunk-4khtsmrf.js";import"./chunk-yvnm25nb.js";import"./chunk-jkh9s1ht.js";import"./chunk-67ddp3ns.js";import"./chunk-4ehgjdm0.js";import"./chunk-4cpgcm7q.js";import"./chunk-p7y79y6c.js";import"./chunk-k82ff14t.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-kka51s0k.js";import"./chunk-tzytnhbp.js";import"./chunk-948efzyp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-1ava19kd.js";import"./chunk-mefb27ch.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,2 +1,2 @@
1
- import{Ih as F}from"./chunk-zf96d5we.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
- export{M as yh,z as zh,J as Ah,A as Bh,N as Ch,O as Dh,Q as Eh,T as Fh,E as Gh,U as Hh};
1
+ import{Mh as F}from"./chunk-0hrj06t7.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
+ export{M as Ch,z as Dh,J as Eh,A as Fh,N as Gh,O as Hh,Q as Ih,T as Jh,E as Kh,U as Lh};
@@ -0,0 +1,18 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-DUPwAzs4.js","assets/index-gjBOFzd1.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-DovdPN7M.js","assets/session-events-Bgir_Gl_.js","assets/index-8G4ejlcH.css"])))=>i.map(i=>d[i]);
2
+ import{r as f,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as D,a as y,b as ke,s as Be,c as Xe,d as Y,D as Ie,e as _e,f as Ze,g as Pe,h as Ve,i as Le,j as M,k as H,B as fe,_ as Oe,S as et,l as Ue,m as tt,n as st,C as at,o as rt}from"./index-gjBOFzd1.js";import{U as Se,Q as nt,G as He,Z as it,L as $,E as Ke,T as X,C as oe,_ as ot,w as lt,$ as ct,B as dt,a0 as qe,z as Z,n as le,R as je,t as ut,H as mt,a1 as ze,V as ht,a2 as xt,a3 as pt,a4 as ft,P as Ge,a5 as bt,X as We,a6 as vt,a7 as gt,f as ye,a8 as kt,a9 as jt,aa as yt,ab as wt,W as Nt,a as St}from"./vendor-icons-DovdPN7M.js";import{k as Ct,g as Et,l as Tt,e as Mt,t as At,j as Rt}from"./session-events-Bgir_Gl_.js";import{j as Ft,k as $t,l as Dt,m as Qe}from"./vendor-radix-DXRuAJHH.js";import{t as F}from"./team-QZ9byb3E.js";import{teamService as Ce}from"./teamService-Bb2kW8Hh.js";function Ee(t){return t.split("/").filter(Boolean).at(-1)||t}function Bt(){const t=D(),s=y(w=>w.sessions),a=y(w=>w.currentSessionRef),r=y(w=>w.taskDeliveryActions),o=y(w=>w.deliverTask),i=ke(w=>w.openFilePreview),[u,b]=f.useState(!1),d=s.find(w=>Be({sessionId:w.sessionId,projectPath:w.projectPath},a));if(!(d!=null&&d.taskIsolation))return null;const c=d.taskDiffStat,k=d.taskIsolation==="worktree",l=Xe(d),p=r[Y(l)],x=d.taskDelivery,j=(x==null?void 0:x.status)==="conflicted",S=!!(c&&(c.changedFiles>0||c.commits>0)),h=!["queued","running"].includes(d.taskStatus),N=(x==null?void 0:x.status)==="applied"||(x==null?void 0:x.status)==="discarded",v=k&&S&&h&&!N,n=c?c.additions+c.deletions:0,m=n>0&&c?c.additions/n*100:0,E=w=>{o(l,w).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(Se,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Ee(d.taskSourceProjectPath||d.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[k?e.jsx(nt,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(Se,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:k?"text-[hsl(var(--deck-accent))]":void 0,children:t(k?"artifact.env.isolated":"artifact.env.local")})]}),d.taskWorktreeBranch&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 truncate",title:d.taskWorktreeBranch,children:[e.jsx(He,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:d.taskWorktreeBranch})]})]})]}),c&&e.jsxs("div",{className:"ml-auto flex max-w-full items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(it,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:c.changedFiles})]}),n>0&&e.jsxs("span",{className:"relative hidden h-1.5 w-14 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:inline-flex","aria-hidden":"true",children:[e.jsx("span",{className:"h-full bg-[hsl(var(--deck-accent))]",style:{width:`${m}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-m}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",c.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",c.deletions]}),c.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:c.commits})}),S&&(x==null?void 0:x.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>i({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!p,onClick:()=>E("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[p==="apply"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(Ke,{className:"h-3 w-3"}),t(p==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!p,onClick:()=>b(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:p==="discard"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(X,{className:"h-3 w-3"})})]}),(x==null?void 0:x.status)==="applied"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-2 py-1 font-semibold text-emerald-700 dark:text-emerald-300",children:[e.jsx(oe,{className:"h-3 w-3"}),t("artifact.applied")]}),(x==null?void 0:x.status)==="discarded"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-surface-2))] px-2 py-1 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(X,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(x==null?void 0:x.status)==="conflicted"&&e.jsxs("div",{className:"flex w-full items-start gap-1.5 border-t border-amber-500/20 pt-1.5 text-amber-700 dark:text-amber-300",role:"alert",children:[e.jsx(ot,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block",children:x.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Ie,{open:u,onOpenChange:b,children:e.jsxs(_e,{className:"w-[calc(100%_-_2rem)] max-w-md border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]",children:[e.jsxs(Ze,{children:[e.jsx(Pe,{children:t("artifact.discardDialog.title")}),e.jsx(Ve,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Ee(d.taskSourceProjectPath||d.projectPath),count:(c==null?void 0:c.changedFiles)??0})})]}),e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs leading-relaxed text-red-700 dark:text-red-300",children:t("artifact.discardDialog.warning")}),e.jsxs(Le,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{b(!1),E("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(X,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const It=new Set(["completed","stale","failed","aborted","interrupted"]),_t={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Pt={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function ne(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Vt(t){const s=ne(t),a=ne(s==null?void 0:s.codeLocation),r=s==null?void 0:s.priority,o=s==null?void 0:s.confidenceScore,i=a==null?void 0:a.lineStart,u=a==null?void 0:a.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof o!="number"||!Number.isFinite(o)||typeof(a==null?void 0:a.path)!="string"||!Number.isInteger(i)||!Number.isInteger(u)))return{title:s.title,body:s.body,priority:r,confidenceScore:o,codeLocation:{path:a.path,lineStart:i,lineEnd:u}}}function Lt(t){const s=ne(t),a=ne(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!It.has(s.status)||typeof(a==null?void 0:a.label)!="string"||a.kind!=="uncommitted"&&a.kind!=="base"&&a.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const r=s.findings.map(Vt);if(!r.some(o=>o===void 0))return{status:s.status,target:{kind:a.kind,label:a.label,...typeof a.reference=="string"?{reference:a.reference}:{}},overallExplanation:s.overallExplanation,findings:r,...typeof s.error=="string"?{error:s.error}:{}}}function Ot(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function Ut({report:t}){const s=D(),a=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",a]})]}),e.jsxs("span",{className:M("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Pt[t.status]),children:[s("chat.review.status"),": ",s(_t[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((r,o)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:r.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Ot(r)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:r.body})]},`${r.codeLocation.path}:${r.codeLocation.lineStart}:${o}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function Ht({elicitation:t,messageId:s}){const a=D(),r=y(v=>v.currentSessionRef),o=y(v=>v.setElicitation),[i,u]=f.useState(()=>qt(t.details.fields??[])),[b,d]=f.useState(()=>zt(t.details.fields??[])),[c,k]=f.useState(!1),[l,p]=f.useState(),x=t.details.fields??[],j=f.useMemo(()=>x.every(v=>{var m;if(!v.required)return!0;if(ce(v))return!!((m=b[v.name])!=null&&m.trim()||v.defaultValue!==void 0);const n=i[v.name]??v.defaultValue;return Array.isArray(n)?n.length>0:n!==void 0}),[x,b,i]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const S=async(v,n)=>{if(!(!r||c)){k(!0),p(void 0);try{await H.respondToElicitation(r,t.toolCallId,{action:v,...n?{content:n}:{}}),o(s,{...t,status:"responded"})}catch(m){p(m instanceof Error?m.message:a("interaction.elicitation.failed"))}finally{k(!1)}}},h=async()=>{try{await S("accept",Gt(x,i,b))}catch(v){p(v instanceof Error?v.message:String(v))}},N=()=>{const v=t.details.url;if(!v){p("MCP URL is unavailable");return}if(!window.open(v,"_blank","noopener,noreferrer")){p("The browser blocked the external window");return}S("accept")};return e.jsxs("div",{"data-pending-interaction":"elicitation",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(lt,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[a("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:a("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{onClick:N,disabled:c,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(ct,{className:"h-3.5 w-3.5"})}),e.jsx(z,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(z,{onClick:()=>void S("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[x.map(v=>e.jsx(Kt,{field:v,value:i[v.name],rawValue:b[v.name]??"",onValueChange:n=>u(m=>({...m,[v.name]:n})),onRawChange:n=>d(m=>({...m,[v.name]:n}))},v.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{onClick:()=>void h(),disabled:c||!j,primary:!0,label:a("interaction.elicitation.submit"),icon:c?e.jsx($,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(z,{onClick:()=>void S("decline"),disabled:c,label:a("interaction.elicitation.decline")}),e.jsx(z,{onClick:()=>void S("cancel"),disabled:c,label:a("interaction.elicitation.cancel")})]})]}),l&&e.jsx("div",{className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:l})]})}function Kt({field:t,value:s,rawValue:a,onValueChange:r,onRawChange:o}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Wt(t).map(i=>{const u=Array.isArray(s)?s.includes(i.value):s===i.typedValue;return e.jsx("button",{type:"button","aria-pressed":u,onClick:()=>{if(t.type==="multi-select"){const b=Array.isArray(s)?s:[];r(b.includes(i.value)?b.filter(d=>d!==i.value):[...b,i.value])}else r(i.typedValue)},className:M("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",u?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:i.label},i.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Qt(t),value:a,onChange:i=>o(i.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function z({onClick:t,disabled:s,primary:a=!1,label:r,icon:o}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:M("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",a?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[o,r]})}function qt(t){return Object.fromEntries(t.filter(s=>!ce(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function zt(t){return Object.fromEntries(t.filter(s=>ce(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Gt(t,s,a){var o;const r={};for(const i of t){if(ce(i)){const b=((o=a[i.name])==null?void 0:o.trim())??"";if(!b){if(i.defaultValue!==void 0)r[i.name]=i.defaultValue;else if(i.required)throw new Error(`${i.title} is required`);continue}if(i.type==="number"||i.type==="integer"){const d=Number(b);if(!Number.isFinite(d))throw new Error(`${i.title} must be a finite number`);if(i.type==="integer"&&!Number.isSafeInteger(d))throw new Error(`${i.title} must be a safe integer`);r[i.name]=d}else r[i.name]=b;continue}const u=s[i.name]??i.defaultValue;if(u===void 0){if(i.required)throw new Error(`${i.title} is required`);continue}if(Array.isArray(u)){if(i.minItems!==void 0&&u.length<i.minItems)throw new Error(`${i.title} requires at least ${i.minItems} choices`);if(i.maxItems!==void 0&&u.length>i.maxItems)throw new Error(`${i.title} allows at most ${i.maxItems} choices`)}r[i.name]=u}return r}function Wt(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function ce(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Qt(t){return t.type==="number"||t.type==="integer"?"number":t.format==="email"?"email":t.format==="uri"?"url":t.format==="date"?"date":t.format==="date-time"?"datetime-local":"text"}function Jt(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function Yt({report:t}){const s=D(),[a,r]=f.useState(!1),o=JSON.stringify(t.output,null,2),i=async()=>{try{await navigator.clipboard.writeText(o),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(dt,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:i,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(oe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(qe,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:o})]})}const Xt=f.lazy(()=>Oe(()=>import("./MarkdownRenderer-DUPwAzs4.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Te({text:t,label:s}){const[a,r]=f.useState(!1);if(!t.trim())return null;const o=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:o,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:a?e.jsx(oe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(qe,{className:"h-3.5 w-3.5"})})}function Zt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] shadow-[0_1px_0_hsl(var(--deck-hairline))]",children:e.jsx(fe,{size:20,pulse:!1})})}function es(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-full border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas-veil))]",children:e.jsx("span",{className:"font-mono text-[11px] font-medium text-[hsl(var(--deck-ink))]",children:"U"})})}function Me(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function ts(t){if(typeof t=="string")return{text:Me(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
3
+ `),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:Me(s),images:a}}function we(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+ `)}function ss(t){const s=t.agentContent;return s?Ct(s):we(t.content)}function Ae({content:t,syntaxHighlight:s=!0}){return e.jsx(f.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(Xt,{content:t,syntaxHighlight:s})})}function Ne({status:t}){if(!t)return null;const s={running:"bg-[#FEF3C7] text-[#92400E] dark:bg-[#F59E0B]/20 dark:text-[#FBBF24]",success:"bg-[#DCFCE7] text-[#15803D] dark:bg-[#22C55E]/20 dark:text-[#22C55E]",error:"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]",pending:"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]",info:"bg-[#DBEAFE] text-[#1D4ED8] dark:bg-[#3B82F6]/20 dark:text-[#60A5FA]"},a={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:M("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function as(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}const Re=500;function Je(t,s){if(t.length<=s)return t;let a=Math.max(0,s);return a>0&&/[\uD800-\uDBFF]/.test(t.charAt(a-1))&&(a-=1),t.slice(0,a)}function Fe(t,s){if(t.length<=s)return t;let a=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(a))&&(a+=1),t.slice(a)}function me(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
5
+ ... (display clipped) ...
6
+ `,r=s-a.length;if(r<=0)return Fe(t,s);const o=Math.floor(r/3);return`${Je(t,o)}${a}${Fe(t,r-o)}`}function rs(t){const s=t.split(`
7
+ `),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,o=r?s.slice(0,-1).join(`
8
+ `):t,i=r?`
9
+ ${r}`:"",u=Math.max(0,Re-i.length),d=o.indexOf(`
10
+ stderr:
11
+ `);let c;if(d>=0&&o.includes(`
12
+ stdout:
13
+ `)){const k=o.slice(0,d),l=o.slice(d+1),p=Math.max(0,u-1),x=Math.floor(p/2);c=`${me(k,x)}
14
+ ${me(l,p-x)}`}else c=me(o,u);return{body:Je(c,u),...r?{notice:r}:{},truncated:!!r||t.length>Re}}function ns({tool:t}){const[s,a]=f.useState(!1),r=as(t.arguments),o=t.output?rs(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":o!=null&&o.truncated?"true":"false",className:"bg-white dark:bg-[#18181b] border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":s,"data-tool-call-id":t.toolCallId,onClick:()=>a(i=>!i),className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--deck-surface-2))] hover:bg-[hsl(var(--deck-surface))] transition-colors",children:[e.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[s?e.jsx(Z,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(le,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}),e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink))] font-mono shrink-0",children:t.toolName}),t.summary&&e.jsx("span",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono truncate",children:t.summary})]}),e.jsx(Ne,{status:t.status})]}),t.status==="running"&&t.progressMessage&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{className:"truncate",children:t.progressMessage}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsxs("span",{className:"shrink-0",children:[Math.max(0,Math.min(100,Math.round(t.progress/t.progressTotal*100))),"%"]})]}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${t.toolName} progress`,"aria-valuemin":0,"aria-valuemax":t.progressTotal,"aria-valuenow":Math.min(t.progress,t.progressTotal),className:"h-1 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,t.progress/t.progressTotal*100))}%`}})})]}),s&&e.jsxs("div",{className:"px-3 py-2 space-y-2 border-t border-[hsl(var(--deck-border))]",children:[r&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Arguments"}),e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:r})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Output"}),e.jsxs("pre",{"data-tool-output":!0,className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:[o.body,o.notice&&e.jsxs(e.Fragment,{children:[`
15
+ `,e.jsx("span",{"data-tool-truncation-notice":!0,children:o.notice})]})]})]})]})]})}function Ye({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(ns,{tool:s},s.toolCallId))})}function is({toolCalls:t,toolCallIds:s}){const a=D(),[r,o]=f.useState(!1),i=f.useMemo(()=>new Map(t.map(l=>[l.toolCallId,l])),[t]),u=s.flatMap(l=>{const p=i.get(l);return p?[p]:[]});if(u.length===0)return null;const b=u.filter(l=>l.status==="running").length,d=u.filter(l=>l.status==="error").length,c=[...u].reverse().find(l=>l.status==="running"&&!!l.progressMessage),k=b>0?a(u.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:u.length}):d>0?a(u.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:u.length,errors:d}):a(u.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:u.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>o(l=>!l),className:"group flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[r?e.jsx(Z,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(le,{className:"h-3.5 w-3.5 shrink-0"}),b>0&&e.jsx($,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:k}),(c==null?void 0:c.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[c.progressMessage,c.progress!==void 0&&c.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(c.progress/c.progressTotal*100)))}%`]})]}),(c==null?void 0:c.progress)!==void 0&&c.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${c.toolName} progress`,"aria-valuemin":0,"aria-valuemax":c.progressTotal,"aria-valuenow":Math.min(c.progress,c.progressTotal),className:"mx-1.5 h-0.5 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,c.progress/c.progressTotal*100))}%`}})}),r&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"mt-2 space-y-2 pl-1",children:e.jsx(Ye,{toolCalls:u})})]})}function os({content:t}){const s=D(),[a,r]=f.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>r(o=>!o),className:"flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[a?e.jsx(Z,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(le,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),a&&e.jsx("div",{className:"ml-1 mt-1 border-l border-[hsl(var(--deck-border))] py-1 pl-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:t})})]}):null}function ls({tasks:t}){if(t.length===0)return null;const s=t.filter(r=>r.status==="completed").length,a=s===t.length;return e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"flex gap-2 items-center",children:e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function cs({toolCalls:t}){const s=ke(r=>r.openFilePreview),a=f.useMemo(()=>{const r=new Map,o=["Write","SearchReplace","Edit","ApplyPatch"];for(const i of t){if(i.status!=="success")continue;const u=i.metadata;if(i.toolName==="ApplyPatch"&&Array.isArray(u==null?void 0:u.changes)){for(const d of u.changes)d&&typeof d=="object"&&"path"in d&&typeof d.path=="string"&&r.set(d.path,{path:d.path,toolName:i.toolName});continue}const b=u==null?void 0:u.file_path;b&&o.includes(i.toolName)&&r.set(b,{path:b,toolName:i.toolName})}return Array.from(r.values())},[t]);return a.length===0?null:e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono mb-1.5",children:["Changed files (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(({path:r})=>{const o=r.split("/").pop()||r;return e.jsxs("button",{onClick:()=>s({tab:"diff",targetPath:r}),className:"flex items-center gap-1 px-2 py-1 text-[11px] font-mono bg-[#E5E7EB] dark:bg-[#27272a] text-[hsl(var(--deck-ink))] rounded hover:bg-[#D1D5DB] dark:hover:bg-[#3f3f46] transition-colors",title:r,children:[e.jsx(ut,{className:"w-3 h-3"}),o]},r)})})]})}function ds({subagent:t}){var W,q,ee,te;const s=D(),[a,r]=f.useState(null),[o,i]=f.useState(!1),[u,b]=f.useState(null),[d,c]=f.useState(!1),[k,l]=f.useState(""),[p,x]=f.useState(!1),[j,S]=f.useState(null),[h,N]=f.useState(null),[v,n]=f.useState(null),m=y(A=>A.currentSessionRef),E=y(A=>A.isStreaming),w=y(A=>A.isTemporarySession);if(!t)return null;const C=t.status==="running",R=a!==null?a:C,O=t.toolCalls||u||[],P=t.output||t.thinking||O.length>0||t.sessionId,T=h&&h.status!=="running"?h:v,I=(T==null?void 0:T.id)??t.sessionId,K=((W=T==null?void 0:T.restartRecovery)==null?void 0:W.outcome)==="failed",de=!C&&!E&&!w&&!K&&(h==null?void 0:h.status)!=="running"&&!!(I&&m);f.useEffect(()=>{if(!R||C||!t.sessionId||!(m!=null&&m.projectPath)||u!==null||t.toolCalls&&t.toolCalls.length>0)return;let A=!0;return i(!0),H.getMessages({sessionId:t.sessionId,projectPath:m.projectPath}).then(V=>{var _,B;if(!A)return;const L=Mt(V),g=new Map;for(const Q of L)if((B=(_=Q.agentContent)==null?void 0:_.toolCalls)!=null&&B.length)for(const ue of Q.agentContent.toolCalls)g.has(ue.toolCallId)||g.set(ue.toolCallId,ue);b(Array.from(g.values()))}).finally(()=>{A&&i(!1)}),()=>{A=!1}},[R,C,t.sessionId,t.toolCalls,u,m==null?void 0:m.projectPath]),f.useEffect(()=>{if(!t.sessionId||!m)return;let A=!0;const V=t.rootAgentId??t.sessionId,L=t.resumeDepth??0;return H.listSubagents(m).then(g=>{if(!A)return;n(g.find(B=>B.id===t.sessionId)??null);const _=g.filter(B=>B.id!==t.sessionId&&B.rootAgentId===V&&B.resumeDepth>L).sort((B,Q)=>Q.resumeDepth-B.resumeDepth||Q.lastActiveAt-B.lastActiveAt)[0];_&&N(_)}).catch(()=>{}),()=>{A=!1}},[m==null?void 0:m.sessionId,m==null?void 0:m.projectPath,t.sessionId,t.rootAgentId,t.resumeDepth]),f.useEffect(()=>{if(!h||h.status!=="running"||!m)return;let A=!0;const V=async()=>{try{const _=(await H.listSubagents(m)).find(B=>B.id===h.id);A&&_&&N(_)}catch{}},L=window.setInterval(()=>{V()},1e3);return()=>{A=!1,window.clearInterval(L)}},[m,h==null?void 0:h.id,h==null?void 0:h.status]);const G=async()=>{if(!(!m||!I||!k.trim()||p)){x(!0),S(null);try{const A=await H.resumeSubagent(m,I,k.trim());N(A.session),l(""),c(!1),r(!0)}catch(A){S(A instanceof Error?A.message:s("chat.subagent.resumeFailed"))}finally{x(!1)}}};return e.jsxs("div",{"data-subagent-id":t.id,"data-subagent-session-id":t.sessionId,className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(!R),className:"flex gap-2 justify-between items-center w-full transition-opacity cursor-pointer hover:opacity-80",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[C&&e.jsx($,{className:"h-3 w-3 animate-spin text-[hsl(var(--deck-ink-muted))]"}),e.jsxs("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[t.type,": ",t.description]}),e.jsx(Ne,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:M("rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",t.verificationVerdict==="pass"?"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":t.verificationVerdict==="fail"?"bg-red-500/10 text-red-600 dark:text-red-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"),children:t.verificationVerdict}),t.resumedFrom&&e.jsx("span",{className:"rounded bg-[#EDE9FE] px-1.5 py-0.5 text-[10px] font-mono text-[#6D28D9] dark:bg-[#2E1065] dark:text-[#C4B5FD]",title:s("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:s("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),P&&e.jsx(Z,{className:M("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",R&&"rotate-180")})]}),!R&&!C&&t.output&&e.jsx("div",{"data-subagent-output-summary":!0,className:"mt-2 max-h-10 overflow-hidden whitespace-pre-wrap break-words font-mono text-[11px] text-[hsl(var(--deck-ink))]",children:t.output}),R&&e.jsxs("div",{className:"mt-2 space-y-2",children:[(t.output||t.thinking)&&e.jsxs(e.Fragment,{children:[t.output&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[160px] overflow-y-auto",children:t.output}),t.thinking&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:t.thinking})]}),o&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx($,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!o&&O.length>0&&e.jsx(Ye,{toolCalls:O}),h&&e.jsxs("div",{className:"rounded-md border border-[#DDD6FE] bg-[#F5F3FF] p-2 text-[11px] font-mono text-[#5B21B6] dark:border-[#4C1D95] dark:bg-[#1E1B4B] dark:text-[#C4B5FD]",children:[e.jsx("div",{children:s("chat.subagent.resumedAs",{id:h.id,status:h.status,depth:h.resumeDepth??1})}),(((q=h.result)==null?void 0:q.message)||((ee=h.result)==null?void 0:ee.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:h.result.message||h.result.error})]}),K&&((te=T==null?void 0:T.result)==null?void 0:te.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:T.result.error}),de&&e.jsxs("div",{className:"space-y-2",children:[d?e.jsxs("div",{className:"space-y-2 rounded-md border border-[#E5E7EB] bg-white p-2 dark:border-[#27272a] dark:bg-[#111113]",children:[e.jsx("textarea",{"aria-label":s("chat.subagent.followUpAria"),value:k,onChange:A=>l(A.target.value),placeholder:s("chat.subagent.followUpPlaceholder"),rows:3,className:"w-full resize-y rounded border border-[#D1D5DB] bg-white p-2 text-[11px] text-[#111827] outline-none focus:border-[#8B5CF6] dark:border-[#3f3f46] dark:bg-[#18181b] dark:text-[#f4f4f5]"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>{c(!1),S(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:s("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void G(),disabled:!k.trim()||p,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[p&&e.jsx($,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-md border border-[#D1D5DB] px-2 py-1 text-[11px] font-medium text-[#374151] transition-colors hover:bg-[#F3F4F6] dark:border-[#3f3f46] dark:text-[#d4d4d8] dark:hover:bg-[#27272a]",children:[e.jsx(je,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),j&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:j})]})]})]})}function us({confirmation:t,messageId:s}){const a=D(),[r,o]=f.useState(!1),[i,u]=f.useState(null),b=y(k=>k.currentSessionRef),d=y(k=>k.setConfirmation);if(!t)return null;const c=async(k,l)=>{if(!(!b||r)){o(!0),u(null);try{await H.respondPermission(b,t.toolCallId,{approved:k,scope:l}),d(s,{...t,status:k?"approved":"denied"})}catch(p){u(p instanceof Error?p.message:a("interaction.permission.failed"))}finally{o(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"space-y-3 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:a("interaction.permission.title",{tool:t.toolName})}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t.description}),t.diff&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[200px] overflow-y-auto",children:t.diff}),i&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:i}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void c(!0,"once"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:r?e.jsx($,{className:"h-3.5 w-3.5 animate-spin"}):a("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void c(!0,"session"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#3B82F6] text-white rounded-md hover:bg-[#2563EB] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void c(!0,"project"),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#6366F1] text-white rounded-md hover:bg-[#4F46E5] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void c(!1),disabled:r,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#EF4444] text-white rounded-md hover:bg-[#DC2626] disabled:cursor-wait disabled:opacity-50",children:a("interaction.permission.deny")})]})]})}function ms({question:t,messageId:s}){const a=D(),[r,o]=f.useState({}),[i,u]=f.useState({}),[b,d]=f.useState(!1),[c,k]=f.useState(null),l=y(h=>h.currentSessionRef),p=y(h=>h.setQuestion),x=f.useMemo(()=>t?t.questions.reduce((h,N)=>{var E;const v=(E=i[N.header])==null?void 0:E.trim(),n=r[N.header];if(N.multiSelect){const w=Array.isArray(n)?[...n]:[];return v&&w.push(v),w.length>0&&(h[N.header]=w),h}const m=v||(typeof n=="string"?n:"");return m&&(h[N.header]=m),h},{}):{},[r,i,t]),j=(t==null?void 0:t.questions.every(h=>h.header in x))??!1;if(!t)return null;const S=async()=>{if(!(!l||b||!j)){d(!0),k(null);try{await H.respondToQuestion(l,t.toolCallId,x),p(s,{...t,status:"answered",answers:x})}catch(h){k(h instanceof Error?h.message:a("interaction.question.failed"))}finally{d(!1)}}};return t.status!=="pending"?e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:a("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((h,N)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:h.question}),e.jsxs("div",{className:"space-y-1",children:[h.options.map((v,n)=>e.jsxs("button",{type:"button",onClick:()=>{if(h.multiSelect){const m=r[h.header]||[],E=m.includes(v.label)?m.filter(w=>w!==v.label):[...m,v.label];o({...r,[h.header]:E})}else o({...r,[h.header]:v.label}),u({...i,[h.header]:""})},className:M("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(h.multiSelect?(r[h.header]||[]).includes(v.label):r[h.header]===v.label)?"bg-[#DCFCE7] text-[#166534] dark:bg-[#22C55E]/20 dark:text-[#E5E5E5]":"bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))]"),children:[e.jsx("div",{children:v.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:v.description})]},n)),e.jsx("input",{"aria-label":`${h.header} other response`,value:i[h.header]??"",onChange:v=>u({...i,[h.header]:v.target.value}),placeholder:a("interaction.question.other"),className:"w-full rounded-md border border-[#E5E7EB] bg-white px-3 py-2 text-[12px] text-[#111827] outline-none focus:border-[#22C55E] dark:border-[#27272a] dark:bg-[#111113] dark:text-[#E5E5E5]"})]})]},N)),c&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:c}),e.jsxs("button",{type:"button",onClick:()=>void S(),disabled:b||!j,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[b&&e.jsx($,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function hs({message:t}){const s=t.agentContent,a=y(j=>j.isStreaming&&j.currentAssistantMessageId===t.id);if(!s){const j=we(t.content);return j?e.jsx(Ae,{content:j}):null}const{toolCalls:r,tasks:o,confirmation:i,question:u,elicitation:b}=s,d=Et(s),c=Tt(s);if(!(c.length>0||o.length>0||d.length>0||i||u||b)&&a)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx($,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const p=r.length>0&&r.every(j=>j.status==="success"||j.status==="error")&&!a,x=!a;return e.jsxs("div",{className:"space-y-3",children:[c.map(j=>j.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(os,{content:j.content})},j.id):j.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Ae,{content:j.content,syntaxHighlight:x})},j.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(is,{toolCalls:r,toolCallIds:j.toolCallIds})},j.id)),o.length>0&&e.jsx(ls,{tasks:o}),d.map(j=>e.jsx(ds,{subagent:j},j.id)),i&&e.jsx(us,{confirmation:i,messageId:t.id}),u&&e.jsx(ms,{question:u,messageId:t.id}),b&&e.jsx(Ht,{elicitation:b,messageId:t.id}),p&&e.jsx(cs,{toolCalls:r})]})}function xs({message:t,showAvatar:s=!0}){var b,d,c,k;const a=t.role==="user";if(t.role==="system"){const l=we(t.content);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"system",className:"flex justify-center p-2 w-full",children:e.jsx("div",{className:"text-xs text-[hsl(var(--deck-ink-muted))] bg-[#F3F4F6] dark:bg-[#18181b] px-3 py-1 rounded-full font-mono",children:l})})}if(a){const l=(b=t.metadata)!=null&&b.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(d=t.metadata)!=null&&d.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(l){const j=typeof l.command=="string"?l.command:"",S=l.status==="running"?"running":l.status==="completed"?"success":"error",h=typeof l.output=="string"?l.output:[typeof l.stdout=="string"?l.stdout:"",typeof l.stderr=="string"&&l.stderr?`stderr:
16
+ ${l.stderr}`:""].filter(Boolean).join(`
17
+ `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),j]}),e.jsx(Ne,{status:S})]}),e.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:h||"(no output)"}),typeof l.exitCode=="number"&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-1.5 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:["exit ",l.exitCode,typeof l.durationMs=="number"?` · ${(l.durationMs/1e3).toFixed(3)}s`:"",l.truncated===!0?" · truncated":""]})]})})}const{text:p,images:x}=ts(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"group flex gap-2 justify-end p-4 w-full items-start",children:[e.jsx("div",{className:"mt-1 flex shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Te,{text:p,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[p&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:p}),x.length>0&&e.jsx("div",{className:M("grid gap-2",x.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:x.map((j,S)=>e.jsx("img",{src:j,alt:`attachment-${S+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${j}-${S}`))})]}),e.jsx(es,{})]})}const o=ss(t),i=Lt((c=t.metadata)==null?void 0:c.codeReview),u=Jt((k=t.metadata)==null?void 0:k.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:M("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(Zt,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[i?e.jsx(Ut,{report:i}):u?e.jsx(Yt,{report:u}):e.jsx(hs,{message:t}),!u&&o.trim()&&e.jsx("div",{className:"mt-1.5 flex opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Te,{text:o,label:"Copy response"})})]})]})}const ps=f.memo(xs);function fs(t,s,a){return Math.max(0,t+(a-s))}function bs(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function $e(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function vs({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const o=D(),[i,u]=f.useState(null),[b,d]=f.useState(!1),c=f.useRef(null),k=f.useCallback(()=>{var h;const p=s.current,x=a.current;if(!p||!x||t.length===0)return;const j=p.getBoundingClientRect().top;let S=((h=t[0])==null?void 0:h.id)??null;for(const N of t){const v=$e(x,N.id);if(v)if(v.getBoundingClientRect().top-j<=24)S=N.id;else break}u(S)},[t,s,a]);f.useEffect(()=>{const p=s.current;if(!p)return;const x=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,k()}))};return k(),p.addEventListener("scroll",x,{passive:!0}),()=>{p.removeEventListener("scroll",x),c.current!==null&&(window.cancelAnimationFrame(c.current),c.current=null)}},[k,s]);const l=f.useCallback(p=>{const x=()=>{const S=$e(a.current,p.id);S&&(S.scrollIntoView({behavior:"smooth",block:"start"}),u(p.id))};r(p.index)?x():window.requestAnimationFrame(()=>window.requestAnimationFrame(x))},[a,r]);return t.length<2?null:e.jsx("nav",{"aria-label":o("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onFocusCapture:()=>d(!0),onBlurCapture:p=>{p.currentTarget.contains(p.relatedTarget)||d(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:M("flex flex-col items-center gap-2 py-2 transition-opacity",b?"opacity-0":"opacity-100"),"aria-hidden":b,children:t.map(p=>e.jsx("li",{children:e.jsx("span",{className:M("block rounded-full transition-all",p.id===i?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},p.id))}),e.jsx("div",{className:M("absolute right-0 max-h-[min(70vh,520px)] w-[280px] overflow-y-auto rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/95 p-1 shadow-xl backdrop-blur transition-all",b?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((p,x)=>e.jsxs("button",{type:"button",onClick:()=>l(p),className:M("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",p.id===i?"bg-[hsl(var(--deck-hairline))]/70 text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-hairline))]/50 hover:text-[hsl(var(--deck-ink))]"),children:[e.jsx("span",{className:M("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",p.id===i?"bg-[hsl(var(--deck-accent))]":"bg-[hsl(var(--deck-ink-faint))]/40")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block font-mono text-[9.5px] uppercase tracking-[0.12em] text-[hsl(var(--deck-ink-faint))]",children:o("chat.turns.label",{n:x+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:p.preview})]})]},p.id))})]})})}const De=80;function gs(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function ks(t){const s=gs(t).replace(/\s+/g," ").trim();return s?s.length>De?`${s.slice(0,De-1)}…`:s:""}function js(t){const s=[];for(let a=0;a<t.length;a+=1){const r=t[a];if(r.role!=="user"||!r.id)continue;const o=ks(r.content);o&&s.push({id:r.id,index:a,preview:o})}return s}const he=120,xe=80,ys=96;function J(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function ws({messages:t,isLoading:s}){const a=D(),r=f.useRef(null),o=f.useRef(null),i=f.useRef(!0),u=f.useRef(t.length),b=f.useRef(null),[d,c]=f.useState(he),[k,l]=f.useState(!1);f.useEffect(()=>{const n=J(r.current);if(!n||!i.current)return;const m=window.requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight});return()=>window.cancelAnimationFrame(m)},[t]),f.useEffect(()=>{const n=J(r.current);if(!n)return;o.current=n;const m=()=>{const w=n.scrollHeight-n.scrollTop-n.clientHeight<=ys;i.current=w,l(!w)};return m(),n.addEventListener("scroll",m,{passive:!0}),()=>n.removeEventListener("scroll",m)},[]),f.useEffect(()=>{const n=u.current;u.current=t.length,c(m=>m>=n&&t.length>n?t.length:Math.min(Math.max(m,he),t.length||he))},[t.length]);const p=Math.max(t.length-d,0),x=p,j=f.useMemo(()=>t.slice(x),[t,x]),S=f.useMemo(()=>js(t),[t]);if(f.useLayoutEffect(()=>{var E;const n=b.current;if(!n)return;const m=J(r.current);if(b.current=null,!!m){if((E=n.element)!=null&&E.isConnected){const w=n.element.getBoundingClientRect().top-n.viewportTop;m.scrollTop+=w;return}m.scrollTop=fs(n.scrollTop,n.scrollHeight,m.scrollHeight)}},[d]),s)return e.jsx("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"flex overflow-hidden flex-1 justify-center items-center px-5 py-8 min-h-0",children:e.jsxs("div",{className:"w-full max-w-[560px]",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-[hsl(var(--deck-accent-soft))] blur-xl"}),e.jsx(fe,{size:42,className:"relative"})]}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.16em] text-[hsl(var(--deck-accent))]",children:[e.jsx(mt,{className:"w-3 h-3"}),a("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.loading.title")}),e.jsx("p",{className:"mt-1 max-w-sm text-[11.5px] leading-5 text-[hsl(var(--deck-ink-faint))]",children:a("chat.list.loading.hint")})]}),e.jsx("div",{"aria-hidden":"true",className:"mt-7 space-y-4 rounded-xl border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))]/45 px-4 py-5",children:[72,88,64].map((n,m)=>e.jsxs("div",{className:M("flex gap-3",m%2===1&&"flex-row-reverse"),children:[e.jsx("span",{className:"h-7 w-7 shrink-0 animate-pulse rounded-md bg-[hsl(var(--deck-surface-2))]"}),e.jsx("span",{className:"h-10 animate-pulse rounded-lg bg-[hsl(var(--deck-surface-2))]",style:{width:`${n}%`,animationDelay:`${m*120}ms`}})]},n))})]})});if(t.length===0&&!s)return e.jsx("div",{className:"flex flex-1 justify-center items-center",children:e.jsxs("div",{className:"flex flex-col gap-4 items-center text-center",children:[e.jsx(fe,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:a("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:a("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:a("chat.list.empty.hint")})]})]})});const h=()=>{const n=J(r.current);n&&(i.current=!0,l(!1),n.scrollTo({top:n.scrollHeight,behavior:"smooth"}))},N=()=>{var m;const n=J(r.current);if(n){const E=((m=r.current)==null?void 0:m.querySelector("[data-chat-message-id]"))??null;b.current={element:E,viewportTop:(E==null?void 0:E.getBoundingClientRect().top)??0,scrollHeight:n.scrollHeight,scrollTop:n.scrollTop}}c(E=>bs(E,t.length,xe))},v=n=>n>=x?!0:(c(t.length),!1);return e.jsxs("div",{ref:r,className:"relative flex-1 min-h-0",children:[e.jsx(et,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[p>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:N,"aria-label":a("chat.list.showEarlierWithRemaining",{count:Math.min(p,xe),remaining:p}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:a("chat.list.showEarlier",{count:Math.min(p,xe)})})}),j.map((n,m)=>{const E=x+m,w=E>0?t[E-1]:null,C=!w||w.role!==n.role||w.role==="user";return e.jsx(ps,{message:n,showAvatar:C},n.id||`msg-${E}`)})]})}),e.jsx(vs,{turns:S,viewportRef:o,containerRef:r,onRevealTurn:v}),k&&e.jsxs("button",{type:"button",onClick:h,className:"absolute bottom-4 left-1/2 z-10 inline-flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))]/95 px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] shadow-lg backdrop-blur transition-colors hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(ze,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),a("chat.list.jumpLatest")]})]})}const Ns=f.memo(ws),be=Ft,ve=$t,ge=Dt,ie=f.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(Qe,{ref:r,sideOffset:s,className:M("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",t),...a}));ie.displayName=Qe.displayName;const Ss={active:{labelKey:"goal.status.active",dot:"bg-[hsl(var(--deck-accent))] shadow-[0_0_6px_hsl(var(--deck-accent-glow)/0.5)]",accent:"text-[hsl(var(--deck-accent))]"},verifying:{labelKey:"goal.status.active",dot:"animate-pulse bg-sky-400",accent:"text-sky-600 dark:text-sky-300"},paused:{labelKey:"goal.status.paused",dot:"bg-amber-400",accent:"text-amber-600 dark:text-amber-300"},blocked:{labelKey:"goal.status.blocked",dot:"bg-rose-500",accent:"text-rose-600 dark:text-rose-300"},usage_limited:{labelKey:"goal.status.usageLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},budget_limited:{labelKey:"goal.status.budgetLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},complete:{labelKey:"goal.status.complete",dot:"bg-emerald-500",accent:"text-emerald-600 dark:text-emerald-300"}};function se(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Cs(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),a=t%60;return a===0?`${s}m`:`${s}m ${a}s`}function Es(){var P;const t=D(),{locale:s}=Ue(),a=y(T=>T.goal),r=y(T=>T.pauseGoal),o=y(T=>T.resumeGoal),i=y(T=>T.editGoal),u=y(T=>T.clearGoal),[b,d]=f.useState(!1),[c,k]=f.useState(!1),[l,p]=f.useState(""),[x,j]=f.useState(null),[S,h]=f.useState(!1);if(f.useEffect(()=>{d(!1),k(!1),p((a==null?void 0:a.objective)??""),h(!1)},[a==null?void 0:a.goalId]),!a)return null;const N=Ss[a.status],v=["active","verifying","paused","blocked"].includes(a.status),n=a.status==="active"||a.status==="verifying",m=a.status==="paused"||a.status==="blocked",E=x!==null,w=async(T,I)=>{j(T);try{await I()}finally{j(null)}},C=()=>{p(a.objective),k(!0),d(!0)},R=async T=>{T.preventDefault();const I=l.trim();if(!I||I===a.objective){k(!1);return}await w("edit",()=>i(I)),k(!1)},O=async()=>{await w("delete",u),h(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(be,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":a.status,children:[e.jsxs("div",{className:M("flex h-9 items-center gap-2 rounded-lg border px-3 transition-colors","border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 backdrop-blur-sm",b&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(ht,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(xt,{className:M("h-3.5 w-3.5 shrink-0",N.accent)}),e.jsx("span",{className:M("h-1.5 w-1.5 shrink-0 rounded-full",N.dot)}),e.jsx("span",{className:M("shrink-0 text-[10px] font-medium leading-none",N.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(N.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(b?"goal.action.collapse":"goal.action.expand"),className:"min-w-0 flex-1 truncate text-left text-[12px] leading-5 text-[hsl(var(--deck-ink))]/85 outline-none transition-colors hover:text-[hsl(var(--deck-ink))]",onClick:()=>d(T=>!T),"aria-expanded":b,title:a.objective,children:a.objective}),a.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[se(a.tokensUsed),a.tokenBudget!==void 0&&`/${se(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[n&&e.jsx(ae,{label:t("goal.action.pause"),disabled:E,onClick:()=>void w("pause",r),children:x==="pause"?e.jsx($,{className:"animate-spin"}):e.jsx(pt,{})}),m&&e.jsx(ae,{label:t("goal.action.resume"),disabled:E,onClick:()=>void w("resume",o),children:x==="resume"?e.jsx($,{className:"animate-spin"}):e.jsx(ft,{})}),e.jsx(ae,{label:t(v?"goal.action.edit":"goal.action.expand"),disabled:!v&&!b,onClick:v?C:()=>d(T=>!T),children:v?e.jsx(Ge,{}):e.jsx(bt,{})}),e.jsx(ae,{label:t("goal.action.delete"),disabled:E,destructive:!0,onClick:()=>h(!0),children:e.jsx(X,{})})]})]}),b&&e.jsx("div",{className:"rounded-b-lg border border-t-0 border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 px-4 py-3 backdrop-blur-sm",children:c?e.jsxs("form",{onSubmit:R,children:[e.jsx("textarea",{id:"goal-objective",value:l,onChange:T=>p(T.target.value),onKeyDown:T=>{T.key==="Escape"&&k(!1)},rows:3,autoFocus:!0,className:"w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] outline-none transition-shadow focus:border-[hsl(var(--deck-accent))] focus:ring-1 focus:ring-[hsl(var(--deck-accent-glow))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(!1),className:"inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-hairline))]/60",children:[e.jsx(We,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!l.trim()||x==="edit",className:"inline-flex h-7 items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2.5 text-[11px] font-medium text-white transition-colors hover:bg-[hsl(var(--deck-accent))]/90 disabled:cursor-not-allowed disabled:opacity-50",children:[x==="edit"?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(oe,{className:"h-3 w-3"}),t("goal.action.save")]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink))]/90",children:a.objective}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(vt,{className:"h-3 w-3"}),se(a.tokensUsed),a.tokenBudget!==void 0&&` / ${se(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(gt,{className:"h-3 w-3"}),Cs(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(je,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.completionVerification&&e.jsxs("div",{"data-goal-verification":a.completionVerification.status,className:"mt-2 rounded-md border border-sky-200/50 bg-sky-50/60 px-2.5 py-2 text-[11px] text-sky-900 dark:border-sky-400/15 dark:bg-sky-400/[0.05] dark:text-sky-100",children:[e.jsxs("p",{className:"font-mono font-medium",children:["#",a.completionVerification.attempt," ·"," ",a.completionVerification.status.toUpperCase()," ·"," ",((P=a.completionVerification.verifierSessionId)==null?void 0:P.slice(0,12))??"-"]}),a.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:a.completionVerification.summary}),a.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",a.completionVerification.evidenceSha256.slice(0,12)]})]}),a.statusReason&&e.jsx("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-1.5 text-[11px] text-amber-800 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-200",children:a.statusReason})]})})]})}),e.jsx(Ie,{open:S,onOpenChange:h,children:e.jsxs(_e,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(Pe,{children:t("goal.dialog.title")}),e.jsx(Ve,{children:t("goal.dialog.description")}),e.jsxs(Le,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>h(!1),className:"inline-flex h-8 items-center justify-center rounded-md border border-[hsl(var(--deck-border))] px-3 text-[12px] text-[hsl(var(--deck-ink))] hover:bg-[hsl(var(--deck-hairline))]/60",children:t("goal.action.cancel")}),e.jsxs("button",{type:"button",disabled:x==="delete",onClick:()=>void O(),className:"inline-flex gap-1.5 justify-center items-center px-3 h-8 text-[12px] font-medium text-white bg-rose-600 rounded-md hover:bg-rose-500 disabled:opacity-50",children:[x==="delete"&&e.jsx($,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function ae({label:t,children:s,disabled:a,destructive:r,onClick:o}){return e.jsxs(ve,{children:[e.jsx(ge,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:o,className:M("flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-muted))] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent-glow))]/50 disabled:cursor-not-allowed disabled:opacity-35 [&_svg]:h-3.5 [&_svg]:w-3.5",r?"hover:bg-rose-500/10 hover:text-rose-500":"hover:bg-[hsl(var(--deck-hairline))]/60 hover:text-[hsl(var(--deck-ink))]"),children:s})}),e.jsx(ie,{side:"top",className:"text-[10px]",children:t})]})}function Ts(){const t=D(),s=y(d=>d.currentSessionRef),a=y(d=>d.sessions),r=y(d=>d.messages),o=f.useMemo(()=>{var c,k,l,p,x;const d=s?(c=tt(a,s))==null?void 0:c.pendingInteraction:void 0;if(d)return d.type;for(let j=r.length-1;j>=0;j-=1){const S=(k=r[j])==null?void 0:k.agentContent;if(((l=S==null?void 0:S.confirmation)==null?void 0:l.status)==="pending")return"permission";if(((p=S==null?void 0:S.question)==null?void 0:p.status)==="pending")return"question";if(((x=S==null?void 0:S.elicitation)==null?void 0:x.status)==="pending")return"elicitation"}return null},[s,r,a]);if(!o)return null;const i=()=>{const d=document.querySelector(`[data-pending-interaction="${o}"]`);d==null||d.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>d==null?void 0:d.focus(),250)},u=o==="question",b=o==="elicitation";return e.jsxs("div",{role:"alert",className:"mx-3 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber-300/80 bg-amber-50/95 px-3 py-2 font-mono text-amber-950 shadow-sm backdrop-blur dark:border-amber-800/80 dark:bg-amber-950/90 dark:text-amber-100 sm:mx-5",children:[e.jsx(ye,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(u?"interaction.bar.questionTitle":b?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(u?"interaction.bar.questionHint":b?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:i,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(ze,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}const Ms=f.lazy(()=>Oe(()=>import("./MarkdownRenderer-DUPwAzs4.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function As(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Rs(){const t=D(),s=y(r=>r.sideConversation),a=y(r=>r.dismissSideConversation);return s?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"shrink-0 border-y border-[hsl(var(--deck-accent)/0.28)] bg-[hsl(var(--deck-accent-soft)/0.42)]",children:e.jsxs("div",{className:"px-4 py-3 md:px-6",children:[e.jsxs("header",{className:"flex min-h-7 items-start gap-2",children:[e.jsx(kt,{"aria-hidden":!0,className:"mt-0.5 h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("h2",{className:"font-mono text-[11px] font-semibold uppercase text-[hsl(var(--deck-accent))]",children:t("chat.side.title")}),s.durationMs!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(jt,{"aria-hidden":!0,className:"h-3 w-3"}),As(s.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:s.question})]}),e.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:e.jsx(We,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"mt-2 max-h-[min(36vh,320px)] overflow-y-auto border-l-2 border-[hsl(var(--deck-accent)/0.42)] pl-3 pr-1",children:[s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx($,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),s.status==="error"&&e.jsxs("div",{role:"alert",className:"flex min-h-9 items-start gap-2 font-mono text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(ye,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:s.error??t("chat.side.failed")})]}),s.status==="completed"&&s.response&&e.jsx(f.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:s.response}),children:e.jsx(Ms,{content:s.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function pe(t){return Number.isFinite(t)?Math.max(0,t):0}function Fs(t){const s=pe(t.totalInputTokens),a=pe(t.cacheReadTokens),r=pe(t.cacheWriteTokens),o=Math.min(a,s),i=Math.min(r,Math.max(0,s-o)),u=Math.max(0,s-o-i),b=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:o,cacheWriteTokens:i,uncachedInputTokens:u,...b?{hitRate:o/s}:{}}}function $s(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const Ds={running:"status.phase.running",compacting:"status.phase.compacting",recovering_context:"status.phase.recoveringContext",switching_model:"status.phase.switchingModel",waiting_permission:"status.phase.waitingPermission",error:"status.phase.error",idle:""},Bs={model_changed:"status.cacheBreak.model",system_prompt_changed:"status.cacheBreak.system",tools_changed:"status.cacheBreak.tools",request_policy_changed:"status.cacheBreak.policy",ttl_expired:"status.cacheBreak.ttl",server_side:"status.cacheBreak.server"},U=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),re=t=>{const s=Math.max(0,Math.ceil(t/1e3)),a=Math.floor(s/60),r=s%60;return a>0?`${a}m ${r}s`:`${r}s`};function Is(){const t=D(),s=y(N=>N.tokenUsage),a=y(N=>N.isStreaming),r=y(N=>N.agentPhase),o=y(N=>N.providerAdmission),i=y(N=>N.providerCircuit),u=y(N=>N.providerRetry),b=y(N=>N.providerStall),d=y(N=>N.actionStationarity),c=Ds[r]??"",k=(u==null?void 0:u.delayMs)!==void 0?` · ${Math.max(0,Math.ceil(u.delayMs/1e3))}s`:"",l=d?`${t(d.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${d.toolName} · ${d.runLength}/${d.haltThreshold}`:i?i.phase==="probe"?"Provider · Recovery probe":`Provider · Circuit open${i.retryAfterMs!==void 0?` · probe in ${re(i.retryAfterMs)}`:""}${i.recoveryRemainingMs!==void 0?` · ${re(i.recoveryRemainingMs)}`:""}`:o?`Provider · Capacity queue ${o.queuePosition}/${Math.max(o.queueDepth,o.queuePosition)} · ${o.scope} · ${re(o.waitMs)}`:u?u.mode==="bounded_foreground"?`Provider · Bounded recovery · ${u.attempt}/${u.maxRetries} · ${re(u.recoveryRemainingMs??0)}`:`Provider · ${t("chat.error.action.retryingTask")} · ${u.attempt}/${u.maxRetries}${k}`:b?`${t("status.phase.providerStall")} · ${Math.ceil(b.durationMs/1e3)}s / ${Math.ceil(b.timeoutMs/1e3)}s`:c?t(c):"",p=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,x=Fs(s),j=$s(x.hitRate),S=Math.min(p,100),h=p>95?"danger":p>80?"warn":"safe";return e.jsxs("div",{className:"flex items-center gap-2 border-t border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/70 px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:gap-4 sm:px-5",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.context")}),e.jsxs("span",{className:"flex gap-1 items-baseline tabular-nums",children:[e.jsx("span",{className:M("text-[12px] font-medium",h==="safe"&&"text-[hsl(var(--deck-ink))]",h==="warn"&&"text-amber-600 dark:text-amber-400",h==="danger"&&"text-red-600 dark:text-red-400"),children:U(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",U(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(be,{children:e.jsxs(ve,{children:[e.jsx(ge,{asChild:!0,children:e.jsx(yt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(ie,{side:"top",className:"max-w-[220px]",children:e.jsx("p",{className:"text-xs",children:t("status.tokenLimitTooltip")})})]})}),e.jsxs("div",{className:"relative hidden h-2 w-32 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:block","aria-hidden":"true",children:[e.jsx("div",{className:M("absolute inset-y-0 left-0 transition-[width] duration-300",h==="safe"&&"bg-[hsl(var(--deck-accent))]",h==="warn"&&"bg-amber-500",h==="danger"&&"bg-red-500"),style:{width:`${S}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(N=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${N}%`}},N))})]}),e.jsxs("span",{className:M("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",h==="warn"&&"text-amber-600 dark:text-amber-400",h==="danger"&&"text-red-600 dark:text-red-400"),children:[p,"%"]})]}),e.jsx(be,{children:e.jsxs(ve,{children:[e.jsx(ge,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 cursor-help items-baseline gap-2 border-l border-[hsl(var(--deck-hairline))] pl-2 sm:pl-4","data-testid":"prompt-cache-hit-rate","aria-label":`${t("status.cache")} ${j}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:M("tabular-nums",x.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:j})]})}),e.jsx(ie,{side:"top",className:"max-w-[280px]",children:x.hitRate===void 0?e.jsx("p",{className:"text-xs",children:t("status.cacheUnavailable")}):e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("p",{children:t("status.cacheTooltip")}),e.jsx("p",{className:"font-mono tabular-nums",children:t("status.cacheDetails",{read:U(x.cacheReadTokens),write:U(x.cacheWriteTokens),uncached:U(x.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Bs[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:U(s.cacheBreak.previousCacheReadTokens),current:U(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),a&&l&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"text-[hsl(var(--deck-accent))]",children:l})]})]})}function _s(){const{locale:t}=Ue(),s=st(n=>n.agentTeamsEnabled),a=y(n=>n.teams),r=y(n=>n.currentSessionRef),o=y(n=>n.loadTeams),[i,u]=f.useState({}),[b,d]=f.useState({}),[c,k]=f.useState({}),[l,p]=f.useState(null),[x,j]=f.useState(null),[S,h]=f.useState(null);if(f.useEffect(()=>{o(r??void 0)},[s,r,o]),!s||!r||a.length===0)return null;const N=async n=>{var E;const m=(E=c[n])==null?void 0:E.trim();if(!(!m||l)){p(n),h(null);try{await Ce.sendMessage(r,n,b[n]??"*",m),k(w=>({...w,[n]:""})),await o(r)}catch(w){h(w instanceof Error?w.message:F(t,"actionFailed"))}finally{p(null)}}},v=async n=>{if(!x){j(n),h(null);try{await Ce.delete(r,n),await o(r)}catch(m){h(m instanceof Error?m.message:F(t,"actionFailed"))}finally{j(null)}}};return e.jsxs("section",{"aria-label":F(t,"title"),"data-blade-team-panel":!0,className:"shrink-0 border-y border-emerald-300/50 bg-emerald-50/55 dark:border-emerald-800/55 dark:bg-emerald-950/20",children:[S&&e.jsx("div",{role:"alert",className:"border-b border-red-200 bg-red-50 px-4 py-2 font-mono text-[10px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300 md:px-6",children:S}),a.filter(n=>n.status!=="deleted").map(n=>{var w;const m=i[n.name]??n.status==="running",E=n.tasks.filter(C=>C.status==="completed").length;return e.jsxs("div",{className:"border-b border-emerald-200/40 last:border-0 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-2 px-4 py-2 md:px-6",children:[e.jsx("button",{type:"button",onClick:()=>u(C=>({...C,[n.name]:!m})),"aria-label":m?F(t,"collapse"):F(t,"expand"),className:"flex h-7 w-7 items-center justify-center rounded-md text-emerald-700 hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/50",children:m?e.jsx(Z,{className:"h-4 w-4"}):e.jsx(le,{className:"h-4 w-4"})}),e.jsx(wt,{className:"h-4 w-4 shrink-0 text-emerald-700 dark:text-emerald-300"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx("h2",{className:"truncate font-mono text-[11px] font-semibold uppercase text-emerald-800 dark:text-emerald-200",children:n.name}),e.jsxs("span",{className:"font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[n.status," · ",n.members.length-1," ",F(t,"members")," · ",E,"/",n.tasks.length," ",F(t,"tasks")]})]}),n.description&&e.jsx("p",{className:"truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:n.description})]}),e.jsx("button",{type:"button",onClick:()=>void v(n.name),disabled:x===n.name,"aria-label":F(t,"delete"),title:F(t,"delete"),className:"flex h-7 w-7 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-red-50 hover:text-red-600 disabled:opacity-40 dark:hover:bg-red-950/40",children:e.jsx(X,{className:"h-3.5 w-3.5"})})]}),m&&e.jsxs("div",{className:"max-h-[min(40vh,360px)] overflow-y-auto border-t border-emerald-200/40 px-4 py-3 md:px-6 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"grid gap-x-6 gap-y-2 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:F(t,"members")}),n.members.map(C=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsx("span",{"aria-label":C.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${C.status==="running"?"bg-emerald-500":C.status==="completed"||C.status==="leader"?"bg-sky-500":C.status==="failed"?"bg-red-500":"bg-zinc-400"}`}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:C.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.subagentType}),C.worktreePath&&e.jsx(He,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":F(t,"worktree")})]},C.id))]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:F(t,"tasks")}),n.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:F(t,"noTasks")}):n.tasks.map(C=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsxs("span",{className:"w-5 shrink-0 font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["#",C.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:C.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:C.status})]},C.id))]})]}),n.peerMessagingEnabled&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-emerald-200/40 pt-3 dark:border-emerald-900/40",children:[e.jsxs("select",{"aria-label":F(t,"recipient"),value:b[n.name]??"*",onChange:C=>d(R=>({...R,[n.name]:C.target.value})),className:"h-8 max-w-32 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10px]",children:[e.jsx("option",{value:"*",children:F(t,"broadcast")}),n.members.filter(C=>C.status!=="leader").map(C=>e.jsx("option",{value:C.name,children:C.name},C.id))]}),e.jsx("input",{value:c[n.name]??"",onChange:C=>k(R=>({...R,[n.name]:C.target.value})),onKeyDown:C=>{C.key==="Enter"&&N(n.name)},placeholder:F(t,"messagePlaceholder"),className:"h-8 min-w-0 flex-1 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10.5px] outline-none focus:border-emerald-500"}),e.jsx("button",{type:"button",onClick:()=>void N(n.name),disabled:!((w=c[n.name])!=null&&w.trim())||l===n.name,"aria-label":F(t,"send"),title:F(t,"send"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-emerald-700 text-white hover:bg-emerald-800 disabled:opacity-40 dark:bg-emerald-600",children:e.jsx(Ke,{className:"h-3.5 w-3.5"})})]})]})]},n.name)})]})}function Ps(t){const s=[...t].reverse().find(o=>o.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const a=s.content.filter(o=>o.type==="text").map(o=>o.text).join(`
18
+ `),r=s.content.filter(o=>o.type==="image_url").map((o,i)=>{var b;const u=((b=o.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:b[1])??"application/octet-stream";return{id:`recovery-${s.id}-${i}`,name:`attachment-${i+1}`,mimeType:u,dataUrl:o.image_url.url}});return{content:a,attachments:r}}function zs(){var L;const t=D(),s=y(g=>g.messages),a=y(g=>g.currentSessionRef),r=y(g=>g.isStreaming),o=y(g=>g.isStopping),i=y(g=>g.sessionEventConnectionState),u=y(g=>g.pendingSteeringCount),b=y(g=>g.pendingInputDelivery),d=y(g=>g.recoveredSteeringCount),c=y(g=>g.isLoading),k=y(g=>g.error),l=y(g=>g.errorContext),p=y(g=>g.sessions),x=y(g=>g.sendMessage),j=y(g=>g.abortSession),S=y(g=>g.retryTask),h=y(g=>g.retryingTaskKeys),N=ke(g=>g.openSettings),v=y(g=>g.reconnectSessionEvents),n=y(g=>g.clearError),[m,E]=f.useState(null),w=a?p.find(g=>g.sessionId===a.sessionId&&g.projectPath===a.projectPath):void 0,C=!!k&&((l==null?void 0:l.kind)==="navigation"||!(l!=null&&l.sessionRef)||Be(l.sessionRef,a)),R=(l==null?void 0:l.failureCode)??((L=w==null?void 0:w.taskFailure)==null?void 0:L.code),O=(l==null?void 0:l.kind)==="execution"&&R?t(At(R)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,P=i==="connecting"||i==="reconnecting",T=r&&i!=="connected",I=a?`session:${Y(a)}`:"session:temporary",K=f.useMemo(()=>Ps(s),[s]),de=a?Y(a):"temporary-session",G=!!(a&&(w!=null&&w.taskRetryAvailable)&&(!R||Rt(R)))&&((l==null?void 0:l.kind)==="execution"||(l==null?void 0:l.kind)==="task_action"),W=(l==null?void 0:l.kind)==="execution"&&(R==="authentication"||R==="permission"||R==="model_unavailable"),q=a?h.includes(Y(a)):!1;f.useEffect(()=>{E(null)},[de]);const ee=async g=>x({content:g.content,modelId:g.modelId,reasoningEffort:g.reasoningEffort,serviceTier:g.serviceTier,responseVerbosity:g.responseVerbosity,communicationStyle:g.communicationStyle,...g.outputSchema?{outputSchema:g.outputSchema}:{},attachments:g.attachments.map(_=>({type:"image",content:_.dataUrl,mimeType:_.mimeType,name:_.name}))}),te=()=>j(),A=async()=>{if(W){n(),N("models");return}if(G&&a){n(),await S(a).catch(()=>{});return}if((l==null?void 0:l.kind)==="execution"&&K){E({...K,revision:Date.now()}),n();return}n(),requestAnimationFrame(()=>rt())},V=G?t(q?"chat.error.action.retryingTask":"chat.error.action.retryTask"):W?t("chat.error.action.checkModels"):(l==null?void 0:l.kind)==="execution"&&K?t("chat.error.action.editResend"):(l==null?void 0:l.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[C&&e.jsxs("div",{role:"alert","data-blade-session-error":!0,className:"flex min-h-11 flex-wrap items-center gap-2 border-b border-red-200/60 bg-red-50/80 px-4 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300 sm:px-5",children:[e.jsx(ye,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[e.jsx("span",{className:"font-semibold",children:t((l==null?void 0:l.kind)==="submission"?"chat.error.title.submission":(l==null?void 0:l.kind)==="execution"?"chat.error.title.execution":(l==null?void 0:l.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",O]}),V&&e.jsxs("button",{type:"button",onClick:()=>void A(),disabled:q,className:"inline-flex min-h-7 shrink-0 items-center gap-1.5 rounded-md border border-red-300/70 bg-white/65 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:cursor-wait disabled:opacity-60 dark:border-red-800 dark:bg-red-950/45 dark:hover:bg-red-900/60",children:[G?q?e.jsx($,{className:"h-3 w-3 animate-spin"}):e.jsx(je,{className:"h-3 w-3"}):e.jsx(Ge,{className:"h-3 w-3"}),V]}),e.jsx("button",{type:"button",onClick:n,"aria-label":t("chat.error.dismiss"),className:"p-1 text-red-500 rounded transition-colors hover:bg-red-100/60 hover:text-red-700 dark:hover:bg-red-950/60 dark:hover:text-red-100",children:"✕"})]}),(P||i==="offline")&&e.jsxs("div",{role:i==="offline"?"alert":"status","aria-live":"polite",className:"flex min-h-10 flex-wrap items-center gap-2 border-b border-amber-300/60 bg-amber-50/80 px-4 py-2 font-mono text-[11px] text-amber-900 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-200 sm:px-5",children:[P?e.jsx($,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(P?"chat.connection.reconnecting":"chat.connection.offline")}),i==="offline"&&e.jsxs("button",{type:"button",onClick:()=>void v().catch(()=>{}),className:"inline-flex min-h-7 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/60 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[e.jsx(St,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Bt,{}),e.jsx(Ns,{messages:s,isLoading:c},a?Y(a):"temporary-session"),e.jsx(_s,{}),e.jsx(Rs,{}),e.jsx(Ts,{}),e.jsx(Es,{}),e.jsx(at,{draftKey:I,draft:m==null?void 0:m.content,draftAttachments:m==null?void 0:m.attachments,draftRevision:m==null?void 0:m.revision,onSend:ee,onAbort:te,disabled:c||T,isStreaming:r,isStopping:o,pendingSteeringCount:u,pendingInputDelivery:b,recoveredSteeringCount:d,workspacePath:a==null?void 0:a.projectPath},I),e.jsx(Is,{})]})}export{zs as ChatView};