blade-code 0.10.97 → 0.10.99

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 (118) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-j1t2qedg.js → chunk-0zhdjaen.js} +1 -1
  3. package/dist/{chunk-bztsz28c.js → chunk-10taec1j.js} +2 -2
  4. package/dist/{chunk-sdvfyzv0.js → chunk-12vzyc3x.js} +2 -2
  5. package/dist/{chunk-qeznbnd1.js → chunk-1gjn9bp7.js} +2 -2
  6. package/dist/{chunk-vchv2x9y.js → chunk-1pscfw5q.js} +2 -2
  7. package/dist/{chunk-88mf53ak.js → chunk-2hb222re.js} +1 -1
  8. package/dist/{chunk-xjyr40bn.js → chunk-2jffgzdf.js} +2 -2
  9. package/dist/{chunk-zyfacwgn.js → chunk-2va6ex5v.js} +1 -1
  10. package/dist/{chunk-21ycnzsv.js → chunk-39qzk9nm.js} +1 -1
  11. package/dist/chunk-3awjdsef.js +5 -0
  12. package/dist/{chunk-p5ewrebt.js → chunk-3ghvdscg.js} +1 -1
  13. package/dist/{chunk-fm93hym6.js → chunk-425p4nwx.js} +2 -2
  14. package/dist/{chunk-23qhbq46.js → chunk-45sgvghd.js} +1 -1
  15. package/dist/{chunk-p87j2g40.js → chunk-4fmtv329.js} +1 -1
  16. package/dist/{chunk-a1vhp8sa.js → chunk-53xtssbf.js} +2 -2
  17. package/dist/chunk-5dkzqgxa.js +1 -0
  18. package/dist/{chunk-fbs90qgx.js → chunk-5tq3s9h5.js} +1 -1
  19. package/dist/{chunk-2mwgykjs.js → chunk-6vcy0nq7.js} +1 -1
  20. package/dist/{chunk-s47ypj8n.js → chunk-6yz49rz2.js} +3 -3
  21. package/dist/{chunk-2c2cxrc0.js → chunk-70hwyc2w.js} +1 -1
  22. package/dist/{chunk-630jj776.js → chunk-71jnx206.js} +1 -1
  23. package/dist/{chunk-dsnz4a1d.js → chunk-9hsbjy6a.js} +1 -1
  24. package/dist/{chunk-mybhqpc7.js → chunk-9sx3vsyj.js} +1 -1
  25. package/dist/chunk-9z0yx0bn.js +1 -0
  26. package/dist/{chunk-8htbttg5.js → chunk-a42rvwg4.js} +1 -1
  27. package/dist/chunk-akfez2cs.js +1 -0
  28. package/dist/{chunk-825r9sfe.js → chunk-ap8539bw.js} +419 -414
  29. package/dist/{chunk-qm83ezt6.js → chunk-b4d43ap3.js} +1 -1
  30. package/dist/{chunk-cvpvncza.js → chunk-bdbyy2ah.js} +1 -1
  31. package/dist/chunk-c2s9rgyj.js +1 -0
  32. package/dist/{chunk-xtm0sp0k.js → chunk-c6tq09mt.js} +1 -1
  33. package/dist/chunk-cc3d4nne.js +23 -0
  34. package/dist/{chunk-c6p5mj1k.js → chunk-cp7xsjj2.js} +2 -2
  35. package/dist/{chunk-s36efnxd.js → chunk-czcxx8tb.js} +1 -1
  36. package/dist/{chunk-csr9d8yx.js → chunk-d7j7z8hy.js} +2 -2
  37. package/dist/{chunk-zvms9ap7.js → chunk-d8wzc602.js} +2 -2
  38. package/dist/{chunk-3saxqsn7.js → chunk-dg0d3303.js} +1 -1
  39. package/dist/chunk-et6pvc3y.js +1 -0
  40. package/dist/{chunk-0v74fhhc.js → chunk-f9asjkfz.js} +1 -1
  41. package/dist/{chunk-88ykfsbv.js → chunk-fqwq3626.js} +2 -2
  42. package/dist/{chunk-q5t2rnx0.js → chunk-fvfc95g3.js} +1 -1
  43. package/dist/{chunk-3229684w.js → chunk-ga15nptz.js} +1 -1
  44. package/dist/chunk-gmnv1jme.js +1 -0
  45. package/dist/chunk-gwj637ey.js +1 -0
  46. package/dist/{chunk-7bhk8qk5.js → chunk-h8qjkxee.js} +2 -2
  47. package/dist/chunk-hcz98dbj.js +1 -0
  48. package/dist/chunk-hyk4fw18.js +10 -0
  49. package/dist/{chunk-n407vvwt.js → chunk-hz5rsfxv.js} +1 -1
  50. package/dist/{chunk-ps2rv1gg.js → chunk-j00px1es.js} +1 -1
  51. package/dist/{chunk-t5es94zk.js → chunk-k7vv9vne.js} +1 -1
  52. package/dist/chunk-kvdk0pfk.js +1 -0
  53. package/dist/chunk-maebpz1j.js +2 -0
  54. package/dist/{chunk-v2bvrk83.js → chunk-mhfwp1f0.js} +2 -2
  55. package/dist/{chunk-g2hxj68b.js → chunk-mq4x8zhq.js} +36 -36
  56. package/dist/chunk-n4cw6vt1.js +1 -0
  57. package/dist/{chunk-dretwm9j.js → chunk-p0rvgzpx.js} +1 -1
  58. package/dist/chunk-p7t010gq.js +1 -0
  59. package/dist/chunk-p7zvg7e3.js +1 -0
  60. package/dist/{chunk-ycr6tsfs.js → chunk-pmb5kr86.js} +2 -2
  61. package/dist/{chunk-h5xw792m.js → chunk-q3vza5gt.js} +2 -2
  62. package/dist/{chunk-9mnspb2d.js → chunk-qcy79mva.js} +1 -1
  63. package/dist/{chunk-n7p994w1.js → chunk-qdgwprcv.js} +1 -1
  64. package/dist/{chunk-z6we2tr8.js → chunk-qwjfxvda.js} +1 -1
  65. package/dist/{chunk-qhsmhx0y.js → chunk-r22mdmtr.js} +2 -2
  66. package/dist/{chunk-jy4s51bt.js → chunk-rej5bbbs.js} +2 -2
  67. package/dist/chunk-s0tq8gyx.js +2 -0
  68. package/dist/{chunk-nxmn37zx.js → chunk-spdrxj5e.js} +1 -1
  69. package/dist/chunk-vd6kmnc7.js +1 -0
  70. package/dist/{chunk-g2yaghbk.js → chunk-w9xfks7f.js} +1 -1
  71. package/dist/{chunk-6qxzcx0a.js → chunk-x5j6nexe.js} +39 -39
  72. package/dist/chunk-xg959k9w.js +1 -0
  73. package/dist/chunk-xz5ar75z.js +8 -0
  74. package/dist/{chunk-m67hdwk8.js → chunk-ykkqywtq.js} +1 -1
  75. package/dist/web/assets/{ChatView-DRfyX8iK.js → ChatView-Cwc3fRAC.js} +4 -4
  76. package/dist/web/assets/{CodeBlockHighlighter-DAFduwex.js → CodeBlockHighlighter-IGDocZUy.js} +1 -1
  77. package/dist/web/assets/FilePreview-EWE-k9VN.js +65 -0
  78. package/dist/web/assets/{KanbanBoard-CWMPGJNx.js → KanbanBoard-FiiVQgTQ.js} +1 -1
  79. package/dist/web/assets/{MarkdownRenderer-Dp8ahj7G.js → MarkdownRenderer-DjhWmikM.js} +3 -3
  80. package/dist/web/assets/{SettingsModal-BR_98FMD.js → SettingsModal-bHPx0fVG.js} +1 -1
  81. package/dist/web/assets/{TaskSwitcher-D5WijUhR.js → TaskSwitcher-CclOfJEl.js} +1 -1
  82. package/dist/web/assets/{TerminalPanel-CE33pxwb.js → TerminalPanel-Bnep8jE2.js} +1 -1
  83. package/dist/web/assets/{arrow-left-Cv-KDeEq.js → arrow-left-CiX0E9Mt.js} +1 -1
  84. package/dist/web/assets/{calendar-clock-Cv_w0wjo.js → calendar-clock-Bgfr-twh.js} +1 -1
  85. package/dist/web/assets/{chevrons-up-down-BAdiQ6sx.js → chevrons-up-down-B4T5fHUs.js} +1 -1
  86. package/dist/web/assets/{clock-3-wrrODhWr.js → clock-3-CGIhJjon.js} +1 -1
  87. package/dist/web/assets/{external-link-CBEu1rS8.js → external-link-DnQv1VYE.js} +1 -1
  88. package/dist/web/assets/{folder-aphP4iXp.js → folder-C5f8TpGj.js} +1 -1
  89. package/dist/web/assets/index-DGf6Z2kM.css +1 -0
  90. package/dist/web/assets/{index-rQ1P5u3I.js → index-DNoVz0u1.js} +61 -57
  91. package/dist/web/assets/{pause-Bp8TFDGG.js → pause-Cb0ijwnO.js} +1 -1
  92. package/dist/web/assets/{play-CuOkQMyB.js → play-Dsw1qmpk.js} +1 -1
  93. package/dist/web/assets/{session-events-C95VE6d2.js → session-events-B4Cq2TwN.js} +1 -1
  94. package/dist/web/assets/{teamService-BXTinwSE.js → teamService-C69fFhny.js} +1 -1
  95. package/dist/web/index.html +3 -3
  96. package/package.json +1 -1
  97. package/dist/chunk-0p6qkcft.js +0 -1
  98. package/dist/chunk-0pdkfzgc.js +0 -1
  99. package/dist/chunk-2vt67deg.js +0 -1
  100. package/dist/chunk-31g86axj.js +0 -5
  101. package/dist/chunk-64kpbdpc.js +0 -1
  102. package/dist/chunk-6tzphr1p.js +0 -10
  103. package/dist/chunk-7t2nf0rz.js +0 -1
  104. package/dist/chunk-7wtbhnfr.js +0 -2
  105. package/dist/chunk-ah15z613.js +0 -1
  106. package/dist/chunk-b9thsjxh.js +0 -2
  107. package/dist/chunk-cp9mj5he.js +0 -1
  108. package/dist/chunk-g7yfjy30.js +0 -1
  109. package/dist/chunk-krym2q8y.js +0 -23
  110. package/dist/chunk-perp57h6.js +0 -1
  111. package/dist/chunk-pxmfnkf3.js +0 -1
  112. package/dist/chunk-qkmsw3km.js +0 -1
  113. package/dist/chunk-s91r4emx.js +0 -1
  114. package/dist/chunk-t5y1ebdn.js +0 -8
  115. package/dist/chunk-wgg7ysqn.js +0 -1
  116. package/dist/chunk-zr27h1p0.js +0 -1
  117. package/dist/web/assets/FilePreview-DP5FG_5E.js +0 -59
  118. package/dist/web/assets/index-zY4JU9fd.css +0 -1
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-rQ1P5u3I.js";/**
1
+ import{c as e}from"./index-DNoVz0u1.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as o}from"./index-rQ1P5u3I.js";/**
1
+ import{c as o}from"./index-DNoVz0u1.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,7 +1,7 @@
1
1
  var Re=Object.defineProperty;var Me=(e,t,n)=>t in e?Re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var K=(e,t,n)=>Me(e,typeof t!="symbol"?t+"":t,n);import{R as D}from"./vendor-react-DofNRwfy.js";const ue=e=>{let t;const n=new Set,r=(d,c)=>{const l=typeof d=="function"?d(t):d;if(!Object.is(l,t)){const g=t;t=c??(typeof l!="object"||l===null)?l:Object.assign({},t,l),n.forEach(f=>f(t,g))}},s=()=>t,o={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d))},u=t=e(r,s,o);return o},xe=e=>e?ue(e):ue,_e=e=>e;function je(e,t=_e){const n=D.useSyncExternalStore(e.subscribe,D.useCallback(()=>t(e.getState()),[e,t]),D.useCallback(()=>t(e.getInitialState()),[e,t]));return D.useDebugValue(n),n}const de=e=>{const t=xe(e),n=r=>je(t,r);return Object.assign(n,t),n},fe=e=>e?de(e):de;function $(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function P(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function W(e,t,n){const r=(n?t.find(s=>s.id===n||s.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:r}}function Ie(e,t){const n=[...P(e)];let r=n.findIndex(i=>i.id===t.id||!!(i.sessionId&&t.sessionId&&i.sessionId===t.sessionId));if(r===-1&&t.sessionId&&(r=n.findIndex(i=>!i.sessionId&&i.status==="running"&&i.type===t.type&&i.description===t.description)),r===-1)return n.push(t),W(e,n,t.id);const s=n[r],a={...s,...t,id:s.id};return n[r]=a,W(e,n,a.id)}function G(e,t){return`${t}-${e.length}`}function De(e,t){if(!t)return e;const n=[...p(e)],r=n[n.length-1];return(r==null?void 0:r.type)==="text"?n[n.length-1]={...r,content:r.content+t}:n.push({id:G(n,"text"),type:"text",content:t}),{...e,timeline:n}}function Oe(e,t){if(!t)return e;const n=[...p(e)],r=n[n.length-1];return(r==null?void 0:r.type)==="thinking"?n[n.length-1]={...r,content:r.content+t}:n.push({id:G(n,"thinking"),type:"thinking",content:t}),{...e,timeline:n}}function le(e,t){const n=e.toolCalls.some(i=>i.toolCallId===t.toolCallId),r=n?e.toolCalls:[...e.toolCalls,t];if(n)return{...e,toolCalls:r};const s=[...p(e)],a=s[s.length-1];return(a==null?void 0:a.type)==="tool_group"?s[s.length-1]={...a,toolCallIds:[...a.toolCallIds,t.toolCallId]}:s.push({id:G(s,"tool_group"),type:"tool_group",toolCallIds:[t.toolCallId]}),{...e,timeline:s,toolCalls:r}}function p(e){if(e.timeline&&e.timeline.length>0)return e.timeline;const t=[];return e.thinkingContent&&t.push({id:"legacy-thinking",type:"thinking",content:e.thinkingContent}),e.textBefore&&t.push({id:"legacy-text-before",type:"text",content:e.textBefore}),e.toolCalls.length>0&&t.push({id:"legacy-tool-group",type:"tool_group",toolCallIds:e.toolCalls.map(n=>n.toolCallId)}),e.textAfter&&t.push({id:"legacy-text-after",type:"text",content:e.textAfter}),t}function pe(e){return p(e).filter(t=>t.type==="text").map(t=>t.content).filter(Boolean).join(`
2
2
 
3
3
  `)}const Fe=2166136261,Ee=16777619;function L(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(t=>L(t)).join(",")}]`:typeof e=="object"?`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${L(r)}`).join(",")}}`:JSON.stringify(e)}function Se(e){let t=Fe>>>0;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,Ee);return(t>>>0).toString(16)}function he(e){return typeof e=="string"?e:L(e??{})}function Q(e){return e==="completed"?"completed":e==="failed"||e==="cancelled"?"failed":"running"}function H({explicitId:e,messageId:t,toolName:n,argumentsValue:r,toolKind:s,output:a}){if(e)return e;const i=[t||"unknown-message",n||"Unknown",he(r),s||"",a||""].join("|");return`tool-${Se(i)}`}function F({explicitId:e,sessionId:t,messageId:n,agentType:r,description:s,summary:a}){if(e)return e;if(t)return t;const i=[n||"unknown-message",r||"subagent",s||"",a||""].join("|");return`subagent-${Se(i)}`}const qe=(e,t)=>{if(!t||typeof t!="object")return null;const n=Q(t.status),r=typeof t.summary=="string"?t.summary:void 0;return{id:F({explicitId:typeof t.subagentId=="string"?t.subagentId:void 0,sessionId:t.childSessionId,messageId:e,agentType:t.agentType,description:t.description,summary:t.summary}),type:t.agentType||"subagent",description:t.description||t.summary||"",status:n,startTime:Date.now(),sessionId:t.childSessionId,resumedFrom:t.resumedFrom,rootAgentId:t.rootAgentId,resumeDepth:typeof t.resumeDepth=="number"?t.resumeDepth:void 0,verificationVerdict:t.verificationVerdict==="pass"||t.verificationVerdict==="fail"||t.verificationVerdict==="partial"?t.verificationVerdict:void 0,output:n==="running"?void 0:r}},Be=(e,t)=>!t||typeof t!="object"?[]:(Array.isArray(t.subtaskRefs)?t.subtaskRefs:t.subtaskRef&&typeof t.subtaskRef=="object"?[t.subtaskRef]:[]).map(r=>qe(e,r)).filter(r=>r!==null);function x(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
4
- `)}function U(e){if(!e.agentContent)return e;let t=e.agentContent;for(const n of Be(e.id,e.metadata))t=Ie(t,n);return{...e,agentContent:t}}function Ve(e){var r,s,a;const t=[];let n=null;for(const i of e)if(i.role!=="system"){if(i.role==="user")n&&(t.push(U(n)),n=null),t.push({id:i.id,role:i.role,content:i.content,timestamp:i.timestamp||Date.now(),metadata:i.metadata});else if(i.role==="assistant"){n&&t.push(U(n));const o=i.metadata;let u=$();i.thinkingContent&&(u=Oe(u,i.thinkingContent),u.thinkingContent=i.thinkingContent);const d=x(i.content);if(d&&(u=De(u,d),u.textBefore=d),i.tool_calls&&Array.isArray(i.tool_calls))for(const c of i.tool_calls){const l=((r=c.function)==null?void 0:r.name)||"Unknown",g=he((s=c.function)==null?void 0:s.arguments);if(l==="Task"){let m={};try{m=JSON.parse(g)}catch{}const S=typeof m.subagent_type=="string"?m.subagent_type:"subagent",y=typeof m.description=="string"?m.description:S;u=Ie(u,{id:F({explicitId:c.id,sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,messageId:i.id,agentType:S,description:y}),type:S,description:y,status:"running",startTime:Date.now(),sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,resumedFrom:typeof m.resume_from=="string"?m.resume_from:typeof m.resume=="string"?m.resume:void 0});continue}const f={toolCallId:H({explicitId:c.id,messageId:i.id,toolName:l,argumentsValue:(a=c.function)==null?void 0:a.arguments}),toolName:l,arguments:g,status:"running",startTime:Date.now()};u=le(u,f)}n={id:i.id,role:"assistant",content:x(i.content),timestamp:i.timestamp||Date.now(),metadata:o,agentContent:u}}else if(i.role==="tool"&&n&&n.agentContent){const o=i,u=i.metadata,d=o.tool_call_id||(u==null?void 0:u.toolCallId),c=o.name||(u==null?void 0:u.toolName)||"Tool",l=u!=null&&u.metadata&&typeof u.metadata=="object"&&!Array.isArray(u.metadata)?u.metadata:u,g=u!=null&&u.independentVerification&&typeof u.independentVerification=="object"&&!Array.isArray(u.independentVerification)?u.independentVerification:void 0,f=(u==null?void 0:u.status)==="failed"||(u==null?void 0:u.status)==="error"||typeof(u==null?void 0:u.error)=="string"&&u.error.length>0,m=P(n.agentContent),S=m.findIndex(h=>h.id===d);if(S>=0){const h=m[S],I=typeof(l==null?void 0:l.subagentStatus)=="string"?Q(l.subagentStatus):f?"failed":"completed";m[S]={...h,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:h.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:h.type,status:I,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:h.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:h.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:h.resumeDepth,verificationVerdict:(l==null?void 0:l.verificationVerdict)==="pass"||(l==null?void 0:l.verificationVerdict)==="fail"||(l==null?void 0:l.verificationVerdict)==="partial"?l.verificationVerdict:(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:h.verificationVerdict,output:typeof(l==null?void 0:l.subagentSummary)=="string"?l.subagentSummary:x(i.content)||h.output},n.agentContent=W(n.agentContent,m,h.id);continue}const y=n.agentContent.toolCalls.find(h=>h.toolCallId===d);y?(y.output=x(i.content),y.status=f?"error":"success",y.metadata=l,y.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:y.summary,(!y.toolName||y.toolName==="Unknown")&&(y.toolName=c)):n.agentContent=le(n.agentContent,{toolCallId:H({explicitId:d,messageId:n.id,toolName:c,output:x(i.content)}),toolName:c,output:x(i.content),status:f?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(U(n)),t}const ye={authentication:"task.failure.authentication",permission:"task.failure.permission",rate_limit:"task.failure.rateLimit",timeout:"task.failure.timeout",network:"task.failure.network",model_unavailable:"task.failure.modelUnavailable",context_limit:"task.failure.contextLimit",unsupported_input:"task.failure.unsupportedInput",workspace_unavailable:"task.failure.workspaceUnavailable",capacity:"task.failure.capacity",runtime:"task.failure.runtime"},Ke={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,workspace_unavailable:!1,capacity:!0,runtime:!0};function Ue(e){if(typeof e=="string"&&Object.keys(ye).includes(e))return e}function bn(e){return ye[e]}function Cn(e){return Ke[e]}const be="blade.sidebar.view",Ce="blade.preview.width",J=640,Je=360,We=960,Le=()=>{if(typeof localStorage>"u")return"project";const e=localStorage.getItem(be);return e==="status"||e==="project"?e:"project"},ve=e=>Math.min(We,Math.max(Je,Math.round(e))),He=()=>{if(typeof localStorage>"u")return J;const e=localStorage.getItem(Ce);if(!e)return J;const t=Number(e);return Number.isFinite(t)?ve(t):J},Ge=fe(e=>({mainView:"workspace",setMainView:t=>e(n=>({mainView:t,isFilePreviewOpen:t==="board"?!1:n.isFilePreviewOpen})),boardProjectPath:null,setBoardProjectPath:t=>e({boardProjectPath:t}),isSidebarOpen:!0,toggleSidebar:()=>e(t=>({isSidebarOpen:!t.isSidebarOpen})),setSidebarOpen:t=>e({isSidebarOpen:t}),sidebarView:Le(),setSidebarView:t=>{typeof localStorage<"u"&&localStorage.setItem(be,t),e({sidebarView:t})},isFilePreviewOpen:!1,toggleFilePreview:()=>e(t=>({isFilePreviewOpen:!t.isFilePreviewOpen})),setFilePreviewOpen:t=>e({isFilePreviewOpen:t}),previewWidth:He(),setPreviewWidth:t=>{const n=ve(t);typeof localStorage<"u"&&localStorage.setItem(Ce,String(n)),e({previewWidth:n})},previewTab:"diff",setPreviewTab:t=>e({previewTab:t}),previewTargetPath:null,previewRequestId:0,openFilePreview:t=>e(n=>({isFilePreviewOpen:!0,previewTab:(t==null?void 0:t.tab)??n.previewTab,previewTargetPath:(t==null?void 0:t.targetPath)??null,previewRequestId:n.previewRequestId+1})),isSettingsOpen:!1,settingsSection:"general",toggleSettings:()=>e(t=>({isSettingsOpen:!t.isSettingsOpen,...t.isSettingsOpen?{}:{settingsSection:"general"}})),openSettings:(t="general")=>e({isSettingsOpen:!0,settingsSection:t}),isTerminalOpen:!1,toggleTerminal:()=>e(t=>({isTerminalOpen:!t.isTerminalOpen})),isTaskSwitcherOpen:!1,taskSwitcherMode:"tasks",setTaskSwitcherOpen:(t,n)=>e(r=>({isTaskSwitcherOpen:t,taskSwitcherMode:n??r.taskSwitcherMode})),setTaskSwitcherMode:t=>e({taskSwitcherMode:t})})),Qe=new Set(["BrowserNavigate","BrowserSnapshot","BrowserInteract","BrowserWait","BrowserInspect","BrowserPage"]),Ye=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);function ce(e,t){return(e==null?void 0:e.sessionId)===t.sessionId&&e.projectPath===t.projectPath}function N(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ae(e){return typeof e=="string"&&Ye.has(e)?e:void 0}function ze(e){const t=N(e),n=Ae(t==null?void 0:t.action);if(!t||!n)return;const r=N(t.viewport),s=N(t.targetBox),a=i=>typeof i=="number"&&Number.isFinite(i);return{action:n,...typeof t.ref=="string"?{ref:t.ref}:{},...r&&a(r.width)&&a(r.height)?{viewport:{width:r.width,height:r.height}}:{},...s&&a(s.x)&&a(s.y)&&a(s.width)&&a(s.height)?{targetBox:{x:s.x,y:s.y,width:s.width,height:s.height}}:{}}}function Xe(e){if(typeof e!="string")return N(e);try{return N(JSON.parse(e))}catch{return}}function Ze(e){return typeof e=="string"&&Qe.has(e)}const et=fe(e=>({agentActivity:null,beginAgentActivity:(t,n)=>e(r=>{var o,u;const s=ce((o=r.agentActivity)==null?void 0:o.sessionRef,t)?r.agentActivity:null,a=Xe(n.argumentsValue),i=n.toolName==="BrowserInteract"?Ae((u=N(a==null?void 0:a.action))==null?void 0:u.kind):void 0;return{agentActivity:{sessionRef:t,toolCallId:n.toolCallId,toolName:n.toolName,phase:"running",revision:((s==null?void 0:s.revision)??0)+1,frameRevision:(s==null?void 0:s.frameRevision)??0,pointerRevision:(s==null?void 0:s.pointerRevision)??0,...s!=null&&s.pageId?{pageId:s.pageId}:{},...s!=null&&s.origin?{origin:s.origin}:{},...s!=null&&s.url?{url:s.url}:{},...s!=null&&s.title?{title:s.title}:{},...i?{pendingAction:{action:i,...typeof(a==null?void 0:a.ref)=="string"?{ref:a.ref}:{}}}:{},...n.toolName!=="BrowserNavigate"&&(s!=null&&s.interaction)?{interaction:s.interaction}:{}}}}),completeAgentActivity:(t,n)=>e(r=>{var c,l;const s=ce((c=r.agentActivity)==null?void 0:c.sessionRef,t)?r.agentActivity:null,a=N((l=N(n.metadata))==null?void 0:l.browser),i=ze(a==null?void 0:a.interaction),o=typeof(a==null?void 0:a.pageId)=="string"?a.pageId:s==null?void 0:s.pageId,u=typeof(a==null?void 0:a.origin)=="string"?a.origin:s==null?void 0:s.origin,d=n.toolName!=="BrowserNavigate"&&n.toolName!=="BrowserPage";return{agentActivity:{sessionRef:t,toolCallId:n.toolCallId,toolName:n.toolName,phase:n.success?"ready":"error",revision:((s==null?void 0:s.revision)??0)+1,frameRevision:o&&u?((s==null?void 0:s.frameRevision)??0)+1:(s==null?void 0:s.frameRevision)??0,pointerRevision:i!=null&&i.targetBox?((s==null?void 0:s.pointerRevision)??0)+1:(s==null?void 0:s.pointerRevision)??0,...o?{pageId:o}:{},...u?{origin:u}:{},...typeof(a==null?void 0:a.url)=="string"?{url:a.url}:s!=null&&s.url?{url:s.url}:{},...typeof(a==null?void 0:a.title)=="string"?{title:a.title}:s!=null&&s.title?{title:s.title}:{},...typeof(a==null?void 0:a.errorCode)=="string"?{errorCode:a.errorCode}:{},...i?{interaction:i}:d&&(s!=null&&s.interaction)?{interaction:s.interaction}:{}}}}),clearAgentActivity:()=>e({agentActivity:null})})),tt={flushTimeout:80};class nt{constructor(t){K(this,"config");K(this,"channels",new Map);this.config={...tt,...t}}append(t,n,r){let s=this.channels.get(t);s||(s={buffer:"",timer:null,flushFn:null},this.channels.set(t,s)),s.buffer+=n,s.flushFn=r,s.timer||(s.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const r=n.buffer,s=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),s==null||s(r)}drainAll(){for(const[t]of this.channels)this.flushChannel(t);this.channels.clear()}drainAllExcept(t){for(const[n]of this.channels)n!==t&&this.flushChannel(n);for(const[n,r]of this.channels)n!==t&&!r.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const w=new nt,st=100,C=(e,t,n)=>{if(t)for(const r of e){const s=P(r.agentContent).find(a=>a.id===t||a.sessionId===t);if(s)return{messageId:r.id,subagent:s}}if(n){const r=e.find(i=>i.id===n),s=P(r==null?void 0:r.agentContent),a=s.find(i=>i.status==="running")??s[s.length-1];if(a)return{messageId:n,subagent:a}}for(const r of[...e].reverse()){const s=P(r.agentContent),a=s.find(i=>i.status==="running")??s[s.length-1];if(a)return{messageId:r.id,subagent:a}}};function it(e,t,n){n(r=>{const s={...r.pendingSubagentCompletions??{}};if(s[e]===void 0&&Object.keys(s).length>=st){const a=Object.keys(s)[0];a&&delete s[a]}return s[e]={...t},{pendingSubagentCompletions:s}})}function Y(e,t,n){var a;if(!e)return;const r=(a=t().pendingSubagentCompletions)==null?void 0:a[e];!r||!C(t().messages,e,t().currentAssistantMessageId)||(X({...r,subagentSessionId:e,success:r.status==="completed"},t),n(i=>{const o={...i.pendingSubagentCompletions??{}};return delete o[e],{pendingSubagentCompletions:o}}))}const v=(e,t,n,r=!1)=>{const{currentAssistantMessageId:s,messages:a,addMessage:i,startAgentResponse:o}=e();if(n&&r){const l=a.find(f=>f.id===n&&f.role==="assistant");if(l)return o(l.id),l.id;const g={id:n,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};return i(g),o(n),n}if(s&&!s.startsWith("call_")&&a.some(l=>l.id===s&&l.role==="assistant"))return s;if(n){const l=a.find(g=>g.id===n&&g.role==="assistant");if(l)return o(l.id),l.id}const u=a[a.length-1];if((u==null?void 0:u.role)==="assistant")return u.id;const d=n||`assistant-${Date.now()}`,c={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};return i(c),o(d),t(l=>({messages:l.messages.map(g=>g.id===d?{...g,agentContent:{...g.agentContent||$()}}:g)})),d},ot=(e,t,n)=>{const{currentSessionId:r,addMessage:s,startAgentResponse:a,messages:i,updateMessage:o}=t();if(e.sessionId!==r)return;const u=e.messageId,d=e.role||"assistant",c=i.find(g=>g.id===u),l={id:u,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?$():void 0};c?o(u,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||$()}:void 0}):s(l),d==="assistant"&&a(u)},at=(e,t,n)=>{const{currentSessionId:r,appendDelta:s,currentAssistantMessageId:a,hasToolCalls:i,addMessage:o,startAgentResponse:u}=t();if(e.sessionId!==r)return;const d=e.messageId,c=e.delta;if(!a){const g={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};o(g),u(d),t().appendDelta(d,c,"before");return}s(a,c,i?"after":"before")},rt=(e,t)=>{const{currentSessionId:n,updateMessage:r,messages:s}=t();if(e.sessionId!==n)return;const a=e.messageId,i=s.find(o=>o.id===a);i!=null&&i.agentContent&&r(a,{content:pe(i.agentContent)})},ut=(e,t,n)=>{var u;const{currentSessionId:r}=t();if(e.sessionId!==r)return;const s=e.output;if(!s||typeof s!="object"||Array.isArray(s))return;const a=v(t,n,e.messageId);if(!a)return;const i=t().messages.find(d=>d.id===a);if(!i)return;const o=JSON.stringify(s,null,2);t().updateMessage(a,{content:o,metadata:{...i.metadata,structuredOutput:{output:s,schemaDigest:e.schemaDigest}},agentContent:i.agentContent?{...i.agentContent,textBefore:"",textAfter:"",timeline:(u=i.agentContent.timeline)==null?void 0:u.filter(d=>d.type!=="text")}:void 0})},dt=(e,t,n)=>{const{currentSessionId:r,appendThinking:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId);a&&s(a,e.delta)},lt=()=>{},ke=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s,setHasToolCalls:a,setSubagent:i}=t();if(e.sessionId!==r)return;const o=v(t,n,e.messageId||e.toolCallId,typeof e.messageId=="string");if(!o)return;a(!0);const u=e.toolName||"Unknown",d=e.arguments;let c,l="",g,f;if(u==="Task")try{const S=JSON.parse(d);c=S.subagent_type,l=S.description||S.query||c||"",g=S.subagent_session_id,f=S.resume_from||S.resume}catch{}if(c){i(o,{id:F({explicitId:e.toolCallId,sessionId:g,messageId:o,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:g,resumedFrom:f,output:"",thinking:""}),Y(g,t,n);return}const m={toolCallId:H({explicitId:e.toolCallId,messageId:o,toolName:u,argumentsValue:d,toolKind:e.toolKind}),toolName:u,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};s(o,m)};function Te(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(!(t.kind!=="readonly"&&t.kind!=="write"&&t.kind!=="execute")&&!(t.scope!=="global"&&t.scope!=="session")&&!(!Number.isSafeInteger(t.queuePosition)||t.queuePosition<=0||!Number.isSafeInteger(t.inFlight)||t.inFlight<0||!Number.isSafeInteger(t.limit)||t.limit<=0))return{kind:t.kind,scope:t.scope,queuePosition:t.queuePosition,inFlight:t.inFlight,limit:t.limit}}const we=(e,t)=>{const{currentSessionId:n,updateToolCall:r,messages:s}=t();if(e.sessionId!==n)return;const a=e.toolCallId;if(!a)return;const i=s.find(o=>{var u;return(u=o.agentContent)==null?void 0:u.toolCalls.some(d=>d.toolCallId===a)});i&&r(i.id,a,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message,admission:Te(e.admission)})},Pe=(e,t,n)=>{var ae;const{currentSessionId:r,appendToolCall:s,setHasToolCalls:a,updateToolCall:i,updateSubagent:o,messages:u}=t();if(e.sessionId!==r)return;const d=e.toolCallId;if(!d)return;const c=u.find(A=>{var T;return(T=A.agentContent)==null?void 0:T.toolCalls.some(M=>M.toolCallId===d)}),l=u.find(A=>P(A.agentContent).some(T=>T.id===d)),g=(c==null?void 0:c.id)||(l==null?void 0:l.id)||v(t,n,e.messageId,!0);if(!g)return;const f=typeof e.output=="string"?e.output:"",m=e.success===!0||e.status==="completed",S=e.summary||(f&&f.trim()?f.trim().split(`
4
+ `)}function U(e){if(!e.agentContent)return e;let t=e.agentContent;for(const n of Be(e.id,e.metadata))t=Ie(t,n);return{...e,agentContent:t}}function Ve(e){var r,s,a;const t=[];let n=null;for(const i of e)if(i.role!=="system"){if(i.role==="user")n&&(t.push(U(n)),n=null),t.push({id:i.id,role:i.role,content:i.content,timestamp:i.timestamp||Date.now(),metadata:i.metadata});else if(i.role==="assistant"){n&&t.push(U(n));const o=i.metadata;let u=$();i.thinkingContent&&(u=Oe(u,i.thinkingContent),u.thinkingContent=i.thinkingContent);const d=x(i.content);if(d&&(u=De(u,d),u.textBefore=d),i.tool_calls&&Array.isArray(i.tool_calls))for(const c of i.tool_calls){const l=((r=c.function)==null?void 0:r.name)||"Unknown",g=he((s=c.function)==null?void 0:s.arguments);if(l==="Task"){let m={};try{m=JSON.parse(g)}catch{}const S=typeof m.subagent_type=="string"?m.subagent_type:"subagent",y=typeof m.description=="string"?m.description:S;u=Ie(u,{id:F({explicitId:c.id,sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,messageId:i.id,agentType:S,description:y}),type:S,description:y,status:"running",startTime:Date.now(),sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,resumedFrom:typeof m.resume_from=="string"?m.resume_from:typeof m.resume=="string"?m.resume:void 0});continue}const f={toolCallId:H({explicitId:c.id,messageId:i.id,toolName:l,argumentsValue:(a=c.function)==null?void 0:a.arguments}),toolName:l,arguments:g,status:"running",startTime:Date.now()};u=le(u,f)}n={id:i.id,role:"assistant",content:x(i.content),timestamp:i.timestamp||Date.now(),metadata:o,agentContent:u}}else if(i.role==="tool"&&n&&n.agentContent){const o=i,u=i.metadata,d=o.tool_call_id||(u==null?void 0:u.toolCallId),c=o.name||(u==null?void 0:u.toolName)||"Tool",l=u!=null&&u.metadata&&typeof u.metadata=="object"&&!Array.isArray(u.metadata)?u.metadata:u,g=u!=null&&u.independentVerification&&typeof u.independentVerification=="object"&&!Array.isArray(u.independentVerification)?u.independentVerification:void 0,f=(u==null?void 0:u.status)==="failed"||(u==null?void 0:u.status)==="error"||typeof(u==null?void 0:u.error)=="string"&&u.error.length>0,m=P(n.agentContent),S=m.findIndex(h=>h.id===d);if(S>=0){const h=m[S],I=typeof(l==null?void 0:l.subagentStatus)=="string"?Q(l.subagentStatus):f?"failed":"completed";m[S]={...h,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:h.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:h.type,status:I,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:h.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:h.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:h.resumeDepth,verificationVerdict:(l==null?void 0:l.verificationVerdict)==="pass"||(l==null?void 0:l.verificationVerdict)==="fail"||(l==null?void 0:l.verificationVerdict)==="partial"?l.verificationVerdict:(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:h.verificationVerdict,output:typeof(l==null?void 0:l.subagentSummary)=="string"?l.subagentSummary:x(i.content)||h.output},n.agentContent=W(n.agentContent,m,h.id);continue}const y=n.agentContent.toolCalls.find(h=>h.toolCallId===d);y?(y.output=x(i.content),y.status=f?"error":"success",y.metadata=l,y.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:y.summary,(!y.toolName||y.toolName==="Unknown")&&(y.toolName=c)):n.agentContent=le(n.agentContent,{toolCallId:H({explicitId:d,messageId:n.id,toolName:c,output:x(i.content)}),toolName:c,output:x(i.content),status:f?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(U(n)),t}const ye={authentication:"task.failure.authentication",permission:"task.failure.permission",rate_limit:"task.failure.rateLimit",timeout:"task.failure.timeout",network:"task.failure.network",model_unavailable:"task.failure.modelUnavailable",context_limit:"task.failure.contextLimit",unsupported_input:"task.failure.unsupportedInput",workspace_unavailable:"task.failure.workspaceUnavailable",capacity:"task.failure.capacity",runtime:"task.failure.runtime"},Ke={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,workspace_unavailable:!1,capacity:!0,runtime:!0};function Ue(e){if(typeof e=="string"&&Object.keys(ye).includes(e))return e}function bn(e){return ye[e]}function Cn(e){return Ke[e]}const be="blade.sidebar.view",Ce="blade.preview.width",J=640,Je=360,We=960,Le=()=>{if(typeof localStorage>"u")return"project";const e=localStorage.getItem(be);return e==="status"||e==="project"?e:"project"},ve=e=>Math.min(We,Math.max(Je,Math.round(e))),He=()=>{if(typeof localStorage>"u")return J;const e=localStorage.getItem(Ce);if(!e)return J;const t=Number(e);return Number.isFinite(t)?ve(t):J},Ge=fe(e=>({mainView:"workspace",setMainView:t=>e(n=>({mainView:t,isSettingsOpen:!1,isFilePreviewOpen:t==="board"?!1:n.isFilePreviewOpen})),boardProjectPath:null,setBoardProjectPath:t=>e({boardProjectPath:t}),isSidebarOpen:!0,toggleSidebar:()=>e(t=>({isSidebarOpen:!t.isSidebarOpen})),setSidebarOpen:t=>e({isSidebarOpen:t}),sidebarView:Le(),setSidebarView:t=>{typeof localStorage<"u"&&localStorage.setItem(be,t),e({sidebarView:t})},isFilePreviewOpen:!1,toggleFilePreview:()=>e(t=>({isFilePreviewOpen:!t.isFilePreviewOpen})),setFilePreviewOpen:t=>e({isFilePreviewOpen:t}),previewWidth:He(),setPreviewWidth:t=>{const n=ve(t);typeof localStorage<"u"&&localStorage.setItem(Ce,String(n)),e({previewWidth:n})},previewTab:"diff",setPreviewTab:t=>e({previewTab:t}),previewTargetPath:null,previewRequestId:0,openFilePreview:t=>e(n=>({isFilePreviewOpen:!0,previewTab:(t==null?void 0:t.tab)??n.previewTab,previewTargetPath:(t==null?void 0:t.targetPath)??null,previewRequestId:n.previewRequestId+1})),isSettingsOpen:!1,settingsSection:"general",toggleSettings:()=>e(t=>({isSettingsOpen:!t.isSettingsOpen,...t.isSettingsOpen?{}:{settingsSection:"general"}})),openSettings:(t="general")=>e({isSettingsOpen:!0,settingsSection:t}),isTerminalOpen:!1,toggleTerminal:()=>e(t=>({isTerminalOpen:!t.isTerminalOpen})),isTaskSwitcherOpen:!1,taskSwitcherMode:"tasks",setTaskSwitcherOpen:(t,n)=>e(r=>({isTaskSwitcherOpen:t,taskSwitcherMode:n??r.taskSwitcherMode})),setTaskSwitcherMode:t=>e({taskSwitcherMode:t})})),Qe=new Set(["BrowserNavigate","BrowserSnapshot","BrowserInteract","BrowserWait","BrowserInspect","BrowserPage"]),Ye=new Set(["click","click_at","hover","fill","type","press","select","check","uncheck","scroll"]);function ce(e,t){return(e==null?void 0:e.sessionId)===t.sessionId&&e.projectPath===t.projectPath}function N(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ae(e){return typeof e=="string"&&Ye.has(e)?e:void 0}function ze(e){const t=N(e),n=Ae(t==null?void 0:t.action);if(!t||!n)return;const r=N(t.viewport),s=N(t.targetBox),a=i=>typeof i=="number"&&Number.isFinite(i);return{action:n,...typeof t.ref=="string"?{ref:t.ref}:{},...r&&a(r.width)&&a(r.height)?{viewport:{width:r.width,height:r.height}}:{},...s&&a(s.x)&&a(s.y)&&a(s.width)&&a(s.height)?{targetBox:{x:s.x,y:s.y,width:s.width,height:s.height}}:{}}}function Xe(e){if(typeof e!="string")return N(e);try{return N(JSON.parse(e))}catch{return}}function Ze(e){return typeof e=="string"&&Qe.has(e)}const et=fe(e=>({agentActivity:null,beginAgentActivity:(t,n)=>e(r=>{var o,u;const s=ce((o=r.agentActivity)==null?void 0:o.sessionRef,t)?r.agentActivity:null,a=Xe(n.argumentsValue),i=n.toolName==="BrowserInteract"?Ae((u=N(a==null?void 0:a.action))==null?void 0:u.kind):void 0;return{agentActivity:{sessionRef:t,toolCallId:n.toolCallId,toolName:n.toolName,phase:"running",revision:((s==null?void 0:s.revision)??0)+1,frameRevision:(s==null?void 0:s.frameRevision)??0,pointerRevision:(s==null?void 0:s.pointerRevision)??0,...s!=null&&s.pageId?{pageId:s.pageId}:{},...s!=null&&s.origin?{origin:s.origin}:{},...s!=null&&s.url?{url:s.url}:{},...s!=null&&s.title?{title:s.title}:{},...i?{pendingAction:{action:i,...typeof(a==null?void 0:a.ref)=="string"?{ref:a.ref}:{}}}:{},...n.toolName!=="BrowserNavigate"&&(s!=null&&s.interaction)?{interaction:s.interaction}:{}}}}),completeAgentActivity:(t,n)=>e(r=>{var c,l;const s=ce((c=r.agentActivity)==null?void 0:c.sessionRef,t)?r.agentActivity:null,a=N((l=N(n.metadata))==null?void 0:l.browser),i=ze(a==null?void 0:a.interaction),o=typeof(a==null?void 0:a.pageId)=="string"?a.pageId:s==null?void 0:s.pageId,u=typeof(a==null?void 0:a.origin)=="string"?a.origin:s==null?void 0:s.origin,d=n.toolName!=="BrowserNavigate"&&n.toolName!=="BrowserPage";return{agentActivity:{sessionRef:t,toolCallId:n.toolCallId,toolName:n.toolName,phase:n.success?"ready":"error",revision:((s==null?void 0:s.revision)??0)+1,frameRevision:o&&u?((s==null?void 0:s.frameRevision)??0)+1:(s==null?void 0:s.frameRevision)??0,pointerRevision:i!=null&&i.targetBox?((s==null?void 0:s.pointerRevision)??0)+1:(s==null?void 0:s.pointerRevision)??0,...o?{pageId:o}:{},...u?{origin:u}:{},...typeof(a==null?void 0:a.url)=="string"?{url:a.url}:s!=null&&s.url?{url:s.url}:{},...typeof(a==null?void 0:a.title)=="string"?{title:a.title}:s!=null&&s.title?{title:s.title}:{},...typeof(a==null?void 0:a.errorCode)=="string"?{errorCode:a.errorCode}:{},...i?{interaction:i}:d&&(s!=null&&s.interaction)?{interaction:s.interaction}:{}}}}),clearAgentActivity:()=>e({agentActivity:null})})),tt={flushTimeout:80};class nt{constructor(t){K(this,"config");K(this,"channels",new Map);this.config={...tt,...t}}append(t,n,r){let s=this.channels.get(t);s||(s={buffer:"",timer:null,flushFn:null},this.channels.set(t,s)),s.buffer+=n,s.flushFn=r,s.timer||(s.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const r=n.buffer,s=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),s==null||s(r)}drainAll(){for(const[t]of this.channels)this.flushChannel(t);this.channels.clear()}drainAllExcept(t){for(const[n]of this.channels)n!==t&&this.flushChannel(n);for(const[n,r]of this.channels)n!==t&&!r.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const w=new nt,st=100,C=(e,t,n)=>{if(t)for(const r of e){const s=P(r.agentContent).find(a=>a.id===t||a.sessionId===t);if(s)return{messageId:r.id,subagent:s}}if(n){const r=e.find(i=>i.id===n),s=P(r==null?void 0:r.agentContent),a=s.find(i=>i.status==="running")??s[s.length-1];if(a)return{messageId:n,subagent:a}}for(const r of[...e].reverse()){const s=P(r.agentContent),a=s.find(i=>i.status==="running")??s[s.length-1];if(a)return{messageId:r.id,subagent:a}}};function it(e,t,n){n(r=>{const s={...r.pendingSubagentCompletions??{}};if(s[e]===void 0&&Object.keys(s).length>=st){const a=Object.keys(s)[0];a&&delete s[a]}return s[e]={...t},{pendingSubagentCompletions:s}})}function Y(e,t,n){var a;if(!e)return;const r=(a=t().pendingSubagentCompletions)==null?void 0:a[e];!r||!C(t().messages,e,t().currentAssistantMessageId)||(X({...r,subagentSessionId:e,success:r.status==="completed"},t),n(i=>{const o={...i.pendingSubagentCompletions??{}};return delete o[e],{pendingSubagentCompletions:o}}))}const v=(e,t,n,r=!1)=>{const{currentAssistantMessageId:s,messages:a,addMessage:i,startAgentResponse:o}=e();if(n&&r){const l=a.find(f=>f.id===n&&f.role==="assistant");if(l)return o(l.id),l.id;const g={id:n,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};return i(g),o(n),n}if(s&&!s.startsWith("call_")&&a.some(l=>l.id===s&&l.role==="assistant"))return s;if(n){const l=a.find(g=>g.id===n&&g.role==="assistant");if(l)return o(l.id),l.id}const u=a[a.length-1];if((u==null?void 0:u.role)==="assistant")return u.id;const d=n||`assistant-${Date.now()}`,c={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};return i(c),o(d),t(l=>({messages:l.messages.map(g=>g.id===d?{...g,agentContent:{...g.agentContent||$()}}:g)})),d},ot=(e,t,n)=>{const{currentSessionId:r,addMessage:s,startAgentResponse:a,messages:i,updateMessage:o}=t();if(e.sessionId!==r)return;const u=e.messageId,d=e.role||"assistant",c=i.find(g=>g.id===u),l={id:u,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?$():void 0};c?o(u,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||$()}:void 0}):s(l),d==="assistant"&&a(u)},at=(e,t,n)=>{const{currentSessionId:r,appendDelta:s,currentAssistantMessageId:a,hasToolCalls:i,addMessage:o,startAgentResponse:u}=t();if(e.sessionId!==r)return;const d=e.messageId,c=e.delta;if(!a){const g={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:$()};o(g),u(d),t().appendDelta(d,c,"before");return}s(a,c,i?"after":"before")},rt=(e,t)=>{const{currentSessionId:n,updateMessage:r,messages:s}=t();if(e.sessionId!==n)return;const a=e.messageId,i=s.find(o=>o.id===a);i!=null&&i.agentContent&&r(a,{content:pe(i.agentContent)})},ut=(e,t,n)=>{var u;const{currentSessionId:r}=t();if(e.sessionId!==r)return;const s=e.output;if(!s||typeof s!="object"||Array.isArray(s))return;const a=v(t,n,e.messageId);if(!a)return;const i=t().messages.find(d=>d.id===a);if(!i)return;const o=JSON.stringify(s,null,2);t().updateMessage(a,{content:o,metadata:{...i.metadata,structuredOutput:{output:s,schemaDigest:e.schemaDigest}},agentContent:i.agentContent?{...i.agentContent,textBefore:"",textAfter:"",timeline:(u=i.agentContent.timeline)==null?void 0:u.filter(d=>d.type!=="text")}:void 0})},dt=(e,t,n)=>{const{currentSessionId:r,appendThinking:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId);a&&s(a,e.delta)},lt=()=>{},ke=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s,setHasToolCalls:a,setSubagent:i}=t();if(e.sessionId!==r)return;const o=v(t,n,e.messageId||e.toolCallId,typeof e.messageId=="string");if(!o)return;a(!0);const u=e.toolName||"Unknown",d=e.arguments;let c,l="",g,f;if(u==="Task")try{const S=JSON.parse(d);c=S.subagent_type,l=S.description||S.query||c||"",g=S.subagent_session_id,f=S.resume_from||S.resume}catch{}if(c){i(o,{id:F({explicitId:e.toolCallId,sessionId:g,messageId:o,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:g,resumedFrom:f,output:"",thinking:""}),Y(g,t,n);return}const m={toolCallId:H({explicitId:e.toolCallId,messageId:o,toolName:u,argumentsValue:d,toolKind:e.toolKind}),toolName:u,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};s(o,m)};function Te(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(!(t.kind!=="readonly"&&t.kind!=="write"&&t.kind!=="execute")&&!(t.scope!=="global"&&t.scope!=="session")&&!(!Number.isSafeInteger(t.queuePosition)||t.queuePosition<=0||!Number.isSafeInteger(t.inFlight)||t.inFlight<0||!Number.isSafeInteger(t.limit)||t.limit<=0))return{kind:t.kind,scope:t.scope,queuePosition:t.queuePosition,inFlight:t.inFlight,limit:t.limit}}const we=(e,t)=>{const{currentSessionId:n,updateToolCall:r,messages:s}=t();if(e.sessionId!==n)return;const a=e.toolCallId;if(!a)return;const i=s.find(o=>{var u;return(u=o.agentContent)==null?void 0:u.toolCalls.some(d=>d.toolCallId===a)});i&&r(i.id,a,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message,admission:Te(e.admission)})},Pe=(e,t,n)=>{var ae;const{currentSessionId:r,appendToolCall:s,setHasToolCalls:a,updateToolCall:i,updateSubagent:o,messages:u}=t();if(e.sessionId!==r)return;const d=e.toolCallId;if(!d)return;const c=u.find(A=>{var T;return(T=A.agentContent)==null?void 0:T.toolCalls.some(M=>M.toolCallId===d)}),l=u.find(A=>P(A.agentContent).some(T=>T.id===d)),g=(c==null?void 0:c.id)||(l==null?void 0:l.id)||v(t,n,e.messageId,!0);if(!g)return;const f=typeof e.output=="string"?e.output:"",m=e.success===!0||e.status==="completed",S=e.summary||(f&&f.trim()?f.trim().split(`
5
5
  `)[0].slice(0,120):m?"执行成功":"执行失败"),y=(ae=c==null?void 0:c.agentContent)==null?void 0:ae.toolCalls.find(A=>A.toolCallId===d),h=typeof e.toolName=="string"?e.toolName:(y==null?void 0:y.toolName)??"Unknown",I=e.metadata;c?i(g,d,{status:m?"success":"error",summary:S,output:f,metadata:I}):l||(a(!0),s(g,{toolCallId:d,toolName:h,status:m?"success":"error",summary:S,output:f,startTime:Date.now(),metadata:I}));const E=t().messages.find(A=>A.id===g),k=P(E==null?void 0:E.agentContent).find(A=>A.id===d),R=I&&typeof I.subagentSessionId=="string"?I.subagentSessionId:void 0,_=I&&typeof I.subagentStatus=="string"?I.subagentStatus:void 0,ee=I&&typeof I.subagentType=="string"?I.subagentType:void 0,te=I&&typeof I.subagentSummary=="string"?I.subagentSummary:void 0,ne=I&&typeof I.subagentResumedFrom=="string"?I.subagentResumedFrom:void 0,se=I&&typeof I.subagentRootId=="string"?I.subagentRootId:void 0,ie=I&&typeof I.subagentResumeDepth=="number"?I.subagentResumeDepth:void 0,oe=(I==null?void 0:I.verificationVerdict)==="pass"||(I==null?void 0:I.verificationVerdict)==="fail"||(I==null?void 0:I.verificationVerdict)==="partial"?I.verificationVerdict:void 0;if(k){const A=_?Q(_):e.success?"completed":"failed",T=k.status!=="running"&&A==="running";o(g,k.id,{sessionId:k.sessionId||R,type:ee||k.type,status:T?k.status:A,resumedFrom:ne||k.resumedFrom,rootAgentId:se||k.rootAgentId,resumeDepth:ie??k.resumeDepth,verificationVerdict:oe??k.verificationVerdict,output:T?k.output:te||k.output})}R&&_&&n(A=>({messages:A.messages.map(T=>{if(T.id!==g)return T;const M=T.metadata??{},q=Array.isArray(M.subtaskRefs)?M.subtaskRefs:[],j=q.findIndex(re=>re.childSessionId===R||re.subagentId===d),b=j>=0?q[j]:M.subtaskRef??{},B={...b,subagentId:d,childSessionId:R,agentType:ee||(typeof(b==null?void 0:b.agentType)=="string"?b.agentType:"subagent"),status:_,summary:te||(typeof(b==null?void 0:b.summary)=="string"?b.summary:""),resumedFrom:ne||(typeof(b==null?void 0:b.resumedFrom)=="string"?b.resumedFrom:void 0),rootAgentId:se||(typeof(b==null?void 0:b.rootAgentId)=="string"?b.rootAgentId:R),resumeDepth:ie??(typeof(b==null?void 0:b.resumeDepth)=="number"?b.resumeDepth:0),verificationVerdict:oe||(typeof(b==null?void 0:b.verificationVerdict)=="string"?b.verificationVerdict:void 0)},V=[...q];return j>=0?V[j]=B:V.push(B),{...T,metadata:{...M,subtaskRef:B,subtaskRefs:V}}})})),Y(R,t,n)},ct=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId||`mcp-catalog-${String(e.revision)}`);if(!a)return;const i=Array.isArray(e.added)?e.added.map(String):[],o=Array.isArray(e.removed)?e.removed.map(String):[],u=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP catalog r${String(e.revision)}: +${i.length} -${o.length} ~${u.length}`;s(a,{toolCallId:`mcp-catalog:${String(e.revision)}`,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:i,removed:o,updated:u}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[i.length>0?`Added: ${i.join(", ")}`:"",o.length>0?`Removed: ${o.join(", ")}`:"",u.length>0?`Updated: ${u.join(", ")}`:""].filter(Boolean).join(`
6
6
  `)})},gt=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId||`mcp-content-${String(e.revision)}`);if(!a)return;const i=Array.isArray(e.added)?e.added.map(String):[],o=Array.isArray(e.removed)?e.removed.map(String):[],u=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP ${String(e.contentKind)} r${String(e.revision)}: +${i.length} -${o.length} ~${u.length}`;s(a,{toolCallId:`mcp-content:${String(e.revision)}`,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:i,removed:o,updated:u}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[i.length>0?`Added: ${i.join(", ")}`:"",o.length>0?`Removed: ${o.join(", ")}`:"",u.length>0?`Updated: ${u.join(", ")}`:""].filter(Boolean).join(`
7
7
  `)})},mt=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId||`mcp-resource-${String(e.revision)}`);a&&s(a,{toolCallId:`mcp-resource:${String(e.revision)}`,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`,output:`${String(e.serverName)} · revision ${String(e.revision)}`})},ft=(e,t,n)=>{const{currentSessionId:r,appendToolCall:s}=t();if(e.sessionId!==r)return;const a=v(t,n,e.messageId||`mcp-connection-${String(e.revision)}`);if(!a)return;const i=String(e.phase),o=`MCP ${String(e.serverName)} ${i}`+(i==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:"");s(a,{toolCallId:`mcp-connection:${String(e.revision)}`,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:i,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:i==="failed"?"error":"success",startTime:Date.now(),summary:o,output:[`Reason: ${String(e.reason)}`,e.error?`Error: ${String(e.error)}`:""].filter(Boolean).join(`
@@ -1 +1 @@
1
- import{ar as e,as as t,at as a,a3 as s,au as m}from"./index-rQ1P5u3I.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-Bc1_Q9tz.js";import"./session-events-C95VE6d2.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:a(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:a(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:a(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:a(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(a(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,r,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:r,message:g})})},delete:async(n,i)=>{const r=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${r.toString()}`,{method:"DELETE"}))}};export{u as teamService};
1
+ import{at as e,au as t,av as a,a3 as s,aw as m}from"./index-DNoVz0u1.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-Bc1_Q9tz.js";import"./session-events-B4Cq2TwN.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:a(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:a(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:a(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:a(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(a(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,r,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:r,message:g})})},delete:async(n,i)=>{const r=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${r.toString()}`,{method:"DELETE"}))}};export{u as teamService};
@@ -5,11 +5,11 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>BladeCode</title>
8
- <script type="module" crossorigin src="/assets/index-rQ1P5u3I.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-DNoVz0u1.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DofNRwfy.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/vendor-radix-Bc1_Q9tz.js">
11
- <link rel="modulepreload" crossorigin href="/assets/session-events-C95VE6d2.js">
12
- <link rel="stylesheet" crossorigin href="/assets/index-zY4JU9fd.css">
11
+ <link rel="modulepreload" crossorigin href="/assets/session-events-B4Cq2TwN.js">
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DGf6Z2kM.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.97",
3
+ "version": "0.10.99",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{ce as a,de as b,ee as c,fe as d,ge as e,he as f,ie as g,je as h}from"./chunk-7bhk8qk5.js";import"./chunk-zvms9ap7.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.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};
@@ -1 +0,0 @@
1
- import{Jf as a,Kf as b,Lf as c,Mf as d,Nf as e,Of as f,Pf as g,Qf as h,Rf as i,Sf as j}from"./chunk-csr9d8yx.js";import"./chunk-q5t2rnx0.js";import"./chunk-9mnspb2d.js";import"./chunk-dretwm9j.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +0,0 @@
1
- import{Bb as d,Cb as e,Db as f,Eb as g,Fb as h,Gb as i,Hb as j,Ib as k,Pb as l,Qb as m,Rb as n,Sb as o,Ub as p,Vb as q,Wb as r,ub as a,vb as b,xb as c}from"./chunk-g2hxj68b.js";import"./chunk-8hprmrd5.js";import"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import"./chunk-3saxqsn7.js";import"./chunk-31g86axj.js";import"./chunk-88mf53ak.js";import"./chunk-q5t2rnx0.js";import"./chunk-9mnspb2d.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.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};
@@ -1,5 +0,0 @@
1
- import{$h as Cf,Nh as E_,Oh as qf,Ph as gf,Qh as __,Rh as Wf,Th as $f,Vh as If,Xh as q,Yh as Kf,_h as Df,bi as s}from"./chunk-2c2cxrc0.js";import{ji as l}from"./chunk-zvms9ap7.js";import{ni as AE,pi as Xf}from"./chunk-fm93hym6.js";import{si as lE}from"./chunk-t5es94zk.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 Ze,WT as _e,xE as $e,ff as af,tf as bf,vE as cf,fT as df,Rh as ef,e as ff,qE as gf,lf as hf,Gh as if};
@@ -1 +0,0 @@
1
- import{jf as a,kf as b,lf as c}from"./chunk-a1vhp8sa.js";import"./chunk-88mf53ak.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,10 +0,0 @@
1
- import{a as T,b as W,c as X,d as Y}from"./chunk-t5y1ebdn.js";import"./chunk-ps2rv1gg.js";import"./chunk-21ycnzsv.js";import"./chunk-3229684w.js";import"./chunk-8htbttg5.js";import"./chunk-2mwgykjs.js";import"./chunk-825r9sfe.js";import"./chunk-j1t2qedg.js";import"./chunk-cvpvncza.js";import"./chunk-n407vvwt.js";import"./chunk-g2hxj68b.js";import"./chunk-8hprmrd5.js";import"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import{re as R}from"./chunk-sdvfyzv0.js";import"./chunk-jy4s51bt.js";import{Ne as Q}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import"./chunk-3saxqsn7.js";import"./chunk-31g86axj.js";import"./chunk-a1vhp8sa.js";import"./chunk-88mf53ak.js";import"./chunk-qhsmhx0y.js";import"./chunk-csr9d8yx.js";import"./chunk-q5t2rnx0.js";import"./chunk-9mnspb2d.js";import"./chunk-dretwm9j.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import{xi as M}from"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";import m from"chalk";import K from"open";var A=`
2
- ____ _ _
3
- | __ )| | __ _ __| | ___
4
- | _ \\| |/ _\` |/ _\` |/ _ \\
5
- | |_) | | (_| | (_| | __/
6
- |____/|_|\\__,_|\\__,_|\\___|
7
- `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
- `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
- `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
- `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -1 +0,0 @@
1
- import{Ai as e,Bi as f,wi as a,xi as b,yi as c,zi as d}from"./chunk-v2bvrk83.js";import"./chunk-g2yaghbk.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,2 +0,0 @@
1
- var f;((c)=>{c.ReadOnly="readonly";c.Write="write";c.Execute="execute"})(f||={});function g(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function h(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}function j(b){return b==="readonly"}
2
- export{f as Pd,g as Qd,h as Rd,j as Sd};
@@ -1 +0,0 @@
1
- import{ke as a,le as b}from"./chunk-qeznbnd1.js";import"./chunk-v2bvrk83.js";import"./chunk-g2yaghbk.js";export{a as globalOptions,b as cliConfig};
@@ -1,2 +0,0 @@
1
- var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
- export{_ as Bh,E as Ch,T as Dh,A as Eh,S as Fh};
@@ -1 +0,0 @@
1
- import{Id as a,Jd as b,Kd as c,Ld as d,Md as e,Nd as f,Od as g}from"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import"./chunk-88mf53ak.js";import"./chunk-9mnspb2d.js";import"./chunk-xtm0sp0k.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-zvms9ap7.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.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};
@@ -1 +0,0 @@
1
- import{He as a,Ie as b,Je as c,Ke as d,Le as e,Me as f,Ne as g,Oe as h,Pe as i,Qe as j,Re as k,Se as l,Te as m,Ue as n,Ve as o,We as p,Xe as q}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import"./chunk-3saxqsn7.js";import"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,23 +0,0 @@
1
- import{s as hz,t as Sz}from"./chunk-3229684w.js";import{u as b}from"./chunk-8htbttg5.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-2mwgykjs.js";import{G as N,P as $z,Q as Qz,U as Wz,X as Yz,Y as Hz,aa as jz,qa as Fz,ra as Uz,sa as Vz,ta as wz}from"./chunk-825r9sfe.js";import"./chunk-j1t2qedg.js";import{Ha as Tz}from"./chunk-cvpvncza.js";import{Ja as Zz}from"./chunk-n407vvwt.js";import{Db as zz,Mb as Jz,rb as e}from"./chunk-g2hxj68b.js";import{Xb as I}from"./chunk-8hprmrd5.js";import{$c as l,Ad as C,Bd as s,Dd as x,Gd as t,Ld as q,Od as U,jd as i,kd as r,pd as a,sd as o,ud as n}from"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import{re as Mz}from"./chunk-sdvfyzv0.js";import"./chunk-jy4s51bt.js";import{Me as Nz,Ne as Ez}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import{Ye as f}from"./chunk-3saxqsn7.js";import{bf as v}from"./chunk-31g86axj.js";import"./chunk-a1vhp8sa.js";import{mf as xz}from"./chunk-88mf53ak.js";import"./chunk-qhsmhx0y.js";import"./chunk-csr9d8yx.js";import"./chunk-q5t2rnx0.js";import{cg as bz}from"./chunk-9mnspb2d.js";import"./chunk-dretwm9j.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import{Wg as qz,Zg as Pz}from"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import{Bh as S,Ch as d,Eh as M,Fh as k}from"./chunk-b9thsjxh.js";import{Jh as Oz}from"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import{ji as T}from"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import{qi as Az,ti as Rz}from"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import{Pi as m}from"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function pz(z){if(!v(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...i("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Gz({maxPendingItems:Xz,maxPendingBytes:Dz,writeTimeoutMs:Lz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return jz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?uz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Wz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(D)=>Q.onOutput?.("stdout",D)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Uz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=e.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:D}=W.properties,X=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof D==="string"&&Qz(X,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(D,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:X});if(!L?.accepted)return;if(await new $z(Q,m()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!n(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of gz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=!1,X,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(D)L(B);else X=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),D=!0,X)L(X);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,D)},complete:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,D)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),X=await D.completion,L=(await b.list(this.cwd,this.id)).find((F)=>F.start.reviewId===D.reviewId);if(!L)throw Error(`Review not found: ${D.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:D.reviewId,status:X.status,findings:X.findings.length,content:l(L.start,X)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,D)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(D);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Vz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=wz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Zz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController,X=!1,L,F=new Promise((B)=>{L=B});this.pendingPrompt=D,this.pendingPromptCompletion=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Fz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,D.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await zz(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let P=JSON.parse(V.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")w=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,kz=Hz(o(Yz(K,O),a));R.push({type:"content",content:{type:"text",text:kz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let P=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:P,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":X=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":for(let V of $.messages){if(!V.recovered||V.persisted)continue;for(let O of Kz(V.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:O})}if($.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${$.recovered} queued instruction${$.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())D.abort("acp-egress-failed")});if(!await this.flushUpdates())D.abort("acp-egress-failed");this.contextMessages=[...B.messages];let g=await U.loadSession(this.id,this.cwd);if(this.messages=g.length>0?g:[...B.messages],!A.success){let $=A.error?.type??"unknown",V=A.error?.details??A.error?.message??"Agent execution failed",O=pz(V)??r(V);throw Cz.internalError({failureType:$,taskFailure:{code:O.code,retryable:O.retryable,...O.resource?{resource:O.resource}:{}}},`Agent turn failed (${$})`)}if(D.signal.aborted)return{stopReason:"cancelled"};let c={...A.metadata?.structuredOutput?{structuredOutput:A.metadata.structuredOutput,outputSchemaDigest:A.metadata.structuredOutputSchemaDigest}:{},...A.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:A.metadata.goalVerificationVerdict,...A.metadata.goalVerifierSessionId?{verifierSessionId:A.metadata.goalVerifierSessionId}:{},...A.metadata.goalVerificationEvidenceSha256?{evidenceSha256:A.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(c).length>0?{_meta:c}:{}}}catch(B){if(D.signal.aborted||B instanceof Error&&B.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,B),B}finally{if(X&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(L(),this.pendingPromptCompletion===F)this.pendingPromptCompletion=null;if(this.pendingPrompt===D){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,Y,H=new Promise((j)=>{Y=j});this.pendingUserShell=J,this.pendingUserShellCompletion=H;let W,Q="";try{let j=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(X)=>{if(W=X.executionId,X.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.executionId,status:"in_progress",title:`! ${X.command}`,content:[],kind:"execute"});return}if(X.type==="output"){Q+=X.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:X.chunk}}]});return}let L=C(X.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.executionId,status:X.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?cz(X.record):L}}]})}}),D={role:"user",content:j.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(j.record))}};if(this.messages.push(D),this.contextMessages.push(D),j.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:j.record.status==="aborted"?"cancelled":"end_turn"}}catch(j){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:j instanceof Error?j.message:String(j)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw j}finally{if(Y(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,Z=z?null:await this.runtime.getGoal(),J=Z?.status==="active"||Z?.status==="verifying";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await U.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await U.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof q)&&J.code!=="ENOENT")throw J;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await U.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof q)&&J.code!=="ENOENT")throw J;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await U.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof q)&&J.code!=="ENOENT")throw J;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await U.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof q)&&J.code!=="ENOENT")throw J;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await U.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(Y){if(!(Y instanceof q)&&Y.code!=="ENOENT")throw Y;await U.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.updateEgress.close(new Bz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,H=this.pendingUserShellCompletion,W=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Q,j=async(D)=>{try{await D()}catch(X){Q??=X}};if(await j(()=>this.cancel()),Y)await j(()=>Y);if(H)await j(()=>H);if(W)await j(()=>W);if(z&&Y&&J)await j(()=>J.discardPendingInput());if(Z)await j(()=>Z.destroy());if(J)await j(()=>J.dispose());if(await j(()=>N.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(z){let Z=[],J=[],Y=0,H=0,W=0,Q=(X)=>{if(J.length>0)J.push({type:"text",text:`
13
- `}),W+=1;if(J.push(X),X.type==="text")W+=X.text.length};for(let X of z)if(X.type==="text")Z.push(X.text),Q({type:"text",text:X.text});else if(X.type==="image"){let L=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=L.length,Z.push(`[Image: ${X.mimeType}]`),Q({type:"image_url",image_url:{url:L}})}else if(X.type==="resource"){let L=X.resource;if("text"in L){let F=`<file path="${L.uri}">
14
- ${L.text}
15
- </file>`;Z.push(F),Q({type:"text",text:F})}}else if(X.type==="resource_link"){let L=`[Resource: ${X.uri}]`;Z.push(L),Q({type:"text",text:L})}if(Y>S)throw Error(`ACP prompt contains more than ${S} images`);if(H>d)throw Error("ACP prompt images exceed the 5 MiB limit");if(W>M)throw Error(`ACP prompt text exceeds ${M} characters`);if(Buffer.byteLength(Z.join(`
16
- `),"utf8")>k)throw Error(`ACP prompt text exceeds ${k} bytes`);let D=Z.join(`
17
- `);return{content:Y>0?J:D,displayText:D}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let Z=this.updateEgress.offer({sessionId:this.id,update:z});if(!Z.accepted)return!1;try{return await Z.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let Z=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(z){let Z=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,Z);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,Z);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return G.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),H=[];if(z.message)H.push({type:"content",content:{type:"text",text:z.message}});if(z.details)H.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
18
- - ${z.risks.join(`
19
- - `)}`}});let W=this.mapToolKind(J),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:H,kind:W}},j=await this.waitForClientInteraction(this.connection.requestPermission(Q),Z);if(!j)return{approved:!1,reason:I};let D=j.outcome;if(D.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=D.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,Z){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,W]of J.entries()){let Q=W.options.map((L,F)=>`answer:${H}:${F}`),j=`answer:${H}:cancel`,D=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...W.options.map((L,F)=>({optionId:Q[F],name:L.label,kind:"allow_once"})),{optionId:j,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:W.header,kind:"think",content:[{type:"content",content:{type:"text",text:[W.question,...W.options.map((L)=>`${L.label}: ${L.description}`)].join(`
20
- `)}}]}}),Z);if(!D)return{approved:!1,reason:I};if(D.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=Q.indexOf(D.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[W.header]=W.options[X].label}return{approved:!0,answers:Y}}catch(H){return G.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,Z){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
21
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of J.fields??[]){let W=await this.collectAcpElicitationField(H,Z);if(W.cancelled)return{approved:!1,reason:W.reason,elicitation:{action:"cancel"}};if(W.value!==void 0)Y[H.name]=W.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,Z){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((W,Q)=>({id:`option:${Q}`,label:W.label,value:W.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
- `),[...J.map((W)=>({id:W.id,label:W.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=J.find((W)=>W.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(z.defaultValue!==void 0){let J=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
23
- `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,Z,J,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((W)=>({optionId:W.id,name:W.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(z,Z){if(!Z)return z;if(Z.aborted)return;return new Promise((J,Y)=>{let H=!1,W=(j)=>{if(H)return;H=!0,Z.removeEventListener("abort",Q),j()},Q=()=>W(()=>J(void 0));if(Z.addEventListener("abort",Q,{once:!0}),Z.aborted)Q();z.then((j)=>W(()=>J(j)),(j)=>W(()=>Y(j)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var _=T("Agent");class u{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=Nz();this.runtimeResidencyValue=new Sz({maxResident:z?.maxResidentSessionRuntimes??qz,idleMs:z?.sessionRuntimeIdleMs??Pz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(Z){if(Z instanceof hz)throw dz.internalError({resource:Z.resource,limit:Z.limit,retryable:Z.retryable},Z.message);throw Z}}async initialize(z){return _.info("[BladeAgent] Initializing ACP connection"),_.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Ez(),{protocolVersion:mz,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let Z=f("acp"),J=await this.reserveSessionRuntime(Z),Y=z.cwd||Oz(),H=z._meta?.["blade/taskIsolation"],W=H==="local"||H==="worktree"?H:void 0,Q=z._meta?.["blade/taskPrompt"],j;try{let D=W?await yz.createSessionTask({sessionId:Z,prompt:typeof Q==="string"&&Q.trim()?Q:"ACP task session",sourceProjectPath:Y,isolation:W}):void 0,X=D?.metadata.projectPath??Y;return _.info(`[BladeAgent] Creating new session: ${Z}`),_.debug(`[BladeAgent] Session cwd: ${X}`),j=new E(Z,X,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...D?.taskWorktree?{taskWorktree:D.taskWorktree}:{},...D?.metadata.taskIsolation?{taskIsolation:D.metadata.taskIsolation}:{}}),await j.initialize(),this.assertNotDestroyed(),this.commitSession(Z,j,J),_.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),j.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,D?.metadata,j.getModelConfiguration())}catch(D){throw J.cancel(),await j?.destroy().catch(()=>{return}),D}}async listSessions(z){if(z.cwd!=null&&!_z.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=await U.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime,_meta:{"blade/taskStatus":J.taskStatus,...J.taskStatusReason?{"blade/taskStatusReason":J.taskStatusReason}:{},...J.taskFailure?{"blade/taskFailure":J.taskFailure}:{},...J.taskStartedAt?{"blade/taskStartedAt":J.taskStartedAt}:{},...J.taskCompletedAt?{"blade/taskCompletedAt":J.taskCompletedAt}:{},...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskIsolation?{"blade/taskIsolation":J.taskIsolation}:{},...J.taskSourceProjectPath?{"blade/taskSourceProjectPath":J.taskSourceProjectPath}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{},...J.taskDiffStat?{"blade/taskDiffStat":J.taskDiffStat}:{},...J.taskQueuePosition?{"blade/taskQueuePosition":J.taskQueuePosition}:{},...J.taskQueueDepth!==void 0?{"blade/taskQueueDepth":J.taskQueueDepth}:{},...J.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":J.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!_z.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Z=f("fork"),J=await this.reserveSessionRuntime(Z),Y;try{let H=await U.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:Z});return this.assertNotDestroyed(),Y=new E(H.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H.messages,permissionMode:H.metadata.permissionMode,mcpServers:z.mcpServers}),await Y.initialize(),this.assertNotDestroyed(),this.commitSession(H.sessionId,Y,J),Y.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H.sessionId,H.metadata,Y.getModelConfiguration())}catch(H){throw J.cancel(),await Y?.destroy().catch(()=>{return}),H}}async loadSession(z){this.assertNotDestroyed(),_.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await U.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let Z=await this.reserveSessionRuntime(z.sessionId),J;try{let[Y,H]=await Promise.all([U.loadSession(z.sessionId,z.cwd),U.findSessionMetadata(z.sessionId,z.cwd)]);if(!H)throw Error(`Session not found: ${z.sessionId}`);return J=new E(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:Y,permissionMode:H.permissionMode,mcpServers:z.mcpServers}),await J.initialize(),await J.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,J,Z),J.sendAvailableCommandsDelayed(),this.buildSessionSetup(J.getModelConfiguration(),J.getMode())}catch(Y){throw Z.cancel(),await J?.destroy().catch(()=>{return}),Y}}commitSession(z,Z,J){let Y=J.commit({key:z,surface:"acp",value:Z,canEvict:()=>Z.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===Z)this.sessions.delete(z);await Z.destroy()}});this.sessions.set(z,Z),Y.release()}async closeResidentSession(z,Z={}){let J=this.sessions.get(z);if(!J)return;let Y=this.runtimeResidency.owns(z,J),H;try{await J.destroy(Z)}catch(Q){H=Q}let W=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(Y&&!W&&H===void 0)throw Error(`ACP Session is still active: ${z}`);if(H!==void 0)throw H}buildChildSessionResponse(z,Z,J){return{sessionId:z,...this.buildSessionSetup(J,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,Z="default"){let J=z?.models??[],Y=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],W=[];if(J.length>0)W.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)W.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)W.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)W.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)W.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:W.length>0?W:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{return await Z.value.prompt(z)}finally{Z.release()}}async cancel(z){_.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z){_.info("[BladeAgent] Found session, calling session.cancel()");try{Z.value.cancel()}finally{Z.release()}}else _.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){_.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z)try{await Z.value.setMode(z.modeId)}finally{Z.release()}return{}}async setSessionConfigOption(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{let J=Z.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")_.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&xz(z.value))_.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Rz(z.value))_.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Az(z.value))_.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&bz(z.value))_.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{Z.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let Z of[...this.sessions.keys()])try{await this.closeResidentSession(Z)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(Z){z??=Z}this.sessions.clear();try{await Tz.getInstance().disconnectAll()}catch(Z){z??=Z}if(z!==void 0)throw z}}async function cJ(){let z=lz.toWeb(process.stdout),Z=vz.toWeb(process.stdin),J=y.ndJsonStream(z,Z),Y,H=new y.AgentSideConnection((Q)=>{return Y=new u(Q),Y},J),W=Mz(async()=>{await Y?.destroy()});try{await H.closed}finally{W(),await Y?.destroy()}}export{cJ as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-t5y1ebdn.js";import"./chunk-ps2rv1gg.js";import"./chunk-21ycnzsv.js";import"./chunk-3229684w.js";import"./chunk-8htbttg5.js";import"./chunk-2mwgykjs.js";import"./chunk-825r9sfe.js";import"./chunk-j1t2qedg.js";import"./chunk-cvpvncza.js";import"./chunk-n407vvwt.js";import"./chunk-g2hxj68b.js";import"./chunk-8hprmrd5.js";import"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import{re as n}from"./chunk-sdvfyzv0.js";import"./chunk-jy4s51bt.js";import{Ne as s}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import"./chunk-3saxqsn7.js";import"./chunk-31g86axj.js";import"./chunk-a1vhp8sa.js";import"./chunk-88mf53ak.js";import"./chunk-qhsmhx0y.js";import"./chunk-csr9d8yx.js";import"./chunk-q5t2rnx0.js";import"./chunk-9mnspb2d.js";import"./chunk-dretwm9j.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.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 +0,0 @@
1
- import{h as a,i as b,j as c,k as d,l as e}from"./chunk-630jj776.js";import"./chunk-v2bvrk83.js";import"./chunk-g2yaghbk.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};