@seqyuan/annovibe 0.8.140 → 0.8.141
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/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +12 -12
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/agent/runtime/route.js +1 -1
- package/.next/server/app/api/internal/runtime/route.js +1 -1
- package/.next/server/app/api/version/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +1 -1
- package/.next/server/app/login.segments/_full.segment.rsc +1 -1
- package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/page.js +3 -3
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/session-stream/page.js +1 -1
- package/.next/server/app/smoke/session-stream/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/session-stream.html +1 -1
- package/.next/server/app/smoke/session-stream.rsc +4 -4
- package/.next/server/app/smoke/session-stream.segments/_full.segment.rsc +4 -4
- package/.next/server/app/smoke/session-stream.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/smoke/session-stream.segments/smoke/session-stream/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/smoke.html +1 -1
- package/.next/server/app/smoke.rsc +1 -1
- package/.next/server/app/smoke.segments/_full.segment.rsc +1 -1
- package/.next/server/app/smoke.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/smoke.segments/smoke/__PAGE__.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +12 -12
- package/.next/server/chunks/658.js +22 -0
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/preview-props.json +3 -3
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/3824-2ecb57e47009f9c4.js +22 -0
- package/.next/static/chunks/app/{page-b9bbcb2073e77894.js → page-b56ed167d2c7978b.js} +3 -3
- package/.next/static/chunks/app/smoke/session-stream/{page-9c9a9a2aafa69000.js → page-ce422d02fbbe900d.js} +2 -2
- package/package.json +1 -1
- package/.next/server/chunks/7734.js +0 -22
- package/.next/static/chunks/2257-a948751c1a3d4608.js +0 -22
- /package/.next/static/{YRLT_dWnNGA0kvsTREpEW → rPVMly3awjAYAgBD6W0mU}/_buildManifest.js +0 -0
- /package/.next/static/{YRLT_dWnNGA0kvsTREpEW → rPVMly3awjAYAgBD6W0mU}/_ssgManifest.js +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8982],{18416:(e,t,n)=>{Promise.resolve().then(n.bind(n,77593))},77593:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>g});var s=n(95155),o=n(12115),r=n(
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8982],{18416:(e,t,n)=>{Promise.resolve().then(n.bind(n,77593))},77593:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>g});var s=n(95155),o=n(12115),r=n(63824),i=n(99867);let a="session-stream-smoke",d={role:"user",content:"baseline",timestamp:1},l={role:"assistant",content:[{type:"text",text:"remote completion"}],provider:"smoke",model:"smoke-model",timestamp:2},m={role:"assistant",content:[{type:"text",text:"remote progress before conflict"}],provider:"smoke",model:"smoke-model",timestamp:3},c={role:"assistant",content:[],provider:"smoke",model:"smoke-model",stopReason:"error",errorMessage:"stream_read_error",timestamp:2},u={id:a,path:"/tmp/session-stream-smoke.jsonl",cwd:"/tmp/annovibe-session-stream-smoke",created:new Date(0).toISOString(),modified:new Date(0).toISOString(),messageCount:1,firstMessage:"baseline"};function p(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}function h(){let e=(0,r.T)({session:u,newSessionCwd:null}),t=e.messages.filter(e=>"assistant"===e.role).length,n=(0,o.useRef)(0),[a,d]=(0,o.useState)(!1),l=e.messages.filter(e=>"user"===e.role&&"concurrent prompt"===e.content).length,m=e.agentPhase?.kind??"idle";return(0,o.useEffect)(()=>{t<n.current?d(!0):n.current=t},[t]),(0,s.jsxs)("main",{style:{padding:24,fontFamily:"sans-serif"},children:[(0,s.jsx)("h1",{children:"Session stream smoke"}),(0,s.jsx)("div",{"data-smoke-running":e.agentRunning?"true":"false",children:e.agentRunning?"running":"idle"}),(0,s.jsx)("div",{"data-smoke-message-count":e.messages.length,children:e.messages.length}),(0,s.jsx)("div",{"data-smoke-assistant-count":t,children:t}),(0,s.jsx)("div",{"data-smoke-assistant-regressed":a?"true":"false",children:a?"regressed":"stable"}),(0,s.jsx)("div",{"data-smoke-conflict-optimistic-count":l,children:l}),(0,s.jsx)("div",{"data-smoke-error":e.agentError??"none",children:e.agentError??"none"}),(0,s.jsx)("div",{"data-smoke-phase":m,children:m}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remoteStart(),children:"Remote start"}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remoteToolStart(),children:"Remote tool start"}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remoteFinish(),children:"Remote finish"}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remoteFinishWithStaleRead(),children:"Remote finish with stale read"}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remoteFail(),children:"Remote fail"}),(0,s.jsx)("button",{type:"button",onClick:()=>window.__sessionStreamSmoke?.remotePromptError(),children:"Prompt error"}),(0,s.jsx)("button",{type:"button",onClick:()=>{window.__sessionStreamSmoke?.prepareConcurrentPrompt(),e.handleSend("concurrent prompt")},children:"Concurrent prompt"}),(0,s.jsx)("section",{style:{marginTop:24,maxWidth:760},children:e.messages.map((e,t)=>(0,s.jsx)(i.D,{message:e},t))})]})}function g(){let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)(!0);return(0,o.useEffect)(()=>{let e=window.fetch.bind(window),n=window.EventSource,s=!1,o=!1,r=null,i="idle",h=[],g=[d],S=["entry-user"],w=0,f=new Set,k=new Set,y=new TextEncoder;class _{static{this.CONNECTING=0}static{this.OPEN=1}static{this.CLOSED=2}static{this.instances=new Set}constructor(e){this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.withCredentials=!1,this.readyState=1,this.onopen=null,this.onmessage=null,this.onerror=null,this.url=String(e),_.instances.add(this),window.setTimeout(()=>{this.onopen?.call(this,new Event("open")),this.emitRunning()},0)}close(){this.readyState=2,_.instances.delete(this)}addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}emitRunning(){1===this.readyState&&this.url.includes("/api/agent/running/events")&&this.onmessage?.call(this,new MessageEvent("message",{data:JSON.stringify({type:"running",runningSessionIds:s?[a]:[]})}))}}let b=()=>{let e=s?[a]:[];for(let t of f)t(e);for(let e of _.instances)e.emitRunning()},v=(e,t)=>{let n=y.encode(`id: ${e}
|
|
2
2
|
data: ${JSON.stringify(t)}
|
|
3
3
|
|
|
4
4
|
`);for(let e of k)e.enqueue(n)};return window.fetch=async(t,n)=>{let l="string"==typeof t?t:t instanceof URL?t.toString():t.url,c=n?.method??"GET";if(l.includes(`/api/agent/${a}/events`)){let e=null;return new Response(new ReadableStream({start(t){e=t,k.add(t),t.enqueue(y.encode(`data: ${JSON.stringify({type:"connected",sessionId:a})}
|
|
5
5
|
|
|
6
|
-
`))},cancel(){e&&k.delete(e),e=null}}),{headers:{"Content-Type":"text/event-stream"}})}if(l.includes(`/api/sessions/${a}`)){let e=w>0;e&&(w-=1);let t=e?[d]:g,n=e?["entry-user"]:S;return e&&await new Promise(e=>window.setTimeout(e,75)),p({sessionId:a,filePath:u.path,info:u,tree:[],leafId:n[n.length-1]??null,context:{messages:t,entryIds:n,thinkingLevel:"off",model:{provider:"smoke",modelId:"smoke-model"}},totalMessages:t.length,hasMore:!1,agentState:{running:s,state:{isStreaming:"streaming"===i,isCompacting:!1,phase:i,activeTools:h,thinkingLevel:"off",contextUsage:null}}})}if(l.endsWith(`/api/agent/${a}`)&&"GET"===c)return p({running:s,state:{isStreaming:"streaming"===i,isCompacting:!1,phase:i,activeTools:h,thinkingLevel:"off",contextUsage:null}});if(l.endsWith(`/api/agent/${a}/prepare`)&&"POST"===c)return p({ok:!0,sessionId:a});if(l.endsWith(`/api/agent/${a}`)&&"POST"===c){let e=JSON.parse(String(n?.body??"{}"));return("prompt"===e.type&&(r=e),"prompt"===e.type&&o)?(o=!1,g=[...g,m],S=[...S,"entry-assistant-conflict"],v("smoke-epoch:conflict",{type:"message_end",message:m,__entryId:"entry-assistant-conflict"}),p({error:"Session is already processing",code:"SESSION_BUSY"},409)):p({success:!0,data:"get_tools"===e.type?[]:null})}return"/api/models"===l||l.endsWith("/api/models")?p({models:{"smoke:smoke-model":"Smoke model"},modelList:[{id:"smoke-model",name:"Smoke model",provider:"smoke"}],defaultModel:{provider:"smoke",modelId:"smoke-model"}}):e(t,n)},Object.defineProperty(window,"EventSource",{configurable:!0,writable:!0,value:_}),window.__annovibeRunningSessionSubscribe=e=>(f.add(e),e(s?[a]:[]),()=>f.delete(e)),window.__sessionStreamSmoke={remoteStart(){s=!0,i="waiting_model",h=[],b()},remoteToolStart(){s=!0,i="running_tools",h=[{id:"tool-background",name:"bash"}],b()},remoteFinish(){g=[d,l],S=["entry-user","entry-assistant"],s=!1,i="idle",h=[],v("smoke-epoch:1",{type:"message_end",message:l,__entryId:"entry-assistant"}),v("smoke-epoch:2",{type:"agent_end"}),b()},remoteFinishWithStaleRead(){g=[d,l],S=["entry-user","entry-assistant"],w=1,s=!1,i="idle",h=[],v("smoke-epoch:stale:1",{type:"message_end",message:l,__entryId:"entry-assistant"}),v("smoke-epoch:stale:2",{type:"agent_end"}),b()},remoteFail(){g=[d,c],S=["entry-user","entry-assistant-error"],s=!1,i="idle",h=[],v("smoke-epoch:error:1",{type:"message_end",message:c,__entryId:"entry-assistant-error"}),v("smoke-epoch:error:2",{type:"agent_end"}),b()},remotePromptError(){s=!1,i="idle",h=[],v("smoke-epoch:prompt-error",{type:"prompt_error",error:"No API key configured for smoke provider"}),b()},prepareConcurrentPrompt(){s=!0,i="waiting_model",h=[],o=!0},streamCount:()=>k.size,lastPromptModel:()=>r?.provider&&r.modelId?`${r.provider}/${r.modelId}`:null},t(!0),()=>{for(let t of(delete window.__sessionStreamSmoke,delete window.__annovibeRunningSessionSubscribe,f.clear(),window.fetch=e,Object.defineProperty(window,"EventSource",{configurable:!0,writable:!0,value:n}),k))try{t.close()}catch{}k.clear()}},[]),e?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{type:"button",onClick:()=>r(e=>!e),children:n?"Switch away":"Switch back"}),n?(0,s.jsx)(h,{}):(0,s.jsx)("div",{"data-smoke-switched-away":!0,children:"away"})]}):null}}},e=>{e.O(0,[7330,2941,2995,2693,9867,
|
|
6
|
+
`))},cancel(){e&&k.delete(e),e=null}}),{headers:{"Content-Type":"text/event-stream"}})}if(l.includes(`/api/sessions/${a}`)){let e=w>0;e&&(w-=1);let t=e?[d]:g,n=e?["entry-user"]:S;return e&&await new Promise(e=>window.setTimeout(e,75)),p({sessionId:a,filePath:u.path,info:u,tree:[],leafId:n[n.length-1]??null,context:{messages:t,entryIds:n,thinkingLevel:"off",model:{provider:"smoke",modelId:"smoke-model"}},totalMessages:t.length,hasMore:!1,agentState:{running:s,state:{isStreaming:"streaming"===i,isCompacting:!1,phase:i,activeTools:h,thinkingLevel:"off",contextUsage:null}}})}if(l.endsWith(`/api/agent/${a}`)&&"GET"===c)return p({running:s,state:{isStreaming:"streaming"===i,isCompacting:!1,phase:i,activeTools:h,thinkingLevel:"off",contextUsage:null}});if(l.endsWith(`/api/agent/${a}/prepare`)&&"POST"===c)return p({ok:!0,sessionId:a});if(l.endsWith(`/api/agent/${a}`)&&"POST"===c){let e=JSON.parse(String(n?.body??"{}"));return("prompt"===e.type&&(r=e),"prompt"===e.type&&o)?(o=!1,g=[...g,m],S=[...S,"entry-assistant-conflict"],v("smoke-epoch:conflict",{type:"message_end",message:m,__entryId:"entry-assistant-conflict"}),p({error:"Session is already processing",code:"SESSION_BUSY"},409)):p({success:!0,data:"get_tools"===e.type?[]:null})}return"/api/models"===l||l.endsWith("/api/models")?p({models:{"smoke:smoke-model":"Smoke model"},modelList:[{id:"smoke-model",name:"Smoke model",provider:"smoke"}],defaultModel:{provider:"smoke",modelId:"smoke-model"}}):e(t,n)},Object.defineProperty(window,"EventSource",{configurable:!0,writable:!0,value:_}),window.__annovibeRunningSessionSubscribe=e=>(f.add(e),e(s?[a]:[]),()=>f.delete(e)),window.__sessionStreamSmoke={remoteStart(){s=!0,i="waiting_model",h=[],b()},remoteToolStart(){s=!0,i="running_tools",h=[{id:"tool-background",name:"bash"}],b()},remoteFinish(){g=[d,l],S=["entry-user","entry-assistant"],s=!1,i="idle",h=[],v("smoke-epoch:1",{type:"message_end",message:l,__entryId:"entry-assistant"}),v("smoke-epoch:2",{type:"agent_end"}),b()},remoteFinishWithStaleRead(){g=[d,l],S=["entry-user","entry-assistant"],w=1,s=!1,i="idle",h=[],v("smoke-epoch:stale:1",{type:"message_end",message:l,__entryId:"entry-assistant"}),v("smoke-epoch:stale:2",{type:"agent_end"}),b()},remoteFail(){g=[d,c],S=["entry-user","entry-assistant-error"],s=!1,i="idle",h=[],v("smoke-epoch:error:1",{type:"message_end",message:c,__entryId:"entry-assistant-error"}),v("smoke-epoch:error:2",{type:"agent_end"}),b()},remotePromptError(){s=!1,i="idle",h=[],v("smoke-epoch:prompt-error",{type:"prompt_error",error:"No API key configured for smoke provider"}),b()},prepareConcurrentPrompt(){s=!0,i="waiting_model",h=[],o=!0},streamCount:()=>k.size,lastPromptModel:()=>r?.provider&&r.modelId?`${r.provider}/${r.modelId}`:null},t(!0),()=>{for(let t of(delete window.__sessionStreamSmoke,delete window.__annovibeRunningSessionSubscribe,f.clear(),window.fetch=e,Object.defineProperty(window,"EventSource",{configurable:!0,writable:!0,value:n}),k))try{t.close()}catch{}k.clear()}},[]),e?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("button",{type:"button",onClick:()=>r(e=>!e),children:n?"Switch away":"Switch back"}),n?(0,s.jsx)(h,{}):(0,s.jsx)("div",{"data-smoke-switched-away":!0,children:"away"})]}):null}}},e=>{e.O(0,[7330,2941,2995,2693,9867,3824,8441,3794,7358],()=>e(e.s=18416)),_N_E=e.O()}]);
|
package/package.json
CHANGED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
"use strict";exports.id=7734,exports.ids=[7734],exports.modules={29947:(a,b,c)=>{c.d(b,{ES:()=>l,IB:()=>m,SN:()=>e,tE:()=>n});let d="subagent",e=["retain","recall","reflect"],f=[],g=["read","bash","edit","write"],h=["bash","read","edit","write","grep","find","ls"],i=[...h,"kernel_plot_run","kernel_plot_render","kernel_plot_inspect","kernel_plot_stop","kernel_plot_artifacts"],j=[...h,d];function k(a){return[...a].sort().join(",")}function l(a){let b=a.filter(a=>a.active).map(a=>a.name),c=b.filter(a=>!e.includes(a)),f=k(b),l=k(c);return""===f?"none":f===k(g)?"default":f===k(h)?"full":f===k(i)?"workbench":f===k(j)?"agent":""===l?"none":l===k(g)?"default":l===k(h)?"full":l===k(i)?"workbench":l===k(j)||b.includes(d)?"agent":"default"}function m(a){return e.filter(b=>a.some(a=>a.active&&a.name===b))}function n(a,b){return[...new Set([...function(a){switch(a){case"none":return f;case"default":return g;case"workbench":return i;case"agent":return j;default:return h}}(a),...b])]}},81537:(a,b,c)=>{c.d(b,{O:()=>k});let d=new Set,e=null,f=null,g=null,h=null,i=null,j=!1;function k(a){return d.add(a),e&&a(e),()=>{if(d.delete(a),0===d.size&&j){if(j=!1,h&&clearTimeout(h),h=null,g&&(clearInterval(g),g=null),i?.(),i=null,f){try{f.port.postMessage({type:"disconnect"})}catch{}try{f.port.close()}catch{}}f=null,e=null}}}},87734:(a,b,c)=>{c.d(b,{T:()=>X});var d=c(67484);function e(a){if("assistant"!==a.role)return a;let b=a.content;if(!Array.isArray(b))return a;let c=b.map(a=>("object"!=typeof a||null===a||Array.isArray(a)||"toolCall"!==a.type?null:{type:"toolCall",toolCallId:"string"==typeof a.toolCallId?a.toolCallId:"string"==typeof a.id?a.id:"",toolName:"string"==typeof a.toolName?a.toolName:"string"==typeof a.name?a.name:"",input:"object"!=typeof a.input||null===a.input||Array.isArray(a.input)?"object"!=typeof a.arguments||null===a.arguments||Array.isArray(a.arguments)?{}:a.arguments:a.input})??a);return{...a,content:c}}let f={isStreaming:!1,streamingMessage:null};function g(){return{role:"assistant",content:[],model:"",provider:"",timestamp:Date.now()}}function h(a,b,c){if(!Number.isInteger(b)||void 0===b||b<0)return a;let d=a.streamingMessage??g(),e=[...d.content],f=c(e[b]);return f?(e[b]=f,{isStreaming:!0,streamingMessage:{...d,content:e}}):a}function i(a){if(a.id||a.toolName)return{...a.id?{id:a.id}:{},...a.toolName?{toolName:a.toolName}:{}};let b=a.partial,c=a.contentIndex;if(!b||!Array.isArray(b.content)||void 0===c)return{};let d=b.content[c];return d&&"toolCall"===d.type?{..."string"==typeof d.id?{id:d.id}:"string"==typeof d.toolCallId?{id:d.toolCallId}:{},..."string"==typeof d.name?{toolName:d.name}:"string"==typeof d.toolName?{toolName:d.toolName}:{}}:{}}function j(a,b){switch(b.type){case"start":return{isStreaming:!0,streamingMessage:null};case"snapshot":return"assistant"===b.message.role?{isStreaming:!0,streamingMessage:b.message}:a;case"delta":var c=b.event;switch(c.type){case"start":return{isStreaming:!0,streamingMessage:a.streamingMessage??g()};case"text_start":return h(a,c.contentIndex,a=>a?.type==="text"?a:{type:"text",text:""});case"text_delta":return h(a,c.contentIndex,a=>({type:"text",text:(a?.type==="text"?a.text:"")+(c.delta??"")}));case"text_end":return h(a,c.contentIndex,a=>({type:"text",text:c.content??(a?.type==="text"?a.text:"")}));case"thinking_start":return h(a,c.contentIndex,a=>a?.type==="thinking"?a:{type:"thinking",thinking:""});case"thinking_delta":return h(a,c.contentIndex,a=>({type:"thinking",thinking:(a?.type==="thinking"?a.thinking:"")+(c.delta??"")}));case"thinking_end":return h(a,c.contentIndex,a=>({type:"thinking",thinking:c.content??(a?.type==="thinking"?a.thinking:"")}));case"toolcall_start":return h(a,c.contentIndex,a=>{let b=i(c);return a?.type==="toolCall"?{...a,...b.id?{toolCallId:b.id}:{},...b.toolName?{toolName:b.toolName}:{},rawInput:a.rawInput??""}:{type:"toolCall",toolCallId:b.id??"",toolName:b.toolName??"tool",input:{},rawInput:""}});case"toolcall_delta":return h(a,c.contentIndex,a=>{let b=i(c),d=a?.type==="toolCall"?a:{type:"toolCall",toolCallId:b.id??"",toolName:b.toolName??"tool",input:{}};return{...d,...b.id?{toolCallId:b.id}:{},...b.toolName?{toolName:b.toolName}:{},rawInput:(d.rawInput??"")+(c.delta??"")}});case"toolcall_end":return h(a,c.contentIndex,()=>({type:"toolCall",toolCallId:c.toolCall?.id??"",toolName:c.toolCall?.name??"tool",input:c.toolCall?.arguments??{}}));default:return a}case"end":case"reset":return f;default:return a}}function k(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function l(a){if("assistant"!==a.role)return null;let b=a.timestamp;return"number"!=typeof b?null:`assistant:${b}`}class m extends Error{constructor(a,b,c){super(a),this.status=b,this.code=c,this.name="AgentCommandError"}}async function n(a,b){let c=await fetch(`/api/agent/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),d=await c.json().catch(()=>({}));if(!c.ok||d.error)throw new m(d.error??`HTTP ${c.status}`,c.status,d.code);return d.data}var o=c(31343);async function p(a,b){if(!b.length)return[];let c=await fetch("/api/images/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,images:b.map(a=>({data:a.data,mimeType:a.mimeType,name:a.name}))})}),d=await c.json().catch(()=>({}));if(!c.ok||d.error)throw Error(d.error??`Upload failed (HTTP ${c.status})`);return(d.uploaded??[]).map((a,c)=>({...a,previewUrl:b[c]?.previewUrl}))}async function q(a,b,c){let d,e=new TextDecoder,f="",g=a=>{if(a.startsWith("id: ")){d=a.slice(4);return}if(!a.startsWith("data: "))return;let c=a.slice(6);if("[DONE]"!==c)try{b(c,d)}catch{}finally{d=void 0}},h=new Promise(a=>{c?.aborted?a():c?.addEventListener("abort",()=>a(),{once:!0})});for(;;){let b=await Promise.race([a.read(),h.then(()=>({done:!0,value:void 0}))]);if(b.done)break;let c=(f+=e.decode(b.value,{stream:!0})).split("\n");for(let a of(f=c.pop()||"",c))g(a)}if(f.trim())for(let a of f.split("\n"))g(a)}c(81537);let r="__annovibeStreamSessions__",s="__annovibeStreamListeners__",t="__annovibeStreamErrorCallbacks__";function u(){let a=globalThis;return a[r]||(a[r]=new Map),a[r]}function v(){let a=globalThis;return a[t]||(a[t]=new Map),a[t]}function w(a){return{sessionId:a,phase:"idle",startedAt:null,lastEventAt:null,lastHeartbeatAt:null,reconnectCount:0,lastSyncReason:null,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!1,error:null}}function x(a,b){let c;for(let d of(!(c=globalThis)[s]&&(c[s]=new Map),c[s]).get(a)??[])try{d(b)}catch{}}function y(a){a.textThrottleTimer&&(clearTimeout(a.textThrottleTimer),a.textThrottleTimer=null),a.textDirty&&(a.textDirty=!1,A(a))}function z(a,b=!1){let c=Date.now();if(a.snapshot.lastEventAt=c,!b){a.textDirty=!0,a.textThrottleTimer||(a.textThrottleTimer=setTimeout(()=>{a.textThrottleTimer=null,a.textDirty&&(a.textDirty=!1,A(a))},100));return}y(a),A(a)}function A(a,b){let c=Date.now(),d=function(a){let b=[];for(let c of a.toolCalls.values())b.push({type:"toolCall",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input??{}});let c=a.accumulatedText.trim();return c&&b.push({type:"text",text:c}),b}(a),e=(b??a.snapshot.phase)==="active";a.snapshot={...a.snapshot,phase:b??a.snapshot.phase,lastEventAt:c,accumulatedText:a.accumulatedText,toolCalls:[...a.toolCalls.values()],toolResults:[...a.toolResults.values()],statusText:e?function(a){if(a.activeToolId){let b=a.toolCalls.get(a.activeToolId);if(b){let a=Math.max(0,Math.floor((Date.now()-b.startedAt)/1e3));return`Running ${b.toolName||"tool"}… (${a}s)`}}return a.accumulatedText.trim()?"Generating response…":a.toolCalls.size>0?"Finishing tool results…":null}(a):a.snapshot.statusText,streamingMessage:e&&d.length>0?{role:"assistant",content:d}:null,isStreaming:e},x(a.snapshot.sessionId,{type:"snapshot-updated",snapshot:a.snapshot})}function B(a){C(a),a.idleCheckTimer=setInterval(()=>{if("connected"!==a.connectionState)return;let b=Math.max(a.snapshot.lastEventAt??0,a.snapshot.lastHeartbeatAt??0);if(Date.now()-b>=18e4){D(a),y(a);let b="Stream idle timeout — no activity for 180s.";a.snapshot={...a.snapshot,phase:"error",isStreaming:!1,streamingMessage:null,statusText:null,error:b},C(a),x(a.snapshot.sessionId,{type:"error",snapshot:a.snapshot});let c=v().get(a.snapshot.sessionId);if(c)try{c(a.snapshot.sessionId,b)}catch{}}},1e4)}function C(a){a.idleCheckTimer&&(clearInterval(a.idleCheckTimer),a.idleCheckTimer=null)}function D(a){a.toolProgressTimer&&(clearInterval(a.toolProgressTimer),a.toolProgressTimer=null)}function E(a){let b=u(),c=b.get(a);return c||(c={snapshot:w(a),accumulatedText:"",toolCalls:new Map,toolResults:new Map,toolProgressTimer:null,activeToolId:null,textThrottleTimer:null,textDirty:!1,connectionState:"idle",idleCheckTimer:null},b.set(a,c)),c}function F(a,b){let c=v();return c.set(a,b),()=>{c.get(a)===b&&c.delete(a)}}function G(a){let b=u(),c=b.get(a);c&&(D(c),C(c),y(c)),b.delete(a)}function H(a){let b=u().get(a);b&&(b.snapshot={...b.snapshot,reconnectCount:b.snapshot.reconnectCount+1,lastSyncReason:"sse-reconnect",lastEventAt:Date.now()},z(b,!0))}let I="__annovibeSessionMessageCache__";function J(){let a=globalThis;if(!a[I]){var b;let c={entries:new Map,cleanupTimer:null};a[I]=c,(b=c).cleanupTimer||(b.cleanupTimer=setInterval(()=>{let a=Date.now();for(let[c,d]of b.entries)a-d.loadedAt>72e5&&b.entries.delete(c)},6e4))}return a[I]}function K(a){let b=J(),c=b.entries.get(a);return c?Date.now()-c.loadedAt>72e5?(b.entries.delete(a),null):(c.loadedAt=Date.now(),{...c,messages:[...c.messages],entryIds:[...c.entryIds]}):null}function L(a,b,c,d,e){let f=J(),g=f.entries.get(a);if(!g)return;let h=new Set(g.entryIds),i=[],j=[];for(let a=0;a<b.length;a++){let d=c[a];d&&!h.has(d)&&(i.push(b[a]),j.push(d))}0!==i.length&&f.entries.set(a,{...g,messages:[...i,...g.messages],entryIds:[...j,...g.entryIds],hasMore:d,loadedMessagesCount:e,loadedAt:Date.now()})}function M(a){J().entries.delete(a)}var N=c(29947);function O(a){return{steering:a?.steering??[],followUp:a?.followUp??[]}}let P=[500,1500,3e3];function Q(a,b){return new DOMException(a,b)}function R(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}-${Math.random().toString(36).slice(2,11)}`}function S(a,b){return a.trim()||0!==b?`text:${a}|images:${b}`:null}function T(a){return"string"==typeof a?S(a,0):Array.isArray(a)?S(a.filter(a=>!!a&&"object"==typeof a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"),a.filter(a=>!!a&&"object"==typeof a&&"image"===a.type).length):null}function U(a){let b=new Map;for(let c of a){let a="user"!==c.role?null:T(c.content);a&&b.set(a,(b.get(a)??0)+1)}return b}function V(a,b,c){return a.sessionId===b&&(!a.leafId||c.includes(a.leafId))}function W(a,b){let c=a.timestamp,d=b.timestamp;if("number"!=typeof c||"number"!=typeof d||c!==d||a.role!==b.role)return!1;try{return JSON.stringify(a)===JSON.stringify(b)}catch{return!1}}function X(a){let{session:b,newSessionCwd:c,onAgentEnd:g,onSessionCreated:h,onSessionForked:i,modelsRefreshKey:r,onBranchDataChange:s,chatInputRef:t}=a,v=null===b&&null!==c,[A,I]=(0,d.useState)(null),[X,Y]=(0,d.useState)(!v),[Z,$]=(0,d.useState)(null),[_,aa]=(0,d.useState)(null),[ab,ac]=(0,d.useState)([]),[ad,ae]=(0,d.useState)([]),[af,ag]=(0,d.useState)(0),[ah,ai]=(0,d.useState)(!1),[aj,ak]=(0,d.useState)(0),[al,am]=(0,d.useReducer)(j,f),[an,ao]=(0,d.useState)(!1),[ap,aq]=(0,d.useState)({}),[ar,as]=(0,d.useState)([]),[at,au]=(0,d.useState)({}),[av,aw]=(0,d.useState)({}),[ax,ay]=(0,d.useState)(null),[az,aA]=(0,d.useState)("full"),[aB,aC]=(0,d.useState)([...N.SN]),[aD,aE]=(0,d.useState)([]),[aF,aG]=(0,d.useState)(null),[aH,aI]=(0,d.useState)(!1),[aJ,aK]=(0,d.useState)("auto"),[aL,aM]=(0,d.useState)(null),[aN,aO]=(0,d.useState)(null),[aP,aQ]=(0,d.useState)(null),[aR,aS]=(0,d.useState)(null),[aT,aU]=(0,d.useState)(null),[aV,aW]=(0,d.useState)(null),[aX,aY]=(0,d.useState)(!1),[aZ,a$]=(0,d.useState)(null),[a_,a0]=(0,d.useState)(null),[a1,a2]=(0,d.useState)(null),[a3,a4]=(0,d.useState)({steering:[],followUp:[]}),[a5,a6]=(0,d.useState)(null),a7=(0,d.useRef)(null),a8=(0,d.useRef)(b?.id??null),{statuses:a9,widgets:ba,dialog:bb,notices:bc,applyFromState:bd,handleEvent:be,respond:bf,dismissNotice:bg}=function({chatInputRef:a,sessionIdRef:b,onError:c,noticeTtlMs:e=8e3}){let[f,g]=(0,d.useState)([]),[h,i]=(0,d.useState)([]),[j,k]=(0,d.useState)(null),[l,m]=(0,d.useState)([]),o=(0,d.useRef)(new Set),p=(0,d.useCallback)(()=>{for(let a of o.current)clearTimeout(a);o.current.clear()},[]),q=(0,d.useCallback)((a,b)=>{let c={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,message:a,type:b};m(a=>[...a,c].slice(-4));let d=setTimeout(()=>{o.current.delete(d),m(a=>a.filter(a=>a.id!==c.id))},e);o.current.add(d)},[e]),r=(0,d.useCallback)(a=>{a&&(Array.isArray(a.extensionStatuses)&&g(a.extensionStatuses),Array.isArray(a.extensionWidgets)&&i(a.extensionWidgets))},[]),s=(0,d.useCallback)(b=>{if("extension_error"===b.type)return q("string"==typeof b.error?b.error:"Extension command failed","error"),!0;if("extension_ui_request"!==b.type)return!1;let c="string"==typeof b.method?b.method:"";if("select"===c||"confirm"===c||"input"===c||"editor"===c)return k({id:String(b.id??""),method:c,title:"string"==typeof b.title?b.title:"",...Array.isArray(b.options)?{options:b.options}:{},..."string"==typeof b.message?{message:b.message}:{},..."string"==typeof b.placeholder?{placeholder:b.placeholder}:{},..."string"==typeof b.prefill?{prefill:b.prefill}:{}}),!0;if("notify"===c){let a="warning"===b.notifyType||"error"===b.notifyType?b.notifyType:"info";return q(String(b.message??""),a),!0}if("setStatus"===c){let a=String(b.statusKey??"");if(!a)return!0;let c="string"==typeof b.statusText?b.statusText:null;return g(b=>{let d=b.filter(b=>b.key!==a);return c?[...d,{key:a,text:c}]:d}),!0}if("setWidget"===c){let a=String(b.widgetKey??"");if(!a)return!0;let c=Array.isArray(b.widgetLines)?b.widgetLines.filter(a=>"string"==typeof a):null;return i(d=>{let e=d.filter(b=>b.key!==a);return c&&c.length>0?[...e,{key:a,lines:c,placement:"string"==typeof b.widgetPlacement?b.widgetPlacement:"aboveEditor"}]:e}),!0}return"dismiss"===c?k(a=>a?.id===b.id?null:a):"set_editor_text"===c&&"string"==typeof b.text?a?.current?.setText?.(b.text):"setTitle"===c&&"string"==typeof b.title&&(document.title=b.title),!0},[a,q]),t=(0,d.useCallback)(async(a,d)=>{let e=b.current;if(k(b=>b?.id===a?null:b),e)try{await n(e,{type:"extension_ui_response",id:a,...d})}catch(a){c(a instanceof Error?a.message:String(a))}},[c,b]);return{statuses:f,widgets:h,dialog:j,notices:l,applyFromState:r,handleEvent:s,respond:t,dismissNotice:(0,d.useCallback)(a=>{m(b=>b.filter(b=>b.id!==a))},[]),reset:(0,d.useCallback)(()=>{p(),g([]),i([]),k(null),m([])},[p])}}({chatInputRef:t,sessionIdRef:a8,onError:a6}),bh=(0,d.useRef)(!1),bi=(0,d.useRef)(null),bj=(0,d.useRef)(null),bk=(0,d.useRef)(null),bl=(0,d.useRef)(!1),bm=(0,d.useRef)(null),bn=(0,d.useRef)(!1),bo=(0,d.useRef)(null),bp=(0,d.useRef)(null),bq=(0,d.useRef)(new Map),br=(0,d.useRef)(new Map),bs=(0,d.useRef)(new Map),bt=(0,d.useRef)(new Map),bu=(0,d.useRef)(null),bv=(0,d.useRef)([]),bw=(0,d.useRef)(null),bx=(0,d.useRef)(0),by=(0,d.useRef)(!1),bz=(0,d.useRef)(0),bA=(0,d.useRef)(!1);(0,d.useRef)(!1),(0,d.useRef)(0);let bB=(0,d.useRef)(null),bC=(0,d.useRef)(null),bD=(0,d.useRef)(0);(0,d.useRef)(!1);let bE=(0,d.useRef)(!1),bF=(0,d.useRef)(""),bG=(0,d.useRef)(null),bH=a.setNewSessionModel??ay,bI=a.setToolPreset??aA,bJ=a.setMemoryTools??aC,bK=aT??A?.context.model??aV??null,bL=v?ax:bK,bM=(0,d.useCallback)(()=>(0,N.tE)(az,aB),[aB,az]),bN=(0,d.useCallback)(a=>a?.length?a.map((a,b)=>{let c=`Attachment ${b+1}: ${a.fileName} (${a.mimeType||"application/octet-stream"}, ${a.size} bytes)`;if(a.extractedText){let b=a.truncated?"\n[The extracted text was truncated before sending.]":"";return`${c}
|
|
2
|
-
${b}
|
|
3
|
-
${a.extractedText}`.trim()}return`${c}
|
|
4
|
-
[Text extraction unavailable: ${a.extractionError??"unsupported file type"}]`}).join("\n\n---\n\n"):"",[]),bO=(0,d.useCallback)(async a=>{let b=await fetch(`/api/agent/${encodeURIComponent(a)}/prepare`,{method:"POST"});if(!b.ok)throw Error((await b.json().catch(()=>({}))).error??`Failed to prepare session (HTTP ${b.status})`)},[]),bP=(()=>{let a={input:0,output:0,cacheRead:0,cacheWrite:0};for(let b of ab){if("assistant"!==b.role)continue;let c=b.usage;c&&(a.input+=c.input??0,a.output+=c.output??0,a.cacheRead+=c.cacheRead??0,a.cacheWrite+=c.cacheWrite??0)}return a.input+a.output+a.cacheRead+a.cacheWrite>0?{tokens:a}:null})(),bQ=(0,d.useRef)(!1),bR=(0,d.useCallback)(async()=>{let a=a8.current;if(!a||bQ.current||bA.current)return;bQ.current=!0,by.current=!0;let b=0,c=K(a);b=c?c.loadedMessagesCount:50;try{for(;;)try{let c=await fetch(`/api/sessions/${encodeURIComponent(a)}?limit=100&offset=${b}&deferThinking=1&deferMedia=1`);if(!c.ok)break;let d=await c.json();if(a8.current!==a)break;let e=d.context.messages,f=d.context.entryIds??[];if(0===e.length)break;ac(a=>[...e,...a]),ae(a=>{let b=[...f,...a];return bv.current=b,b});let g=b+e.length;if(ak(g),bz.current=g,ai(d.hasMore??!1),L(a,e,f,d.hasMore??!1,g),b=g,!d.hasMore)break;await new Promise(a=>setTimeout(a,800))}catch{break}}finally{bQ.current=!1,bA.current=!0,by.current=!1}},[]),bS=(0,d.useCallback)(async(a,b=!1,c=!1,d=!1)=>{var e;let f=null;try{if(b&&Y(!0),!c&&!bh.current&&!d){let c=K(a);if(c)return ag(c.totalMessages),ai(c.hasMore),ak(c.loadedMessagesCount),ac(c.messages),bv.current=c.entryIds,ae(c.entryIds),bu.current=c.leafId,aa(c.leafId),bz.current=c.loadedMessagesCount,b&&Y(!1),c.hasMore&&!bA.current&&setTimeout(()=>{bR()},1500),null}let g=c?`/api/sessions/${encodeURIComponent(a)}?includeState&deferThinking=1&deferMedia=1`:`/api/sessions/${encodeURIComponent(a)}?limit=50&offset=0&deferThinking=1&deferMedia=1`,h=bC.current;if(h?.sid===a&&!b)return null;h?.controller.abort(Q("Session load superseded","AbortError"));let i=new AbortController;f=i,bC.current={sid:a,controller:i};let j=setTimeout(()=>{i.abort(Q("Session load timed out after 30 seconds","TimeoutError"))},3e4),k=await fetch(g,{signal:i.signal}).finally(()=>clearTimeout(j));if(a8.current&&a8.current!==a)return null;if(404===k.status)return b&&(I(null),bu.current=null,aa(null),ac([]),$(null)),null;if(!k.ok)throw Error(`HTTP ${k.status}`);let m=await k.json();c?(ag(m.totalMessages??m.context.messages.length),ai(!1)):(ag(m.totalMessages??m.context.messages.length),ai(m.hasMore??!1)),ak(m.context.messages.length),I(m),bu.current=m.leafId,aa(m.leafId);let n=m.context.messages,o=U(n),p=new Map,q=Date.now();for(let[b,c]of bq.current)if(c.sessionId===a){if(q-c.createdAt>12e4){bq.current.delete(b);continue}if(c.confirmKey){let a=o.get(c.confirmKey)??0,d=p.get(c.confirmKey)??0;a-d>c.confirmCountAtCreate&&(bq.current.delete(b),p.set(c.confirmKey,d+1))}}br.current=o;let r=m.context.entryIds??[],s=[...bq.current.values()].filter(b=>V(b,a,r)).map(a=>a.message),t=s.length>0?[...n,...s]:n,u=function(a,b,c){if(0===b.size)return a;let d=!1,e=a.map(a=>{let e=l(a);if(!e)return a;let f=b.get(e);return f?c-f.observedAt>5e3||function(a,b){let c=a.timestamp,d=b.timestamp;if("number"!=typeof c||"number"!=typeof d||c!==d||a.role!==b.role)return!1;try{return JSON.stringify(a)===JSON.stringify(b)}catch{return!1}}(f.message,a)?(b.delete(e),a):(d=!0,f.message):a});return d?e:a}(t,bt.current,Date.now()),v=bs.current.get(a);if(v){for(let[a,b]of v)q-b>12e4&&v.delete(a);0===v.size&&bs.current.delete(a)}let w=v?.size?v:null,x=w?new Set(r):null,y=!!w&&!!x&&[...w.keys()].some(a=>!x.has(a));w&&x&&!y&&bs.current.delete(a);let z=u.length;return!c&&(bz.current>z||y)?(ag(m.totalMessages??m.context.messages.length),ai(m.hasMore??!1)):(ac(a=>(function(a,b){if(a.length!==b.length)return b;let c=!1,d=b.map((b,d)=>W(a[d],b)?a[d]:(c=!0,b));return c?d:a})(a,u)),bv.current=r,ae(r),c?bz.current=z:bz.current=Math.max(bz.current,z),e={sessionId:a,leafId:m.leafId,messages:u,entryIds:r,totalMessages:m.totalMessages??m.context.messages.length,hasMore:!c&&(m.hasMore??!1),loadedMessagesCount:m.context.messages.length},J().entries.set(a,{...e,loadedAt:Date.now()})),aU(a=>{if(!a)return null;let b=m.context.model;return b?.provider===a.provider&&b.modelId===a.modelId?null:a}),$(null),!m.agentState?.state?.thinkingLevel&&m.context.thinkingLevel&&"off"!==m.context.thinkingLevel&&aK(m.context.thinkingLevel),m.agentState??null}catch(a){if(a instanceof DOMException&&("AbortError"===a.name||"TimeoutError"===a.name)||a instanceof Error&&/aborted without reason|AbortError|Session load (?:timed out|superseded)/i.test(a.message))return null;return $(String(a)),null}finally{f&&bC.current?.controller===f&&(bC.current=null),b&&Y(!1)}},[bR]),bT=(0,d.useRef)(!1),bU=(0,d.useCallback)(async()=>{if(bT.current)return;bT.current=!0;let a=a8.current;if(!a){bT.current=!1;return}try{let b=await fetch(`/api/sessions/${encodeURIComponent(a)}?limit=50&offset=${aj}&deferThinking=1&deferMedia=1`);if(!b.ok)return;let c=await b.json(),d=c.context.messages,e=c.context.entryIds??[];ac(a=>[...d,...a]),ae(a=>{let b=[...e,...a];return bv.current=b,b}),ak(a=>a+d.length),ai(c.hasMore??!1),L(a,d,e,c.hasMore??!1,aj+d.length)}catch{}finally{bT.current=!1}},[aj]),bV=(0,d.useCallback)(async a=>{let b=a8.current;if(!b)return[];let c=bu.current,d=c?`?leafId=${encodeURIComponent(c)}`:"";try{let c=await fetch(`/api/sessions/${encodeURIComponent(b)}/shadowed${d}`);if(!c.ok)return[];let e=await c.json(),f=e.groups?.find(b=>b.compactionEntryId===a);return f?.messages??[]}catch{return[]}},[]),bW=(0,d.useCallback)(async(a,b)=>{try{let c=b?`/api/sessions/${encodeURIComponent(a)}/context?leafId=${encodeURIComponent(b)}&deferThinking=1&deferMedia=1`:`/api/sessions/${encodeURIComponent(a)}/context?deferThinking=1&deferMedia=1`,d=await fetch(c);if(!d.ok)throw Error(`HTTP ${d.status}`);let e=await d.json(),f=e.context.messages,g=e.context.entryIds??[],h=U(f),i=new Map,j=Date.now();for(let[b,c]of bq.current)if(c.sessionId===a){if(j-c.createdAt>12e4){bq.current.delete(b);continue}if(c.confirmKey){let a=h.get(c.confirmKey)??0,d=i.get(c.confirmKey)??0;a-d>c.confirmCountAtCreate&&(bq.current.delete(b),i.set(c.confirmKey,d+1))}}br.current=h;let k=[...bq.current.values()].filter(b=>V(b,a,g)).map(a=>a.message);ac(k.length>0?[...f,...k]:f),bv.current=g,ae(g)}catch(a){console.error("Failed to load context:",a)}},[]),bX=(0,d.useCallback)(async a=>{try{let b=await n(a,{type:"get_tools"});b&&(bI((0,N.ES)(b)),bJ((0,N.IB)(b)))}catch(a){console.error("Failed to load tools:",a)}},[bJ,bI]),bY=(0,d.useCallback)(async a=>{try{let b=await n(a,{type:"get_commands"});aE(Array.isArray(b?.commands)?b.commands:[])}catch{aE([])}},[]),bZ=(0,d.useCallback)((a,b={})=>{a7.current?.close(),a7.current=null;let c=`/api/agent/${encodeURIComponent(a)}/events${b.replay?"?replay=1":""}`;return!function(a){let b=E(a);if("active"===b.snapshot.phase)return z(b,!0),B(b),b.snapshot;let c=Date.now();b.snapshot={...w(a),phase:"active",startedAt:c,lastEventAt:c,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},B(b),z(b,!0),b.snapshot}(a),new Promise((d,e)=>{let f=!1,g=!1,h=null,i=a=>{if(!f){if(f=!0,clearTimeout(j),a){h?.close(),a7.current===h&&(a7.current=null),e(a);return}d()}},j=setTimeout(()=>{b.requireConnected?i(Error("Timed out waiting for event stream connection")):i()},b.timeoutMs??3e4);a7.current=h=function(a){let{url:b,onEvent:c,onStateChange:d,onFatalError:e,maxReconnectAttempts:f=1/0,reconnectBaseMs:g=1e3,reconnectMaxMs:h=3e4,autoReconnect:i=!0}=a,j="idle",k=new AbortController,l=0,m=null,n=null,o=!1,p=(a,b)=>{b&&(n=b),c(a,b)},r=a=>{j!==a&&(j=a,d?.(a))},s=()=>{null!==m&&(clearTimeout(m),m=null)},t=()=>{if(o)return;if(!i)return void r("error");if(l>=f){r("error"),e?.(Error(`Max reconnect attempts (${f}) reached`));return}let a=Math.min(h,g*2**l);l+=1,r("connecting"),m=setTimeout(()=>{m=null,u()},a)},u=async()=>{if(!o){s(),k=new AbortController,r("connecting");try{let a=await fetch(b,{signal:k.signal,headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...n?{"Last-Event-ID":n}:{}}});if(!a.ok)throw Error(`HTTP ${a.status}: ${a.statusText}`);let c=a.body;if(!c)throw Error("Response has no readable body");let d=c.getReader();if(r("connected"),l=0,await q(d,p,k.signal),k.signal.aborted)try{await d.cancel()}catch{}d.releaseLock(),r("closed"),!o&&i&&t()}catch(a){if(o||a instanceof DOMException&&"AbortError"===a.name)return void r("closed");r("error"),i&&t()}}};return{get state(){return j},connect:()=>{o=!1,l=0,s(),u()},close:()=>{o=!0,s(),k.abort(),r("closed")},get abortController(){return k}}}({url:c,onEvent:b=>{try{let c=JSON.parse(b);if("connected"===c.type&&i(),a8.current!==a)return;bi.current?.(c)}catch{}},onStateChange:b=>{!function(a,b){let c=u().get(a);if(!c)return;let d=c.connectionState;c.connectionState=b,"connected"===b&&"connected"!==d&&(c.snapshot={...c.snapshot,lastEventAt:Date.now(),lastHeartbeatAt:Date.now()},B(c)),"connected"!==b&&"connected"===d&&C(c)}(a,b),"connected"===b&&(g&&(H(a),bj.current?.(a,"sse_reconnected")),g=!0)},reconnectBaseMs:1e3,reconnectMaxMs:3e4}),h.connect()})},[]),b$=(0,d.useCallback)(async(a,b="manual")=>{if(!a||a8.current!==a)return;let c=bx.current;try{let b=await fetch(`/api/agent/${encodeURIComponent(a)}`),e=await b.json().catch(()=>({}));if(a8.current!==a||bx.current!==c)return;if(e.running){var d;bh.current=!0,ao(!0),a2((d=e.state,d?.phase==="running_tools"?{kind:"running_tools",tools:(d.activeTools??[]).map(a=>({id:a.id,name:a.name}))}:d?.phase==="streaming"||d?.phase==="compacting"||d?.phase==="idle"?null:{kind:"waiting_model"})),a7.current&&"closed"!==a7.current.state&&"error"!==a7.current.state||(H(a),bZ(a,{replay:!0}))}else bh.current=!1,a7.current?.close(),a7.current=null,G(a),ao(!1),a2(null),aM(null),am({type:"end"}),M(a),await bS(a,!1,!1,!0);e.state?.contextUsage!==void 0&&aO(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&aQ(e.state.systemPrompt??null),e.state?.isCompacting!==void 0&&aY(e.state.isCompacting),e.state?.thinkingLevel!==void 0&&aK(e.state.thinkingLevel??"auto"),e.state?.queuedMessages!==void 0&&a4(O(e.state.queuedMessages)),bd(e.state),e.state?.isBashRunning&&(bE.current=!0,aI(!0),ao(!0),a2({kind:"running_tools",tools:[{id:"bash",name:"bash"}]}))}catch{}},[bZ,bS,bd]);bi.current=(0,d.useCallback)(a=>{let b=a8.current;switch(b&&function(a,b){let c=E(a),d=Date.now();switch(b.type){case"agent_start":if("active"===c.snapshot.phase)return z(c,!0),c.snapshot;return D(c),c.accumulatedText="",c.toolCalls.clear(),c.toolResults.clear(),c.activeToolId=null,c.snapshot={...w(a),phase:"active",startedAt:d,lastEventAt:d,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},B(c),z(c,!0),c.snapshot;case"message_update":{let a=b.message;if(a?.role==="assistant"){let b=a.content;for(let a of Array.isArray(b)?b:[])"object"==typeof a&&null!==a&&"type"in a&&("text"===a.type?c.accumulatedText=a.text??"":"toolCall"===a.type&&a.toolCallId&&!c.toolCalls.has(a.toolCallId)&&c.toolCalls.set(a.toolCallId,{...a,startedAt:d}))}else{let a=b.assistantMessageEvent;a?.type==="text_delta"?c.accumulatedText+=a.delta??"":a?.type==="text_end"?c.accumulatedText=a.content??c.accumulatedText:(a?.type==="toolcall_start"||a?.type==="toolcall_delta")&&a.id&&!c.toolCalls.has(a.id)&&c.toolCalls.set(a.id,{type:"toolCall",toolCallId:a.id,toolName:a.toolName??"tool",input:{},startedAt:d})}return z(c,!1),c.snapshot}case"tool_execution_start":{let a="string"==typeof b.toolCallId?b.toolCallId:"",e="string"==typeof b.toolName?b.toolName:"tool",f=b.input??{};if(!a)return c.snapshot;let g=c.toolCalls.get(a);return c.toolCalls.set(a,{type:"toolCall",toolCallId:a,toolName:e,input:g&&Object.keys(g.input).length>0?g.input:f,startedAt:g?.startedAt??d}),c.activeToolId=a,D(c),c.activeToolId&&(c.toolProgressTimer=setInterval(()=>z(c,!0),1e3)),z(c,!0),c.snapshot}case"tool_execution_end":{let a="string"==typeof b.toolCallId?b.toolCallId:"",e="string"==typeof b.toolName?b.toolName:"tool",f="string"==typeof b.result?b.result:JSON.stringify(b.result??"");if(a){let g=c.toolCalls.get(a);g&&c.toolCalls.set(a,{...g,endedAt:d}),c.toolResults.set(a,{role:"toolResult",toolCallId:a,toolName:e,content:[{type:"text",text:f}],isError:!!b.isError,timestamp:d}),c.activeToolId===a&&(c.activeToolId=null,D(c))}return z(c,!0),c.snapshot}case"message_end":return y(c),z(c,!0),c.snapshot;case"agent_end":{if(y(c),D(c),c.activeToolId=null,!0===b.willRetry)return c.accumulatedText="",c.toolCalls.clear(),c.toolResults.clear(),c.snapshot={...c.snapshot,phase:"active",lastEventAt:d,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!0,error:null},B(c),x(a,{type:"snapshot-updated",snapshot:c.snapshot}),c.snapshot;C(c);let e="string"==typeof b.error?b.error:null;return c.snapshot={...c.snapshot,phase:e?"error":"completed",isStreaming:!1,streamingMessage:null,statusText:null,error:e},x(a,e?{type:"error",snapshot:c.snapshot}:{type:"completed",snapshot:c.snapshot}),c.snapshot}case"heartbeat":return c.snapshot={...c.snapshot,lastHeartbeatAt:d},c.snapshot;default:return c.snapshot}}(b,a),"heartbeat"!==a.type&&(bD.current=Date.now()),a.type){case"prompt_admitted":case"agent_start":a6(null),bh.current=!0,ao(!0),a2({kind:"waiting_model"}),am({type:"start"});break;case"agent_end":if(!0===a.willRetry){bh.current=!0,ao(!0),a2({kind:"waiting_model"});break}if(bh.current=!1,ao(!1),a2(null),aM(null),am({type:"end"}),b){bB.current&&clearTimeout(bB.current);let a=bx.current,c=0,d=async()=>{if(a8.current!==b||bh.current||bx.current!==a)return;M(b),await bS(b,!1,!1,!0);let e=P[c++];void 0===e||a8.current!==b||bh.current||bx.current!==a||(bB.current=setTimeout(()=>{bB.current=null,d()},e))};d(),fetch(`/api/agent/${encodeURIComponent(b)}`).then(a=>a.json()).then(a=>{a.state?.contextUsage!==void 0&&aO(a.state.contextUsage??null),a.state?.systemPrompt!==void 0&&aQ(a.state.systemPrompt??null),a.state?.isCompacting!==void 0&&aY(a.state.isCompacting)}).catch(()=>{})}g?.();break;case"agent_settled":a2(null),aM(null),bh.current&&(bh.current=!1,ao(!1),am({type:"end"}));break;case"message_start":case"message_update":{let b=a.message;if(b?.role==="user")break;bh.current||(bh.current=!0,ao(!0),a2({kind:"waiting_model"}));let c=a.assistantMessageEvent;b?.role==="assistant"?am({type:"snapshot",message:e(b)}):c&&am({type:"delta",event:c}),a2(null);break}case"message_end":{let c=a.message,d="string"==typeof a.__entryId?a.__entryId:null,f=bh.current;if(c&&"user"!==c.role){"assistant"===c.role&&"error"===c.stopReason&&c.errorMessage?.trim()&&a6(`Model response failed: ${c.errorMessage.trim()}`);let a=e(c),f=l(a);if(f&&bt.current.set(f,{observedAt:Date.now(),message:a}),!(d&&bv.current.includes(d))){if(b&&d){let a=bs.current.get(b)??new Map;a.set(d,Date.now()),bs.current.set(b,a)}ac(b=>b.some(b=>W(b,a))?b:[...b,a]),d&&ae(a=>{if(a.includes(d))return a;let b=[...a,d];return bv.current=b,b})}}f&&(am({type:"reset"}),a2({kind:"waiting_model"}));break}case"replay_gap":b&&(M(b),bS(b,!1,!1,!0));break;case"prompt_done":if(!bh.current)break;b$(a8.current??"","prompt_done");break;case"prompt_error":{let c="string"==typeof a.error&&a.error.trim()?a.error.trim():"The model request failed before producing a response.";if(bh.current=!1,ao(!1),a2(null),aM(null),am({type:"end"}),a7.current?.close(),a7.current=null,b){for(let[a,c]of(G(b),bq.current))c.sessionId===b&&"prompt"===c.kind&&bq.current.delete(a);M(b),bS(b,!1,!1,!0)}a6(`Model request failed: ${c}`),g?.();break}case"tool_execution_start":{let b=a.toolCallId,c=a.toolName,d=a.args,e="bash"===c&&"string"==typeof d?.command?d.command:void 0;a2(a=>{let d=a?.kind==="running_tools"?[...a.tools]:[];return d.some(a=>a.id===b)||d.push({id:b,name:c,args:e}),{kind:"running_tools",tools:d}});break}case"tool_execution_update":{let b=a.toolCallId,c=a.toolName,d=function(a){if(!k(a))return null;let b=a.content;if(!Array.isArray(b))return null;let c=b.filter(a=>k(a)&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n").split(/\r?\n/),d="";for(let a=c.length-1;a>=0&&!(d=c[a].trim());a-=1);if(!d)return null;let e=d.replace(/\s+/g," ");return e.length<=500?e:`...${e.slice(-497)}`}(a.partialResult);if(!b)break;a2(a=>{let e=a?.kind==="running_tools"?[...a.tools]:[],f=e.find(a=>a.id===b),g={id:b,name:c||f?.name||"tool",args:f?.args,progress:d??f?.progress};return{kind:"running_tools",tools:[...e.filter(a=>a.id!==b),g]}});break}case"tool_execution_end":{let b=a.toolCallId;a2(a=>{if(a?.kind!=="running_tools")return a;let c=a.tools.filter(a=>a.id!==b);return 0===c.length?{kind:"waiting_model"}:{kind:"running_tools",tools:c}});break}case"extension_ui_request":case"extension_error":be(a);break;case"bash_execution_start":{let b=String(a.command??"");bE.current=!0,aI(!0),aG({command:b,output:""}),ao(!0),a2({kind:"running_tools",tools:[{id:"bash",name:"bash",args:b}]});break}case"bash_execution_update":{let b="string"==typeof a.chunk?a.chunk:"";if(!b)break;bF.current+=b,bG.current||(bG.current=setTimeout(()=>{bG.current=null;let a=bF.current;bF.current="",a&&aG(b=>b?{...b,output:b.output+a}:b)},60));break}case"bash_done":{bG.current&&(clearTimeout(bG.current),bG.current=null),bF.current="",bE.current=!1,aI(!1),aG(null),ao(!1),a2(null);let a=a8.current;a&&(M(a),bS(a,!1,!1,!0));break}case"queue_update":a4(O({steering:Array.isArray(a.steering)?a.steering:[],followUp:Array.isArray(a.followUp)?a.followUp:[]}));break;case"auto_retry_start":a6(null),bh.current=!0,ao(!0),a2({kind:"waiting_model"}),aM({attempt:a.attempt,maxAttempts:a.maxAttempts,errorMessage:a.errorMessage});break;case"auto_retry_end":aM(null),!1===a.success&&"string"==typeof a.finalError&&a.finalError.trim()?a6(`Model response failed after retries: ${a.finalError.trim()}`):!0===a.success&&a6(null);break;case"auto_compaction_start":case"compaction_start":aY(!0),a$(null);break;case"auto_compaction_end":case"compaction_end":aY(!1),a.errorMessage?a$(a.errorMessage):!a.aborted&&a8.current&&bS(a8.current)}},[bS,g,b$,be]);let b_=(0,d.useCallback)(async(a,d,e,f)=>{if(!a.trim()&&!d?.length&&!e?.length||an)return;bx.current+=1;let g=bN(e),i=a.trim()?g?`${a}
|
|
5
|
-
|
|
6
|
-
Attached document text:
|
|
7
|
-
|
|
8
|
-
${g}`:a:g?`Attached document text:
|
|
9
|
-
|
|
10
|
-
${g}`:"",j=[],k=v?c:b?.cwd??A?.info?.cwd;if(d?.length&&k)try{j=await p(k,d)}catch(a){a6(a instanceof Error?a.message:String(a));return}let l=j.length?j.map(a=>{var b;return{type:"image",path:a.path,mimeType:a.mimeType,name:a.name,source:{type:"url",url:(b=a.path,`/api/files/${(0,o.HG)(b)}?type=read`),media_type:a.mimeType}}}):d?.map(a=>({type:"image",source:{type:"base64",media_type:a.mimeType,data:a.data}})),q={role:"user",content:l?.length?[...i.trim()?[{type:"text",text:i}]:[],...l]:i,timestamp:Date.now()},r=R(),s=v?null:b?.id??null;s&&M(s);let u=bu.current,w=T(q.content);bq.current.set(r,{localId:r,sessionId:s??"__new__",leafId:u,message:q,createdAt:Date.now(),kind:"prompt",confirmKey:w,confirmCountAtCreate:v?0:w?br.current.get(w)??0:0}),ac(a=>[...a,q]),a6(null),bh.current=!0,ao(!0),a2({kind:"waiting_model"}),am({type:"start"}),bn.current=!0;let x=ar.find(a=>a.provider===bK?.provider&&a.id===bK?.modelId)?.input,y=!x||0===x.length||x.includes("image")?d?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})):void 0;try{if(v&&c){ax&&aW(ax);let b=f??bM(),d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:c,type:"prompt",message:i,toolNames:b,deferPrompt:!0,...y?.length?{images:y}:{},...ax?{provider:ax.provider,modelId:ax.modelId}:{},..."auto"!==aJ?{thinkingLevel:aJ}:{}})}),e=await d.json().catch(()=>({}));if(!d.ok||e.error||!e.sessionId)throw Error(e.error??`HTTP ${d.status}`);let g=e.sessionId;a8.current=g;let j=bq.current.get(r);j&&(j.sessionId=g),bk.current?.(),bk.current=F(g,()=>{a8.current===g&&(ao(!1),a2(null))}),bw.current=g,await bZ(g,{requireConnected:!0,timeoutMs:1e4}),await n(g,{type:"prompt",message:i,toolNames:b,...y?.length?{images:y}:{}}),h?.({id:g,path:"",cwd:c,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:a})}else if(b){let a=f??bM();await bO(b.id),bk.current?.(),bk.current=F(b.id,()=>{a8.current===b.id&&(ao(!1),a2(null))}),await bZ(b.id,{requireConnected:!0,timeoutMs:1e4}),await n(b.id,{type:"prompt",message:i,toolNames:a,leafId:u,...bK?{provider:bK.provider,modelId:bK.modelId}:{},..."auto"!==aJ?{thinkingLevel:aJ}:{},...y?.length?{images:y}:{}})}}catch(c){let b=a8.current;if(bq.current.delete(r),ac(a=>a.filter(a=>a!==q)),c instanceof m&&(409===c.status||"SESSION_BUSY"===c.code)){a6("This session is already running in another tab. Showing that active run instead."),bh.current=!0,ao(!0),a2({kind:"waiting_model"}),am({type:"start"}),b&&(a7.current?.close(),a7.current=null,H(b),bZ(b,{replay:!0}),bj.current?.(b,"prompt_conflict"));return}if(console.error("Failed to send message:",c),v&&a8.current){let a=a8.current;a8.current=null,bw.current=null,fetch(`/api/sessions/${encodeURIComponent(a)}`,{method:"DELETE"}).catch(()=>{})}t?.current&&a.trim()&&t.current.insertIfEmpty(a),t?.current&&d?.length&&t.current.addBase64Images?.(d.map(({data:a,mimeType:b})=>({data:a,mimeType:b}))),a6(c instanceof Error?c.message:String(c)),a7.current?.close(),a7.current=null,b&&G(b),bh.current=!1,ao(!1),a2(null),am({type:"end"})}},[v,c,ax,bM,aJ,b,A?.info?.cwd,an,bZ,h,bN,ar,bK,bO,t]),b0=(0,d.useCallback)(async()=>{let a=a8.current;if(!a)return;let b=bE.current;bh.current=!1,aI(!1),aG(null),a6(null),ao(!1),a2(null),am({type:"end"}),a7.current?.close(),a7.current=null,G(a),M(a);try{await n(a,{type:b?"abort_bash":"abort"}),await bS(a,!1,!1,!0)}catch(b){console.error("Failed to abort:",b),await bS(a,!1,!1,!0)}finally{b&&(bE.current=!1,aI(!1),aG(null))}},[bS]),b1=(0,d.useCallback)(async(a,b)=>{let c=a8.current,d=a.trim();if(c&&d){bE.current=!0,aI(!0),a6(null),aG({command:d,output:""}),bh.current=!0,ao(!0),a2({kind:"running_tools",tools:[{id:"bash",name:"bash",args:d}]});try{await n(c,{type:"bash",command:d,excludeFromContext:b})}catch(a){a6(a instanceof Error?a.message:String(a))}finally{bG.current&&(clearTimeout(bG.current),bG.current=null),bF.current="",bE.current=!1,aI(!1),aG(null),bh.current=!1,ao(!1),a2(null),M(c),await bS(c,!1,!1,!0)}}},[bS]),b2=(0,d.useCallback)(async a=>{let b=a8.current;if(b){aS(a);try{let{cancelled:c,newSessionId:d}=await n(b,{type:"fork",entryId:a})??{};!c&&d&&i?.(d)}catch(a){console.error("Fork failed:",a)}finally{aS(null)}}},[i]),b3=(0,d.useCallback)(async a=>{let d=a8.current,e=A?.info?.cwd??b?.cwd??c??null;if(!d||!e)return{ok:!1,error:"No active session to fork"};if(bh.current)return{ok:!1,error:"Agent is still running"};try{let b=bM(),c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,type:"prompt",parentSessionId:d,deferPrompt:!0,toolNames:b,...bK?{provider:bK.provider,modelId:bK.modelId}:{},..."auto"!==aJ?{thinkingLevel:aJ}:{}})}),f=await c.json().catch(()=>({}));if(!c.ok||f.error||!f.sessionId)return{ok:!1,error:f.error??`HTTP ${c.status}`};let g=f.sessionId;try{await n(g,{type:"append_message",message:a,customType:"fork_handoff",display:!0})}catch{}return h?.({id:g,path:"",cwd:e,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:a.slice(0,120),parentSessionId:d}),{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}},[A?.info?.cwd,b?.cwd,c,bK,aJ,bM,h]),b4=(0,d.useCallback)(async a=>{let b=a8.current;b&&(bs.current.delete(b),M(b),bu.current=a,aa(a),await bW(b,a))},[bW]);(0,d.useCallback)(async a=>{bu.current=a,aa(a);let b=a8.current;b&&(bs.current.delete(b),M(b),await bW(b,a))},[bW]);let b5=(0,d.useCallback)(async(a,b)=>{if(v)return void bH({provider:a,modelId:b});let c=a8.current;if(c)try{var d;a6(null);let e=await n(c,{type:"set_model",provider:a,modelId:b}),f={provider:e.provider,modelId:e.id};e.thinkingLevel&&(d=e.thinkingLevel,"auto"===d||"off"===d||"minimal"===d||"low"===d||"medium"===d||"high"===d||"xhigh"===d)&&aK(e.thinkingLevel),aU(f),I(a=>a?{...a,context:{...a.context,model:f}}:a)}catch(b){let a=b instanceof Error?b.message:String(b);console.error("Failed to set model:",b),a6(a)}},[v,bH]),b6=(0,d.useCallback)(async()=>{let a=a8.current;if(a&&!aX){aY(!0),a$(null),a0(null);try{let b=await n(a,{type:"compact"});b?.reducedBy!=null&&a0(`Compacted ~${b.tokensBefore??"?"} → ~${b.tokensAfter??"?"} tokens (−${b.reducedBy})`),await bS(a,!0)}catch(a){a$(a instanceof Error?a.message:String(a))}finally{aY(!1)}}},[aX,bS]),b7=(0,d.useCallback)(async(a,b,c)=>{let d=a8.current;if(!d)return;M(d);let e=bN(c),f=a.trim()?e?`${a}
|
|
11
|
-
|
|
12
|
-
Attached document text:
|
|
13
|
-
|
|
14
|
-
${e}`:a:e?`Attached document text:
|
|
15
|
-
|
|
16
|
-
${e}`:"",g=ar.find(a=>a.provider===bK?.provider&&a.id===bK?.modelId)?.input,h=!g||0===g.length||g.includes("image")?b?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})):void 0,i={role:"user",content:`[steer] ${f}`,timestamp:Date.now()},j=R(),k=S(f,h?.length??0);bq.current.set(j,{localId:j,sessionId:d,leafId:bu.current,message:i,createdAt:Date.now(),kind:"steer",confirmKey:k,confirmCountAtCreate:k?br.current.get(k)??0:0}),ac(a=>[...a,i]);try{await n(d,{type:"steer",message:f,...h?.length?{images:h}:{}})}catch(a){bq.current.delete(j),console.error("Failed to steer:",a)}},[bN,ar,bK]),b8=(0,d.useCallback)(async(a,b,c)=>{let d=a8.current;if(!d)return;M(d);let e=bN(c),f=a.trim()?e?`${a}
|
|
17
|
-
|
|
18
|
-
Attached document text:
|
|
19
|
-
|
|
20
|
-
${e}`:a:e?`Attached document text:
|
|
21
|
-
|
|
22
|
-
${e}`:"",g=ar.find(a=>a.provider===bK?.provider&&a.id===bK?.modelId)?.input,h=!g||0===g.length||g.includes("image")?b?.map(a=>({type:"image",data:a.data,mimeType:a.mimeType})):void 0,i={role:"user",content:f,timestamp:Date.now()},j=R(),k=S(f,h?.length??0);bq.current.set(j,{localId:j,sessionId:d,leafId:bu.current,message:i,createdAt:Date.now(),kind:"follow_up",confirmKey:k,confirmCountAtCreate:k?br.current.get(k)??0:0}),ac(a=>[...a,i]);try{await n(d,{type:"follow_up",message:f,...h?.length?{images:h}:{}})}catch(a){bq.current.delete(j),console.error("Failed to follow up:",a)}},[bN,ar,bK]),b9=(0,d.useCallback)(async()=>{let a=a8.current;if(a)try{await n(a,{type:"abort_compaction"})}catch(a){console.error("Failed to abort compaction:",a)}},[]),ca=(0,d.useCallback)(async a=>{if(aK(a),"auto"===a)return;let b=a8.current;if(b)try{await n(b,{type:"set_thinking_level",level:a})}catch(a){console.error("Failed to set thinking level:",a)}},[]),cb=(0,d.useCallback)(async a=>{bI(a);let b=(0,N.tE)(a,aB),c=a8.current;if(c)try{await n(c,{type:"set_tools",toolNames:b})}catch(a){console.error("Failed to set tools:",a)}},[aB,bI]),cc=(0,d.useCallback)(async a=>{bJ(a);let b=(0,N.tE)(az,a),c=a8.current;if(c)try{await n(c,{type:"set_tools",toolNames:b})}catch(a){console.error("Failed to set memory tools:",a)}},[bJ,az]);(0,d.useCallback)((a="smooth")=>{bo.current?.scrollIntoView({behavior:a})},[]),(0,d.useCallback)(()=>{let a=bp.current,b=bm.current;if(!a||!b)return;let c=b.getBoundingClientRect().top-a.getBoundingClientRect().top+a.scrollTop;a.scrollTo({top:c-16,behavior:"smooth"})},[]);let cd=(0,d.useCallback)(async()=>{let a=a8.current;if(a)try{await n(a,{type:"clear_queue"}),a4({steering:[],followUp:[]})}catch(a){a6(a instanceof Error?a.message:String(a))}},[]);return{data:A,loading:X,error:Z,activeLeafId:_,messages:ab,entryIds:ad,streamState:al,agentRunning:an,modelNames:ap,modelList:ar,modelThinkingLevels:at,modelThinkingLevelMaps:av,newSessionModel:ax,toolPreset:az,memoryTools:aB,thinkingLevel:aJ,retryInfo:aL,queuedMessages:a3,extensionStatuses:a9,extensionWidgets:ba,extensionDialog:bb,extensionNotices:bc,bashLive:aF,bashRunning:aH,contextUsage:aN,systemPrompt:aP,forkingEntryId:aR,isCompacting:aX,compactError:aZ,compactInfo:a_,currentModel:bK,displayModel:bL,sessionStats:bP,agentPhase:a1,agentError:a5,isNew:v,sessionIdRef:a8,sseReaderRef:a7,messagesEndRef:bo,scrollContainerRef:bp,lastUserMsgRef:bm,pendingScrollToUserRef:bn,initialScrollDoneRef:bl,handleSend:b_,handleAbort:b0,handleFork:b2,handleNavigate:b4,handleModelChange:b5,handleCompact:b6,handleSteer:b7,handleFollowUp:b8,handleAbortCompaction:b9,handleToolPresetChange:cb,handleMemoryToolsChange:cc,handleThinkingLevelChange:ca,handleClearQueue:cd,handleBash:b1,respondToExtensionUi:bf,dismissExtensionNotice:bg,loadTools:bX,loadSlashCommands:bY,slashCommands:aD,setActiveLeafId:aa,setData:I,setMessages:ac,dispatch:am,setAgentRunning:ao,setForkingEntryId:aS,forkToNewSession:b3,loadMoreMessages:bU,hasMoreMessages:ah,totalMessages:af,loadedMessagesCount:aj,loadShadowedMessages:bV,handleAgentEventRef:bi}}}};
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2257],{12257:(e,t,n)=>{n.d(t,{T:()=>Q});var r=n(12115);function a(e){return e?.phase==="running_tools"?{kind:"running_tools",tools:(e.activeTools??[]).map(e=>({id:e.id,name:e.name}))}:e?.phase==="streaming"||e?.phase==="compacting"||e?.phase==="idle"?null:{kind:"waiting_model"}}function o(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}let s={isStreaming:!1,streamingMessage:null};function l(){return{role:"assistant",content:[],model:"",provider:"",timestamp:Date.now()}}function i(e,t,n){if(!Number.isInteger(t)||void 0===t||t<0)return e;let r=e.streamingMessage??l(),a=[...r.content],o=n(a[t]);return o?(a[t]=o,{isStreaming:!0,streamingMessage:{...r,content:a}}):e}function u(e){if(e.id||e.toolName)return{...e.id?{id:e.id}:{},...e.toolName?{toolName:e.toolName}:{}};let t=e.partial,n=e.contentIndex;if(!t||!Array.isArray(t.content)||void 0===n)return{};let r=t.content[n];return r&&"toolCall"===r.type?{..."string"==typeof r.id?{id:r.id}:"string"==typeof r.toolCallId?{id:r.toolCallId}:{},..."string"==typeof r.name?{toolName:r.name}:"string"==typeof r.toolName?{toolName:r.toolName}:{}}:{}}function c(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"snapshot":return"assistant"===t.message.role?{isStreaming:!0,streamingMessage:t.message}:e;case"delta":var n=t.event;switch(n.type){case"start":return{isStreaming:!0,streamingMessage:e.streamingMessage??l()};case"text_start":return i(e,n.contentIndex,e=>e?.type==="text"?e:{type:"text",text:""});case"text_delta":return i(e,n.contentIndex,e=>({type:"text",text:(e?.type==="text"?e.text:"")+(n.delta??"")}));case"text_end":return i(e,n.contentIndex,e=>({type:"text",text:n.content??(e?.type==="text"?e.text:"")}));case"thinking_start":return i(e,n.contentIndex,e=>e?.type==="thinking"?e:{type:"thinking",thinking:""});case"thinking_delta":return i(e,n.contentIndex,e=>({type:"thinking",thinking:(e?.type==="thinking"?e.thinking:"")+(n.delta??"")}));case"thinking_end":return i(e,n.contentIndex,e=>({type:"thinking",thinking:n.content??(e?.type==="thinking"?e.thinking:"")}));case"toolcall_start":return i(e,n.contentIndex,e=>{let t=u(n);return e?.type==="toolCall"?{...e,...t.id?{toolCallId:t.id}:{},...t.toolName?{toolName:t.toolName}:{},rawInput:e.rawInput??""}:{type:"toolCall",toolCallId:t.id??"",toolName:t.toolName??"tool",input:{},rawInput:""}});case"toolcall_delta":return i(e,n.contentIndex,e=>{let t=u(n),r=e?.type==="toolCall"?e:{type:"toolCall",toolCallId:t.id??"",toolName:t.toolName??"tool",input:{}};return{...r,...t.id?{toolCallId:t.id}:{},...t.toolName?{toolName:t.toolName}:{},rawInput:(r.rawInput??"")+(n.delta??"")}});case"toolcall_end":return i(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall?.id??"",toolName:n.toolCall?.name??"tool",input:n.toolCall?.arguments??{}}));default:return e}case"end":case"reset":return s;default:return e}}function d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function p(e){if("assistant"!==e.role)return null;let t=e.timestamp;return"number"!=typeof t?null:`assistant:${t}`}class m extends Error{constructor(e,t,n){super(e),this.status=t,this.code=n,this.name="AgentCommandError"}}async function f(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new m(r.error??`HTTP ${n.status}`,n.status,r.code);return r.data}var g=n(28999);async function h(e,t){if(!t.length)return[];let n=await fetch("/api/images/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,images:t.map(e=>({data:e.data,mimeType:e.mimeType,name:e.name}))})}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw Error(r.error??`Upload failed (HTTP ${n.status})`);return(r.uploaded??[]).map((e,n)=>({...e,previewUrl:t[n]?.previewUrl}))}async function y(e,t,n){let r,a=new TextDecoder,o="",s=e=>{if(e.startsWith("id: ")){r=e.slice(4);return}if(!e.startsWith("data: "))return;let n=e.slice(6);if("[DONE]"!==n)try{t(n,r)}catch{}finally{r=void 0}},l=new Promise(e=>{n?.aborted?e():n?.addEventListener("abort",()=>e(),{once:!0})});for(;;){let t=await Promise.race([e.read(),l.then(()=>({done:!0,value:void 0}))]);if(t.done)break;let n=(o+=a.decode(t.value,{stream:!0})).split("\n");for(let e of(o=n.pop()||"",n))s(e)}if(o.trim())for(let e of o.split("\n"))s(e)}var w=n(16865);let k="__annovibeStreamSessions__",v="__annovibeStreamListeners__",b="__annovibeStreamErrorCallbacks__";function C(){let e=globalThis;return e[k]||(e[k]=new Map),e[k]}function x(){let e=globalThis;return e[b]||(e[b]=new Map),e[b]}function _(e){return{sessionId:e,phase:"idle",startedAt:null,lastEventAt:null,lastHeartbeatAt:null,reconnectCount:0,lastSyncReason:null,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!1,error:null}}function T(e,t){let n;for(let r of(!(n=globalThis)[v]&&(n[v]=new Map),n[v]).get(e)??[])try{r(t)}catch{}}function I(e){e.textThrottleTimer&&(clearTimeout(e.textThrottleTimer),e.textThrottleTimer=null),e.textDirty&&(e.textDirty=!1,M(e))}function S(e,t=!1){let n=Date.now();if(e.snapshot.lastEventAt=n,!t){e.textDirty=!0,e.textThrottleTimer||(e.textThrottleTimer=setTimeout(()=>{e.textThrottleTimer=null,e.textDirty&&(e.textDirty=!1,M(e))},100));return}I(e),M(e)}function M(e,t){let n=Date.now(),r=function(e){let t=[];for(let n of e.toolCalls.values())t.push({type:"toolCall",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input??{}});let n=e.accumulatedText.trim();return n&&t.push({type:"text",text:n}),t}(e),a=(t??e.snapshot.phase)==="active";e.snapshot={...e.snapshot,phase:t??e.snapshot.phase,lastEventAt:n,accumulatedText:e.accumulatedText,toolCalls:[...e.toolCalls.values()],toolResults:[...e.toolResults.values()],statusText:a?function(e){if(e.activeToolId){let t=e.toolCalls.get(e.activeToolId);if(t){let e=Math.max(0,Math.floor((Date.now()-t.startedAt)/1e3));return`Running ${t.toolName||"tool"}… (${e}s)`}}return e.accumulatedText.trim()?"Generating response…":e.toolCalls.size>0?"Finishing tool results…":null}(e):e.snapshot.statusText,streamingMessage:a&&r.length>0?{role:"assistant",content:r}:null,isStreaming:a},T(e.snapshot.sessionId,{type:"snapshot-updated",snapshot:e.snapshot})}function A(e){E(e),e.idleCheckTimer=setInterval(()=>{if("connected"!==e.connectionState)return;let t=Math.max(e.snapshot.lastEventAt??0,e.snapshot.lastHeartbeatAt??0);if(Date.now()-t>=18e4){R(e),I(e);let t="Stream idle timeout — no activity for 180s.";e.snapshot={...e.snapshot,phase:"error",isStreaming:!1,streamingMessage:null,statusText:null,error:t},E(e),T(e.snapshot.sessionId,{type:"error",snapshot:e.snapshot});let n=x().get(e.snapshot.sessionId);if(n)try{n(e.snapshot.sessionId,t)}catch{}}},1e4)}function E(e){e.idleCheckTimer&&(clearInterval(e.idleCheckTimer),e.idleCheckTimer=null)}function R(e){e.toolProgressTimer&&(clearInterval(e.toolProgressTimer),e.toolProgressTimer=null)}function $(e){let t=C(),n=t.get(e);return n||(n={snapshot:_(e),accumulatedText:"",toolCalls:new Map,toolResults:new Map,toolProgressTimer:null,activeToolId:null,textThrottleTimer:null,textDirty:!1,connectionState:"idle",idleCheckTimer:null},t.set(e,n)),n}function N(e,t){let n=x();return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function D(e){let t=C(),n=t.get(e);n&&(R(n),E(n),I(n)),t.delete(e)}function L(e){let t=C().get(e);t&&(t.snapshot={...t.snapshot,reconnectCount:t.snapshot.reconnectCount+1,lastSyncReason:"sse-reconnect",lastEventAt:Date.now()},S(t,!0))}let U="__annovibeSessionMessageCache__";function P(){let e=globalThis;if(!e[U]){var t;let n={entries:new Map,cleanupTimer:null};e[U]=n,(t=n).cleanupTimer||(t.cleanupTimer=setInterval(()=>{let e=Date.now();for(let[n,r]of t.entries)e-r.loadedAt>72e5&&t.entries.delete(n)},6e4))}return e[U]}function j(e){let t=P(),n=t.entries.get(e);return n?Date.now()-n.loadedAt>72e5?(t.entries.delete(e),null):(n.loadedAt=Date.now(),{...n,messages:[...n.messages],entryIds:[...n.entryIds]}):null}function O(e,t,n,r,a){let o=P(),s=o.entries.get(e);if(!s)return;let l=new Set(s.entryIds),i=[],u=[];for(let e=0;e<t.length;e++){let r=n[e];r&&!l.has(r)&&(i.push(t[e]),u.push(r))}0!==i.length&&o.entries.set(e,{...s,messages:[...i,...s.messages],entryIds:[...u,...s.entryIds],hasMore:r,loadedMessagesCount:a,loadedAt:Date.now()})}function F(e){P().entries.delete(e)}var q=n(14755);function H(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}let B=[500,1500,3e3];function W(e,t){return new DOMException(e,t)}function J(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}-${Math.random().toString(36).slice(2,11)}`}function K(e,t){return e.trim()||0!==t?`text:${e}|images:${t}`:null}function z(e){return"string"==typeof e?K(e,0):Array.isArray(e)?K(e.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n"),e.filter(e=>!!e&&"object"==typeof e&&"image"===e.type).length):null}function G(e){let t=new Map;for(let n of e){let e="user"!==n.role?null:z(n.content);e&&t.set(e,(t.get(e)??0)+1)}return t}function V(e,t,n){return e.sessionId===t&&(!e.leafId||n.includes(e.leafId))}function Y(e,t){let n=e.timestamp,r=t.timestamp;if("number"!=typeof n||"number"!=typeof r||n!==r||e.role!==t.role)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Q(e){let{session:t,newSessionCwd:n,onAgentEnd:l,onSessionCreated:i,onSessionForked:u,modelsRefreshKey:k,onBranchDataChange:v,chatInputRef:b}=e,x=null===t&&null!==n,[M,U]=(0,r.useState)(null),[Q,X]=(0,r.useState)(!x),[Z,ee]=(0,r.useState)(null),[et,en]=(0,r.useState)(null),[er,ea]=(0,r.useState)([]),[eo,es]=(0,r.useState)([]),[el,ei]=(0,r.useState)(0),[eu,ec]=(0,r.useState)(!1),[ed,ep]=(0,r.useState)(0),[em,ef]=(0,r.useReducer)(c,s),[eg,eh]=(0,r.useState)(!1),[ey,ew]=(0,r.useState)({}),[ek,ev]=(0,r.useState)([]),[eb,eC]=(0,r.useState)({}),[ex,e_]=(0,r.useState)({}),[eT,eI]=(0,r.useState)(null),[eS,eM]=(0,r.useState)("full"),[eA,eE]=(0,r.useState)([...q.SN]),[eR,e$]=(0,r.useState)([]),[eN,eD]=(0,r.useState)(null),[eL,eU]=(0,r.useState)(!1),[eP,ej]=(0,r.useState)("auto"),[eO,eF]=(0,r.useState)(null),[eq,eH]=(0,r.useState)(null),[eB,eW]=(0,r.useState)(null),[eJ,eK]=(0,r.useState)(null),[ez,eG]=(0,r.useState)(null),[eV,eY]=(0,r.useState)(null),[eQ,eX]=(0,r.useState)(!1),[eZ,e0]=(0,r.useState)(null),[e1,e3]=(0,r.useState)(null),[e4,e5]=(0,r.useState)(null),[e2,e6]=(0,r.useState)({steering:[],followUp:[]}),[e8,e7]=(0,r.useState)(null),e9=(0,r.useRef)(null),te=(0,r.useRef)(t?.id??null),{statuses:tt,widgets:tn,dialog:tr,notices:ta,applyFromState:to,handleEvent:ts,respond:tl,dismissNotice:ti}=function({chatInputRef:e,sessionIdRef:t,onError:n,noticeTtlMs:a=8e3}){let[o,s]=(0,r.useState)([]),[l,i]=(0,r.useState)([]),[u,c]=(0,r.useState)(null),[d,p]=(0,r.useState)([]),m=(0,r.useRef)(new Set),g=(0,r.useCallback)(()=>{for(let e of m.current)clearTimeout(e);m.current.clear()},[]);(0,r.useEffect)(()=>g,[g]);let h=(0,r.useCallback)((e,t)=>{let n={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,message:e,type:t};p(e=>[...e,n].slice(-4));let r=setTimeout(()=>{m.current.delete(r),p(e=>e.filter(e=>e.id!==n.id))},a);m.current.add(r)},[a]),y=(0,r.useCallback)(e=>{e&&(Array.isArray(e.extensionStatuses)&&s(e.extensionStatuses),Array.isArray(e.extensionWidgets)&&i(e.extensionWidgets))},[]),w=(0,r.useCallback)(t=>{if("extension_error"===t.type)return h("string"==typeof t.error?t.error:"Extension command failed","error"),!0;if("extension_ui_request"!==t.type)return!1;let n="string"==typeof t.method?t.method:"";if("select"===n||"confirm"===n||"input"===n||"editor"===n)return c({id:String(t.id??""),method:n,title:"string"==typeof t.title?t.title:"",...Array.isArray(t.options)?{options:t.options}:{},..."string"==typeof t.message?{message:t.message}:{},..."string"==typeof t.placeholder?{placeholder:t.placeholder}:{},..."string"==typeof t.prefill?{prefill:t.prefill}:{}}),!0;if("notify"===n){let e="warning"===t.notifyType||"error"===t.notifyType?t.notifyType:"info";return h(String(t.message??""),e),!0}if("setStatus"===n){let e=String(t.statusKey??"");if(!e)return!0;let n="string"==typeof t.statusText?t.statusText:null;return s(t=>{let r=t.filter(t=>t.key!==e);return n?[...r,{key:e,text:n}]:r}),!0}if("setWidget"===n){let e=String(t.widgetKey??"");if(!e)return!0;let n=Array.isArray(t.widgetLines)?t.widgetLines.filter(e=>"string"==typeof e):null;return i(r=>{let a=r.filter(t=>t.key!==e);return n&&n.length>0?[...a,{key:e,lines:n,placement:"string"==typeof t.widgetPlacement?t.widgetPlacement:"aboveEditor"}]:a}),!0}return"dismiss"===n?c(e=>e?.id===t.id?null:e):"set_editor_text"===n&&"string"==typeof t.text?e?.current?.setText?.(t.text):"setTitle"===n&&"string"==typeof t.title&&(document.title=t.title),!0},[e,h]),k=(0,r.useCallback)(async(e,r)=>{let a=t.current;if(c(t=>t?.id===e?null:t),a)try{await f(a,{type:"extension_ui_response",id:e,...r})}catch(e){n(e instanceof Error?e.message:String(e))}},[n,t]);return{statuses:o,widgets:l,dialog:u,notices:d,applyFromState:y,handleEvent:w,respond:k,dismissNotice:(0,r.useCallback)(e=>{p(t=>t.filter(t=>t.id!==e))},[]),reset:(0,r.useCallback)(()=>{g(),s([]),i([]),c(null),p([])},[g])}}({chatInputRef:b,sessionIdRef:te,onError:e7}),tu=(0,r.useRef)(!1),tc=(0,r.useRef)(null),td=(0,r.useRef)(null),tp=(0,r.useRef)(null),tm=(0,r.useRef)(!1),tf=(0,r.useRef)(null),tg=(0,r.useRef)(!1),th=(0,r.useRef)(null),ty=(0,r.useRef)(null),tw=(0,r.useRef)(new Map),tk=(0,r.useRef)(new Map),tv=(0,r.useRef)(new Map),tb=(0,r.useRef)(new Map),tC=(0,r.useRef)(null),tx=(0,r.useRef)([]),t_=(0,r.useRef)(null),tT=(0,r.useRef)(0),tI=(0,r.useRef)(!1),tS=(0,r.useRef)(0),tM=(0,r.useRef)(!1),tA=(0,r.useRef)(!1),tE=(0,r.useRef)(0),tR=(0,r.useRef)(null),t$=(0,r.useRef)(null),tN=(0,r.useRef)(0),tD=(0,r.useRef)(!1),tL=(0,r.useRef)(!1),tU=(0,r.useRef)(""),tP=(0,r.useRef)(null);(0,r.useEffect)(()=>{tC.current=et},[et]),(0,r.useEffect)(()=>{tD.current=em.isStreaming},[em.isStreaming]),(0,r.useEffect)(()=>{tb.current.clear()},[t?.id]);let tj=e.setNewSessionModel??eI,tO=e.setToolPreset??eM,tF=e.setMemoryTools??eE,tq=ez??M?.context.model??eV??null,tH=x?eT:tq,tB=(0,r.useCallback)(()=>(0,q.tE)(eS,eA),[eA,eS]),tW=(0,r.useCallback)(e=>e?.length?e.map((e,t)=>{let n=`Attachment ${t+1}: ${e.fileName} (${e.mimeType||"application/octet-stream"}, ${e.size} bytes)`;if(e.extractedText){let t=e.truncated?"\n[The extracted text was truncated before sending.]":"";return`${n}
|
|
2
|
-
${t}
|
|
3
|
-
${e.extractedText}`.trim()}return`${n}
|
|
4
|
-
[Text extraction unavailable: ${e.extractionError??"unsupported file type"}]`}).join("\n\n---\n\n"):"",[]),tJ=(0,r.useCallback)(async e=>{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/prepare`,{method:"POST"});if(!t.ok)throw Error((await t.json().catch(()=>({}))).error??`Failed to prepare session (HTTP ${t.status})`)},[]),tK=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0};for(let t of er){if("assistant"!==t.role)continue;let n=t.usage;n&&(e.input+=n.input??0,e.output+=n.output??0,e.cacheRead+=n.cacheRead??0,e.cacheWrite+=n.cacheWrite??0)}return e.input+e.output+e.cacheRead+e.cacheWrite>0?{tokens:e}:null})(),tz=(0,r.useRef)(!1),tG=(0,r.useCallback)(async()=>{let e=te.current;if(!e||tz.current||tM.current)return;tz.current=!0,tI.current=!0;let t=0,n=j(e);t=n?n.loadedMessagesCount:50;try{for(;;)try{let n=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=100&offset=${t}&deferThinking=1&deferMedia=1`);if(!n.ok)break;let r=await n.json();if(te.current!==e)break;let a=r.context.messages,o=r.context.entryIds??[];if(0===a.length)break;ea(e=>[...a,...e]),es(e=>{let t=[...o,...e];return tx.current=t,t});let s=t+a.length;if(ep(s),tS.current=s,ec(r.hasMore??!1),O(e,a,o,r.hasMore??!1,s),t=s,!r.hasMore)break;await new Promise(e=>setTimeout(e,800))}catch{break}}finally{tz.current=!1,tM.current=!0,tI.current=!1}},[]),tV=(0,r.useCallback)(async(e,t=!1,n=!1,r=!1)=>{var a;let o=null;try{if(t&&X(!0),!n&&!tu.current&&!r){let n=j(e);if(n)return ei(n.totalMessages),ec(n.hasMore),ep(n.loadedMessagesCount),ea(n.messages),tx.current=n.entryIds,es(n.entryIds),tC.current=n.leafId,en(n.leafId),tS.current=n.loadedMessagesCount,t&&X(!1),n.hasMore&&!tM.current&&setTimeout(()=>{tG()},1500),null}let s=n?`/api/sessions/${encodeURIComponent(e)}?includeState&deferThinking=1&deferMedia=1`:`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=0&deferThinking=1&deferMedia=1`,l=t$.current;if(l?.sid===e&&!t)return null;l?.controller.abort(W("Session load superseded","AbortError"));let i=new AbortController;o=i,t$.current={sid:e,controller:i};let u=setTimeout(()=>{i.abort(W("Session load timed out after 30 seconds","TimeoutError"))},3e4),c=await fetch(s,{signal:i.signal}).finally(()=>clearTimeout(u));if(te.current&&te.current!==e)return null;if(404===c.status)return t&&(U(null),tC.current=null,en(null),ea([]),ee(null)),null;if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();n?(ei(d.totalMessages??d.context.messages.length),ec(!1)):(ei(d.totalMessages??d.context.messages.length),ec(d.hasMore??!1)),ep(d.context.messages.length),U(d),tC.current=d.leafId,en(d.leafId);let m=d.context.messages,f=G(m),g=new Map,h=Date.now();for(let[t,n]of tw.current)if(n.sessionId===e){if(h-n.createdAt>12e4){tw.current.delete(t);continue}if(n.confirmKey){let e=f.get(n.confirmKey)??0,r=g.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(tw.current.delete(t),g.set(n.confirmKey,r+1))}}tk.current=f;let y=d.context.entryIds??[],w=[...tw.current.values()].filter(t=>V(t,e,y)).map(e=>e.message),k=w.length>0?[...m,...w]:m,v=function(e,t,n){if(0===t.size)return e;let r=!1,a=e.map(e=>{let a=p(e);if(!a)return e;let o=t.get(a);return o?n-o.observedAt>5e3||function(e,t){let n=e.timestamp,r=t.timestamp;if("number"!=typeof n||"number"!=typeof r||n!==r||e.role!==t.role)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}(o.message,e)?(t.delete(a),e):(r=!0,o.message):e});return r?a:e}(k,tb.current,Date.now()),b=tv.current.get(e);if(b){for(let[e,t]of b)h-t>12e4&&b.delete(e);0===b.size&&tv.current.delete(e)}let C=b?.size?b:null,x=C?new Set(y):null,_=!!C&&!!x&&[...C.keys()].some(e=>!x.has(e));C&&x&&!_&&tv.current.delete(e);let T=v.length;return!n&&(tS.current>T||_)?(ei(d.totalMessages??d.context.messages.length),ec(d.hasMore??!1)):(ea(e=>(function(e,t){if(e.length!==t.length)return t;let n=!1,r=t.map((t,r)=>Y(e[r],t)?e[r]:(n=!0,t));return n?r:e})(e,v)),tx.current=y,es(y),n?tS.current=T:tS.current=Math.max(tS.current,T),a={sessionId:e,leafId:d.leafId,messages:v,entryIds:y,totalMessages:d.totalMessages??d.context.messages.length,hasMore:!n&&(d.hasMore??!1),loadedMessagesCount:d.context.messages.length},P().entries.set(e,{...a,loadedAt:Date.now()})),eG(e=>{if(!e)return null;let t=d.context.model;return t?.provider===e.provider&&t.modelId===e.modelId?null:e}),ee(null),!d.agentState?.state?.thinkingLevel&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&ej(d.context.thinkingLevel),d.agentState??null}catch(e){if(e instanceof DOMException&&("AbortError"===e.name||"TimeoutError"===e.name)||e instanceof Error&&/aborted without reason|AbortError|Session load (?:timed out|superseded)/i.test(e.message))return null;return ee(String(e)),null}finally{o&&t$.current?.controller===o&&(t$.current=null),t&&X(!1)}},[tG]),tY=(0,r.useRef)(!1),tQ=(0,r.useCallback)(async()=>{if(tY.current)return;tY.current=!0;let e=te.current;if(!e){tY.current=!1;return}try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=${ed}&deferThinking=1&deferMedia=1`);if(!t.ok)return;let n=await t.json(),r=n.context.messages,a=n.context.entryIds??[];ea(e=>[...r,...e]),es(e=>{let t=[...a,...e];return tx.current=t,t}),ep(e=>e+r.length),ec(n.hasMore??!1),O(e,r,a,n.hasMore??!1,ed+r.length)}catch{}finally{tY.current=!1}},[ed]),tX=(0,r.useCallback)(async e=>{let t=te.current;if(!t)return[];let n=tC.current,r=n?`?leafId=${encodeURIComponent(n)}`:"";try{let n=await fetch(`/api/sessions/${encodeURIComponent(t)}/shadowed${r}`);if(!n.ok)return[];let a=await n.json(),o=a.groups?.find(t=>t.compactionEntryId===e);return o?.messages??[]}catch{return[]}},[]),tZ=(0,r.useCallback)(async(e,t)=>{try{let n=t?`/api/sessions/${encodeURIComponent(e)}/context?leafId=${encodeURIComponent(t)}&deferThinking=1&deferMedia=1`:`/api/sessions/${encodeURIComponent(e)}/context?deferThinking=1&deferMedia=1`,r=await fetch(n);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json(),o=a.context.messages,s=a.context.entryIds??[],l=G(o),i=new Map,u=Date.now();for(let[t,n]of tw.current)if(n.sessionId===e){if(u-n.createdAt>12e4){tw.current.delete(t);continue}if(n.confirmKey){let e=l.get(n.confirmKey)??0,r=i.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(tw.current.delete(t),i.set(n.confirmKey,r+1))}}tk.current=l;let c=[...tw.current.values()].filter(t=>V(t,e,s)).map(e=>e.message);ea(c.length>0?[...o,...c]:o),tx.current=s,es(s)}catch(e){console.error("Failed to load context:",e)}},[]),t0=(0,r.useCallback)(async e=>{try{let t=await f(e,{type:"get_tools"});t&&(tO((0,q.ES)(t)),tF((0,q.IB)(t)))}catch(e){console.error("Failed to load tools:",e)}},[tF,tO]),t1=(0,r.useCallback)(async e=>{try{let t=await f(e,{type:"get_commands"});e$(Array.isArray(t?.commands)?t.commands:[])}catch{e$([])}},[]),t3=(0,r.useCallback)((e,t={})=>{e9.current?.close(),e9.current=null;let n=`/api/agent/${encodeURIComponent(e)}/events${t.replay?"?replay=1":""}`;return!function(e){let t=$(e);if("active"===t.snapshot.phase)return S(t,!0),A(t),t.snapshot;let n=Date.now();t.snapshot={..._(e),phase:"active",startedAt:n,lastEventAt:n,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},A(t),S(t,!0),t.snapshot}(e),new Promise((r,a)=>{let o=!1,s=!1,l=null,i=e=>{if(!o){if(o=!0,clearTimeout(u),e){l?.close(),e9.current===l&&(e9.current=null),a(e);return}r()}},u=setTimeout(()=>{t.requireConnected?i(Error("Timed out waiting for event stream connection")):i()},t.timeoutMs??3e4);e9.current=l=function(e){let{url:t,onEvent:n,onStateChange:r,onFatalError:a,maxReconnectAttempts:o=1/0,reconnectBaseMs:s=1e3,reconnectMaxMs:l=3e4,autoReconnect:i=!0}=e,u="idle",c=new AbortController,d=0,p=null,m=null,f=!1,g=(e,t)=>{t&&(m=t),n(e,t)},h=e=>{u!==e&&(u=e,r?.(e))},w=()=>{null!==p&&(clearTimeout(p),p=null)},k=()=>{if(f)return;if(!i)return void h("error");if(d>=o){h("error"),a?.(Error(`Max reconnect attempts (${o}) reached`));return}let e=Math.min(l,s*2**d);d+=1,h("connecting"),p=setTimeout(()=>{p=null,v()},e)},v=async()=>{if(!f){w(),c=new AbortController,h("connecting");try{let e=await fetch(t,{signal:c.signal,headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...m?{"Last-Event-ID":m}:{}}});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);let n=e.body;if(!n)throw Error("Response has no readable body");let r=n.getReader();if(h("connected"),d=0,await y(r,g,c.signal),c.signal.aborted)try{await r.cancel()}catch{}r.releaseLock(),h("closed"),!f&&i&&k()}catch(e){if(f||e instanceof DOMException&&"AbortError"===e.name)return void h("closed");h("error"),i&&k()}}};return{get state(){return u},connect:()=>{f=!1,d=0,w(),v()},close:()=>{f=!0,w(),c.abort(),h("closed")},get abortController(){return c}}}({url:n,onEvent:t=>{try{let n=JSON.parse(t);if("connected"===n.type&&i(),te.current!==e)return;tc.current?.(n)}catch{}},onStateChange:t=>{!function(e,t){let n=C().get(e);if(!n)return;let r=n.connectionState;n.connectionState=t,"connected"===t&&"connected"!==r&&(n.snapshot={...n.snapshot,lastEventAt:Date.now(),lastHeartbeatAt:Date.now()},A(n)),"connected"!==t&&"connected"===r&&E(n)}(e,t),"connected"===t&&(s&&(L(e),td.current?.(e,"sse_reconnected")),s=!0)},reconnectBaseMs:1e3,reconnectMaxMs:3e4}),l.connect()})},[]),t4=(0,r.useCallback)(async(e,t="manual")=>{if(!e||te.current!==e)return;let n=tT.current;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`),r=await t.json().catch(()=>({}));if(te.current!==e||tT.current!==n)return;r.running?(tu.current=!0,eh(!0),e5(a(r.state)),e9.current&&"closed"!==e9.current.state&&"error"!==e9.current.state||(L(e),t3(e,{replay:!0}))):(tu.current=!1,e9.current?.close(),e9.current=null,D(e),eh(!1),e5(null),eF(null),ef({type:"end"}),F(e),await tV(e,!1,!1,!0)),r.state?.contextUsage!==void 0&&eH(r.state.contextUsage??null),r.state?.systemPrompt!==void 0&&eW(r.state.systemPrompt??null),r.state?.isCompacting!==void 0&&eX(r.state.isCompacting),r.state?.thinkingLevel!==void 0&&ej(r.state.thinkingLevel??"auto"),r.state?.queuedMessages!==void 0&&e6(H(r.state.queuedMessages)),to(r.state),r.state?.isBashRunning&&(tL.current=!0,eU(!0),eh(!0),e5({kind:"running_tools",tools:[{id:"bash",name:"bash"}]}))}catch{}},[t3,tV,to]);(0,r.useEffect)(()=>{td.current=t4},[t4]),(0,r.useEffect)(()=>{tu.current=eg},[eg]),tc.current=(0,r.useCallback)(e=>{let t=te.current;switch(t&&function(e,t){let n=$(e),r=Date.now();switch(t.type){case"agent_start":if("active"===n.snapshot.phase)return S(n,!0),n.snapshot;return R(n),n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.activeToolId=null,n.snapshot={..._(e),phase:"active",startedAt:r,lastEventAt:r,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},A(n),S(n,!0),n.snapshot;case"message_update":{let e=t.message;if(e?.role==="assistant"){let t=e.content;for(let e of Array.isArray(t)?t:[])"object"==typeof e&&null!==e&&"type"in e&&("text"===e.type?n.accumulatedText=e.text??"":"toolCall"===e.type&&e.toolCallId&&!n.toolCalls.has(e.toolCallId)&&n.toolCalls.set(e.toolCallId,{...e,startedAt:r}))}else{let e=t.assistantMessageEvent;e?.type==="text_delta"?n.accumulatedText+=e.delta??"":e?.type==="text_end"?n.accumulatedText=e.content??n.accumulatedText:(e?.type==="toolcall_start"||e?.type==="toolcall_delta")&&e.id&&!n.toolCalls.has(e.id)&&n.toolCalls.set(e.id,{type:"toolCall",toolCallId:e.id,toolName:e.toolName??"tool",input:{},startedAt:r})}return S(n,!1),n.snapshot}case"tool_execution_start":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",o=t.input??{};if(!e)return n.snapshot;let s=n.toolCalls.get(e);return n.toolCalls.set(e,{type:"toolCall",toolCallId:e,toolName:a,input:s&&Object.keys(s.input).length>0?s.input:o,startedAt:s?.startedAt??r}),n.activeToolId=e,R(n),n.activeToolId&&(n.toolProgressTimer=setInterval(()=>S(n,!0),1e3)),S(n,!0),n.snapshot}case"tool_execution_end":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",o="string"==typeof t.result?t.result:JSON.stringify(t.result??"");if(e){let s=n.toolCalls.get(e);s&&n.toolCalls.set(e,{...s,endedAt:r}),n.toolResults.set(e,{role:"toolResult",toolCallId:e,toolName:a,content:[{type:"text",text:o}],isError:!!t.isError,timestamp:r}),n.activeToolId===e&&(n.activeToolId=null,R(n))}return S(n,!0),n.snapshot}case"message_end":return I(n),S(n,!0),n.snapshot;case"agent_end":{if(I(n),R(n),n.activeToolId=null,!0===t.willRetry)return n.accumulatedText="",n.toolCalls.clear(),n.toolResults.clear(),n.snapshot={...n.snapshot,phase:"active",lastEventAt:r,accumulatedText:"",toolCalls:[],toolResults:[],statusText:null,streamingMessage:null,isStreaming:!0,error:null},A(n),T(e,{type:"snapshot-updated",snapshot:n.snapshot}),n.snapshot;E(n);let a="string"==typeof t.error?t.error:null;return n.snapshot={...n.snapshot,phase:a?"error":"completed",isStreaming:!1,streamingMessage:null,statusText:null,error:a},T(e,a?{type:"error",snapshot:n.snapshot}:{type:"completed",snapshot:n.snapshot}),n.snapshot}case"heartbeat":return n.snapshot={...n.snapshot,lastHeartbeatAt:r},n.snapshot;default:return n.snapshot}}(t,e),"heartbeat"!==e.type&&(tN.current=Date.now()),e.type){case"prompt_admitted":case"agent_start":e7(null),tu.current=!0,eh(!0),e5({kind:"waiting_model"}),ef({type:"start"});break;case"agent_end":if(!0===e.willRetry){tu.current=!0,eh(!0),e5({kind:"waiting_model"});break}if(tu.current=!1,eh(!1),e5(null),eF(null),ef({type:"end"}),t){tR.current&&clearTimeout(tR.current);let e=tT.current,n=0,r=async()=>{if(te.current!==t||tu.current||tT.current!==e)return;F(t),await tV(t,!1,!1,!0);let a=B[n++];void 0===a||te.current!==t||tu.current||tT.current!==e||(tR.current=setTimeout(()=>{tR.current=null,r()},a))};r(),fetch(`/api/agent/${encodeURIComponent(t)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eH(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eW(e.state.systemPrompt??null),e.state?.isCompacting!==void 0&&eX(e.state.isCompacting)}).catch(()=>{})}l?.();break;case"agent_settled":e5(null),eF(null),tu.current&&(tu.current=!1,eh(!1),ef({type:"end"}));break;case"message_start":case"message_update":{let t=e.message;if(t?.role==="user")break;tu.current||(tu.current=!0,eh(!0),e5({kind:"waiting_model"}));let n=e.assistantMessageEvent;t?.role==="assistant"?ef({type:"snapshot",message:o(t)}):n&&ef({type:"delta",event:n}),e5(null);break}case"message_end":{let n=e.message,r="string"==typeof e.__entryId?e.__entryId:null,a=tu.current;if(n&&"user"!==n.role){"assistant"===n.role&&"error"===n.stopReason&&n.errorMessage?.trim()&&e7(`Model response failed: ${n.errorMessage.trim()}`);let e=o(n),a=p(e);if(a&&tb.current.set(a,{observedAt:Date.now(),message:e}),!(r&&tx.current.includes(r))){if(t&&r){let e=tv.current.get(t)??new Map;e.set(r,Date.now()),tv.current.set(t,e)}ea(t=>t.some(t=>Y(t,e))?t:[...t,e]),r&&es(e=>{if(e.includes(r))return e;let t=[...e,r];return tx.current=t,t})}}a&&(ef({type:"reset"}),e5({kind:"waiting_model"}));break}case"replay_gap":t&&(F(t),tV(t,!1,!1,!0));break;case"prompt_done":if(!tu.current)break;t4(te.current??"","prompt_done");break;case"prompt_error":{let n="string"==typeof e.error&&e.error.trim()?e.error.trim():"The model request failed before producing a response.";if(tu.current=!1,eh(!1),e5(null),eF(null),ef({type:"end"}),e9.current?.close(),e9.current=null,t){for(let[e,n]of(D(t),tw.current))n.sessionId===t&&"prompt"===n.kind&&tw.current.delete(e);F(t),tV(t,!1,!1,!0)}e7(`Model request failed: ${n}`),l?.();break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,a="bash"===n&&"string"==typeof r?.command?r.command:void 0;e5(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n,args:a}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{let t=e.toolCallId,n=e.toolName,r=function(e){if(!d(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>d(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let a=r.replace(/\s+/g," ");return a.length<=500?a:`...${a.slice(-497)}`}(e.partialResult);if(!t)break;e5(e=>{let a=e?.kind==="running_tools"?[...e.tools]:[],o=a.find(e=>e.id===t),s={id:t,name:n||o?.name||"tool",args:o?.args,progress:r??o?.progress};return{kind:"running_tools",tools:[...a.filter(e=>e.id!==t),s]}});break}case"tool_execution_end":{let t=e.toolCallId;e5(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"extension_ui_request":case"extension_error":ts(e);break;case"bash_execution_start":{let t=String(e.command??"");tL.current=!0,eU(!0),eD({command:t,output:""}),eh(!0),e5({kind:"running_tools",tools:[{id:"bash",name:"bash",args:t}]});break}case"bash_execution_update":{let t="string"==typeof e.chunk?e.chunk:"";if(!t)break;tU.current+=t,tP.current||(tP.current=setTimeout(()=>{tP.current=null;let e=tU.current;tU.current="",e&&eD(t=>t?{...t,output:t.output+e}:t)},60));break}case"bash_done":{tP.current&&(clearTimeout(tP.current),tP.current=null),tU.current="",tL.current=!1,eU(!1),eD(null),eh(!1),e5(null);let e=te.current;e&&(F(e),tV(e,!1,!1,!0));break}case"queue_update":e6(H({steering:Array.isArray(e.steering)?e.steering:[],followUp:Array.isArray(e.followUp)?e.followUp:[]}));break;case"auto_retry_start":e7(null),tu.current=!0,eh(!0),e5({kind:"waiting_model"}),eF({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eF(null),!1===e.success&&"string"==typeof e.finalError&&e.finalError.trim()?e7(`Model response failed after retries: ${e.finalError.trim()}`):!0===e.success&&e7(null);break;case"auto_compaction_start":case"compaction_start":eX(!0),e0(null);break;case"auto_compaction_end":case"compaction_end":eX(!1),e.errorMessage?e0(e.errorMessage):!e.aborted&&te.current&&tV(te.current)}},[tV,l,t4,ts]);let t5=(0,r.useCallback)(async(e,r,a,o)=>{if(!e.trim()&&!r?.length&&!a?.length||eg)return;tT.current+=1;let s=tW(a),l=e.trim()?s?`${e}
|
|
5
|
-
|
|
6
|
-
Attached document text:
|
|
7
|
-
|
|
8
|
-
${s}`:e:s?`Attached document text:
|
|
9
|
-
|
|
10
|
-
${s}`:"",u=[],c=x?n:t?.cwd??M?.info?.cwd;if(r?.length&&c)try{u=await h(c,r)}catch(e){e7(e instanceof Error?e.message:String(e));return}let d=u.length?u.map(e=>{var t;return{type:"image",path:e.path,mimeType:e.mimeType,name:e.name,source:{type:"url",url:(t=e.path,`/api/files/${(0,g.HG)(t)}?type=read`),media_type:e.mimeType}}}):r?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),p={role:"user",content:d?.length?[...l.trim()?[{type:"text",text:l}]:[],...d]:l,timestamp:Date.now()},y=J(),w=x?null:t?.id??null;w&&F(w);let k=tC.current,v=z(p.content);tw.current.set(y,{localId:y,sessionId:w??"__new__",leafId:k,message:p,createdAt:Date.now(),kind:"prompt",confirmKey:v,confirmCountAtCreate:x?0:v?tk.current.get(v)??0:0}),ea(e=>[...e,p]),e7(null),tu.current=!0,eh(!0),e5({kind:"waiting_model"}),ef({type:"start"}),tg.current=!0;let C=ek.find(e=>e.provider===tq?.provider&&e.id===tq?.modelId)?.input,_=!C||0===C.length||C.includes("image")?r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0;try{if(x&&n){eT&&eY(eT);let t=o??tB(),r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,type:"prompt",message:l,toolNames:t,deferPrompt:!0,..._?.length?{images:_}:{},...eT?{provider:eT.provider,modelId:eT.modelId}:{},..."auto"!==eP?{thinkingLevel:eP}:{}})}),a=await r.json().catch(()=>({}));if(!r.ok||a.error||!a.sessionId)throw Error(a.error??`HTTP ${r.status}`);let s=a.sessionId;te.current=s;let u=tw.current.get(y);u&&(u.sessionId=s),tp.current?.(),tp.current=N(s,()=>{te.current===s&&(eh(!1),e5(null))}),t_.current=s,await t3(s,{requireConnected:!0,timeoutMs:1e4}),await f(s,{type:"prompt",message:l,toolNames:t,..._?.length?{images:_}:{}}),i?.({id:s,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:e})}else if(t){let e=o??tB();await tJ(t.id),tp.current?.(),tp.current=N(t.id,()=>{te.current===t.id&&(eh(!1),e5(null))}),await t3(t.id,{requireConnected:!0,timeoutMs:1e4}),await f(t.id,{type:"prompt",message:l,toolNames:e,leafId:k,...tq?{provider:tq.provider,modelId:tq.modelId}:{},..."auto"!==eP?{thinkingLevel:eP}:{},..._?.length?{images:_}:{}})}}catch(n){let t=te.current;if(tw.current.delete(y),ea(e=>e.filter(e=>e!==p)),n instanceof m&&(409===n.status||"SESSION_BUSY"===n.code)){e7("This session is already running in another tab. Showing that active run instead."),tu.current=!0,eh(!0),e5({kind:"waiting_model"}),ef({type:"start"}),t&&(e9.current?.close(),e9.current=null,L(t),t3(t,{replay:!0}),td.current?.(t,"prompt_conflict"));return}if(console.error("Failed to send message:",n),x&&te.current){let e=te.current;te.current=null,t_.current=null,fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})}b?.current&&e.trim()&&b.current.insertIfEmpty(e),b?.current&&r?.length&&b.current.addBase64Images?.(r.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))),e7(n instanceof Error?n.message:String(n)),e9.current?.close(),e9.current=null,t&&D(t),tu.current=!1,eh(!1),e5(null),ef({type:"end"})}},[x,n,eT,tB,eP,t,M?.info?.cwd,eg,t3,i,tW,ek,tq,tJ,b]),t2=(0,r.useCallback)(async()=>{let e=te.current;if(!e)return;let t=tL.current;tu.current=!1,eU(!1),eD(null),e7(null),eh(!1),e5(null),ef({type:"end"}),e9.current?.close(),e9.current=null,D(e),F(e);try{await f(e,{type:t?"abort_bash":"abort"}),await tV(e,!1,!1,!0)}catch(t){console.error("Failed to abort:",t),await tV(e,!1,!1,!0)}finally{t&&(tL.current=!1,eU(!1),eD(null))}},[tV]),t6=(0,r.useCallback)(async(e,t)=>{let n=te.current,r=e.trim();if(n&&r){tL.current=!0,eU(!0),e7(null),eD({command:r,output:""}),tu.current=!0,eh(!0),e5({kind:"running_tools",tools:[{id:"bash",name:"bash",args:r}]});try{await f(n,{type:"bash",command:r,excludeFromContext:t})}catch(e){e7(e instanceof Error?e.message:String(e))}finally{tP.current&&(clearTimeout(tP.current),tP.current=null),tU.current="",tL.current=!1,eU(!1),eD(null),tu.current=!1,eh(!1),e5(null),F(n),await tV(n,!1,!1,!0)}}},[tV]),t8=(0,r.useCallback)(async e=>{let t=te.current;if(t){eK(e);try{let{cancelled:n,newSessionId:r}=await f(t,{type:"fork",entryId:e})??{};!n&&r&&u?.(r)}catch(e){console.error("Fork failed:",e)}finally{eK(null)}}},[u]),t7=(0,r.useCallback)(async e=>{let r=te.current,a=M?.info?.cwd??t?.cwd??n??null;if(!r||!a)return{ok:!1,error:"No active session to fork"};if(tu.current)return{ok:!1,error:"Agent is still running"};try{let t=tB(),n=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:a,type:"prompt",parentSessionId:r,deferPrompt:!0,toolNames:t,...tq?{provider:tq.provider,modelId:tq.modelId}:{},..."auto"!==eP?{thinkingLevel:eP}:{}})}),o=await n.json().catch(()=>({}));if(!n.ok||o.error||!o.sessionId)return{ok:!1,error:o.error??`HTTP ${n.status}`};let s=o.sessionId;try{await f(s,{type:"append_message",message:e,customType:"fork_handoff",display:!0})}catch{}return i?.({id:s,path:"",cwd:a,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:e.slice(0,120),parentSessionId:r}),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},[M?.info?.cwd,t?.cwd,n,tq,eP,tB,i]),t9=(0,r.useCallback)(async e=>{let t=te.current;t&&(tv.current.delete(t),F(t),tC.current=e,en(e),await tZ(t,e))},[tZ]),ne=(0,r.useCallback)(async e=>{tC.current=e,en(e);let t=te.current;t&&(tv.current.delete(t),F(t),await tZ(t,e))},[tZ]),nt=(0,r.useCallback)(async(e,t)=>{if(x)return void tj({provider:e,modelId:t});let n=te.current;if(n)try{var r;e7(null);let a=await f(n,{type:"set_model",provider:e,modelId:t}),o={provider:a.provider,modelId:a.id};a.thinkingLevel&&(r=a.thinkingLevel,"auto"===r||"off"===r||"minimal"===r||"low"===r||"medium"===r||"high"===r||"xhigh"===r)&&ej(a.thinkingLevel),eG(o),U(e=>e?{...e,context:{...e.context,model:o}}:e)}catch(t){let e=t instanceof Error?t.message:String(t);console.error("Failed to set model:",t),e7(e)}},[x,tj]),nn=(0,r.useCallback)(async()=>{let e=te.current;if(e&&!eQ){eX(!0),e0(null),e3(null);try{let t=await f(e,{type:"compact"});t?.reducedBy!=null&&e3(`Compacted ~${t.tokensBefore??"?"} → ~${t.tokensAfter??"?"} tokens (−${t.reducedBy})`),await tV(e,!0)}catch(e){e0(e instanceof Error?e.message:String(e))}finally{eX(!1)}}},[eQ,tV]),nr=(0,r.useCallback)(async(e,t,n)=>{let r=te.current;if(!r)return;F(r);let a=tW(n),o=e.trim()?a?`${e}
|
|
11
|
-
|
|
12
|
-
Attached document text:
|
|
13
|
-
|
|
14
|
-
${a}`:e:a?`Attached document text:
|
|
15
|
-
|
|
16
|
-
${a}`:"",s=ek.find(e=>e.provider===tq?.provider&&e.id===tq?.modelId)?.input,l=!s||0===s.length||s.includes("image")?t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0,i={role:"user",content:`[steer] ${o}`,timestamp:Date.now()},u=J(),c=K(o,l?.length??0);tw.current.set(u,{localId:u,sessionId:r,leafId:tC.current,message:i,createdAt:Date.now(),kind:"steer",confirmKey:c,confirmCountAtCreate:c?tk.current.get(c)??0:0}),ea(e=>[...e,i]);try{await f(r,{type:"steer",message:o,...l?.length?{images:l}:{}})}catch(e){tw.current.delete(u),console.error("Failed to steer:",e)}},[tW,ek,tq]),na=(0,r.useCallback)(async(e,t,n)=>{let r=te.current;if(!r)return;F(r);let a=tW(n),o=e.trim()?a?`${e}
|
|
17
|
-
|
|
18
|
-
Attached document text:
|
|
19
|
-
|
|
20
|
-
${a}`:e:a?`Attached document text:
|
|
21
|
-
|
|
22
|
-
${a}`:"",s=ek.find(e=>e.provider===tq?.provider&&e.id===tq?.modelId)?.input,l=!s||0===s.length||s.includes("image")?t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0,i={role:"user",content:o,timestamp:Date.now()},u=J(),c=K(o,l?.length??0);tw.current.set(u,{localId:u,sessionId:r,leafId:tC.current,message:i,createdAt:Date.now(),kind:"follow_up",confirmKey:c,confirmCountAtCreate:c?tk.current.get(c)??0:0}),ea(e=>[...e,i]);try{await f(r,{type:"follow_up",message:o,...l?.length?{images:l}:{}})}catch(e){tw.current.delete(u),console.error("Failed to follow up:",e)}},[tW,ek,tq]),no=(0,r.useCallback)(async()=>{let e=te.current;if(e)try{await f(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ns=(0,r.useCallback)(async e=>{if(ej(e),"auto"===e)return;let t=te.current;if(t)try{await f(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),nl=(0,r.useCallback)(async e=>{tO(e);let t=(0,q.tE)(e,eA),n=te.current;if(n)try{await f(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[eA,tO]),ni=(0,r.useCallback)(async e=>{tF(e);let t=(0,q.tE)(eS,e),n=te.current;if(n)try{await f(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set memory tools:",e)}},[tF,eS]),nu=(0,r.useCallback)((e="smooth")=>{th.current?.scrollIntoView({behavior:e})},[]),nc=(0,r.useCallback)(()=>{let e=ty.current,t=tf.current;if(!e||!t)return;let n=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop;e.scrollTo({top:n-16,behavior:"smooth"})},[]);(0,r.useEffect)(()=>{if(t){var e;let n;if(te.current=t.id,t.id===t_.current)return t_.current=null,()=>{tR.current&&clearTimeout(tR.current),tR.current=null,e9.current?.close(),e9.current=null,tp.current?.(),tp.current=null};tM.current=!1,tS.current=0;let r=(e=t.id,(n=C().get(e))&&"idle"!==n.snapshot.phase?n.snapshot:null);r?.phase==="active"&&(tu.current=!0,eh(!0),e5({kind:"waiting_model"}),ef({type:"start"})),(async()=>{let e=await tV(t.id,!0,!0,!0);te.current===t.id&&(await t0(t.id),t1(t.id),e?.running?(tu.current=!0,eh(!0),e5(a(e.state)),ef({type:"start"}),t3(t.id,{replay:!0}),tp.current?.(),tp.current=N(t.id,()=>{te.current===t.id&&td.current?.(t.id,"stream_watchdog")})):e&&r?.phase==="active"?(tu.current=!1,eh(!1),e5(null),ef({type:"end"}),D(t.id)):e||r?.phase!=="active"||td.current?.(t.id,"mount_state_load_failed"),e?.state&&(void 0!==e.state.isCompacting&&eX(e.state.isCompacting),void 0!==e.state.contextUsage&&eH(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eW(e.state.systemPrompt??null),void 0!==e.state.queuedMessages&&e6(H(e.state.queuedMessages)),to(e.state),e.state.isBashRunning&&(tL.current=!0,eU(!0),eh(!0),e5({kind:"running_tools",tools:[{id:"bash",name:"bash"}]})),void 0!==e.state.thinkingLevel&&ej(e.state.thinkingLevel??"auto")),e&&!tu.current&&e.state?.contextUsage===void 0&&td.current?.(t.id,"mount_context_usage"))})()}return()=>{t_.current&&te.current===t_.current||(tR.current&&clearTimeout(tR.current),tR.current=null,t$.current?.controller.abort(W("Session changed","AbortError")),t$.current=null,e9.current?.close(),e9.current=null,tp.current?.(),tp.current=null)}},[t3,tV,t0,t1,v,t,to]),(0,r.useEffect)(()=>{let e=()=>{let e=te.current;e&&t4(e,"foreground")},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("focus",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("focus",e),window.removeEventListener("online",e)}},[t4]),(0,r.useEffect)(()=>{let e=te.current;if(e)return tA.current=!1,(0,w.O)(t=>{let n=t.includes(e),r=tA.current;tA.current=n,n&&!tu.current?(F(e),t4(e,"running_feed_start")):!n&&r&&(F(e),tu.current?t4(e,"running_feed_stop"):tV(e,!1,!1,!0))})},[tV,t4,t?.id]),(0,r.useEffect)(()=>{let e=window.setInterval(()=>{let e=te.current;e&&(tu.current?(t4(e,"interval"),tD.current&&Date.now()-tN.current>25e3&&(tN.current=Date.now(),F(e),tV(e,!1,!1,!0))):Date.now()-tE.current>=3e4?(tE.current=Date.now(),F(e),tV(e,!1,!1,!0)):tV(e))},15e3);return()=>window.clearInterval(e)},[tV,t4]),(0,r.useEffect)(()=>{v&&v(M?.tree??[],et,ne)},[M?.tree,et,ne,v]),(0,r.useEffect)(()=>{er.length>0&&!tI.current&&(tg.current?(tg.current=!1,tm.current=!0,nc()):tm.current?tu.current||nu("smooth"):(tm.current=!0,nu("instant")))},[er.length,eg,nu,nc]),(0,r.useEffect)(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{if(ew(e.models),e.thinkingLevels&&eC(e.thinkingLevels),e.thinkingLevelMaps&&e_(e.thinkingLevelMaps),e.modelList&&(ev(e.modelList),x&&e.modelList.length>0)){let t=e.defaultModel,n=t&&e.modelList.find(e=>e.id===t.modelId&&e.provider===t.provider);tj(n?{provider:n.provider,modelId:n.id}:{provider:e.modelList[0].provider,modelId:e.modelList[0].id})}}).catch(()=>{})},[x,k,tj]),(0,r.useEffect)(()=>{if(!eZ)return;let e=setTimeout(()=>e0(null),3e3);return()=>clearTimeout(e)},[eZ]),(0,r.useEffect)(()=>{if(!e1)return;let e=setTimeout(()=>e3(null),6e3);return()=>clearTimeout(e)},[e1]);let nd=(0,r.useCallback)(async()=>{let e=te.current;if(e)try{await f(e,{type:"clear_queue"}),e6({steering:[],followUp:[]})}catch(e){e7(e instanceof Error?e.message:String(e))}},[]);return{data:M,loading:Q,error:Z,activeLeafId:et,messages:er,entryIds:eo,streamState:em,agentRunning:eg,modelNames:ey,modelList:ek,modelThinkingLevels:eb,modelThinkingLevelMaps:ex,newSessionModel:eT,toolPreset:eS,memoryTools:eA,thinkingLevel:eP,retryInfo:eO,queuedMessages:e2,extensionStatuses:tt,extensionWidgets:tn,extensionDialog:tr,extensionNotices:ta,bashLive:eN,bashRunning:eL,contextUsage:eq,systemPrompt:eB,forkingEntryId:eJ,isCompacting:eQ,compactError:eZ,compactInfo:e1,currentModel:tq,displayModel:tH,sessionStats:tK,agentPhase:e4,agentError:e8,isNew:x,sessionIdRef:te,sseReaderRef:e9,messagesEndRef:th,scrollContainerRef:ty,lastUserMsgRef:tf,pendingScrollToUserRef:tg,initialScrollDoneRef:tm,handleSend:t5,handleAbort:t2,handleFork:t8,handleNavigate:t9,handleModelChange:nt,handleCompact:nn,handleSteer:nr,handleFollowUp:na,handleAbortCompaction:no,handleToolPresetChange:nl,handleMemoryToolsChange:ni,handleThinkingLevelChange:ns,handleClearQueue:nd,handleBash:t6,respondToExtensionUi:tl,dismissExtensionNotice:ti,loadTools:t0,loadSlashCommands:t1,slashCommands:eR,setActiveLeafId:en,setData:U,setMessages:ea,dispatch:ef,setAgentRunning:eh,setForkingEntryId:eK,forkToNewSession:t7,loadMoreMessages:tQ,hasMoreMessages:eu,totalMessages:el,loadedMessagesCount:ed,loadShadowedMessages:tX,handleAgentEventRef:tc}}},14755:(e,t,n)=>{n.d(t,{ES:()=>d,IB:()=>p,SN:()=>a,tE:()=>m});let r="subagent",a=["retain","recall","reflect"],o=[],s=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],i=[...l,"kernel_plot_run","kernel_plot_render","kernel_plot_inspect","kernel_plot_stop","kernel_plot_artifacts"],u=[...l,r];function c(e){return[...e].sort().join(",")}function d(e){let t=e.filter(e=>e.active).map(e=>e.name),n=t.filter(e=>!a.includes(e)),o=c(t),d=c(n);return""===o?"none":o===c(s)?"default":o===c(l)?"full":o===c(i)?"workbench":o===c(u)?"agent":""===d?"none":d===c(s)?"default":d===c(l)?"full":d===c(i)?"workbench":d===c(u)||t.includes(r)?"agent":"default"}function p(e){return a.filter(t=>e.some(e=>e.active&&e.name===t))}function m(e,t){return[...new Set([...function(e){switch(e){case"none":return o;case"default":return s;case"workbench":return i;case"agent":return u;default:return l}}(e),...t])]}},16865:(e,t,n)=>{n.d(t,{O:()=>w});let r=new Set,a=null,o=null,s=null,l=null,i=null,u=!1,c=!1;function d(e){for(let t of(a=[...new Set(e.filter(e=>"string"==typeof e))],r))try{t(a)}catch{}}async function p(){try{let e=await fetch("/api/agent/running",{cache:"no-store"});if(!e.ok)return;let t=await e.json();Array.isArray(t.runningSessionIds)&&d(t.runningSessionIds)}catch{}}function m(){s||0===r.size||(p(),s=setInterval(()=>{p()},5e3))}function f(){s&&(clearInterval(s),s=null)}function g(){if(!u){if(u=!0,window.__annovibeRunningSessionSubscribe){i=window.__annovibeRunningSessionSubscribe(d);return}if("u"<typeof SharedWorker)return void m();try{(o=new SharedWorker("/running-session-worker.js?v=1",{name:"annovibe-running-sessions-v1",type:"classic"})).port.onmessage=e=>{let t=e.data;"transport"===t.type?m():"running"===t.type&&Array.isArray(t.runningSessionIds)&&(l&&clearTimeout(l),l=null,f(),d(t.runningSessionIds.filter(e=>"string"==typeof e)))},o.onerror=()=>m(),o.port.start(),o.port.postMessage({type:"subscribe"}),l=setTimeout(()=>m(),3e3)}catch{o=null,m()}}}function h(){if(u){if(u=!1,l&&clearTimeout(l),l=null,f(),i?.(),i=null,o){try{o.port.postMessage({type:"disconnect"})}catch{}try{o.port.close()}catch{}}o=null,a=null}}function y(){r.size>0&&g()}function w(e){return r.add(e),a&&e(a),c||(c=!0,window.addEventListener("pagehide",h),window.addEventListener("pageshow",y)),g(),()=>{r.delete(e),0===r.size&&(h(),c&&(c=!1,window.removeEventListener("pagehide",h),window.removeEventListener("pageshow",y)))}}}}]);
|
|
File without changes
|
|
File without changes
|