blade-code 0.10.14 → 0.10.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-4hawehmd.js → chunk-0ndm72az.js} +2 -2
- package/dist/{chunk-gav4hxcv.js → chunk-1n60pgsq.js} +2 -2
- package/dist/{chunk-dpt56hah.js → chunk-2c3zavy2.js} +1 -1
- package/dist/{chunk-321n9hem.js → chunk-2e03enfb.js} +1 -1
- package/dist/chunk-2g41y2tz.js +1 -0
- package/dist/chunk-334jhwxz.js +160 -0
- package/dist/chunk-3qhqbj09.js +2 -0
- package/dist/{chunk-mcqe9km3.js → chunk-3wbheq1y.js} +1 -1
- package/dist/chunk-4k615fx6.js +1 -0
- package/dist/chunk-4svjvyyd.js +1 -0
- package/dist/chunk-4twtqram.js +22 -0
- package/dist/chunk-51hjqrt8.js +1 -0
- package/dist/{chunk-8j01ssaf.js → chunk-5chec8rs.js} +1 -1
- package/dist/{chunk-4dq9y7zn.js → chunk-6207mbmr.js} +2 -2
- package/dist/{chunk-g11hq0e5.js → chunk-6g5k5de1.js} +1 -1
- package/dist/{chunk-vmq248m7.js → chunk-6pa6c2n0.js} +1 -1
- package/dist/{chunk-heqs3xan.js → chunk-6sb7cg95.js} +1 -1
- package/dist/chunk-87vsgqvy.js +1 -0
- package/dist/chunk-88639hse.js +1 -0
- package/dist/chunk-8brheywa.js +1 -0
- package/dist/{chunk-kvx3sb3z.js → chunk-96h588rd.js} +1 -1
- package/dist/{chunk-8zr7h97n.js → chunk-9m1ayjve.js} +1 -1
- package/dist/chunk-ajy99edp.js +100 -0
- package/dist/{chunk-j7k5x43d.js → chunk-as56atkw.js} +2 -2
- package/dist/chunk-bcxbrbvd.js +1 -0
- package/dist/{chunk-732n8xj6.js → chunk-d9k98jy2.js} +1 -1
- package/dist/chunk-djktk1az.js +1 -0
- package/dist/{chunk-se1tfys3.js → chunk-dskgbv7c.js} +2 -2
- package/dist/{chunk-74shfpve.js → chunk-entmz5b1.js} +1 -1
- package/dist/chunk-f2qj464t.js +1 -0
- package/dist/{chunk-z8c5rhdh.js → chunk-fa6313dv.js} +1 -1
- package/dist/{chunk-xx1d9kfd.js → chunk-fvj1mzgs.js} +1 -1
- package/dist/{chunk-9ajyeqa7.js → chunk-gc9wfvfd.js} +2 -2
- package/dist/chunk-gwx7jz87.js +3 -0
- package/dist/chunk-h1kgh7xz.js +10 -0
- package/dist/{chunk-hrmfhv8k.js → chunk-h37yw6g3.js} +2 -2
- package/dist/{chunk-s5666ta0.js → chunk-jpwfq49n.js} +2 -2
- package/dist/{chunk-ktf3bpmw.js → chunk-k3nkcaap.js} +2 -2
- package/dist/{chunk-2mzcxq6c.js → chunk-kbpc97n3.js} +2 -2
- package/dist/{chunk-2z6261pz.js → chunk-kn8xx8ng.js} +2 -2
- package/dist/{chunk-zvt8ngpt.js → chunk-ky0v990x.js} +3 -3
- package/dist/{chunk-0hbvc51n.js → chunk-mbrevmbp.js} +2 -2
- package/dist/{chunk-rbph12qe.js → chunk-mcr47s40.js} +4 -4
- package/dist/chunk-n2hwfw7v.js +200 -0
- package/dist/{chunk-wznyzdtg.js → chunk-n6jjfyqn.js} +1 -1
- package/dist/{chunk-5s123nbs.js → chunk-prgh321y.js} +1 -1
- package/dist/{chunk-7wjy6kgt.js → chunk-q3c07kb4.js} +1 -1
- package/dist/{chunk-afkhzdfc.js → chunk-qkrssft1.js} +1 -1
- package/dist/{chunk-p4zt7ts9.js → chunk-qt114yth.js} +1 -1
- package/dist/chunk-qwpbwhmn.js +1 -0
- package/dist/{chunk-9tnaads5.js → chunk-r1jxbx1h.js} +1 -1
- package/dist/{chunk-snv4bpbv.js → chunk-s31msata.js} +2 -2
- package/dist/{chunk-8y2zs0p0.js → chunk-sxj3psy3.js} +2 -2
- package/dist/{chunk-mtk2tf9n.js → chunk-t3b689pm.js} +1 -1
- package/dist/chunk-vhxarqb0.js +6 -0
- package/dist/{chunk-632rgzcf.js → chunk-wt7gy9bm.js} +2 -2
- package/dist/{chunk-pt0en61h.js → chunk-wxvkrxf4.js} +2 -2
- package/dist/chunk-xet98pc1.js +5 -0
- package/dist/chunk-xzhk0smg.js +4 -0
- package/dist/chunk-y26ngyc2.js +1 -0
- package/dist/{chunk-3aqdjrtm.js → chunk-y2g5a5bp.js} +1 -1
- package/dist/chunk-y61ne49f.js +1 -0
- package/dist/{chunk-xq403rac.js → chunk-y78smk7g.js} +4 -4
- package/dist/chunk-ynncadtz.js +1 -0
- package/dist/{chunk-dsj62dcg.js → chunk-yqfqj7mh.js} +1 -1
- package/dist/{chunk-363pgv1e.js → chunk-yvf4nmds.js} +2 -2
- package/dist/{chunk-ybvdac8k.js → chunk-yz2bsntj.js} +1 -1
- package/dist/{chunk-r76wc1cn.js → chunk-zdkc4kj1.js} +1 -1
- package/dist/{chunk-4zs5r4n4.js → chunk-zt5wq0qj.js} +1 -1
- package/dist/web/assets/{ChatView-CxSysoN5.js → ChatView-YFotW0KS.js} +5 -5
- package/dist/web/assets/{CodeBlockHighlighter-a5UaDQQg.js → CodeBlockHighlighter-DYuOTwXS.js} +1 -1
- package/dist/web/assets/{FilePreview-CvGTS9CJ.js → FilePreview-CWOBOnzz.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-D50Cw9OM.js → MarkdownRenderer-YiYvkN2w.js} +3 -3
- package/dist/web/assets/{SettingsModal-DtREOjs-.js → SettingsModal-BT-oFKGN.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BlMvq8mt.js → TaskSwitcher-D5Gd6FN9.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B8LccKzq.js → TerminalPanel-C1hLHq_K.js} +1 -1
- package/dist/web/assets/index-DuYx6fkN.js +11 -0
- package/dist/web/assets/{session-events-_Kir2HH_.js → session-events-K_9Lexp8.js} +5 -5
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-2cgcht30.js +0 -1
- package/dist/chunk-3be2feze.js +0 -1
- package/dist/chunk-3jnhd81j.js +0 -3
- package/dist/chunk-4rn3r12e.js +0 -200
- package/dist/chunk-99tdg2ny.js +0 -1
- package/dist/chunk-avsv4e5g.js +0 -1
- package/dist/chunk-cyhmfcqq.js +0 -160
- package/dist/chunk-e0y9nb0a.js +0 -1
- package/dist/chunk-f4z3gkbs.js +0 -2
- package/dist/chunk-fvrmjhz5.js +0 -1
- package/dist/chunk-g3w00xb7.js +0 -5
- package/dist/chunk-h6w3ggx9.js +0 -1
- package/dist/chunk-hpbyvwhm.js +0 -1
- package/dist/chunk-hxp5qs1x.js +0 -1
- package/dist/chunk-k5fw5abr.js +0 -1
- package/dist/chunk-kesgbws4.js +0 -100
- package/dist/chunk-m088381q.js +0 -1
- package/dist/chunk-m2b2w90y.js +0 -1
- package/dist/chunk-qb076ca2.js +0 -6
- package/dist/chunk-r6bha0vm.js +0 -1
- package/dist/chunk-sntbbkbf.js +0 -22
- package/dist/chunk-wj4cjb73.js +0 -10
- package/dist/chunk-xk7svrdb.js +0 -4
- package/dist/chunk-z5zcwwfm.js +0 -1
- package/dist/web/assets/index-CQP8XT9a.js +0 -11
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var ae=Object.defineProperty;var re=(e,t,n)=>t in e?ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>re(e,typeof t!="symbol"?t+"":t,n);function M(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function $(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function V(e,t,n){const a=(n?t.find(o=>o.id===n||o.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:a}}function Y(e,t){const n=[...$(e)];let a=n.findIndex(s=>s.id===t.id||!!(s.sessionId&&t.sessionId&&s.sessionId===t.sessionId));if(a===-1&&t.sessionId&&(a=n.findIndex(s=>!s.sessionId&&s.status==="running"&&s.type===t.type&&s.description===t.description)),a===-1)return n.push(t),V(e,n,t.id);const o=n[a],u={...o,...t,id:o.id};return n[a]=u,V(e,n,u.id)}function U(e,t){return`${t}-${e.length}`}function ue(e,t){if(!t)return e;const n=[...
|
|
1
|
+
var ae=Object.defineProperty;var re=(e,t,n)=>t in e?ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>re(e,typeof t!="symbol"?t+"":t,n);function M(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function $(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function V(e,t,n){const a=(n?t.find(o=>o.id===n||o.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:a}}function Y(e,t){const n=[...$(e)];let a=n.findIndex(s=>s.id===t.id||!!(s.sessionId&&t.sessionId&&s.sessionId===t.sessionId));if(a===-1&&t.sessionId&&(a=n.findIndex(s=>!s.sessionId&&s.status==="running"&&s.type===t.type&&s.description===t.description)),a===-1)return n.push(t),V(e,n,t.id);const o=n[a],u={...o,...t,id:o.id};return n[a]=u,V(e,n,u.id)}function U(e,t){return`${t}-${e.length}`}function ue(e,t){if(!t)return e;const n=[...w(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="text"?n[n.length-1]={...a,content:a.content+t}:n.push({id:U(n,"text"),type:"text",content:t}),{...e,timeline:n}}function de(e,t){if(!t)return e;const n=[...w(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="thinking"?n[n.length-1]={...a,content:a.content+t}:n.push({id:U(n,"thinking"),type:"thinking",content:t}),{...e,timeline:n}}function X(e,t){const n=e.toolCalls.some(s=>s.toolCallId===t.toolCallId),a=n?e.toolCalls:[...e.toolCalls,t];if(n)return{...e,toolCalls:a};const o=[...w(e)],u=o[o.length-1];return(u==null?void 0:u.type)==="tool_group"?o[o.length-1]={...u,toolCallIds:[...u.toolCallIds,t.toolCallId]}:o.push({id:U(o,"tool_group"),type:"tool_group",toolCallIds:[t.toolCallId]}),{...e,timeline:o,toolCalls:a}}function w(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 le(e){return w(e).filter(t=>t.type==="text").map(t=>t.content).filter(Boolean).join(`
|
|
2
2
|
|
|
3
3
|
`)}const ce=2166136261,ge=16777619;function E(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(t=>E(t)).join(",")}]`:typeof e=="object"?`{${Object.entries(e).sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>`${JSON.stringify(n)}:${E(a)}`).join(",")}}`:JSON.stringify(e)}function p(e){let t=ce>>>0;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,ge);return(t>>>0).toString(16)}function ee(e){return typeof e=="string"?e:E(e??{})}function B(e){return e==="completed"?"completed":e==="failed"?"failed":"running"}function K({explicitId:e,messageId:t,toolName:n,argumentsValue:a,toolKind:o,output:u}){if(e)return e;const s=[t||"unknown-message",n||"Unknown",ee(a),o||"",u||""].join("|");return`tool-${p(s)}`}function D({explicitId:e,sessionId:t,messageId:n,agentType:a,description:o,summary:u}){if(e)return e;if(t)return t;const s=[n||"unknown-message",a||"subagent",o||"",u||""].join("|");return`subagent-${p(s)}`}const me=(e,t)=>!t||typeof t!="object"?null:{id:D({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:B(t.status),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},fe=(e,t)=>!t||typeof t!="object"?[]:(Array.isArray(t.subtaskRefs)?t.subtaskRefs:t.subtaskRef&&typeof t.subtaskRef=="object"?[t.subtaskRef]:[]).map(a=>me(e,a)).filter(a=>a!==null);function R(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
4
|
-
`)}function Ie(e){var a,o,u;const t=[];let n=null;for(const s of e)if(s.role!=="system"){if(s.role==="user")n&&(t.push(n),n=null),t.push({id:s.id,role:s.role,content:s.content,timestamp:s.timestamp||Date.now(),metadata:s.metadata});else if(s.role==="assistant"){n&&t.push(n);const i=s.metadata;let r=M();s.thinkingContent&&(r=de(r,s.thinkingContent),r.thinkingContent=s.thinkingContent);const d=R(s.content);d&&(r=ue(r,d),r.textBefore=d);const c=fe(s.id,i);if(s.tool_calls&&Array.isArray(s.tool_calls))for(const l of s.tool_calls){const m=((a=l.function)==null?void 0:a.name)||"Unknown",I=ee((o=l.function)==null?void 0:o.arguments);if(m==="Task"){let g={};try{g=JSON.parse(I)}catch{}const h=typeof g.subagent_type=="string"?g.subagent_type:"subagent",S=typeof g.description=="string"?g.description:h;r=Y(r,{id:D({explicitId:l.id,sessionId:typeof g.subagent_session_id=="string"?g.subagent_session_id:void 0,messageId:s.id,agentType:h,description:S}),type:h,description:S,status:"running",startTime:Date.now(),sessionId:typeof g.subagent_session_id=="string"?g.subagent_session_id:void 0,resumedFrom:typeof g.resume_from=="string"?g.resume_from:typeof g.resume=="string"?g.resume:void 0});continue}const f={toolCallId:K({explicitId:l.id,messageId:s.id,toolName:m,argumentsValue:(u=l.function)==null?void 0:u.arguments}),toolName:m,arguments:I,status:"running",startTime:Date.now()};r=X(r,f)}for(const l of c)r=Y(r,l);n={id:s.id,role:"assistant",content:R(s.content),timestamp:s.timestamp||Date.now(),metadata:i,agentContent:r}}else if(s.role==="tool"&&n&&n.agentContent){const i=s,r=s.metadata,d=i.tool_call_id||(r==null?void 0:r.toolCallId),c=i.name||(r==null?void 0:r.toolName)||"Tool",l=r!=null&&r.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0,m=r!=null&&r.independentVerification&&typeof r.independentVerification=="object"&&!Array.isArray(r.independentVerification)?r.independentVerification:void 0,I=typeof(r==null?void 0:r.error)=="string"&&r.error.length>0,f=$(n.agentContent),g=f.findIndex(S=>S.id===d);if(g>=0){const S=f[g],A=typeof(l==null?void 0:l.subagentStatus)=="string"?B(l.subagentStatus):I?"failed":"completed";f[g]={...S,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:S.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:S.type,status:A,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:S.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:S.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:S.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:(m==null?void 0:m.verificationVerdict)==="pass"||(m==null?void 0:m.verificationVerdict)==="fail"||(m==null?void 0:m.verificationVerdict)==="partial"?m.verificationVerdict:S.verificationVerdict},n.agentContent=V(n.agentContent,f,S.id);continue}const h=n.agentContent.toolCalls.find(S=>S.toolCallId===d);h?(h.output=R(s.content),h.status=I?"error":"success",h.metadata=l,h.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:h.summary,(!h.toolName||h.toolName==="Unknown")&&(h.toolName=c)):n.agentContent=X(n.agentContent,{toolCallId:K({explicitId:d,messageId:n.id,toolName:c,output:R(s.content)}),toolName:c,output:R(s.content),status:I?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(n),t}const te={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",runtime:"task.failure.runtime"},Se={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,runtime:!0};function he(e){if(typeof e=="string"&&Object.keys(te).includes(e))return e}function
|
|
4
|
+
`)}function Ie(e){var a,o,u;const t=[];let n=null;for(const s of e)if(s.role!=="system"){if(s.role==="user")n&&(t.push(n),n=null),t.push({id:s.id,role:s.role,content:s.content,timestamp:s.timestamp||Date.now(),metadata:s.metadata});else if(s.role==="assistant"){n&&t.push(n);const i=s.metadata;let r=M();s.thinkingContent&&(r=de(r,s.thinkingContent),r.thinkingContent=s.thinkingContent);const d=R(s.content);d&&(r=ue(r,d),r.textBefore=d);const c=fe(s.id,i);if(s.tool_calls&&Array.isArray(s.tool_calls))for(const l of s.tool_calls){const m=((a=l.function)==null?void 0:a.name)||"Unknown",I=ee((o=l.function)==null?void 0:o.arguments);if(m==="Task"){let g={};try{g=JSON.parse(I)}catch{}const h=typeof g.subagent_type=="string"?g.subagent_type:"subagent",S=typeof g.description=="string"?g.description:h;r=Y(r,{id:D({explicitId:l.id,sessionId:typeof g.subagent_session_id=="string"?g.subagent_session_id:void 0,messageId:s.id,agentType:h,description:S}),type:h,description:S,status:"running",startTime:Date.now(),sessionId:typeof g.subagent_session_id=="string"?g.subagent_session_id:void 0,resumedFrom:typeof g.resume_from=="string"?g.resume_from:typeof g.resume=="string"?g.resume:void 0});continue}const f={toolCallId:K({explicitId:l.id,messageId:s.id,toolName:m,argumentsValue:(u=l.function)==null?void 0:u.arguments}),toolName:m,arguments:I,status:"running",startTime:Date.now()};r=X(r,f)}for(const l of c)r=Y(r,l);n={id:s.id,role:"assistant",content:R(s.content),timestamp:s.timestamp||Date.now(),metadata:i,agentContent:r}}else if(s.role==="tool"&&n&&n.agentContent){const i=s,r=s.metadata,d=i.tool_call_id||(r==null?void 0:r.toolCallId),c=i.name||(r==null?void 0:r.toolName)||"Tool",l=r!=null&&r.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0,m=r!=null&&r.independentVerification&&typeof r.independentVerification=="object"&&!Array.isArray(r.independentVerification)?r.independentVerification:void 0,I=typeof(r==null?void 0:r.error)=="string"&&r.error.length>0,f=$(n.agentContent),g=f.findIndex(S=>S.id===d);if(g>=0){const S=f[g],A=typeof(l==null?void 0:l.subagentStatus)=="string"?B(l.subagentStatus):I?"failed":"completed";f[g]={...S,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:S.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:S.type,status:A,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:S.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:S.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:S.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:(m==null?void 0:m.verificationVerdict)==="pass"||(m==null?void 0:m.verificationVerdict)==="fail"||(m==null?void 0:m.verificationVerdict)==="partial"?m.verificationVerdict:S.verificationVerdict},n.agentContent=V(n.agentContent,f,S.id);continue}const h=n.agentContent.toolCalls.find(S=>S.toolCallId===d);h?(h.output=R(s.content),h.status=I?"error":"success",h.metadata=l,h.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:h.summary,(!h.toolName||h.toolName==="Unknown")&&(h.toolName=c)):n.agentContent=X(n.agentContent,{toolCallId:K({explicitId:d,messageId:n.id,toolName:c,output:R(s.content)}),toolName:c,output:R(s.content),status:I?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(n),t}const te={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",runtime:"task.failure.runtime"},Se={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,runtime:!0};function he(e){if(typeof e=="string"&&Object.keys(te).includes(e))return e}function Rt(e){return te[e]}function xt(e){return Se[e]}const ye={flushTimeout:80};class Ce{constructor(t){F(this,"config");F(this,"channels",new Map);this.config={...ye,...t}}append(t,n,a){let o=this.channels.get(t);o||(o={buffer:"",timer:null,flushFn:null},this.channels.set(t,o)),o.buffer+=n,o.flushFn=a,o.timer||(o.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const a=n.buffer,o=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),o==null||o(a)}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,a]of this.channels)n!==t&&!a.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const T=new Ce,C=(e,t,n)=>{if(t)for(const a of e){const o=$(a.agentContent).find(u=>u.id===t||u.sessionId===t);if(o)return{messageId:a.id,subagent:o}}if(n){const a=e.find(s=>s.id===n),o=$(a==null?void 0:a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:n,subagent:u}}for(const a of[...e].reverse()){const o=$(a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:a.id,subagent:u}}},b=(e,t,n)=>{const{currentAssistantMessageId:a,messages:o,addMessage:u,startAgentResponse:s}=e();if(a&&!a.startsWith("call_")&&o.some(c=>c.id===a&&c.role==="assistant"))return a;if(n){const c=o.find(l=>l.id===n&&l.role==="assistant");if(c)return s(c.id),c.id}const i=o[o.length-1];if((i==null?void 0:i.role)==="assistant")return i.id;const r=n||`assistant-${Date.now()}`,d={id:r,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return u(d),s(r),t(c=>({messages:c.messages.map(l=>l.id===r?{...l,agentContent:{...l.agentContent||M()}}:l)})),r},be=(e,t,n)=>{const{currentSessionId:a,addMessage:o,startAgentResponse:u,messages:s,updateMessage:i}=t();if(e.sessionId!==a)return;const r=e.messageId,d=e.role||"assistant",c=s.find(m=>m.id===r),l={id:r,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?M():void 0};c?i(r,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||M()}:void 0}):o(l),d==="assistant"&&u(r)},ve=(e,t,n)=>{const{currentSessionId:a,appendDelta:o,currentAssistantMessageId:u,hasToolCalls:s,addMessage:i,startAgentResponse:r}=t();if(e.sessionId!==a)return;const d=e.messageId,c=e.delta;if(!u){const m={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};i(m),r(d),t().appendDelta(d,c,"before");return}o(u,c,s?"after":"before")},Ae=(e,t)=>{const{currentSessionId:n,updateMessage:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.messageId,s=o.find(i=>i.id===u);s!=null&&s.agentContent&&a(u,{content:le(s.agentContent)})},ke=(e,t,n)=>{var r;const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.output;if(!o||typeof o!="object"||Array.isArray(o))return;const u=b(t,n,e.messageId);if(!u)return;const s=t().messages.find(d=>d.id===u);if(!s)return;const i=JSON.stringify(o,null,2);t().updateMessage(u,{content:i,metadata:{...s.metadata,structuredOutput:{output:o,schemaDigest:e.schemaDigest}},agentContent:s.agentContent?{...s.agentContent,textBefore:"",textAfter:"",timeline:(r=s.agentContent.timeline)==null?void 0:r.filter(d=>d.type!=="text")}:void 0})},Te=(e,t,n)=>{const{currentSessionId:a,appendThinking:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId);u&&o(u,e.delta)},$e=()=>{},ne=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o,setHasToolCalls:u,setSubagent:s}=t();if(e.sessionId!==a)return;const i=b(t,n,e.messageId||e.toolCallId);if(!i)return;u(!0);const r=e.toolName||"Unknown",d=e.arguments;let c,l="",m,I;if(r==="Task")try{const g=JSON.parse(d);c=g.subagent_type,l=g.description||g.query||c||"",m=g.subagent_session_id,I=g.resume_from||g.resume}catch{}if(c){s(i,{id:D({explicitId:e.toolCallId,sessionId:m,messageId:i,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:m,resumedFrom:I,output:"",thinking:""});return}const f={toolCallId:K({explicitId:e.toolCallId,messageId:i,toolName:r,argumentsValue:d,toolKind:e.toolKind}),toolName:r,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};o(i,f)},se=(e,t)=>{const{currentSessionId:n,updateToolCall:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.toolCallId;if(!u)return;const s=o.find(i=>{var r;return(r=i.agentContent)==null?void 0:r.toolCalls.some(d=>d.toolCallId===u)});s&&a(s.id,u,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message})},ie=(e,t,n)=>{var Q;const{currentSessionId:a,updateToolCall:o,updateSubagent:u,messages:s}=t();if(e.sessionId!==a)return;const i=e.toolCallId;if(!i)return;const r=s.find(v=>{var k;return(k=v.agentContent)==null?void 0:k.toolCalls.some(N=>N.toolCallId===i)}),d=s.find(v=>$(v.agentContent).some(k=>k.id===i)),c=e.messageId||(r==null?void 0:r.id)||(d==null?void 0:d.id)||((Q=[...s].reverse().find(v=>v.role==="assistant"))==null?void 0:Q.id);if(!c)return;const l=e.output,m=e.summary||(l&&l.trim()?l.trim().split(`
|
|
5
5
|
`)[0].slice(0,120):e.success?"执行成功":"执行失败");o(c,i,{status:e.success?"success":"error",summary:m,output:l,metadata:e.metadata});const I=s.find(v=>v.id===c),f=$(I==null?void 0:I.agentContent).find(v=>v.id===i),g=e.metadata,h=g&&typeof g.subagentSessionId=="string"?g.subagentSessionId:void 0,S=g&&typeof g.subagentStatus=="string"?g.subagentStatus:void 0,A=g&&typeof g.subagentType=="string"?g.subagentType:void 0,oe=g&&typeof g.subagentSummary=="string"?g.subagentSummary:void 0,L=g&&typeof g.subagentResumedFrom=="string"?g.subagentResumedFrom:void 0,H=g&&typeof g.subagentRootId=="string"?g.subagentRootId:void 0,G=g&&typeof g.subagentResumeDepth=="number"?g.subagentResumeDepth:void 0,W=(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:void 0;f&&u(c,f.id,{sessionId:f.sessionId||h,type:A||f.type,status:S?B(S):e.success?"completed":"failed",resumedFrom:L||f.resumedFrom,rootAgentId:H||f.rootAgentId,resumeDepth:G??f.resumeDepth,verificationVerdict:W??f.verificationVerdict}),h&&S&&n(v=>({messages:v.messages.map(k=>{if(k.id!==c)return k;const N=k.metadata??{},_=Array.isArray(N.subtaskRefs)?N.subtaskRefs:[],x=_.findIndex(z=>z.childSessionId===h||z.subagentId===i),y=x>=0?_[x]:N.subtaskRef??{},j={...y,subagentId:i,childSessionId:h,agentType:A||(typeof(y==null?void 0:y.agentType)=="string"?y.agentType:"subagent"),status:S,summary:oe||(typeof(y==null?void 0:y.summary)=="string"?y.summary:""),resumedFrom:L||(typeof(y==null?void 0:y.resumedFrom)=="string"?y.resumedFrom:void 0),rootAgentId:H||(typeof(y==null?void 0:y.rootAgentId)=="string"?y.rootAgentId:h),resumeDepth:G??(typeof(y==null?void 0:y.resumeDepth)=="number"?y.resumeDepth:0),verificationVerdict:W||(typeof(y==null?void 0:y.verificationVerdict)=="string"?y.verificationVerdict:void 0)},q=[..._];return x>=0?q[x]=j:q.push(j),{...k,metadata:{...N,subtaskRef:j,subtaskRefs:q}}})}))},Ne=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId||`mcp-catalog-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP catalog r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-catalog:${String(e.revision)}`,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
|
|
6
6
|
`)})},Me=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId||`mcp-content-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP ${String(e.contentKind)} r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-content:${String(e.revision)}`,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
|
|
7
7
|
`)})},Re=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId||`mcp-resource-${String(e.revision)}`);u&&o(u,{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)}`})},xe=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId||`mcp-connection-${String(e.revision)}`);if(!u)return;const s=String(e.phase),i=`MCP ${String(e.serverName)} ${s}`+(s==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:"");o(u,{toolCallId:`mcp-connection:${String(e.revision)}`,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:s,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:s==="failed"?"error":"success",startTime:Date.now(),summary:i,output:[`Reason: ${String(e.reason)}`,e.error?`Error: ${String(e.error)}`:""].filter(Boolean).join(`
|
|
8
|
-
`)})},
|
|
9
|
-
`)})},
|
|
8
|
+
`)})},Pe=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=b(t,n,e.messageId||`mcp-log-${String(e.revision)}`);if(!u)return;const s=String(e.level),i=typeof e.logger=="string"?e.logger:void 0,r=`MCP ${s} · ${String(e.serverName)}`+(i?` · ${i}`:"");o(u,{toolCallId:`mcp-log:${String(e.revision)}`,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:s,logger:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
9
|
+
`)})},we=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=String(e.serverName),s=String(e.action),i=b(t,n,e.messageId||`mcp-instructions-${String(e.revision)}-${u}`);if(!i)return;const r=`MCP instructions ${s}: ${u}`+(e.truncated===!0?" (truncated)":"");o(i,{toolCallId:`mcp-instructions:${String(e.revision)}:${u}:${s}`,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:u,action:s,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
10
10
|
`)})},De=(e,t,n)=>{var I,f;const{currentSessionId:a,appendToolCall:o,updateToolCall:u}=t();if(e.sessionId!==a)return;const s=String(e.taskId),i=String(e.status),r=`mcp-task:${s}`,d=b(t,n,e.messageId||`mcp-task-${s}`);if(!d)return;const c=`MCP task ${i}: ${s} · ${String(e.serverName)}/${String(e.toolName)}`,l={status:i==="failed"||i==="cancelled"?"error":i==="completed"?"success":"running",summary:c,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
|
|
11
11
|
`)};if((f=(I=t().messages.find(g=>g.id===d))==null?void 0:I.agentContent)==null?void 0:f.toolCalls.some(g=>g.toolCallId===r)){u(d,r,l);return}o(d,{toolCallId:r,toolName:"MCP Task",arguments:JSON.stringify({taskId:s,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:l.status,startTime:Number(e.createdAt)||Date.now(),summary:l.summary,output:l.output})},_e=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],s=b(t,n,e.messageId||`project-rules-${Date.now()}`);if(!s)return;const i=e.blockedWrite===!0,r=`Project rules loaded: ${u.length}`+(i?" (write retry required)":"");o(s,{toolCallId:`project-rules:${u.map(d=>String(d.id)).join(",")}`,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:u.map(d=>`${String(d.relativePath)} ${String(d.source)} SHA-256: ${String(d.contentSha256)}`).join(`
|
|
12
12
|
`)})},J=e=>`user-shell-${e}`,je=(e,t,n)=>{const{currentSessionId:a,addMessage:o,messages:u,updateMessage:s}=t();if(e.sessionId!==a||typeof e.executionId!="string"||typeof e.command!="string")return;const i=J(e.executionId),r={id:i,role:"user",content:`! ${e.command}`,timestamp:Date.now(),metadata:{userShellExecution:{executionId:e.executionId,command:e.command,status:"running",output:""}}};u.some(d=>d.id===i)?s(i,r):o(r),e.auxiliary!==!0&&n({isStreaming:!0,agentPhase:"running",error:null,errorContext:null})},qe=(e,t)=>{var d;const{currentSessionId:n,messages:a,updateMessage:o}=t();if(e.sessionId!==n||typeof e.executionId!="string"||typeof e.chunk!="string")return;const u=J(e.executionId),s=a.find(c=>c.id===u);if(!s)return;const i=(d=s.metadata)!=null&&d.userShellExecution&&typeof s.metadata.userShellExecution=="object"?s.metadata.userShellExecution:{},r=`${typeof i.output=="string"?i.output:""}${e.chunk}`;o(u,{content:`! ${String(i.command??"")}
|
|
@@ -19,4 +19,4 @@ ${c}`:""].filter(Boolean).join(`
|
|
|
19
19
|
`)}]}))},Ze=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(o,e.subagentSessionId,a);if(!s)return;const i=String(e.serverName),r=String(e.action),d=`mcp-instructions:${String(e.revision)}:${i}:${r}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:i,action:r,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP instructions ${r}: ${i}`+(e.truncated===!0?" (truncated)":""),output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
20
20
|
`)}]}))},pe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(o,e.subagentSessionId,a);if(!s)return;const i=String(e.taskId),r=String(e.status),d=`mcp-task:${i}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Task",arguments:JSON.stringify({taskId:i,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:r==="failed"||r==="cancelled"?"error":r==="completed"?"success":"running",startTime:Number(e.createdAt)||Date.now(),summary:`MCP task ${r}: ${i} · ${String(e.serverName)}/${String(e.toolName)}`,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
|
|
21
21
|
`)}]}))},et=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],r=`project-rules:${i.map(d=>String(d.id)).join(",")}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==r),{toolCallId:r,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:e.blockedWrite}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`Project rules loaded: ${i.length}`,output:i.map(c=>`${String(c.relativePath)} ${String(c.source)} SHA-256: ${String(c.contentSha256)}`).join(`
|
|
22
|
-
`)}]}))},tt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=b(t,n,u?`assistant-permission-${u}`:void 0);if(!s)return;const i=e.details,r=e.toolName||(i==null?void 0:i.toolName)||"Tool";o(s,{toolCallId:u,toolName:r,description:e.description,diff:(i==null?void 0:i.details)||(i==null?void 0:i.diff)||"",allowRemember:(i==null?void 0:i.type)!=="mcpSampling",status:"pending"}),n(d=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:d.sessions.map(c=>c.sessionId===e.sessionId&&c.projectPath===e.projectPath?{...c,pendingInteraction:{type:"permission",requestId:u}}:c)}))},nt=(e,t,n)=>{var I,f;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.confirmation)==null?void 0:S.toolCallId)===r}),c=(I=d==null?void 0:d.agentContent)==null?void 0:I.confirmation;d&&(c==null?void 0:c.status)==="pending"&&s(d.id,{...c,status:"denied"});const l=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.elicitation)==null?void 0:S.toolCallId)===r}),m=(f=l==null?void 0:l.agentContent)==null?void 0:f.elicitation;l&&(m==null?void 0:m.status)==="pending"&&i(l.id,{...m,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},Z=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},st=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"compacting"})},it=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},ot=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null})},at=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},rt=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(t,n,u?`assistant-question-${u}`:void 0);s&&(o(s,{toolCallId:u,questions:e.questions,status:"pending"}),n(i=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:i.sessions.map(r=>r.sessionId===e.sessionId&&r.projectPath===e.projectPath?{...r,pendingInteraction:{type:"question",requestId:u}}:r)})))},ut=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(t,n,u?`assistant-elicitation-${u}`:void 0),i=e.elicitation;!s||!i||(o(s,{toolCallId:u,details:i,status:"pending"}),n(r=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:r.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:u}}:d)})))},dt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.requestId;n(u=>({agentPhase:"running",sessions:u.sessions.map(s=>{var i;return s.sessionId===e.sessionId&&s.projectPath===e.projectPath&&((i=s.pendingInteraction)==null?void 0:i.requestId)===o?{...s,pendingInteraction:void 0}:s})}))},O=(e,t)=>{const{currentSessionId:n,endAgentResponse:a}=t();e.sessionId===n&&a()},lt=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:o,endAgentResponse:u}=t();if(e.sessionId!==a)return;const s=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,i=he(s==null?void 0:s.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...o?{sessionRef:o}:{},...i?{failureCode:i}:{}}}),u()},ct=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0});else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const o=typeof e.queued=="number"?Math.max(0,e.queued):0;n({isStreaming:!0,agentPhase:e.status==="waiting_permission"?"waiting_permission":"running",currentRunId:typeof e.runId=="string"?e.runId:t().currentRunId,pendingSteeringCount:o,pendingInputDelivery:o>0&&(e.pendingInputDelivery==="current_turn"||e.pendingInputDelivery==="next_turn")?e.pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})}else e.status==="error"&&n({isStreaming:!1,isStopping:!1,agentPhase:"error",providerRetry:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},gt=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:o,messages:u,updateSubagent:s}=t();if(e.sessionId===a){n(i=>({isStreaming:!1,agentPhase:"idle",messages:i.messages.map(r=>{var c;const d=(c=r.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!r.agentContent?r:{...r,agentContent:{...r.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const i of u)for(const r of $(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o()}},mt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},ft=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},It=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({pendingSteeringCount:a,pendingInputDelivery:a>0?t().pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},St=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({agentPhase:"running",pendingSteeringCount:a,pendingInputDelivery:a>0?"current_turn":null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},ht=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},bt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),o=e.messages.flatMap((u,s)=>{if(typeof u!="object"||u===null)return[];const i=u;return!["user","assistant","system","tool"].includes(String(i.role))||!Array.isArray(i.content)&&typeof i.content!="string"?[]:[{id:`rewind-${s}-${a}`,role:i.role,content:i.content,timestamp:a+s,metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:void 0,thinkingContent:typeof i.thinkingContent=="string"?i.thinkingContent:typeof i.reasoningContent=="string"?i.reasoningContent:void 0,tool_call_id:typeof i.tool_call_id=="string"?i.tool_call_id:void 0,name:typeof i.name=="string"?i.name:void 0,tool_calls:i.tool_calls}]});n({messages:Ie(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},vt=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const o=e.status,u=o==="completed"||o==="stale"?"completed":o==="aborted"?"cancelled":o==="interrupted"?"interrupted":"failed";n(s=>({sessions:s.sessions.map(i=>i.sessionId===a.sessionId&&i.projectPath===a.projectPath?{...i,taskStatus:u,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:i)})),t().selectSession(a)},At=(e,t,n)=>{ne({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},kt=(e,t,n)=>{se(e,t)},Tt=(e,t,n)=>{ie(e,t,n)},w={"message.created":be,"message.delta":ve,"message.complete":Ae,"structured.output":ke,"thinking.delta":Te,"thinking.completed":$e,"tool.start":ne,"tool.progress":se,"tool.result":ie,"mcp.catalog.changed":Ne,"mcp.content.changed":Me,"mcp.resource.updated":Re,"mcp.connection.changed":xe,"mcp.log":we,"mcp.instructions.changed":Pe,"mcp.task.changed":De,"project.rules.loaded":_e,"user.shell.started":je,"user.shell.output":qe,"user.shell.completed":Fe,"token.usage":Oe,"task.updated":Ve,"subagent.start":Ee,"subagent.update":Ke,"subagent.delta":Ue,"subagent.thinking.delta":Be,"subagent.tool.start":Le,"subagent.tool.progress":Ge,"subagent.tool.result":He,"subagent.mcp.catalog.changed":We,"subagent.mcp.content.changed":Qe,"subagent.mcp.resource.updated":ze,"subagent.mcp.connection.changed":Ye,"subagent.mcp.log":Xe,"subagent.mcp.instructions.changed":Ze,"subagent.mcp.task.changed":pe,"subagent.project.rules.loaded":et,"subagent.complete":Je,"permission.asked":tt,"permission.timeout":nt,"turn.started":Z,"committed.turn_started":Z,"committed.turn_completed":O,"committed.turn_aborted":O,"provider.retry":at,"compaction.started":st,"compaction.completed":it,"model.fallback":ot,"question.required":rt,"elicitation.required":ut,"interaction.resolved":dt,"session.completed":O,"session.error":lt,"session.status":ct,"run.cancelled":gt,"steering.queued":mt,"follow_up.queued":ft,"follow_up.started":St,"steering.applied":It,"goal.updated":ht,"goal.cleared":yt,"goal.continuation.started":Ct,"session.rewound":bt,"review.tool.started":At,"review.tool.progress":kt,"review.tool.completed":Tt,"review.completed":vt},$t=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),xt=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if($t.has(n.type)){T.drainAll();const s=w[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&T.drainAll(),n.type==="message.delta"){const{currentSessionId:s,currentAssistantMessageId:i,hasToolCalls:r}=e();if(o.sessionId!==s)return;const d=o.messageId||i,c=o.delta;if(!i){const I=w["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",m=`content:${d}:${l}`;T.drainAllExcept(m),T.append(m,c,I=>{const{appendDelta:f}=e();d&&f(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=w["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;T.drainAllExcept(c),T.append(c,r,l=>{const{appendThinking:m}=e();d&&m(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent:${r}`,{currentAssistantMessageId:c,messages:l}=e(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,output:(A.output||"")+I}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent-thinking:${r}`,{currentAssistantMessageId:c,messages:l}=e(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,thinking:(A.thinking||"")+I}))});return}const u=w[n.type];u&&u(n.properties,e,t)};export{de as a,X as b,M as c,ue as d,Ie as e,xt as f,$ as g,T as h,he as i,Rt as j,le as k,P as l,Mt as t,Y as u,V as w};
|
|
22
|
+
`)}]}))},tt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=b(t,n,u?`assistant-permission-${u}`:void 0);if(!s)return;const i=e.details,r=e.toolName||(i==null?void 0:i.toolName)||"Tool";o(s,{toolCallId:u,toolName:r,description:e.description,diff:(i==null?void 0:i.details)||(i==null?void 0:i.diff)||"",allowRemember:(i==null?void 0:i.type)!=="mcpSampling",status:"pending"}),n(d=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:d.sessions.map(c=>c.sessionId===e.sessionId&&c.projectPath===e.projectPath?{...c,pendingInteraction:{type:"permission",requestId:u}}:c)}))},nt=(e,t,n)=>{var I,f;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.confirmation)==null?void 0:S.toolCallId)===r}),c=(I=d==null?void 0:d.agentContent)==null?void 0:I.confirmation;d&&(c==null?void 0:c.status)==="pending"&&s(d.id,{...c,status:"denied"});const l=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.elicitation)==null?void 0:S.toolCallId)===r}),m=(f=l==null?void 0:l.agentContent)==null?void 0:f.elicitation;l&&(m==null?void 0:m.status)==="pending"&&i(l.id,{...m,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},Z=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},st=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},it=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},ot=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null})},at=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},rt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},ut=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(t,n,u?`assistant-question-${u}`:void 0);s&&(o(s,{toolCallId:u,questions:e.questions,status:"pending"}),n(i=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:i.sessions.map(r=>r.sessionId===e.sessionId&&r.projectPath===e.projectPath?{...r,pendingInteraction:{type:"question",requestId:u}}:r)})))},dt=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(t,n,u?`assistant-elicitation-${u}`:void 0),i=e.elicitation;!s||!i||(o(s,{toolCallId:u,details:i,status:"pending"}),n(r=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:r.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:u}}:d)})))},lt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.requestId;n(u=>({agentPhase:"running",sessions:u.sessions.map(s=>{var i;return s.sessionId===e.sessionId&&s.projectPath===e.projectPath&&((i=s.pendingInteraction)==null?void 0:i.requestId)===o?{...s,pendingInteraction:void 0}:s})}))},O=(e,t)=>{const{currentSessionId:n,endAgentResponse:a}=t();e.sessionId===n&&a()},ct=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:o,endAgentResponse:u}=t();if(e.sessionId!==a)return;const s=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,i=he(s==null?void 0:s.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...o?{sessionRef:o}:{},...i?{failureCode:i}:{}}}),u()},gt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0});else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const o=typeof e.queued=="number"?Math.max(0,e.queued):0;n({isStreaming:!0,agentPhase:e.status==="waiting_permission"?"waiting_permission":"running",currentRunId:typeof e.runId=="string"?e.runId:t().currentRunId,pendingSteeringCount:o,pendingInputDelivery:o>0&&(e.pendingInputDelivery==="current_turn"||e.pendingInputDelivery==="next_turn")?e.pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})}else e.status==="error"&&n({isStreaming:!1,isStopping:!1,agentPhase:"error",providerRetry:null,providerStall:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},mt=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:o,messages:u,updateSubagent:s}=t();if(e.sessionId===a){n(i=>({isStreaming:!1,agentPhase:"idle",messages:i.messages.map(r=>{var c;const d=(c=r.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!r.agentContent?r:{...r,agentContent:{...r.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const i of u)for(const r of $(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o()}},ft=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},It=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},St=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({pendingSteeringCount:a,pendingInputDelivery:a>0?t().pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},ht=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({agentPhase:"running",pendingSteeringCount:a,pendingInputDelivery:a>0?"current_turn":null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},bt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},vt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),o=e.messages.flatMap((u,s)=>{if(typeof u!="object"||u===null)return[];const i=u;return!["user","assistant","system","tool"].includes(String(i.role))||!Array.isArray(i.content)&&typeof i.content!="string"?[]:[{id:`rewind-${s}-${a}`,role:i.role,content:i.content,timestamp:a+s,metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:void 0,thinkingContent:typeof i.thinkingContent=="string"?i.thinkingContent:typeof i.reasoningContent=="string"?i.reasoningContent:void 0,tool_call_id:typeof i.tool_call_id=="string"?i.tool_call_id:void 0,name:typeof i.name=="string"?i.name:void 0,tool_calls:i.tool_calls}]});n({messages:Ie(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},At=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const o=e.status,u=o==="completed"||o==="stale"?"completed":o==="aborted"?"cancelled":o==="interrupted"?"interrupted":"failed";n(s=>({sessions:s.sessions.map(i=>i.sessionId===a.sessionId&&i.projectPath===a.projectPath?{...i,taskStatus:u,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:i)})),t().selectSession(a)},kt=(e,t,n)=>{ne({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},Tt=(e,t,n)=>{se(e,t)},$t=(e,t,n)=>{ie(e,t,n)},P={"message.created":be,"message.delta":ve,"message.complete":Ae,"structured.output":ke,"thinking.delta":Te,"thinking.completed":$e,"tool.start":ne,"tool.progress":se,"tool.result":ie,"mcp.catalog.changed":Ne,"mcp.content.changed":Me,"mcp.resource.updated":Re,"mcp.connection.changed":xe,"mcp.log":Pe,"mcp.instructions.changed":we,"mcp.task.changed":De,"project.rules.loaded":_e,"user.shell.started":je,"user.shell.output":qe,"user.shell.completed":Fe,"token.usage":Oe,"task.updated":Ve,"subagent.start":Ee,"subagent.update":Ke,"subagent.delta":Ue,"subagent.thinking.delta":Be,"subagent.tool.start":Le,"subagent.tool.progress":Ge,"subagent.tool.result":He,"subagent.mcp.catalog.changed":We,"subagent.mcp.content.changed":Qe,"subagent.mcp.resource.updated":ze,"subagent.mcp.connection.changed":Ye,"subagent.mcp.log":Xe,"subagent.mcp.instructions.changed":Ze,"subagent.mcp.task.changed":pe,"subagent.project.rules.loaded":et,"subagent.complete":Je,"permission.asked":tt,"permission.timeout":nt,"turn.started":Z,"committed.turn_started":Z,"committed.turn_completed":O,"committed.turn_aborted":O,"provider.retry":at,"provider.stall":rt,"compaction.started":st,"compaction.completed":it,"model.fallback":ot,"question.required":ut,"elicitation.required":dt,"interaction.resolved":lt,"session.completed":O,"session.error":ct,"session.status":gt,"run.cancelled":mt,"steering.queued":ft,"follow_up.queued":It,"follow_up.started":ht,"steering.applied":St,"goal.updated":yt,"goal.cleared":Ct,"goal.continuation.started":bt,"session.rewound":vt,"review.tool.started":kt,"review.tool.progress":Tt,"review.tool.completed":$t,"review.completed":At},Nt=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Pt=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if(Nt.has(n.type)){T.drainAll();const s=P[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&T.drainAll(),n.type==="message.delta"){const{currentSessionId:s,currentAssistantMessageId:i,hasToolCalls:r}=e();if(o.sessionId!==s)return;const d=o.messageId||i,c=o.delta;if(!i){const I=P["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",m=`content:${d}:${l}`;T.drainAllExcept(m),T.append(m,c,I=>{const{appendDelta:f}=e();d&&f(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=P["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;T.drainAllExcept(c),T.append(c,r,l=>{const{appendThinking:m}=e();d&&m(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent:${r}`,{currentAssistantMessageId:c,messages:l}=e(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,output:(A.output||"")+I}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent-thinking:${r}`,{currentAssistantMessageId:c,messages:l}=e(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,thinking:(A.thinking||"")+I}))});return}const u=P[n.type];u&&u(n.properties,e,t)};export{de as a,X as b,M as c,ue as d,Ie as e,Pt as f,$ as g,T as h,he as i,xt as j,le as k,w as l,Rt as t,Y as u,V as w};
|
package/dist/web/index.html
CHANGED
|
@@ -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-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-DuYx6fkN.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-DG5dkZ_t.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/vendor-radix-DXRuAJHH.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/vendor-icons-ICv1v-tf.js">
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/session-events-
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/session-events-K_9Lexp8.js">
|
|
13
13
|
<link rel="stylesheet" crossorigin href="/assets/index-BC7ygRH_.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
package/package.json
CHANGED
package/dist/chunk-2cgcht30.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Jd as a,Kd as b,Ld as c,Md as d,Nd as e}from"./chunk-j7k5x43d.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-zvt8ngpt.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-se1tfys3.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
|
package/dist/chunk-3be2feze.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-se1tfys3.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
package/dist/chunk-3jnhd81j.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{j as T1,k as b1}from"./chunk-r76wc1cn.js";import{l as E$}from"./chunk-z8c5rhdh.js";import{r as b0}from"./chunk-321n9hem.js";import{s as tO}from"./chunk-mcqe9km3.js";import{A as H$,B as h$,C as A0,D as v$,E as d0,F as z$,I as u$,J as d$,L as nO,M as V1,N as N1,O as W1,P as F1,Q as U1,R as D1,S as _1,T as H1,U as B1,V as q1,Y as $4,ba as g1,u as v1,w as aO,x as t0,y as n$}from"./chunk-rbph12qe.js";import{ea as TO,ka as G0}from"./chunk-8zr7h97n.js";import{Aa as eO,Ba as $1,Ca as O1,Da as FO,Ea as OO,ma as C$,pa as u1,qa as d1,ra as sO,sa as rO,ta as l1,ua as t$,va as c1,wa as m0,xa as R1,ya as j1,za as k1}from"./chunk-p4zt7ts9.js";import{Va as m$,Wa as C0,Xa as f,Ya as b,fb as oO,hb as P0}from"./chunk-4rn3r12e.js";import{sb as uO}from"./chunk-095x2ykj.js";import{$b as j,Fb as dO,Hb as B$,Kb as o0,Nb as f$,Tb as lO,Ub as cO,Yb as iO,Zb as P$,_b as y$}from"./chunk-kesgbws4.js";import{Uc as o,Yc as jO,dd as V0}from"./chunk-xq403rac.js";import{fd as S$}from"./chunk-ybvdac8k.js";import{pd as gO}from"./chunk-8j01ssaf.js";import{rd as _$}from"./chunk-2z6261pz.js";import{Cd as K1,Gd as Z$,Hd as Y$,Ld as x0,yd as f1,zd as P1}from"./chunk-j7k5x43d.js";import{Vd as kO,Wd as pO}from"./chunk-heqs3xan.js";import{$d as l0,_d as AO}from"./chunk-zvt8ngpt.js";import{ee as u}from"./chunk-4dq9y7zn.js";import{Ie as MO,Se as J$,te as qO}from"./chunk-hrmfhv8k.js";import{Ye as S,_e as F,bf as Z0}from"./chunk-kvx3sb3z.js";import{df as A$}from"./chunk-f4z3gkbs.js";import{if as v}from"./chunk-5s123nbs.js";import{nf as f0}from"./chunk-s5666ta0.js";import{pf as CO,qf as hO,sf as RO,tf as vO}from"./chunk-dsj62dcg.js";import{vf as u0}from"./chunk-se1tfys3.js";import{Af as $O}from"./chunk-gav4hxcv.js";import{Ff as F$,Jf as _O}from"./chunk-363pgv1e.js";import{Mf as s$}from"./chunk-g11hq0e5.js";var $5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function O5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as JO,readFileSync as N$}from"node:fs";import{createServer as S2}from"node:http";import{networkInterfaces as f2}from"node:os";import{dirname as P2,extname as y2,join as I0}from"node:path";import{fileURLToPath as m2}from"node:url";import{brotliCompressSync as h2,gzipSync as v2,constants as g2}from"node:zlib";import{Hono as p2}from"hono";import{cors as u2}from"hono/cors";import{WebSocketServer as d2}from"ws";var g0=u("Service"),X4=30000,K4=new Set(["completed","failed","cancelled","interrupted"]);class R${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??FO.getInstance(),this.tickMs=$.tickMs??X4}start(){if(this.timer)return;g0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=b.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!K4.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,g0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){g0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),g0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??V4($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),G=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:C$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:G?G.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),b.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),g0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let G=Y instanceof Error?Y.message:String(Y);g0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:C$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:G,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((G)=>G.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function V4($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class t extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class I extends t{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends t{constructor($){super("BAD_REQUEST",$,400)}}class R extends t{constructor($){super("CONFLICT",$,409)}}class p0 extends t{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class K0 extends t{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends t{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var X5=F.Object({error:F.Object({code:F.String(),message:F.String()})});import{Hono as N4}from"hono";var j$=u("Service"),W4=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(Z0(["local","project","global"])),immediate:F.Optional(F.Boolean())}))});function F4($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,theme:$.theme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var UO=()=>{let $=new N4;return $.get("/",async(O)=>{try{let J=o();return O.json(J?F4(J):{})}catch(J){return j$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=S(W4,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:G}=Z.data;return await V0().updateConfig(Y,G),O.json({success:!0,updates:Y})}catch(J){throw j$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=o();return O.json(J?.permissions||{})}catch(J){return j$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as U4}from"hono";import{streamSSE as D4}from"hono/streaming";var _4=15000,H4=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),B4=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function L4($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=["changedFiles","additions","deletions","commits"];if(J.some((Z)=>typeof O[Z]!=="number"||!Number.isInteger(O[Z])||O[Z]<0))return;return Object.fromEntries(J.map((Z)=>[Z,O[Z]]))}function O$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function w4($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$;if(!["applied","discarded","conflicted"].includes(String(O.status))||typeof O.updatedAt!=="string")return;return{status:O.status,updatedAt:O.updatedAt,...typeof O.sourceCommit==="string"?{sourceCommit:O.sourceCommit}:{},...O$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var DO=()=>{let $=new U4;return $.get("/",(O)=>D4(O,async(J)=>{let Z,Y,G=!1,X=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},V=()=>{if(G)return;G=!0,X()};J.onAbort(V),Z=b.subscribe((W)=>{if(!H4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let w=W.properties.requestId;if(typeof w!=="string"||!w)return;J.writeSSE({data:JSON.stringify({type:"interaction.pending",properties:{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:w}})}).catch(V);return}if(W.type==="interaction.resolved"){let w=W.properties.requestId;if(typeof w!=="string"||!w)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:w}})}).catch(V);return}if(W.type==="session.created"||W.type==="session.deleted"){J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath}})}).catch(V);return}if(W.type==="session.updated"){let w=W.properties.title;if(typeof w!=="string"||!w.trim())return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:w}})}).catch(V);return}if(W.type==="task.delivery"){let w=w4(W.properties.taskDelivery);if(!w)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:w,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(V);return}if(W.type==="schedule.fired"){let w=W.properties.scheduleId,a=W.properties.firedAt;if(typeof w!=="string"||typeof a!=="string")return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{scheduleId:w,firedAt:a,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}}})}).catch(V);return}let H=W.properties.taskStatus;if(typeof H!=="string"||!B4.has(H))return;let q=L4(W.properties.taskDiffStat),T=O$(W.properties.taskQueuePosition,1),C=O$(W.properties.taskQueueDepth,0),c=O$(W.properties.taskConcurrencyLimit,1),s=O$(W.properties.taskInFlight,0);J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:H,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...q?{taskDiffStat:q}:{},...T!==void 0?{taskQueuePosition:T}:{},...C!==void 0?{taskQueueDepth:C}:{},...c!==void 0?{taskConcurrencyLimit:c}:{},...s!==void 0?{taskInFlight:s}:{}}})}).catch(V)});try{if(J.aborted||G)return;if(await J.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||G)return;Y=setInterval(()=>{if(J.aborted||G)return;J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(V)},_4);while(!J.aborted&&!G)await new Promise((W)=>setTimeout(W,1000))}finally{V()}})),$};import{Hono as A4}from"hono";var HO=()=>{let $=new A4;return $.get("/health",(O)=>{return O.json({healthy:!0,version:u0()})}),$.get("/info",(O)=>{let J=v(),Z=o();if(Z)d0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:u0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:_O(J),taskAdmission:d0.getStats()})}),$};import BO from"node:path";import{Hono as M4}from"hono";var E4=F.Object({projectPath:F.String({minLength:1}),action:Z0(["trust","revoke"]),expectedDigest:F.Optional(F.String())}),q4=F.Object({projectPath:F.String({minLength:1}),sessionId:F.String({minLength:1}),enabled:F.Boolean()});function k$($){if(!$||!BO.isAbsolute($))throw new _("projectPath must be absolute");return BO.resolve($)}function LO($){if(!$)throw new _("sessionId is required");try{F$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function W$($){let O=k$($),J=o()?.hooks??MO.hooks,Z=await J$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await x0(O),Y$(O);let Y=l0.getInstance();return Y.loadConfig(Z,O),await Z$(O),Y.getConfig(O)}function wO($,O){let J=l0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var EO=()=>{let $=new M4;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await W$(J),O.json(await l0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=S(E4,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:G}=J.data;await W$(Z);let X=l0.getInstance(),V;try{V=Y==="trust"?await X.trustProject(Z,G):await X.revokeProjectTrust(Z)}catch(W){if(W instanceof AO)throw new R(W.message);throw W}return O.json(V)}),$.get("/session",async(O)=>{let J=k$(O.req.query("projectPath")),Z=LO(O.req.query("sessionId"));return await W$(J),O.json(wO(Z,J))}),$.post("/session",async(O)=>{let J=S(q4,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=k$(J.data.projectPath),Y=LO(J.data.sessionId);await W$(Z);let G=l0.getInstance();if(J.data.enabled)G.enableSession(Y,Z);else G.disableSession(Y,Z);return O.json(wO(Y,Z))}),$};import{Hono as T4}from"hono";var w0=u("Service");function b4($){try{return TO($)}catch{return[]}}function C4($){if(!U$($)||!U$($.reference)||!U$($.argument))throw Error("Invalid MCP completion request");let O=$.reference.type,J=O==="prompt"&&typeof $.reference.name==="string"?{type:"prompt",name:$.reference.name}:O==="resource"&&typeof $.reference.uri==="string"?{type:"resource",uri:$.reference.uri}:void 0;if(!J||typeof $.argument.name!=="string"||typeof $.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if($.context!==void 0){if(!U$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,G]of Object.entries($.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");Z[Y]=G}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function U$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function q0($,O){let J=o()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var bO=()=>{let $=new T4;return $.get("/",async(O)=>{try{let J=G0.getInstance();await q0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([G,X])=>({id:G,name:G,status:X.status==="connected"?"connected":X.status==="reconnecting"?"reconnecting":X.status==="connecting"?"connecting":X.lastError?"error":"offline",endpoint:X.config.command?`${X.config.command} ${(X.config.args||[]).join(" ")}`.trim():X.config.url||"Unknown",description:`MCP server: ${G}`,tools:X.tools.map((V)=>V.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((V)=>({...V,variables:b4(V.uriTemplate)})),prompts:X.contentCatalog.prompts,connectedAt:X.connectedAt?.toISOString(),error:X.lastError?.message,recovery:X.recovery,logging:X.logging,instructions:X.instructions,oauthEnabled:X.client.oauthEnabled,oauthStatus:await X.client.getOAuthStatus()})));return O.json(Y)}catch(J){return w0.error("[McpRoutes] Failed to get MCP servers:",J),O.json({error:J instanceof Error?J.message:"Failed to get MCP servers"},500)}}),$.post("/:name/connect",async(O)=>{try{let J=O.req.param("name"),Z=G0.getInstance();return await q0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to connect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/:name/disconnect",async(O)=>{try{let J=O.req.param("name"),Z=G0.getInstance();return await q0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to disconnect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.get("/:name/logs",async(O)=>{try{let J=O.req.param("name"),Z=Number(O.req.query("limit")??20),Y=Number(O.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(Y)||Y<0)return O.json({error:"Invalid MCP log pagination"},400);let G=G0.getInstance();return await q0(G,J),O.json(G.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return w0.error("[McpRoutes] Failed to get MCP logs:",J),O.json({error:J.message},500)}}),$.post("/:name/logging-level",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();if(!qO(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=G0.getInstance();return await q0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return w0.error("[McpRoutes] Failed to set MCP logging level:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/complete",async(O)=>{try{let J=O.req.param("name"),Z=C4(await O.req.json()),Y=G0.getInstance();await q0(Y,J);let G=await Y.complete(J,Z);return O.json(G)}catch(J){return w0.error("[McpRoutes] Failed to complete MCP argument:",J),O.json({error:J.message},400)}}),$.post("/:name/oauth/login",async(O)=>{try{let J=O.req.param("name"),Z=G0.getInstance();await q0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return w0.error("[McpRoutes] Failed to start MCP OAuth login:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/oauth/logout",async(O)=>{try{let J=O.req.param("name"),Z=G0.getInstance();return await q0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to log out MCP OAuth:",J),O.json({success:!1,error:J.message},400)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name");await G0.getInstance().unregisterServer(J);let Y=o();if(Y?.mcpServers){let{[J]:G,...X}=Y.mcpServers;await V0().updateConfig({mcpServers:X})}return O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to delete MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/",async(O)=>{try{let J=await O.req.json(),{name:Z,config:Y}=J;if(!Z||!Y)return O.json({success:!1,error:"Missing name or config"},400);await G0.getInstance().registerServer(Z,Y);let X=o();return await V0().updateConfig({mcpServers:{...X?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as R4}from"@earendil-works/pi-ai";import{Hono as j4}from"hono";var D$=u("Service");function k4($,O,J=kO.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:R4(O),supportedServiceTiers:RO(O),supportedResponseVerbosities:CO(O),communicationStyles:J,input:O.input}}function I4($){IO($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function IO($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var SO=()=>{let $=new j4;return $.get("/",async(O)=>{try{let J=o();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||v(),[Y,G]=await Promise.all([_$(Z,J),x0(Z)]),X=Y.config.models,V=X.find((T)=>T.id===Y.config.currentModelId)??X[0],W=Y.catalog,H=G.communicationStyles.list(),q=(T)=>k4(T,W.resolveConfig(T),H);return O.json({configured:X.map(q),current:V?q(V):null})}catch(J){D$.error("[ModelsRoutes] Failed to get models:",J);let Z=new d("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=f0(),Z,Y;try{let G=await O.req.json(),{provider:X,displayName:V,model:W,overrides:H,apiKey:q,modelProvider:T}=G;if(!X||!W)throw new _("provider and model are required");IO(H);let C;if(T){if(T.id!==X)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);C={name:T.name,baseUrl:T.baseUrl,wireApi:T.wireApi,...T.apiKeyEnv?{apiKeyEnv:T.apiKeyEnv}:{}};try{J.registerModelProvider(X,C,[W]),Y=X}catch(w){throw new _(w instanceof Error?w.message:"Invalid model provider")}}else J.getModel(X,W);if(q?.trim()){if(await J.setApiKey(X,q.trim()),C)Z=X}let c={provider:X,displayName:V||void 0,model:W,overrides:H||void 0},s=C?await V0().addModelWithProvider(c,C):await V0().addModel(c);return O.json({success:!0,model:s})}catch(G){if(Z)await J.credentials.delete(Z);if(Y){let X=o();J.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw D$.error("[ModelsRoutes] Failed to add model:",G),G}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:G,model:X}=Z,V=jO(J);if(!V)throw new _("model config not found");if(X)f0().getModel(V.provider,X);return await V0().updateModel(J,I4({displayName:Y,overrides:G,model:X})),O.json({success:!0})}catch(J){throw D$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await V0().removeModel(J),O.json({success:!0})}catch(J){throw D$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as a4}from"hono";import{Mutex as fO}from"async-mutex";import{Hono as S4}from"hono";import{streamSSE as f4}from"hono/streaming";import{LRUCache as P4}from"lru-cache";import{nanoid as i0}from"nanoid";import PO from"node:path";var P=u("Service"),y4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),m4=eO,h4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),v4=F.Object({projectPath:F.String()}),g4=F.Object({objective:F.String({minLength:1}),tokenBudget:F.Optional(F.Integer({minimum:1})),permissionMode:F.Optional(Z0(["default","autoEdit","plan","yolo"]))}),p4=F.Union([F.Object({action:F.Literal("pause")}),F.Object({action:F.Literal("resume")}),F.Object({action:F.Literal("edit"),objective:F.String({minLength:1})})]),l=new Map,L$,M0=new Map,a0=new Map,T0=new Map,M$=new P4({max:100,ttl:1800000});function yO($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function Y0($){if(!$)return;return M0.get($)??M$.get($)}function u4($){if(M0.get($.id)!==$)return;M0.delete($.id),M$.set($.id,$)}function d4($){M0.delete($),M$.delete($)}function N0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function w$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:uO}),J)b.publish(yO($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",b.publish(yO($),"run.cancelled",{runId:$.id}),!0}function J1($,O=!1){let{permissionId:J,details:Z}=$;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,questions:Z.questions,details:Z,...O?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,elicitation:Z.mcpElicitation,...O?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:J,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...O?{replayed:!0}:{}}}}function l4(){for(let $ of M0.values())w$($,"route-reset");M0.clear();for(let $ of a0.values())$.controller.abort("route-reset");a0.clear(),M$.clear(),L$=void 0,l.clear()}var Z1=($)=>{if(!$||typeof $!=="object")return $;let O={...$},J=200000,Z=(Y,G)=>typeof Y==="number"&&Number.isSafeInteger(Y)&&Y>=0&&Y<=G?Y:0;if(typeof O.oldContent==="string"&&O.oldContent.length>J)delete O.oldContent;if(typeof O.newContent==="string"&&O.newContent.length>J)delete O.newContent;if(O.mcpResult&&typeof O.mcpResult==="object"&&!Array.isArray(O.mcpResult)){let Y=O.mcpResult,G=Array.isArray(Y.artifacts)?Y.artifacts.slice(0,64).flatMap((X)=>{if(!X||typeof X!=="object"||Array.isArray(X))return[];let V=X,W=new Set(["text","image","audio","resource"]);if(typeof V.id!=="string"||!/^[a-f0-9]{64}$/.test(V.id)||typeof V.sha256!=="string"||V.sha256!==V.id||typeof V.kind!=="string"||!W.has(V.kind)||Z(V.size,67108864)!==V.size||typeof V.persisted!=="boolean")return[];return[{id:V.id.slice(0,128),sha256:V.sha256.slice(0,128),kind:V.kind,size:V.size,persisted:V.persisted,...typeof V.mimeType==="string"?{mimeType:V.mimeType.slice(0,256)}:{},...typeof V.sourceUri==="string"?{sourceUri:V.sourceUri.slice(0,8192)}:{},...typeof V.path==="string"?{path:V.path.slice(0,8192)}:{}}]}):[];O.mcpResult={isError:Y.isError===!0,contentCount:Z(Y.contentCount,64),textBytes:Z(Y.textBytes,4194304),structuredBytes:Z(Y.structuredBytes,4194304),artifactCount:Z(Y.artifactCount,64),truncated:Y.truncated===!0,binaryOmitted:Y.binaryOmitted===!0,artifacts:G}}else delete O.mcpResult;return O};function c4($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)b.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),b.publish($,"subagent.tool.start",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,arguments:J.toolCall.function.arguments,toolKind:J.toolKind});break;case"tool_result":if("function"in J.toolCall)b.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:!J.result.error,summary:J.result.metadata?.summary,output:d$(u$(J.toolCall.function.name,J.result)),metadata:Z1(J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)b.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":b.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":b.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":b.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_retry":b.publish($,"subagent.provider.retry",{subagentSessionId:O,phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,statusCode:J.statusCode,delayMs:J.delayMs,nextRetryAt:J.nextRetryAt});break;case"mcp_catalog_changed":b.publish($,"subagent.mcp.catalog.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_content_changed":b.publish($,"subagent.mcp.content.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,contentKind:J.contentKind,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_resource_updated":b.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":b.publish($,"subagent.mcp.connection.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,maxAttempts:J.maxAttempts,nextRetryAt:J.nextRetryAt,error:J.error});break;case"mcp_log":b.publish($,"subagent.mcp.log",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,level:J.level,logger:J.logger,message:J.message,projectedBytes:J.projectedBytes,dataSha256:J.dataSha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});break;case"mcp_instructions_changed":b.publish($,"subagent.mcp.instructions.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,action:J.action,reason:J.reason,text:J.text,sourceBytes:J.sourceBytes,projectedBytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted});break;case"mcp_task_changed":b.publish($,"subagent.mcp.task.changed",{subagentSessionId:O,revision:J.revision,taskId:J.taskId,serverName:J.serverName,toolName:J.toolName,status:J.status,statusMessage:J.statusMessage,createdAt:J.createdAt,updatedAt:J.updatedAt,completedAt:J.completedAt,hasResult:J.hasResult,error:J.error});break;case"project_rules_loaded":b.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function Q$($,O="projectPath"){if(!PO.isAbsolute($))throw new _(`${O} must be absolute`);return PO.resolve($)}function g$($){try{F$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function e($){return{sessionId:$.id,projectPath:$.projectPath}}function x$($,O,J){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,pendingInteraction:$.pendingInteraction,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:$.taskQueuePosition,taskQueueDepth:$.taskQueueDepth,taskConcurrencyLimit:$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,taskWorktree:J,messages:O}}function I$($){return $.flatMap((O)=>{if(O.role==="system"||O.role==="tool"&&O.name===o0)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==o0),Z=typeof O.content==="string"?O.content.trim():"";if(O.role==="assistant"&&O.tool_calls?.length&&!J?.length&&!Z&&!O.reasoningContent&&!O.metadata)return[];let Y={...O,...O.tool_calls?{tool_calls:J&&J.length>0?J:void 0}:{}},G=cO(O.metadata);return[G?{...Y,content:lO(G)}:Y]})}function G$($,O){$.taskStatus=O.taskStatus,$.taskStatusReason=O.taskStatusReason,$.taskFailure=O.taskFailure,$.taskStartedAt=O.taskStartedAt,$.taskCompletedAt=O.taskCompletedAt,$.taskPromptSummary=O.taskPromptSummary,$.taskModelId=O.taskModelId,$.selectedModelId=O.selectedModelId,$.permissionMode=O.permissionMode,$.reasoningEffort=O.reasoningEffort,$.serviceTier=O.serviceTier,$.responseVerbosity=O.responseVerbosity,$.communicationStyle=O.communicationStyle,$.communicationStyleDigest=O.communicationStyleDigest,$.projectInstructionsDigest=O.projectInstructionsDigest,$.pendingInteraction=O.pendingInteraction,$.taskRetryAvailable=O.taskRetryAvailable,$.taskRetriedFrom=O.taskRetriedFrom,$.taskDelivery=O.taskDelivery,$.taskIsolation=O.taskIsolation,$.taskSourceProjectPath=O.taskSourceProjectPath,$.taskWorktreePath=O.taskWorktreePath,$.taskWorktreeBranch=O.taskWorktreeBranch,$.taskBaseCommit=O.taskBaseCommit,$.taskDiffStat=O.taskDiffStat,$.taskQueuePosition=O.taskQueuePosition,$.taskQueueDepth=O.taskQueueDepth,$.taskConcurrencyLimit=O.taskConcurrencyLimit,$.archivedAt=O.archivedAt,$.archivedBySessionId=O.archivedBySessionId,$.updatedAt=new Date(O.lastMessageTime)}async function y0($){let O=await j.findSessionMetadata($.id,$.projectPath);if(O)G$($,O)}function c0($){let O=Y0($.currentRunId),J=O?.status==="waiting_permission"?"running":O?.status??$.taskStatus;return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,taskStatus:J,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:O?.status==="queued"?O.taskQueuePosition:J==="queued"?$.taskQueuePosition:void 0,taskQueueDepth:O?.status==="queued"?O.taskQueueDepth:J==="queued"?$.taskQueueDepth:void 0,taskConcurrencyLimit:O?.taskConcurrencyLimit??$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,pendingInteraction:O?.pendingPermission?{type:O.pendingPermission.details.type==="askUserQuestion"?"question":O.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:O.pendingPermission.permissionId}:$.pendingInteraction,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function J0($,O){if(g$($),O!==void 0){let Z=C0({sessionId:$,projectPath:Q$(O)});if(l.has(f(Z)))return Z;let Y=await j.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new I("Session",$);return C0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of l.values()){if(Z.id!==$)continue;let Y=e(Z);J.set(f(Y),Y)}for(let Z of await j.listSessions()){if(Z.sessionId!==$)continue;let Y=C0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(f(Y),Y)}if(J.size===0)try{let Z=await j.findSessionMetadata($);if(!Z)throw new I("Session",$);return C0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof I)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new K0;throw Z}if(J.size>1)throw new K0;return J.values().next().value}function p$($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
2
|
-
`)}function mO($,O){let J=(O??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(J.length===0)return $;let Z=[];if($.trim())Z.push({type:"text",text:$});return Z.push(...J),Z}var Y1=()=>{l4();let $=new S4;$.onError((x,N)=>{if(x instanceof t)return N.json(x.toObject(),x.statusCode);return P.error("[SessionRoutes] Unhandled route error:",x),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,G=new Map,X=new Map,V=(x)=>{let N=f(x),Q=G.get(N);if(!Q)Q=new fO,G.set(N,Q);return Q},W=(x)=>{let N=f(x),Q=X.get(N);if(!Q)Q=new fO,X.set(N,Q);return Q},H=async(x,N={})=>{let Q=f(e(x));await Z.get(Q);let z=O.get(Q);if(z)return z;let K=J.get(Q);if(!K){let U=N.communicationStyle??x.communicationStyle;K=z$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:N.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...U?{communicationStyle:U}:{},...U===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,K)}try{let U=await K;return O.set(Q,U),U}finally{if(J.get(Q)===K)J.delete(Q)}},q=async(x,N)=>{let Q=f(e(x)),z=Z.get(Q);if(!z)z=(async()=>{let K=J.get(Q);if(K)await K.catch(()=>{return});J.delete(Q);let U=N??O.get(Q);if(O.delete(Q),U){for(let[D,B]of O)if(B===U)O.delete(D)}await U?.dispose()})().finally(()=>{if(Z.get(Q)===z)Z.delete(Q)}),Z.set(Q,z);await z},T=async(x)=>{let N=f(x),Q=l.get(N);if(Q)return Q;let z=Y.get(N);if(!z)z=(async()=>{let K=await j.findSessionMetadata(x.sessionId,x.projectPath);if(!K)throw new I("Session",x.sessionId);let[U,D]=await Promise.all([j.loadSession(x.sessionId,x.projectPath),j.findSessionTaskWorktree(x.sessionId,x.projectPath)]),B=x$(K,U,D);return l.set(N,B),B})(),Y.set(N,z);try{return await z}finally{if(Y.get(N)===z)Y.delete(N)}},C=async(x,N)=>{let Q=await J0(x,N);try{await j.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(z){if(z instanceof P$)throw new R(z.message);throw z}return T(Q)},c=async(x,N)=>{if(x.permissionMode===N)return;let Q=await j.setSessionPermissionMode(x.id,x.projectPath,N);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),b.publish(e(x),"session.updated",{permissionMode:N})},s=(x,N,Q,z={})=>{let K=i0(12),U={id:K,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:z.taskRuntime!==void 0,createdAt:new Date};if(z.taskRuntime){let D=z.taskRuntime,B=d0.admit({key:`${x.projectPath}\x00${x.id}`,...D.getTaskAdmissionLimits(),signal:U.abortController.signal,onUpdate:(A)=>{U.status=A.state,U.taskQueuePosition=A.queuePosition,U.taskQueueDepth=A.queueDepth,U.taskConcurrencyLimit=A.maxConcurrent,x.taskStatus=A.state,x.taskQueuePosition=A.queuePosition,x.taskQueueDepth=A.queueDepth,x.taskConcurrencyLimit=A.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(A)}).catch((L)=>{P.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,L)})}});U.taskAdmission=B;let M=B.getSnapshot();U.status=M.state,U.taskQueuePosition=M.queuePosition,U.taskQueueDepth=M.queueDepth,U.taskConcurrencyLimit=M.maxConcurrent}return M0.set(K,U),x.currentRunId=K,U.completion=i4(U,x,N,Q,H,{pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:U.taskAdmission,disposeRuntime:q}).catch((D)=>{P.error(`[SessionRoutes] Run ${K} failed:`,D)}),U},w=async(x)=>{let N;if(x.outputSchema)try{N=f$(x.outputSchema).schema}catch(E){throw new _(E instanceof Error?E.message:"Invalid output schema")}let Q=S$("task",12),z=Q$(x.sourceProjectPath),K=x.modelId?.trim(),U=o();if(!U)throw new _("Config not initialized");let[D,B]=await Promise.all([_$(z,U),x0(z)]);if(K&&!D.config.models.some((E)=>E.id===K))throw new _(`Task model not found: ${K}`);let M=K||D.config.models.find((E)=>E.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!M)throw new _("No model is configured. Add or select a model before dispatching a task.");let A=D.config.models.find((E)=>E.id===M);if(!A)throw new _(`Task model not found: ${M}`);let L=x.reasoningEffort??"off",r=x.serviceTier??"auto",E0=x.responseVerbosity??"auto",_0=x.communicationStyle??"auto",X0,k=B.projectRules?.staticRules(z),g=k&&k.files.length>0?k.provenanceSha256:void 0;try{let E=D.catalog.resolveConfig(A);gO(E,L),vO(E,r),hO(E,E0);let h=pO(_0,B.communicationStyles);X0=h.source==="built-in"?void 0:h.contentSha256}catch(E){throw new _(E instanceof Error?E.message:"Invalid reasoning effort")}let e0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:z,isolation:x.isolation,permissionMode:x.permissionMode,modelId:M,reasoningEffort:L,serviceTier:r,responseVerbosity:E0,communicationStyle:_0,...X0?{communicationStyleDigest:X0}:{},...g?{projectInstructionsDigest:g}:{},...x.attachments?{attachments:x.attachments.map((E)=>({...E}))}:{},...N?{outputSchema:N}:{}},H0,y;try{let E=await tO.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:z,isolation:x.isolation,dispatch:e0,retriedFrom:x.retriedFrom}),{metadata:h}=E;H0=E.taskWorktree,y=x$(h,[],H0);let $0=e(y);l.set(f($0),y),b.publish($0,"task.status",{taskStatus:h.taskStatus,updatedAt:h.lastMessageTime});let n=mO(x.prompt,x.attachments),i=await H(y),W0=N?await i.prepareInputTurn(n,{outputSchema:N}):await i.prepareInputTurn(n);if(!W0.accepted)throw new R(`Task prompt was not accepted: ${W0.reason}`);let B0=s(y,n,x.permissionMode,{preparedInputTurn:W0,taskRuntime:i,outputSchema:N});return await B0.taskAdmissionUpdate,{session:c0(y),runId:B0.id,messageId:W0.messageId,status:B0.status==="queued"?"queued":"running",queuePosition:B0.taskQueuePosition,queueDepth:B0.taskQueueDepth,maxConcurrentTasks:B0.taskConcurrencyLimit}}catch(E){if(E instanceof v$&&y){let h=e(y),$0=f(h);if(H0)await A0.exit({sessionId:y.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get($0)?.dispose().catch(()=>{return}),O.delete($0),await j.deleteSession(y.id,y.projectPath).catch(()=>{return}),l.delete($0),new p0("Task admission queue is full")}if(y){let h=await j.findSessionMetadata(y.id,y.projectPath).catch(()=>{return});if(!h||h.taskStatus==="queued"){let $0=B$(E),n=await j.updateSessionMetadata(y.id,y.projectPath,{taskStatus:"failed",taskStatusReason:$0.message,taskFailure:$0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});y.taskStatus=n?.taskStatus??"failed",y.taskStatusReason=n?.taskStatusReason??$0.message,y.taskFailure=n?.taskFailure??$0,y.taskCompletedAt=n?.taskCompletedAt}else y.taskStatus=h.taskStatus,y.taskStatusReason=h.taskStatusReason,y.taskFailure=h.taskFailure,y.taskCompletedAt=h.taskCompletedAt}throw E}},a=async(x,N)=>{let Q=await J0(x,N),z=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!z)throw new I("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(z.taskStatus))throw new R(`Task cannot be retried while status is ${z.taskStatus}`);let K=await j.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!K)throw new R("Task retry payload is unavailable");return w({prompt:K.prompt,title:K.title,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.outputSchema,retriedFrom:Q})},m=async(x,N)=>{let Q=await C(x,N);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await A0.restoreSession(Q.taskWorktree);let z=await A0.getDiffArtifact(Q.id);if(!z)throw new R("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...z}}catch(z){if(z instanceof R)throw z;throw P.error("[SessionRoutes] Failed to load task diff artifact:",z),new R("Task diff artifact is unavailable")}},O0=async(x,N,Q)=>{let z=await J0(x,Q);return W(z).runExclusive(async()=>{let K=await C(z.sessionId,z.projectPath);if(["queued","running"].includes(K.taskStatus))throw new R(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new R("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new R("Task changes have already been discarded");if(!K.taskWorktree)throw new R("Task worktree is unavailable");let U=async(D,B=!1)=>{let M=await j.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(G$(K,M),B)K.taskWorktree=void 0;return b.publish(z,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),c0(K)};try{if(N==="discard"){try{await A0.restoreSession(K.taskWorktree)}catch(M){return P.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,M),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await A0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await A0.restoreSession(K.taskWorktree)}catch(B){throw P.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,B),new h$("artifact_unavailable","Task worktree is unavailable")}let D=await A0.apply(K.id);return U({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof h$)throw await U({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new R(D.message);throw D}})},Q0=async(x)=>{let N=Y0(x.currentRunId);if(N0(N))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await z$.hasPendingInbox(x.projectPath,x.id),z=!Q&&await z$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!z)return;let K=await H(x),U=Y0(x.currentRunId);if(N0(U))return;if(Q&&K.getPendingSteeringCount()===0)await K.reloadPendingInbox();let D=K.getPendingSteeringCount()>0,M=(D?null:await K.getGoal())?.status==="active"||z;if(!D&&!M||K.hasTurnOwner())return;s(x,"",x.permissionMode??"default",{pendingInputOnly:D,goalContinuationOnly:M,...x.taskIsolation?{taskRuntime:K}:{}})};L$=Q0;let S0=async()=>{let x={scheduled:0,failed:0,deferred:0},N=(await j.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,z)=>Q.firstMessageTime.localeCompare(z.firstMessageTime)||Q.projectPath.localeCompare(z.projectPath)||Q.sessionId.localeCompare(z.sessionId));for(let[Q,z]of N.entries()){let K={sessionId:z.sessionId,projectPath:z.projectPath};try{if(!await z$.hasPendingInbox(z.projectPath,z.sessionId)){let D=B$("Queued task input is missing");await j.updateSessionMetadata(z.sessionId,z.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let U=await T(K);if(await Q0(U),U.currentRunId)x.scheduled++}catch(U){if(U instanceof v$){x.deferred+=N.length-Q;break}P.warn(`[SessionRoutes] Failed to recover queued task ${z.sessionId}:`,U),x.deferred++}}return x};return $.get("/",async(x)=>{try{let N=await j.listSessions(),Q=new Set(N.filter((A)=>A.relationType==="subagent").map((A)=>f({sessionId:A.sessionId,projectPath:A.projectPath}))),z=Array.from(l.values()).filter((A)=>!Q.has(f(e(A)))&&A.relationType!=="subagent").map((A)=>c0(A)),K=new Set(z.map((A)=>f({sessionId:A.sessionId,projectPath:A.projectPath}))),U=N.filter((A)=>{if(A.relationType==="subagent")return!1;return!K.has(f({sessionId:A.sessionId,projectPath:A.projectPath}))}),D=new Set(K),B=U.filter((A)=>{let L=f({sessionId:A.sessionId,projectPath:A.projectPath});if(D.has(L))return!1;return D.add(L),!0}),M=[...z,...B];return x.json(M)}catch(N){throw P.error("[SessionRoutes] Failed to list sessions:",N),new d("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let N=x.req.query("limit"),Q=N===void 0?void 0:Number(N),z=x.req.query("cursor"),K=x.req.query("projectPath"),U=x.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let D=U==="true",B=await j.listSessionPage({...K?{cwd:Q$(K)}:{},...z?{cursor:z}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:D}),M=new Map((D?[]:Array.from(l.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[f(e(A)),c0(A)]));return x.json({sessions:B.sessions.map((A)=>M.get(f({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...B.nextCursor?{nextCursor:B.nextCursor}:{}})}catch(N){if(N instanceof _)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new _(N.message);throw P.error("[SessionRoutes] Failed to list session catalog:",N),new d("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let N=await x.req.json(),Q=S(y4,N);if(!Q.success)throw new _("Invalid request body");let{title:z,projectPath:K}=Q.data,U=S$("web",12),D=Q$(K||x.get("directory")||v(),K?"projectPath":"directory"),B=await j.createSessionMetadata(U,D,{title:z,taskStatus:"completed"}),M=x$(B,[]),A=e(M);return l.set(f(A),M),b.publish(A,"session.created",{}),x.json({...c0(M),status:void 0,agentType:void 0,model:void 0})}catch(N){if(P.error("[SessionRoutes] Failed to create session:",N),N instanceof _)throw N;throw new d("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let N=x.req.param("sessionId");try{let Q=x.req.query("includeReasoning");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new _("includeReasoning must be true or false");let z=await J0(N,x.req.query("projectPath")),K=await j.exportSessionMarkdown(z.sessionId,z.projectPath,{includeReasoning:Q==="true"});return x.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new R(Q.message);throw P.error("[SessionRoutes] Failed to export session:",Q),new d("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let N=x.req.param("sessionId");try{g$(N);let Q=await x.req.json(),z=S(v4,Q);if(!z.success)throw new _("Invalid request body");let K=Q$(z.data.projectPath),U=await j.findSessionMetadata(N,K);if(!U)throw new I("Session",N);let D=await j.forkSession(N,{sourceProjectPath:U.projectPath,targetProjectPath:U.projectPath}),B=x$(D.metadata,D.messages),M=e(B);return l.set(f(M),B),b.publish(M,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),x.json({session:D.metadata,messages:I$(D.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof R)throw Q;if(Q instanceof iO)throw new R("Session has no durable creation record");throw P.error("[SessionRoutes] Failed to fork session:",Q),new d("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),z=l.get(f(Q));if(z)return x.json(c0(z));let K=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new I("Session",N);return x.json(K)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)throw Q;throw P.error("[SessionRoutes] Failed to get session:",Q),new d("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await x.req.json(),z=S(h4,Q);if(!z.success)throw new _("Invalid request body");if(z.data.title===void 0)throw new _("title is required");let K=await J0(N,z.data.projectPath),U=await j.updateSessionMetadata(K.sessionId,K.projectPath,{title:z.data.title}),D=l.get(f(K));if(D)D.title=U.title??D.title,D.updatedAt=new Date(U.lastMessageTime);if(U.title)b.publish(K,"session.updated",{title:U.title});return x.json({success:!0,title:U.title})}catch(Q){if(P.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof I||Q instanceof K0)throw Q;throw new d("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(N);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let N=S(sO,await x.req.json());if(!N.success)throw new _("Invalid rewind request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))throw new R("Cannot rewind while a run is active");let U=await H(Q),D;try{D=await U.rewindSession(N.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new R(M.message);throw M}Q.messages=[...D.messages],Q.updatedAt=new Date;let B=I$(D.messages);return b.publish(z,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),x.json({...D,messages:B})})}),$.get("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),z=await b0.list(Q.projectPath,Q.sessionId);return x.json({reviews:z.map((K)=>({...K,content:K.completion?dO(K.start,K.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=S(O1,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let z=await C(N,Q.data.projectPath),K=e(z),U=f(K);return V(K).runExclusive(async()=>{if(N0(Y0(z.currentRunId)))throw new R("Cannot start a review during an active turn");if(T0.has(U))throw new R("Session already has an active review");let D=await H(z);if(await b0.recoverInterrupted(K.projectPath,K.sessionId,D),Q.data.modelId&&!D.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&D.getCurrentModelId()!==Q.data.modelId)await D.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&z.selectedModelId!==Q.data.modelId){let L=await j.updateSessionMetadata(z.id,z.projectPath,{selectedModelId:Q.data.modelId});G$(z,L)}let B=new AbortController,M;try{M=await b0.start({sessionId:K.sessionId,projectPath:K.projectPath,runtime:D,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:B.signal,onEvent:(L)=>{if(L.kind==="tool_start")b.publish(K,"review.tool.started",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,toolName:L.toolCall.function.name});else if(L.kind==="tool_progress")b.publish(K,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,message:L.update.message.slice(0,1000)});else if(L.kind==="tool_result")b.publish(K,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,success:L.result.success})}})}catch(L){if(L instanceof Error&&(L.message.includes("active review")||L.message.includes("interrupted review")||L.message.includes("active turn")))throw new R(L.message);if(L instanceof Error&&(L.message.includes("review")||L.message.includes("Git")||L.message.includes("changes")||L.message.includes("ref")))throw new _(L.message);throw L}if(!M)throw new d("Code review failed to start");await y0(z),b.publish(K,"review.started",{reviewId:M.reviewId,kind:Q.data.kind}),b.publish(K,"task.status",{taskStatus:z.taskStatus,...z.taskStatusReason?{taskStatusReason:z.taskStatusReason}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskPromptSummary?{taskPromptSummary:z.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=M.completion.then(async(L)=>{z.messages=await j.loadSession(K.sessionId,K.projectPath),await y0(z),b.publish(K,"task.status",{taskStatus:z.taskStatus,...z.taskStatusReason?{taskStatusReason:z.taskStatusReason}:{},...z.taskFailure?{taskFailure:z.taskFailure}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskCompletedAt?{taskCompletedAt:z.taskCompletedAt}:{},...z.taskPromptSummary?{taskPromptSummary:z.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),b.publish(K,"review.completed",{reviewId:M.reviewId,status:L.status,findings:L.findings.length})}).catch((L)=>{P.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,L)}).finally(()=>{if(T0.get(U)?.reviewId===M.reviewId)T0.delete(U)});return T0.set(U,{reviewId:M.reviewId,controller:B,completion:A}),x.json({reviewId:M.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(N);return x.json({subagents:Q.listSubagents().map(H$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{g$(x.req.param("agentId"));let N=rO.safeParse(await x.req.json());if(!N.success)throw new _("Invalid subagent resume request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))throw new R("Cannot resume a subagent while a parent run is active");let U=await H(Q),D=!1,B,M=(L)=>{b.publish(z,"subagent.complete",{subagentSessionId:L.id,success:L.status==="completed",status:L.status,summary:L.result?.message?.slice(0,500),type:L.subagentType,verificationVerdict:L.result?.verificationVerdict,resumedFrom:L.resumedFrom,rootAgentId:L.rootAgentId,resumeDepth:L.resumeDepth})},A;try{A=U.resumeSubagent({agentId:x.req.param("agentId"),prompt:N.data.prompt,onEvent:(L,r)=>{c4(z,r,L)},onCompleted:(L)=>{if(D)M(L);else B=L}})}catch(L){if(L instanceof Error&&(L.message.startsWith("Cannot resume")||L.message.startsWith("Subagent cannot")))throw new R(L.message);if(L instanceof Error&&L.message.startsWith("Subagent not found"))throw new I(L.message);throw L}if(b.publish(z,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),D=!0,B)M(B);return x.json({source:H$(A.source),session:H$(A.session)})})}),$.get("/:sessionId/goal",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new aO(N.projectPath,N.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let N=S(g4,await x.req.json());if(!N.success)throw new _("Invalid goal request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))return x.json({status:"rejected",reason:"run_active"},409);let D=N.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==D)await c(Q,D);let B=await H(Q),M=await B.createGoal(N.data);b.publish(z,"goal.updated",{goal:M});let A=s(Q,"",D,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:B}:{}});return await A.taskAdmissionUpdate,x.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:M,queuePosition:A.taskQueuePosition,queueDepth:A.taskQueueDepth,maxConcurrentTasks:A.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let N=S(p4,await x.req.json());if(!N.success)throw new _("Invalid goal update");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),z=e(Q);return V(z).runExclusive(async()=>{let K=await H(Q),U;if(N.data.action==="pause")U=await K.pauseGoal();else if(N.data.action==="edit")U=await K.editGoal(N.data.objective);else U=await K.resumeGoal();if(b.publish(z,"goal.updated",{goal:U}),U.status==="active"&&!N0(Y0(Q.currentRunId))){let D=s(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:K}:{}});return await D.taskAdmissionUpdate,x.json({status:D.status==="queued"?"queued":"running",runId:D.id,goal:U,queuePosition:D.taskQueuePosition,queueDepth:D.taskQueueDepth,maxConcurrentTasks:D.taskConcurrencyLimit},202)}return x.json({status:U.status,goal:U})})}),$.delete("/:sessionId/goal",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=e(N),K=await(await H(N)).clearGoal();if(K)b.publish(Q,"goal.cleared",{});return x.json({cleared:K})}),$.post("/:sessionId/archive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),z=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=l.get(f(D));if(N0(Y0(B?.currentRunId)))throw new R(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=l.get(f(D));if(B)await q(B)}let K=await j.archiveSession(Q.sessionId,Q.projectPath);for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=f(D);l.delete(B),Y.delete(B),J.delete(B),G.delete(B),b.publish(D,"session.archived",{archiveRootId:Q.sessionId,archivedAt:K.archivedAt})}if(O.size===0)await G0.getInstance().disconnectAll();return x.json({session:K,archivedSessionIds:z.map((U)=>U.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0||Q instanceof R)throw Q;if(Q instanceof y$)throw new R(Q.message);throw P.error("[SessionRoutes] Failed to archive session:",Q),new d("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),z=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath),K=await j.unarchiveSession(Q.sessionId,Q.projectPath),U=z.filter((D)=>D.sessionId===Q.sessionId||D.archivedBySessionId===Q.sessionId).map((D)=>D.sessionId);for(let D of U)b.publish({sessionId:D,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:K,restoredSessionIds:U})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)throw Q;if(Q instanceof y$)throw new R(Q.message);throw P.error("[SessionRoutes] Failed to unarchive session:",Q),new d("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let N=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let z=await J0(N,Q),K=f(z),U=l.get(K),D=O.get(K),B=U?.taskWorktree??await j.findSessionTaskWorktree(z.sessionId,z.projectPath),M;if(U?.currentRunId){let L=Y0(U.currentRunId);if(L)w$(L),await L.completion,M=L.id}let A=T0.get(K);if(A)A.controller.abort("session-delete"),await A.completion;if(D)await D.clearGoal().catch((L)=>{P.warn("[SessionRoutes] Failed to clear session goal:",L)});if(await j.deleteSession(z.sessionId,z.projectPath),b.publish(z,"session.deleted",{}),M)d4(M);if(l.delete(K),Y.delete(K),J.delete(K),G.delete(K),D){if(await D.dispose(),O.delete(K),O.size===0)await G0.getInstance().disconnectAll()}if(B)try{await A0.restoreSession(B),await A0.exit({sessionId:z.sessionId,action:"remove",discardChanges:!0})}catch(L){P.warn(`[SessionRoutes] Failed to remove deleted task worktree ${z.sessionId}:`,L)}return x.json({success:!0})}catch(z){if(P.error("[SessionRoutes] Failed to delete session:",z),z instanceof _||z instanceof I||z instanceof K0)throw z;throw new d("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),z=l.get(f(Q)),K=z?.messages?z.messages:await j.loadSession(Q.sessionId,Q.projectPath);return x.json(I$(K))}catch(Q){if(P.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof I||Q instanceof K0)throw Q;throw new d("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath"));try{await j.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(B){if(B instanceof P$)throw new R(B.message);throw B}let z=await T(Q),K=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),U=K?Number.parseInt(K,10):Number.NaN,D=Number.isInteger(U)?U+1:void 0;return f4(x,async(B)=>{let A,L,r=!1,E0=()=>{if(L!==void 0)clearInterval(L),L=void 0;A?.(),A=void 0},_0=()=>{if(r)return;r=!0,E0()},X0=new Set;B.onAbort(_0),A=b.subscribe((k)=>{if(k.sessionId!==Q.sessionId||k.projectPath!==Q.projectPath)return;let g=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof g==="string"){if(X0.has(g))return;X0.add(g)}B.writeSSE({...typeof k.seq==="number"?{id:String(k.seq)}:{},data:JSON.stringify({type:k.type,...typeof k.seq==="number"?{seq:k.seq}:{},properties:{...k.properties,sessionId:k.sessionId,projectPath:k.projectPath}})}).catch(_0)});try{if(B.aborted||r)return;let k=Y0(z.currentRunId),g=N0(k)?await H(z):void 0,e0=g?.getPendingSteeringCount()??0;if(await B.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:N0(k)?k.status:"idle",runId:N0(k)?k.id:void 0,queued:e0,pendingInputDelivery:e0>0?g?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:g?.getRecoveredSteeringCount()??0}})}).catch((E)=>{throw _0(),E}),B.aborted||r)return;if(D!==void 0){if(await oO.for(Q.sessionId,Q.projectPath).replay({onCommitted:(h)=>{if(B.aborted||r)return;B.writeSSE({...typeof h.seq==="number"?{id:String(h.seq)}:{},data:JSON.stringify({type:`committed.${h.type}`,...typeof h.seq==="number"?{seq:h.seq}:{},properties:{event:h,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}},D),B.aborted||r)return}if(!k&&!T0.has(f(Q))){let h=(await b0.list(Q.projectPath,Q.sessionId)).some(($0)=>$0.completion===void 0)?await b0.recoverInterrupted(Q.projectPath,Q.sessionId,await H(z)):void 0;if(h)z.messages=await j.loadSession(Q.sessionId,Q.projectPath),await y0(z),b.publish(Q,"review.completed",{reviewId:h.reviewId,status:h.status,findings:0,recovered:!0})}if(!k)await P0.recoverResponded(Q.projectPath,Q.sessionId);let H0=k?void 0:await P0.findPending(Q.projectPath,Q.sessionId),y=k?.pendingPermission??(H0?{permissionId:H0.request.requestId,details:P0.confirmationDetails(H0),resolve:()=>{return}}:void 0);if(y){X0.add(y.permissionId);let E=J1(y,!0);await B.writeSSE({data:JSON.stringify({type:E.type,properties:{...E.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}Q0(z).catch((E)=>{P.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,E)}),L=setInterval(()=>{if(!B.aborted)B.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(_0)},15000);while(!B.aborted&&!r)await new Promise((E)=>setTimeout(E,1000))}finally{_0()}})}),$.post("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId"),Q=await x.req.json(),z=S(m4,Q);if(!z.success)throw new _("Invalid message format");let{content:K,attachments:U,modelId:D,reasoningEffort:B,serviceTier:M,responseVerbosity:A,communicationStyle:L,permissionMode:r,projectPath:E0,outputSchema:_0}=z.data,X0;if(_0)try{X0=f$(_0).schema}catch(n){throw new _(n instanceof Error?n.message:"Invalid output schema")}let k=L,g=D?.trim();if((U??[]).reduce((n,i)=>n+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>A$)throw new _("Message attachments exceed the 5 MiB limit");let H0=r,y=mO(K,U),E=await C(N,E0??x.req.query("projectPath")),h=H0??E.permissionMode??"default",$0=e(E);return V($0).runExclusive(async()=>{let n=Y0(E.currentRunId);if(N0(n)){if(X0)throw new R("Wait for the active turn to finish before setting an output schema");let p=await H(E);if(g&&!p.getModelById(g))throw new _(`Model not found: ${g}`);if(g&&p.getCurrentModelId()!==g)throw new R("Wait for the active turn to finish before switching models");if(B&&p.getReasoningConfiguration().selection!==B)throw new R("Wait for the active turn to finish before switching reasoning effort");if(M&&p.getServiceTierConfiguration().selection!==M)throw new R("Wait for the active turn to finish before switching service tier");if(A&&p.getResponseVerbosityConfiguration().selection!==A)throw new R("Wait for the active turn to finish before switching response verbosity");if(k&&p.getCommunicationStyleConfiguration().selection!==k)throw new R("Wait for the active turn to finish before switching communication style");if(H0&&E.permissionMode!==H0)throw new R("Wait for the active turn to finish before switching permission mode");let L0=await p.enqueueSteering(y,{allowBeforeTurn:!0});if(!L0.accepted)return x.json({status:"rejected",reason:L0.reason??"turn_unavailable"},409);let b$=L0.messageId??i0(12),WO=L0.queued;b.publish($0,"message.created",{messageId:b$,role:"user",content:p$(y)});let x4=L0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(b.publish($0,x4,{runId:n.id,messageId:b$,queued:WO}),L0.delivery==="next_turn"&&n.status!=="running"&&n.status!=="waiting_permission")Q0(E).catch((G4)=>{P.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,G4)});if(L0.delivery==="next_turn")n.pendingFollowUpRequested=!0;return x.json({runId:n.id,messageId:b$,status:L0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:WO},202)}if(E.permissionMode!==h)await c(E,h);let i=await H(E,{permissionMode:h,...k&&!k.includes(":")?{communicationStyle:k}:{}});if(g&&!i.getModelById(g))throw new _(`Model not found: ${g}`);if(B)try{i.resolveReasoningConfiguration(B,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid reasoning effort")}if(M)try{i.resolveServiceTierConfiguration(M,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid service tier")}if(A)try{i.resolveResponseVerbosityConfiguration(A,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid response verbosity")}let W0=k?i.resolveCommunicationStyleConfiguration(k):void 0;if(W0?.source!==void 0&&W0.source!=="built-in"&&!W0.contentSha256)throw new _("Custom communication style has no provenance");let B0=i.getCurrentModelId(),YO=i.getReasoningConfiguration(),zO=i.getServiceTierConfiguration(),QO=i.getResponseVerbosityConfiguration(),xO=i.getCommunicationStyleConfiguration(),GO=Boolean(g)&&B0!==g,XO=Boolean(B)&&YO.selection!==B,KO=Boolean(M)&&zO.selection!==M,VO=Boolean(A)&&QO.selection!==A,NO=Boolean(k)&&xO.selection!==k;if(GO||XO||KO||VO||NO)await i.refresh({...g?{modelId:g}:{},...B?{reasoningEffort:B}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...k?{communicationStyle:k}:{}});let T$={...g&&E.selectedModelId!==g?{selectedModelId:g}:{},...B&&E.reasoningEffort!==B?{reasoningEffort:B}:{},...M&&E.serviceTier!==M?{serviceTier:M}:{},...A&&E.responseVerbosity!==A?{responseVerbosity:A}:{},...W0&&(E.communicationStyle!==k||E.communicationStyleDigest!==W0.contentSha256)?{communicationStyle:k,communicationStyleDigest:W0.source==="built-in"?null:W0.contentSha256}:{}};if(Object.keys(T$).length>0)try{let p=await j.updateSessionMetadata(E.id,E.projectPath,T$);E.permissionMode=p.permissionMode,E.selectedModelId=p.selectedModelId,E.reasoningEffort=p.reasoningEffort,E.serviceTier=p.serviceTier,E.responseVerbosity=p.responseVerbosity,E.communicationStyle=p.communicationStyle,E.communicationStyleDigest=p.communicationStyleDigest,E.updatedAt=new Date(p.lastMessageTime),b.publish($0,"session.updated",T$)}catch(p){if(GO||XO||KO||VO||NO)await i.refresh({...B0?{modelId:B0}:{},reasoningEffort:YO.selection,serviceTier:zO.selection,responseVerbosity:QO.selection,communicationStyle:xO.selection}).catch((L0)=>P.error("[SessionRoutes] Failed to roll back non-durable model settings:",L0));throw p}let $$=X0?await i.prepareInputTurn(y,{outputSchema:X0}):await i.prepareInputTurn(y);if(!$$.accepted)return x.json({status:"rejected",reason:$$.reason},$$.reason==="queue_full"?429:409);let v0=s(E,y,h,{preparedInputTurn:$$,outputSchema:X0,...E.taskIsolation?{taskRuntime:i}:{}});return await v0.taskAdmissionUpdate,x.json({runId:v0.id,messageId:$$.messageId,status:v0.status==="queued"?"queued":"running",queuePosition:v0.taskQueuePosition,queueDepth:v0.taskQueueDepth,maxConcurrentTasks:v0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let N=x.req.param("sessionId"),Q=S($1,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let z=await C(N,Q.data.projectPath??x.req.query("projectPath")),K=e(z),U=f(K);return V(K).runExclusive(async()=>{if(a0.has(U))throw new R("A user shell command is already running in this Session");let D=await H(z),B=new AbortController,M,A=new Promise((L)=>{M=L});a0.set(U,{controller:B,completion:A});try{let L=await D.executeUserShellCommand(Q.data.command,{signal:B.signal});z.messages=await j.loadSession(z.id,z.projectPath),z.updatedAt=new Date;let r=Y0(z.currentRunId);if(L.delivery==="next_turn"&&N0(r))r.pendingFollowUpRequested=!0;return x.json({executionId:L.executionId,messageId:L.messageId,record:L.record,auxiliary:L.auxiliary,...L.delivery?{delivery:L.delivery}:{},...L.queued!==void 0?{queued:L.queued}:{}})}finally{a0.delete(U),M()}})}),$.post("/:sessionId/abort",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),z=l.get(f(Q));if(z?.currentRunId){let D=Y0(z.currentRunId);if(D)w$(D),await D.completion}let K=a0.get(f(Q));if(K)K.controller.abort("user-cancel"),await K.completion;let U=T0.get(f(Q));if(U)U.controller.abort("user-cancel"),await U.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),z=l.get(f(Q)),K=T0.get(f(Q));if(K)return x.json({sessionId:N,projectPath:Q.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!z?.currentRunId)return x.json({sessionId:N,projectPath:Q.projectPath,status:"idle"});let U=Y0(z.currentRunId);return x.json({sessionId:N,projectPath:Q.projectPath,runId:z.currentRunId,status:U?.status||"idle"})}),{app:$,dispatchTask:w,retryTask:a,getTaskDiff:m,deliverTask:O0,recoverQueuedTasks:S0}};async function i4($,O,J,Z,Y,G={}){let{abortController:X,sessionId:V,id:W}=$,H=G.preparedInputTurn?.messageId??i0(12),T=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:i0(12),C,c,s=e(O),w=(m,O0)=>{b.publish(s,m,O0)},a=async()=>{let m=String(X.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=C??await Y(O).catch(()=>{return});if(m==="user-cancel")await O0?.discardPendingInput().catch((S0)=>{P.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,S0)});let Q0=await O0?.setTaskStatus("cancelled",m).catch(()=>{return});if(Q0)G$(O,Q0);else await y0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=m,O.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await $.taskAdmissionUpdate,X.signal.aborted)throw Error(String(X.signal.reason||"Task run cancelled"))}if(O.taskStatus="running",O.taskStatusReason=void 0,O.taskStartedAt=new Date().toISOString(),O.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)w("message.created",{messageId:H,role:"user",content:p$(J)});if(w("session.status",{status:"running"}),T)w("message.created",{messageId:T,role:"assistant",content:""});C=await Y(O);let m=C,O0=Boolean(G.outputSchema??m.getPendingSteeringMessages().find((z)=>z.outputSchema)?.outputSchema);c=await nO.createWithRuntime(m,{sessionId:V,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let Q0=async(z)=>{let K=z.interactionRequestId??i0(12),U=300000;$.status="waiting_permission";let D=new Promise((L)=>{let r=setTimeout(()=>{P.warn(`[SessionRoutes] Permission ${K} timed out after 300000ms`),w("permission.timeout",{requestId:K}),L({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:K,resolve:(E0)=>{clearTimeout(r),L(E0)},details:z}}),B=$.pendingPermission;if(!B)throw Error("Permission request was not registered");let M=J1(B);w(M.type,M.properties),P.info(`[SessionRoutes] Permission request created: ${K}, runId: ${W}`);let A=await D;if(P.info(`[SessionRoutes] Permission response received: ${K}, approved: ${A.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===B)$.pendingPermission=void 0;return w("interaction.resolved",{requestId:K}),A},S0={messages:[...O.messages],userId:"web-user",sessionId:V,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(z)=>{O.permissionMode=z,O.updatedAt=new Date,w("session.updated",{permissionMode:z})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:Q0}},x=()=>{if(!T)T=i0(12),w("message.created",{messageId:T,role:"assistant",content:""});return T},N=async(z)=>{switch(z.kind){case"content_delta":if(O0)break;w("message.delta",{messageId:x(),delta:z.delta});break;case"structured_output":w("structured.output",{messageId:x(),output:z.output,schemaDigest:z.schemaDigest});break;case"thinking_delta":w("thinking.delta",{messageId:x(),delta:z.delta});break;case"tool_start":if("function"in z.toolCall){if(z.toolCall.function.name===o0)break;w("tool.start",{messageId:x(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,arguments:z.toolCall.function.arguments,toolKind:z.toolKind})}break;case"tool_result":if("function"in z.toolCall){if(z.toolCall.function.name===o0)break;w("tool.result",{messageId:x(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,success:z.result.success,summary:z.result.metadata?.summary,output:d$(u$(z.toolCall.function.name,z.result)),metadata:Z1(z.result.metadata)})}break;case"tool_progress":if("function"in z.toolCall){if(z.toolCall.function.name===o0)break;w("tool.progress",{messageId:x(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,...z.update})}break;case"token_usage":w("token.usage",{...z.usage});break;case"turn_start":w("turn.started",{turn:z.turn,maxTurns:z.maxTurns});break;case"provider_retry":w("provider.retry",{phase:z.phase,attempt:z.attempt,maxRetries:z.maxRetries,reason:z.reason,statusCode:z.statusCode,delayMs:z.delayMs,nextRetryAt:z.nextRetryAt});break;case"mcp_catalog_changed":w("mcp.catalog.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_content_changed":w("mcp.content.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,contentKind:z.contentKind,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_resource_updated":w("mcp.resource.updated",{messageId:x(),revision:z.revision,serverName:z.serverName,uri:z.uri});break;case"mcp_connection_changed":w("mcp.connection.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,phase:z.phase,reason:z.reason,attempt:z.attempt,maxAttempts:z.maxAttempts,nextRetryAt:z.nextRetryAt,error:z.error});break;case"mcp_log":w("mcp.log",{messageId:x(),revision:z.revision,serverName:z.serverName,level:z.level,logger:z.logger,message:z.message,projectedBytes:z.projectedBytes,dataSha256:z.dataSha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted,timestamp:z.timestamp,synthetic:z.synthetic});break;case"mcp_instructions_changed":w("mcp.instructions.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,action:z.action,reason:z.reason,text:z.text,sourceBytes:z.sourceBytes,projectedBytes:z.projectedBytes,sha256:z.sha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted});break;case"mcp_task_changed":w("mcp.task.changed",{messageId:x(),revision:z.revision,taskId:z.taskId,serverName:z.serverName,toolName:z.toolName,status:z.status,statusMessage:z.statusMessage,createdAt:z.createdAt,updatedAt:z.updatedAt,completedAt:z.completedAt,hasResult:z.hasResult,error:z.error});break;case"project_rules_loaded":w("project.rules.loaded",{messageId:x(),files:z.files,triggerPaths:z.triggerPaths,blockedWrite:z.blockedWrite});break;case"steering_applied":w("steering.applied",{runId:W,messageIds:z.messageIds,count:z.count,recovered:z.recovered,delivery:z.delivery,queued:m.getPendingSteeringCount()});break;case"follow_up_started":{if(T)w("message.complete",{messageId:T}),T=void 0;for(let K of z.messages){if(!K.recovered||K.persisted)continue;w("message.created",{messageId:K.id,role:"user",content:p$(K.content),recovered:!0})}w("follow_up.started",{runId:W,queued:z.queued,recovered:z.recovered}),x();break}case"goal_updated":w("goal.updated",{goal:z.goal});break;case"goal_continuation_started":w("goal.continuation.started",{goal:z.goal,continuation:z.continuation}),x();break;case"compaction":w(z.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":w("model.fallback",{});break;case"task_update":w("task.updated",{tasks:z.tasks});break;default:break}},Q=await m$(c.chatStream(J,S0,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),N);if(!Q.success)throw Error(Q.error?.message??"Agent run failed");for(let z=0;z<20;z++){let K=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,m.getPendingSteeringCount()===0){if(!K)break;continue}if(X.signal.aborted)break;if(Q=await m$(c.chatStream("",S0,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),N),!Q.success)throw Error(Q.error?.message??"Agent follow-up failed")}if(O.messages=[...S0.messages],O.updatedAt=new Date,await y0(O),X.signal.aborted||$.status==="cancelled"){await a(),w("session.status",{status:"idle"});return}if(T)w("message.complete",{messageId:T});w("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),w("session.completed",{runId:W,outputTruncated:Q.metadata?.outputTruncated??!1}),w("session.status",{status:"idle"})}catch(m){if(C&&G.preparedInputTurn)await C.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||$.status==="cancelled"){w$($,"runtime-abort"),await a(),w("session.status",{status:"idle"});return}await y0(O).catch(()=>{return}),P.error("[SessionRoutes] Agent execution error:",m),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=B$(m);if(!O.taskFailure){let Q0=C?await C.setTaskStatus("failed",m).catch(()=>{return}):await j.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(Q0)G$(O,Q0)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,w("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),w("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let m=d0.getStats();w("task.status",{taskStatus:O.taskStatus,...O.taskStatusReason?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure?{taskFailure:O.taskFailure}:{},...O.taskStartedAt?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskDiffStat?{taskDiffStat:O.taskDiffStat}:{},taskQueueDepth:m.queued,taskConcurrencyLimit:m.maxConcurrent,taskInFlight:m.inFlight,updatedAt:new Date().toISOString()})}if(await c?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime(O,C).catch((m)=>{P.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,m)});u4($)}}async function z1($,O,J){P.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),P.info(`[SessionRoutes] Active runs: ${M0.size}`);for(let[G,X]of M0.entries())if(P.info(`[SessionRoutes] Checking run ${G}: sessionId=${X.sessionId}, projectPath=${X.projectPath}, pendingPermission=${X.pendingPermission?.permissionId}`),X.sessionId===$.sessionId&&X.projectPath===$.projectPath&&X.pendingPermission?.permissionId===O){if(X.pendingPermission.details.interactionRequestId)await P0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),P.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await P0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return P.error(`[SessionRoutes] Permission not found: ${O}`),!1;await P0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=l.get(f($));if(!Y){let G=await j.findSessionMetadata($.sessionId,$.projectPath);if(!G)return!1;let[X,V]=await Promise.all([j.loadSession($.sessionId,$.projectPath),j.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=x$(G,X,V),l.set(f($),Y)}else await y0(Y);if(b.publish($,"interaction.resolved",{requestId:O}),L$)L$(Y).catch((G)=>{P.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,G)});return!0}var l$=u("Service"),o4=F.Object({approved:F.Boolean(),remember:F.Optional(F.Boolean()),scope:F.Optional(Z0(["once","session","project"])),targetMode:F.Optional(Z0(["default","autoEdit","plan","yolo"])),feedback:F.Optional(F.String({maxLength:4000})),answers:F.Optional(F.Record(F.String({maxLength:80}),F.Union([F.String({maxLength:4000}),F.Array(F.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:F.Optional(F.Object({action:Z0(["accept","decline","cancel"]),content:F.Optional(F.Record(F.String(),F.Union([F.String({maxLength:4000}),F.Number(),F.Boolean(),F.Array(F.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),Q1=()=>{let $=new a4;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");l$.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let G=await O.req.json(),X=S(o4,G);if(!X.success)throw new _("Invalid permission response format");let{approved:V,remember:W,scope:H,targetMode:q,feedback:T,answers:C,elicitation:c}=X.data;if(!Z)throw new _("sessionId query parameter is required");let s=await J0(Z,Y);if(!await z1(s,J,{approved:V,reason:T,scope:H,targetMode:q,feedback:T,answers:C,elicitation:c}))throw new I("Permission request",J);return l$.info(`[PermissionRoutes] Permission ${J} ${V?"approved":"denied"}`),O.json({success:!0,approved:V,remember:W})}catch(G){if(l$.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof _||G instanceof K0||G instanceof I||G instanceof t)throw G;throw G}}),$};import x1 from"node:path";import{Hono as n4}from"hono";var t4=F.Object({projectPath:F.String({minLength:1}),enabled:F.Boolean(),scope:F.Optional(Z0(["local","project","global"]))}),s4=F.Object({projectPath:F.String({minLength:1})}),r4=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),trust:F.Literal(!0),ref:F.Optional(F.String({minLength:1}))}),e4=F.Object({projectPath:F.String({minLength:1}),trust:F.Literal(!0)}),$2=F.Object({projectPath:F.String({minLength:1}),confirm:F.Literal(!0)}),O2=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),ref:F.Optional(F.String({minLength:1}))}),G1=F.Object({projectPath:F.String({minLength:1}),confirm:F.Optional(F.Literal(!0))}),J2=F.Object({projectPath:F.String({minLength:1}),scope:F.Optional(Z0(["local","project","global"])),policy:F.Object({restrictToAllowedSources:F.Boolean(),requireGitCommitSha:F.Boolean(),allowedGitHosts:F.Array(F.String()),allowedMarketplaces:F.Array(F.String()),allowedLocalRoots:F.Array(F.String())})});function U0($){if(!$||!x1.isAbsolute($))throw new _("projectPath must be absolute");return x1.resolve($)}async function X1($){let[O,J]=await Promise.all([x0($),J$.getInstance().loadWorkspacePluginSettingsResolution($)]);return O.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((Y,G)=>Y+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":J.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:J.settings[Z.manifest.name]?.layers??{}}))}async function Z2(){let $=K1(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:G})=>({name:Y.name,description:G.description??G.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:G.plugins.map((X)=>{let V=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:V!==void 0,installedVersion:V?.version}})}))}function n0($,O){if(!$.success)throw new _($.error??O)}var L1=()=>{let $=new n4;return $.get("/",async(O)=>{let J=U0(O.req.query("projectPath"));return O.json(await X1(J))}),$.post("/refresh",async(O)=>{let J=S(s4,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=U0(J.data.projectPath),Y=await N1(Z);return O.json({plugins:await X1(Z),errors:Y.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),$.get("/catalog",async(O)=>{return U0(O.req.query("projectPath")),O.json(await Z2())}),$.get("/policy",async(O)=>{let J=U0(O.req.query("projectPath")),Z=await J$.getInstance().loadWorkspacePluginSourcePolicy(J);return O.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),$.post("/policy",async(O)=>{let J=S(J2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=U0(J.data.projectPath),Y=await W1(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=S(r4,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=U0(J.data.projectPath),{result:Y}=await F1(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return n0(Y,"Plugin installation failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),$.post("/marketplaces",async(O)=>{let J=S(O2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=U0(J.data.projectPath),Y=await _1(Z,J.data.source,J.data.ref);return n0(Y,"Marketplace installation failed"),O.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),$.post("/marketplaces/:name/refresh",async(O)=>{let J=S(G1,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await H1(U0(J.data.projectPath),O.req.param("name"));return n0(Z,"Marketplace refresh failed"),O.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),$.post("/marketplaces/:name/remove",async(O)=>{let J=S(G1,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");U0(J.data.projectPath);let Z=await B1(O.req.param("name"),!0);return n0(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=S(e4,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=U0(J.data.projectPath),{result:Y}=await U1(Z,O.req.param("name"),{trusted:J.data.trust});return n0(Y,"Plugin update failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),$.post("/:name/uninstall",async(O)=>{let J=S($2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=U0(J.data.projectPath),{result:Y}=await D1(Z,O.req.param("name"),J.data.confirm);return n0(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=S(t4,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=U0(J.data.projectPath),Y=O.req.param("name"),X=(await x0(Z)).plugins.get(Y);if(!X)throw new I("Plugin",Y);if(X.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let V=await V1(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(V)}),$};import{Hono as G2}from"hono";import{execFile as Y2}from"node:child_process";import z2 from"node:path";var a$="__BLADE_DIRECTORY_PICKER_CANCELLED__",Q2=900000;function x2($,O){return new Promise((J)=>{Y2($,[...O],{timeout:Q2,maxBuffer:65536,windowsHide:!0},(Z,Y,G)=>{let X=Z?.code;J({stdout:Y,stderr:G,exitCode:typeof X==="number"?X:Z?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function c$($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===a$)return{cancelled:!0};if(!z2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function i$($){return $.exitCode!==0||Boolean($.errorCode)}class w1{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??x2}pick(){if(this.activeSelection)return this.activeSelection;let $=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=$,$}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let $=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${a$}"`,"end try"].join(`
|
|
3
|
-
`),O=await this.runCommand("osascript",["-e",$]);if(i$(O))throw Error("Unable to open the macOS folder picker");return c$(O.stdout)}async pickOnWindows(){let $=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${a$}")`,"}"].join("; "),O=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",$]);if(i$(O))throw Error("Unable to open the Windows folder picker");return c$(O.stdout)}async pickOnLinux(){let $=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let O of $){let J=await this.runCommand(O.command,O.args);if(J.errorCode==="ENOENT")continue;if(J.exitCode===1&&!J.stdout.trim()&&!J.stderr.trim())return{cancelled:!0};if(i$(J))throw Error("Unable to open the Linux folder picker");return c$(J.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var A1=new w1;var X2=F.Object({path:F.String({minLength:1})});function K2($){if(!$)return!1;if($==="tauri://localhost"||$==="http://tauri.localhost")return!0;try{let O=new URL($).hostname;return O==="localhost"||O==="127.0.0.1"||O==="::1"||O==="[::1]"}catch{return!1}}var M1=($={})=>{let O=new G2,J=$.pickDirectory??(()=>A1.pick()),Z=$.allowDirectoryPickerRequest??K2;return O.get("/",async(Y)=>{return Y.json(await E$.list(v()))}),O.post("/",async(Y)=>{let G;try{G=await Y.req.json()}catch{throw new _("A valid JSON body is required")}let X=S(X2,G);if(!X.success)throw new _("A project path is required");try{let V=await E$.bind(X.data.path,v());return Y.json(V,201)}catch(V){throw new _(V instanceof Error?V.message:"Failed to bind project")}}),O.post("/pick",async(Y)=>{if(!Z(Y.req.header("Origin")))throw new t("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await J())}catch(G){throw new _(G instanceof Error?G.message:"Failed to select a folder")}}),O.delete("/",async(Y)=>{let G=Y.req.query("path");if(!G)throw new _("A project path is required");try{let X=await E$.unbind(G);return Y.json({success:!0,removed:X})}catch(X){throw new _(X instanceof Error?X.message:"Failed to unbind project")}}),O};import{Hono as V2}from"hono";var E1=u("Service"),C1=()=>{let $=new V2;return $.get("/",async(O)=>{try{let J=await T1();return O.json(J)}catch(J){return E1.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await b1(J);return O.json(Z)}catch(Z){return E1.error("[ProviderRoutes] Failed to list models:",Z),O.json([])}}),$.put("/:provider/credential",async(O)=>{let J=O.req.param("provider"),Z=await O.req.json();if(!Z.apiKey?.trim())throw new _("apiKey is required");return await f0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await f0().clearCredential(O.req.param("provider")),O.json({success:!0})}),$.put("/:provider",async(O)=>{let J=O.req.param("provider"),Z=o(),Y=Z?.modelProviders[J];if(!Z||!Y)throw new I("Model provider",J);let G=await O.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new _("name, baseUrl and wireApi are required");let X="apiKeyEnv"in G?G.apiKeyEnv?.trim():Y.apiKeyEnv,V={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...X?{apiKeyEnv:X}:{}},W=f0(),H=G.apiKey?.trim()?await W.credentials.read(J):void 0;if(G.apiKey?.trim())await W.setApiKey(J,G.apiKey.trim());try{return await V0().updateModelProvider(J,V),O.json({success:!0})}catch(q){if(G.apiKey?.trim())if(H)await W.credentials.modify(J,async()=>H);else await W.credentials.delete(J);if(q instanceof Error&&(q.message.includes("modelProviders.")||q.message.includes("built-in provider")))throw new _(q.message);throw q}}),$.delete("/:provider",async(O)=>{let J=O.req.param("provider");if(!o()?.modelProviders[J])throw new I("Model provider",J);let Y=O.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("removeModels must be true or false");try{let G=await V0().removeModelProvider(J,{removeModels:Y==="true"});return O.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new R(G.message);throw G}}),$.post("/:provider/probe",async(O)=>{let J=O.req.param("provider"),Z=o();if(!Z?.modelProviders[J])throw new I("Model provider",J);let Y=await O.req.json().catch(()=>({})),G=Z.models.filter((V)=>V.provider===J),X=Y.modelId?G.find((V)=>V.id===Y.modelId):G[0];if(!X)throw new _(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return O.json(await q1(X,Z))}),$};import{Hono as N2}from"hono";var W2=u("Service"),I1=($,O)=>{let J=new N2;return J.onError((Z,Y)=>{if(Z instanceof t)return Y.json(Z.toObject(),Z.statusCode);return W2.error("[ScheduleRoutes] Unhandled route error:",Z),Y.json(new d("Schedule request failed").toObject(),500)}),J.get("/",async(Z)=>{let Y=await $.list();return Z.json(k1.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let G=S(R1,Y);if(!G.success)throw new _("Invalid schedule request");let X=G.data.projectPath||Z.get("directory")||v();try{let V=await $.create({...G.data,projectPath:X});return Z.json(m0.parse(V),201)}catch(V){throw new _(V instanceof Error?V.message:"Failed to create schedule")}}),J.get("/:id",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");return Z.json(m0.parse(Y))}),J.patch("/:id",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let G=S(j1,Y);if(!G.success)throw new _("Invalid schedule update");let{modelId:X,reasoningEffort:V,serviceTier:W,responseVerbosity:H,communicationStyle:q,isolation:T,permissionMode:C,...c}=G.data,s={...X!==void 0?{modelId:X}:{},...V!==void 0?{reasoningEffort:V}:{},...W!==void 0?{serviceTier:W}:{},...H!==void 0?{responseVerbosity:H}:{},...q!==void 0?{communicationStyle:q}:{},...T!==void 0?{isolation:T}:{},...C!==void 0?{permissionMode:C}:{}};try{let w=await $.update(Z.req.param("id"),{...c,...Object.keys(s).length>0?{dispatch:s}:{}});if(!w)throw new I("Schedule not found");return Z.json(m0.parse(w))}catch(w){if(w instanceof t)throw w;throw new _(w instanceof Error?w.message:"Failed to update schedule")}}),J.delete("/:id",async(Z)=>{if(!await $.remove(Z.req.param("id")))throw new I("Schedule not found");return Z.json({ok:!0})}),J.post("/:id/enable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!0);if(!Y)throw new I("Schedule not found");return Z.json(m0.parse(Y))}),J.post("/:id/disable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!1);if(!Y)throw new I("Schedule not found");return Z.json(m0.parse(Y))}),J.post("/:id/run",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");if(!O)throw new d("Scheduler is not running in this process");await O.fire(Y,new Date,{manual:!0});let G=await $.get(Y.id);return Z.json(m0.parse(G??Y),202)}),J};import*as j0 from"node:fs/promises";import{homedir as y1}from"node:os";import*as D0 from"node:path";import{Hono as F2}from"hono";var h0=u("Service"),S1=D0.join(y1(),".blade","skills"),o$=D0.join(y1(),".blade","skills-config.json");async function m1(){try{let $=await j0.readFile(o$,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function U2($){await j0.mkdir(D0.dirname(o$),{recursive:!0}),await j0.writeFile(o$,JSON.stringify($,null,2))}async function D2($,O){let J=await m1();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await U2(J)}var R0=null,_2=300000,H2=6;async function B2(){if(R0&&Date.now()-R0.timestamp<_2)return R0.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok){if(h0.warn(`GitHub API returned ${$.status}`),R0)return R0.data;throw Error(`GitHub skills catalog returned ${$.status}`)}let J=(await $.json()).filter((X)=>X.type==="dir"),Z=Array(J.length),Y=0,G=Math.min(H2,J.length);return await Promise.all(Array.from({length:G},async()=>{while(Y<J.length){let X=Y++,V=J[X];if(!V)continue;let W=`Official ${V.name} skill`;try{let H=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(H.ok){let T=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)W=T[1].trim().slice(0,100)}}catch{}Z[X]={name:V.name,description:W,tag:"Official",author:"Anthropic"}}})),R0={data:Z,timestamp:Date.now()},Z}catch($){if(h0.warn("Failed to fetch skills catalog from GitHub:",$),R0)return R0.data;throw $}}var h1=()=>{let $=new F2;return $.get("/",async(O)=>{try{let J=O.get("directory")||v(),Y=(await x0(J)).skills.getAll(),G=await m1(),X=Y.map((V)=>({id:V.name,name:V.name,enabled:!G.disabled.includes(V.name),description:V.description||"",version:V.version||"1.0.0",provider:"Local",location:V.source==="builtin"?"Built-in":V.basePath,removable:V.source==="user"&&D0.dirname(D0.resolve(V.basePath))===D0.resolve(S1),capabilities:["prompts"],allowedTools:V.allowedTools||[]}));return O.json(X)}catch(J){return h0.error("[SkillsRoutes] Failed to get skills:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills"},500)}}),$.post("/:name/toggle",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();return await D2(J,Z.enabled),O.json({success:!0,enabled:Z.enabled})}catch(J){return h0.error("[SkillsRoutes] Failed to toggle skill:",J),O.json({success:!1,error:J.message},500)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name"),Z=O.get("directory")||v(),Y=(await x0(Z)).skills,G=Y.get(J);if(!G)return O.json({success:!1,error:"Skill not found"},404);let X=D0.resolve(G.basePath),V=D0.resolve(S1);if(G.source!=="user"||D0.dirname(X)!==V)return O.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await j0.rm(X,{recursive:!0,force:!0}),await Y.refresh(),Y$(Z),await Z$(Z),O.json({success:!0})}catch(J){return h0.error("[SkillsRoutes] Failed to uninstall skill:",J),O.json({success:!1,error:J.message},500)}}),$.post("/install",async(O)=>{try{let J=await O.req.json(),Z=f1(),Y=O.get("directory")||v(),G=P1({cwd:Y}),X=!1;if(J.source==="catalog"&&J.name){if(X=await Z.installOfficialSkill(J.name),!X)return O.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(X=await Z.installFromRepo(J.url,J.name),!X)return O.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(J.source==="local"&&J.path){if(X=await Z.installFromLocal(J.path,J.name),!X)return O.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return O.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await G.refresh(),Y$(Y),await Z$(Y),O.json({success:!0})}catch(J){return h0.error("[SkillsRoutes] Failed to install skill:",J),O.json({success:!1,error:J.message},500)}}),$.get("/catalog",async(O)=>{try{let J=await B2();return O.json(J)}catch(J){return h0.error("[SkillsRoutes] Failed to get catalog:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills catalog"},502)}}),$};import{execSync as L2}from"node:child_process";import{readdir as w2}from"node:fs/promises";import q$ from"node:path";import A2 from"fast-glob";import{Hono as M2}from"hono";var X$=u("Service"),E2=($)=>{try{return L2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},q2=[...t0.map(($)=>`${$}/**`),...t0,...t0.map(($)=>`**/${$}/**`),...t0.map(($)=>`**/${$}`),...n$.map(($)=>`**/${$}`)],T2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),p1=()=>{let $=new M2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||v();await x0(Z);let Y=g1(J,Z).filter((G)=>!T2.has(G.command));return O.json(Y)}catch(J){return X$.error("[SuggestionsRoutes] Failed to get command suggestions:",J),O.json([])}}),$.get("/files",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||v(),Y=Math.min(Number(O.req.query("limit"))||100,1000),G=O.req.query("type")==="file",V=(await A2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:q2})).map((q)=>q.replace(/\\/g,"/"));if(!J)return O.json(V.slice(0,Y));let W=J.toLowerCase(),H=V.filter((q)=>q.toLowerCase().includes(W)).slice(0,Y);return O.json(H)}catch(J){return X$.error("[SuggestionsRoutes] Failed to get file suggestions:",J),O.json([])}}),$.get("/files/tree",async(O)=>{try{let J=O.get("directory")||v(),Z=O.req.query("path")||"",Y=Z?q$.join(J,Z):J,X=(await w2(Y,{withFileTypes:!0})).map((H)=>({name:H.name,path:Z?`${Z}/${H.name}`:H.name,type:H.isDirectory()?"dir":"file"}));X.sort((H,q)=>{if(H.type!==q.type)return H.type==="dir"?-1:1;return H.name.localeCompare(q.name)});let V=new Set(t0),W=X.filter((H)=>{let q=H.name;if(q.startsWith("."))return!1;if(V.has(q))return!1;for(let T of n$)if(q.match(new RegExp(T.replace("*",".*"))))return!1;return!0});return O.json(W)}catch(J){return X$.error("[SuggestionsRoutes] Failed to get file tree:",J),O.json([])}}),$.get("/files/content",async(O)=>{try{let J=O.req.query("path");if(!J)return O.json({error:"Missing file path"},400);let Z=O.get("directory")||v(),Y=q$.resolve(Z,J),G=q$.relative(Z,Y);if(G.startsWith("..")||q$.isAbsolute(G))return O.json({error:"Invalid file path"},400);let X=v1(),V=await X.stat(Y);if(!V?.isFile)return O.json({error:"File not found"},404);let W=200000,H=await X.readTextFile(Y),q=H.length>W;return O.json({path:J,content:q?H.slice(0,W):H,truncated:q,size:V.size})}catch(J){return X$.error("[SuggestionsRoutes] Failed to get file content:",J),O.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(O)=>{try{let J=O.get("directory")||v(),Z=E2(J);return O.json({branch:Z})}catch(J){return X$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as b2}from"hono";var K$=u("Service"),i1=($)=>{let O=new b2;return O.onError((J,Z)=>{if(J instanceof t)return Z.json(J.toObject(),J.statusCode);return K$.error("[TaskRoutes] Unhandled route error:",J),Z.json(new d("Failed to dispatch task").toObject(),500)}),O.post("/",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=S(l1,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((X,V)=>X+(typeof V.content==="string"?Buffer.byteLength(V.content):0),0)>A$)throw new _("Task attachments exceed the 5 MiB limit");try{let X=await $.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,sourceProjectPath:Y.data.projectPath||J.get("directory")||v(),isolation:Y.data.isolation,permissionMode:Y.data.permissionMode,modelId:Y.data.modelId,reasoningEffort:Y.data.reasoningEffort,serviceTier:Y.data.serviceTier,responseVerbosity:Y.data.responseVerbosity,communicationStyle:Y.data.communicationStyle,attachments:Y.data.attachments,outputSchema:Y.data.outputSchema});return J.json(t$.parse(X),202)}catch(X){if(X instanceof _||X instanceof R||X instanceof p0)throw X;throw K$.error("[TaskRoutes] Failed to dispatch task:",X),new d("Failed to dispatch task")}}),O.post("/:sessionId/retry",async(J)=>{try{let Z=await $.retryTask(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(t$.parse(Z),202)}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof R||Z instanceof p0)throw Z;throw K$.error("[TaskRoutes] Failed to retry task:",Z),new d("Failed to retry task")}}),O.get("/:sessionId/diff",async(J)=>{try{let Z=await $.getTaskDiff(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(u1.parse(Z))}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof R)throw Z;throw K$.error("[TaskRoutes] Failed to load task diff:",Z),new d("Failed to load task diff")}}),O.post("/:sessionId/delivery",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=S(c1,Z);if(!Y.success)throw new _("Invalid task delivery request");try{let G=await $.deliverTask(J.req.param("sessionId"),Y.data.action,J.req.query("projectPath"));return J.json(d1.parse(G))}catch(G){if(G instanceof _||G instanceof I||G instanceof R)throw G;throw K$.error("[TaskRoutes] Failed to deliver task:",G),new d("Failed to deliver task")}}),O};import{Hono as C2}from"hono";var k0=u("Service"),s0=new Map,a1=2097152,o1=65536;function n1(){return typeof globalThis.Bun<"u"}async function R2($,O,J){if(n1()){let{spawn:G}=await import("bun-pty"),X=G($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:X.pid,write:(V)=>X.write(V),resize:(V,W)=>X.resize(V,W),kill:()=>X.kill(),onData:(V)=>X.onData(V),onExit:(V)=>X.onExit(V)}}let Y=(await import("node-pty")).spawn($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env,cols:80,rows:24});return{pid:Y.pid,write:(G)=>Y.write(G),resize:(G,X)=>Y.resize(G,X),kill:()=>Y.kill(),onData:(G)=>{Y.onData(G)},onExit:(G)=>{Y.onExit(G)}}}var e$=void 0,r$;if(n1())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();r$=O.upgradeWebSocket,e$=O.websocket}catch($){k0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function t1($,O){let J=`term-${Date.now()}`;k0.info(`[Terminal] New connection: ${J}, cwd: ${$}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=Z.endsWith("sh")?["-l"]:[],G=await R2(Z,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),X={id:J,process:G,cwd:$,buffer:"",subscribers:new Set};if(s0.set(J,X),X.subscribers.add(O),G.onData((V)=>{let W=!1;for(let H of X.subscribers)try{H.send(V),W=!0}catch{X.subscribers.delete(H)}if(W)return;if(X.buffer+=V,X.buffer.length>a1)X.buffer=X.buffer.slice(-a1)}),G.onExit(({exitCode:V})=>{k0.info(`[Terminal] Process exited: ${J}, code: ${V}`);for(let W of X.subscribers)try{W.close()}catch{}s0.delete(J)}),X.buffer){let V=X.buffer;X.buffer="";for(let W=0;W<V.length;W+=o1)O.send(V.slice(W,W+o1))}return{session:X,cleanup:()=>{if(k0.info(`[Terminal] Connection closed: ${J}`),X.subscribers.delete(O),X.subscribers.size===0){try{X.process.kill()}catch{}s0.delete(J)}}}}function s1($,O){$.on("connection",async(J,Z)=>{let Y=new URL(Z.url||"/",`http://${Z.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){J.close();return}let G=Y.searchParams.get("cwd")||O()||v();try{let{session:X,cleanup:V}=await t1(G,{send:(W)=>J.send(W),close:()=>J.close()});J.on("message",(W)=>{try{X.process.write(String(W))}catch(H){k0.error("[Terminal] Failed to write to PTY:",H)}}),J.on("close",V),J.on("error",V)}catch(X){k0.error("[Terminal] Failed to spawn PTY:",X),J.close()}})}var r1=()=>{let $=new C2;if($.get("/status",(O)=>{let J=Array.from(s0.values()).map((Z)=>({id:Z.id,cwd:Z.cwd}));return O.json({active:J.length,terminals:J})}),$.post("/kill/:terminalId",(O)=>{let J=O.req.param("terminalId"),Z=s0.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return s0.delete(J),O.json({success:!0})}return O.json({success:!1,error:"Terminal not found"},404)}),r$)$.get("/ws",r$((O)=>{let J=O.req.query("cwd")||O.get("directory")||v(),Z;return{async onOpen(Y,G){try{Z=await t1(J,{send:(X)=>G.send(X),close:()=>G.close()})}catch(X){k0.error("[Terminal] Failed to spawn PTY:",X),G.close()}},onMessage(Y){if(!Z)return;try{Z.session.process.write(String(Y.data))}catch(G){k0.error("[Terminal] Failed to write to PTY:",G)}},onClose(){Z?.cleanup()}}}));else $.get("/ws",(O)=>{return O.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};import j2 from"node:path";import{Hono as k2}from"hono";var I2=F.Object({projectPath:F.String({minLength:1}),action:Z0(["trust","revoke"])});function e1($){if(!j2.isAbsolute($))throw new _("projectPath must be absolute")}var O4=()=>{let $=new k2;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return e1(J),O.json(await $O.getInstance().getStatus(J))}),$.post("/",async(O)=>{let J=S(I2,await O.req.json());if(!J.success)throw new _("Invalid workspace trust request");let{projectPath:Z,action:Y}=J.data;e1(Z);let G=$O.getInstance(),X=Y==="trust"?await G.trust(Z):await G.revoke(Z);return await $4(),O.json({...X,reloadRequired:X.sensitiveSources>0})}),$};var z0=u("Service"),ZO=[],V$,r0,J4=new Map,Z4=new Map,l2=new Set([".css",".html",".js",".json",".svg"]),c2=1024;function i2($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...G]=Z.trim().toLowerCase().split(";"),X=G.find((W)=>W.trim().startsWith("q=")),V=X?Number(X.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(V)?Math.max(0,Math.min(1,V)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function a2($){return["br","gzip"].map((J)=>({encoding:J,quality:i2($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function o2($){let O=J4.get($);if(O)return O;let J=N$($);return J4.set($,J),J}function n2($,O,J){let Z=`${J}:${$}`,Y=Z4.get(Z);if(Y)return Y;let G=J==="br"?h2(O,{params:{[g2.BROTLI_PARAM_QUALITY]:5}}):v2(O,{level:6});return Z4.set(Z,G),G}function t2(){let $=P2(m2(import.meta.url)),O=[I0($,"web"),I0(v(),"dist/web"),I0(v(),"packages/cli/dist/web")];for(let J of O){let Z=I0(J,"index.html");if(JO(Z)){if(N$(Z,"utf-8").includes("/assets/"))return z0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function s2(){let $=new p2;$.onError((Z,Y)=>{if(z0.error("[Server] Request error:",Z),Z instanceof t)return Y.json(Z.toObject(),Z.statusCode);let G=Z instanceof Error?Z.message:String(Z);return Y.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),$.use(async(Z,Y)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Y();let X=Z.req.path;if(X==="/"||X==="/favicon.svg"||X.startsWith("/assets/")||X.endsWith(".html")||X.endsWith(".js")||X.endsWith(".css"))return Y();let V=Z.req.header("Authorization");if(!V?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let W=Buffer.from(V.slice(6),"base64").toString(),[H,q]=W.split(":"),T=process.env.BLADE_SERVER_USERNAME??"blade";if(H!==T||q!==G)return Z.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Y()}),$.use(async(Z,Y)=>{let G=Z.req.path==="/health"||Z.req.path==="/global/health"||Z.req.path.startsWith("/assets/");if(!G)z0.debug(`[Server] ${Z.req.method} ${Z.req.path}`);let X=Date.now();if(await Y(),!G){let V=Date.now()-X;z0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${V}ms)`)}}),$.use(u2({origin(Z){if(!Z)return;if(Z.startsWith("http://localhost:"))return Z;if(Z.startsWith("http://127.0.0.1:"))return Z;if(Z==="tauri://localhost"||Z==="http://tauri.localhost")return Z;if(ZO.includes(Z))return Z;return}})),$.use(async(Z,Y)=>{let G=Z.req.query("directory")||Z.req.header("x-blade-directory")||v();try{G=decodeURIComponent(G)}catch{}return Z.set("directory",G),Y()});let O=Y1();V$=O.recoverQueuedTasks,r0=new R$({dispatch:(Z)=>O.dispatchTask(Z),store:OO}),$.route("/global",HO()),$.route("/events",DO()),$.route("/sessions",O.app),$.route("/tasks",i1(O)),$.route("/schedules",I1(OO,r0)),$.route("/configs",UO()),$.route("/permissions",Q1()),$.route("/plugins",L1()),$.route("/hooks",EO()),$.route("/workspace-trust",O4()),$.route("/providers",C1()),$.route("/models",SO()),$.route("/projects",M1()),$.route("/suggestions",p1()),$.route("/terminal",r1()),$.route("/mcp",bO()),$.route("/skills",h1()),$.get("/health",(Z)=>{return Z.json({healthy:!0,version:u0()})});let J=t2();if(J)z0.info(`[Server] Serving static files from ${J}`),$.get("/favicon.svg",()=>{let Z=I0(J,"favicon.svg");if(!JO(Z))return new Response(null,{status:404});return new Response(N$(Z),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),$.get("/assets/*",(Z)=>{let Y=I0(J,Z.req.path);if(!JO(Y))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Z.req.path}`}},404);let G=o2(Y),X=y2(Y).toLowerCase(),W={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[X]||"application/octet-stream",H=l2.has(X)&&G.byteLength>=c2?a2(Z.req.header("Accept-Encoding")):void 0,q=H?n2(Y,G,H):G;return new Response(new Uint8Array(q),{headers:{"Content-Type":W,"Content-Length":String(q.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...H?{"Content-Encoding":H}:{}}})}),$.get("/",(Z)=>{let Y=I0(J,"index.html"),G=N$(Y,"utf-8");return Z.html(G,200,{"Cache-Control":"no-cache"})}),$.get("*",(Z)=>{let Y=Z.req.path;if(Y.includes("."))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Y}`}},404);let G=I0(J,"index.html"),X=N$(G,"utf-8");return Z.html(X,200,{"Cache-Control":"no-cache"})});else z0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(Z)=>{return Z.json({message:"Blade API Server",version:u0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),$.all("*",(Z)=>{return Z.json({error:{code:"NOT_FOUND",message:`Route not found: ${Z.req.path}`}},404)});return $}function r2(){let $=f2(),O=[];for(let J of Object.keys($)){let Z=$[J];if(!Z)continue;for(let Y of Z){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;O.push(Y.address)}}return O}function Y4(){return typeof globalThis.Bun<"u"}function z4($,O){let J=globalThis.Bun,Z=(G)=>{try{return J.serve({hostname:O.hostname,port:G,fetch:$.fetch,idleTimeout:0,websocket:e$})}catch(X){z0.error("Failed to start Bun server:",X);return}},Y=O.port===0?Z(4096)??Z(0):Z(O.port);if(!Y)throw Error(`Failed to start Bun server on port ${O.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function e2($,O){return new Promise((J,Z)=>{let Y=S2(async(H,q)=>{let T=new URL(H.url||"/",`http://${H.headers.host}`),C=new Headers;for(let[w,a]of Object.entries(H.headers))if(a)if(Array.isArray(a))for(let m of a)C.append(w,m);else C.set(w,a);let c;if(H.method!=="GET"&&H.method!=="HEAD")c=(await new Promise((a)=>{let m=[];H.on("data",(O0)=>m.push(O0)),H.on("end",()=>a(Buffer.concat(m)))})).toString();let s=new Request(T.toString(),{method:H.method,headers:C,body:c});try{let w=await $.fetch(s);if(q.statusCode=w.status,w.headers.forEach((a,m)=>{q.setHeader(m,a)}),w.body){let a=w.body.getReader(),m=async()=>{let{done:O0,value:Q0}=await a.read();if(O0){q.end();return}return q.write(Q0),m()};await m()}else{let a=await w.text();q.end(a)}}catch(w){z0.error("[Server] Node request error:",w),q.statusCode=500,q.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new d2({noServer:!0}),X=v();s1(G,()=>X),Y.on("upgrade",(H,q,T)=>{if(new URL(H.url||"/",`http://${H.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(H,q,T,(c)=>{G.emit("connection",c,H)});else q.destroy()});let V=(H)=>{return new Promise((q,T)=>{Y.once("error",(C)=>{if(C.code==="EADDRINUSE")T(C);else T(C)}),Y.listen(H,O.hostname,()=>{let C=Y.address();if(C&&typeof C==="object")q(C.port);else q(H)})})};(async()=>{let H;if(O.port===0)try{H=await V(4096)}catch{H=await V(0)}else H=await V(O.port);let q=new URL(`http://${O.hostname==="0.0.0.0"?"localhost":O.hostname}:${H}`);J({url:q,port:H,hostname:O.hostname,stop:async()=>{return new Promise((T)=>{G.close(()=>{Y.close(()=>T())})})}})})().catch(Z)})}var Q4;((Z6)=>{let $,O;function J(){if(!O)O=s2();return O}Z6.getApp=J;function Z(X){ZO=X.cors??[];let V=J();if(Y4())$=z4(V,X),z0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let W=$;return V$?.().catch((H)=>{z0.warn("[Server] Failed to recover queued tasks:",H)}),r0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)r0?.stop(),await $.stop(),$=void 0,O=void 0,V$=void 0,z0.info("[Server] Blade server stopped")}}}Z6.listen=Z;async function Y(X){ZO=X.cors??[];let V=J();if(Y4())$=z4(V,X),z0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await e2(V,X),z0.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);let W=$;try{await V$?.()}catch(H){z0.warn("[Server] Failed to recover queued tasks:",H)}return r0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)r0?.stop(),await $.stop(),$=void 0,O=void 0,V$=void 0,z0.info("[Server] Blade server stopped")}}}Z6.listenAsync=Y;function G(){return $!==void 0}Z6.isRunning=G})(Q4||={});export{$5 as f,O5 as g,r2 as h,Q4 as i};
|