@seqyuan/annovibe 0.8.146 → 0.8.147
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 +10 -10
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +4 -4
- 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 +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- 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/sessions/[id]/context/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/shadowed/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 +6 -6
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -6
- package/.next/server/app/index.segments/_full.segment.rsc +6 -6
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- 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 +2 -2
- package/.next/server/app/login.segments/_full.segment.rsc +2 -2
- package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/page.js +4 -4
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/smoke/page.js +2 -2
- 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 +6 -6
- package/.next/server/app/smoke/session-stream.segments/_full.segment.rsc +6 -6
- package/.next/server/app/smoke/session-stream.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/smoke/session-stream.segments/smoke/session-stream/__PAGE__.segment.rsc +6 -6
- package/.next/server/app/smoke.html +3 -51
- package/.next/server/app/smoke.rsc +5 -5
- package/.next/server/app/smoke.segments/_full.segment.rsc +5 -5
- package/.next/server/app/smoke.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/smoke.segments/smoke/__PAGE__.segment.rsc +5 -5
- package/.next/server/app-paths-manifest.json +10 -10
- package/.next/server/chunks/3048.js +264 -0
- package/.next/server/chunks/7180.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/3449-773a78c2b25dadd5.js +260 -0
- package/.next/static/chunks/8477-e7cabb053e63e504.js +22 -0
- package/.next/static/chunks/app/{page-de91c8247d46a20b.js → page-1ea50af93da7d407.js} +4 -4
- package/.next/static/chunks/app/smoke/{page-7226fa31540df8a8.js → page-bad59997a18b33e8.js} +2 -2
- package/.next/static/chunks/app/smoke/session-stream/{page-ed9bc29486c9e75d.js → page-9f43d950df17f1d3.js} +2 -2
- package/.next/static/css/be5cdd302b05dc22.css +1 -0
- package/package.json +1 -1
- package/.next/server/chunks/4801.js +0 -22
- package/.next/server/chunks/8305.js +0 -264
- package/.next/static/chunks/6630-afa0ca63437a28c6.js +0 -22
- package/.next/static/chunks/9867-11130aa00dcc6aa8.js +0 -260
- package/.next/static/css/d68ecb6695873888.css +0 -1
- /package/.next/static/{MHc4xkUiwo0WjuBfXFXEz → 33lxcaITML1UfRwyCMnDs}/_buildManifest.js +0 -0
- /package/.next/static/{MHc4xkUiwo0WjuBfXFXEz → 33lxcaITML1UfRwyCMnDs}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8477],{14755:(e,t,n)=>{n.d(t,{ES:()=>d,IB:()=>p,SN:()=>a,tE:()=>f});let r="subagent",a=["retain","recall","reflect"],s=[],o=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],i=[...l,"kernel_plot_run","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)),s=c(t),d=c(n);return""===s?"none":s===c(o)?"default":s===c(l)?"full":s===c(i)?"workbench":s===c(u)?"agent":""===d?"none":d===c(o)?"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 f(e,t){return[...new Set([...function(e){switch(e){case"none":return s;case"default":return o;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,s=null,o=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 f(){o||0===r.size||(p(),o=setInterval(()=>{p()},5e3))}function m(){o&&(clearInterval(o),o=null)}function g(){if(!u){if(u=!0,window.__annovibeRunningSessionSubscribe){i=window.__annovibeRunningSessionSubscribe(d);return}if("u"<typeof SharedWorker)return void f();try{(s=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?f():"running"===t.type&&Array.isArray(t.runningSessionIds)&&(l&&clearTimeout(l),l=null,m(),d(t.runningSessionIds.filter(e=>"string"==typeof e)))},s.onerror=()=>f(),s.port.start(),s.port.postMessage({type:"subscribe"}),l=setTimeout(()=>f(),3e3)}catch{s=null,f()}}}function h(){if(u){if(u=!1,l&&clearTimeout(l),l=null,m(),i?.(),i=null,s){try{s.port.postMessage({type:"disconnect"})}catch{}try{s.port.close()}catch{}}s=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)))}}},68477:(e,t,n)=>{n.d(t,{T:()=>er});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 s(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 o={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],s=n(a[t]);return s?(a[t]=s,{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:e.streamingMessage??l()};case"text_start":return i(e,t.contentIndex,e=>e?.type==="text"?e:{type:"text",text:""});case"text_delta":return i(e,t.contentIndex,e=>({type:"text",text:(e?.type==="text"?e.text:"")+(t.delta??"")}));case"text_end":return i(e,t.contentIndex,e=>({type:"text",text:t.content??(e?.type==="text"?e.text:"")}));case"thinking_start":return i(e,t.contentIndex,e=>e?.type==="thinking"?e:{type:"thinking",thinking:""});case"thinking_delta":return i(e,t.contentIndex,e=>({type:"thinking",thinking:(e?.type==="thinking"?e.thinking:"")+(t.delta??"")}));case"thinking_end":return i(e,t.contentIndex,e=>({type:"thinking",thinking:t.content??(e?.type==="thinking"?e.thinking:"")}));case"toolcall_start":return i(e,t.contentIndex,e=>{let n=u(t);return e?.type==="toolCall"?{...e,...n.id?{toolCallId:n.id}:{},...n.toolName?{toolName:n.toolName}:{},rawInput:e.rawInput??""}:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName??"tool",input:{},rawInput:""}});case"toolcall_delta":return i(e,t.contentIndex,e=>{let n=u(t),r=e?.type==="toolCall"?e:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName??"tool",input:{}};return{...r,...n.id?{toolCallId:n.id}:{},...n.toolName?{toolName:n.toolName}:{},rawInput:(r.rawInput??"")+(t.delta??"")}});case"toolcall_end":return i(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall?.id??"",toolName:t.toolCall?.name??"tool",input:t.toolCall?.arguments??{}}));default:return e}}function d(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":return c(e,t.event);case"deltas":{let n=e;for(let e of t.events)n=c(n,e);return n}case"end":case"reset":return o;default:return e}}let p=new Set(["text_delta","thinking_delta","toolcall_delta"]);function f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function m(e){if(!e||"object"!=typeof e)return"?";switch(e.type){case"text":return`text:${"string"==typeof e.text?e.text.length:-1}`;case"thinking":return`thinking:${"string"==typeof e.thinking?e.thinking.length:-1}`;case"toolCall":return`toolCall:${String(e.toolCallId??e.id??"")}`;default:return String(e.type??"")}}function g(e,t,n,r){if(0===e.length||0===n.length)return n;let a=e.length===n.length,s=new Map,o=[];for(let n=0;n<e.length;n++){let r=t[n];r&&s.set(r,e[n]),o[n]=e[n]}let l=!1,i=n.map((e,t)=>{let n=r[t],i=n?s.get(n):a?o[t]:void 0;return i&&function(e,t){if(e===t)return!0;if(e.role!==t.role||e.timestamp!==t.timestamp)return!1;if("assistant"===e.role){let n=e.content,r=t.content;if(!Array.isArray(n)||!Array.isArray(r))return!0;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(m(n[e])!==m(r[e]))return!1}return!0}(i,e)?i:(l=!0,e)});return!l&&a?e:i}function h(e){if("assistant"!==e.role)return null;let t=e.timestamp;return"number"!=typeof t?null:`assistant:${t}`}class y extends Error{constructor(e,t,n){super(e),this.status=t,this.code=n,this.name="AgentCommandError"}}async function w(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 y(r.error??`HTTP ${n.status}`,n.status,r.code);return r.data}async function v(e,t,n){let r,a=new TextDecoder,s="",o=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=(s+=a.decode(t.value,{stream:!0})).split("\n");for(let e of(s=n.pop()||"",n))o(e)}if(s.trim())for(let e of s.split("\n"))o(e)}let C="__annovibeStreamSessions__",k="__annovibeStreamListeners__",b="__annovibeStreamErrorCallbacks__";function I(){let e=globalThis;return e[C]||(e[C]=new Map),e[C]}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)[k]&&(n[k]=new Map),n[k]).get(e)??[])try{r(t)}catch{}}function S(e){e.textThrottleTimer&&(clearTimeout(e.textThrottleTimer),e.textThrottleTimer=null),e.textDirty&&(e.textDirty=!1,E(e))}function A(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,E(e))},100));return}S(e),E(e)}function E(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 M(e){R(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){$(e),S(e);let t="Stream idle timeout — no activity for 180s.";e.snapshot={...e.snapshot,phase:"error",isStreaming:!1,streamingMessage:null,statusText:null,error:t},R(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 R(e){e.idleCheckTimer&&(clearInterval(e.idleCheckTimer),e.idleCheckTimer=null)}function $(e){e.toolProgressTimer&&(clearInterval(e.toolProgressTimer),e.toolProgressTimer=null)}function N(e){let t=I(),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 D(e,t){let n=x();return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function L(e){let t=I(),n=t.get(e);n&&($(n),R(n),S(n)),t.delete(e)}function U(e){let t=I().get(e);t&&(t.snapshot={...t.snapshot,reconnectCount:t.snapshot.reconnectCount+1,lastSyncReason:"sse-reconnect",lastEventAt:Date.now()},A(t,!0))}let P={runtime:"idle",phase:null,retry:null,isCompacting:!1,compactError:null,error:null,queued:{steering:[],followUp:[]}};function j(e){return{steering:Array.isArray(e?.steering)?e.steering:[],followUp:Array.isArray(e?.followUp)?e.followUp:[]}}let O={runtime:"running",phase:{kind:"waiting_model"}},q={runtime:"idle",phase:null};var F=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}))}var B=n(16865);let W="__annovibeSessionMessageCache__";function J(){let e=globalThis;if(!e[W]){var t;let n={entries:new Map,cleanupTimer:null};e[W]=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[W]}function K(e){let t=J(),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 z(e,t,n,r,a){let s=J(),o=s.entries.get(e);if(!o)return;let l=new Set(o.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&&s.entries.set(e,{...o,messages:[...i,...o.messages],entryIds:[...u,...o.entryIds],hasMore:r,loadedMessagesCount:a,loadedAt:Date.now()})}function G(e){J().entries.delete(e)}var V=n(14755);let Y=[500,1500,3e3];function Q(e,t){return new DOMException(e,t)}function X(){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 Z(e,t){return e.trim()||0!==t?`text:${e}|images:${t}`:null}function ee(e){return"string"==typeof e?Z(e,0):Array.isArray(e)?Z(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 et(e){let t=new Map;for(let n of e){let e="user"!==n.role?null:ee(n.content);e&&t.set(e,(t.get(e)??0)+1)}return t}function en(e,t,n){return e.sessionId===t&&(!e.leafId||n.includes(e.leafId))}function er(e){let{session:t,newSessionCwd:n,onAgentEnd:l,onSessionCreated:i,onSessionForked:u,modelsRefreshKey:c,onBranchDataChange:m,chatInputRef:C}=e,k=null===t&&null!==n,[b,x]=(0,r.useState)(null),[E,W]=(0,r.useState)(!k),[er,ea]=(0,r.useState)(null),[es,eo]=(0,r.useState)(null),[el,ei]=(0,r.useState)([]),[eu,ec]=(0,r.useState)([]),[ed,ep]=(0,r.useState)(0),[ef,em]=(0,r.useState)(!1),[eg,eh]=(0,r.useState)(0),[ey,ew]=(0,r.useReducer)(d,o),ev=(0,r.useRef)([]),eC=(0,r.useRef)(null),ek=(0,r.useCallback)(()=>{ev.current=[],null!==eC.current&&(clearTimeout(eC.current),eC.current=null)},[]),eb=(0,r.useCallback)(()=>{null!==eC.current&&(clearTimeout(eC.current),eC.current=null);let e=ev.current;0!==e.length&&(ev.current=[],ew({type:"deltas",events:function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.type===n.type&&p.has(e.type)&&"string"==typeof e.delta&&"string"==typeof n.delta&&Number.isInteger(e.contentIndex)&&e.contentIndex===n.contentIndex&&e.id===n.id&&e.toolName===n.toolName&&void 0===e.content&&void 0===n.content&&void 0===e.partial&&void 0===n.partial&&void 0===e.toolCall&&void 0===n.toolCall&&1){t[t.length-1]={...e,delta:`${e.delta}${n.delta}`};continue}t.push(n)}return t}(e)}))},[]),eI=(0,r.useCallback)(e=>{ev.current.push(e);let t=function({pendingCount:e,timerArmed:t,flushMs:n=40,maxPending:r=400}){return e<=0?{flushNow:!1,armTimer:!1,delayMs:0}:e>=r?{flushNow:!0,armTimer:!1,delayMs:0}:{flushNow:!1,armTimer:!t,delayMs:n}}({pendingCount:ev.current.length,timerArmed:null!==eC.current});t.flushNow?eb():t.armTimer&&(eC.current=setTimeout(()=>{eC.current=null,eb()},t.delayMs))},[eb]),ex=(0,r.useCallback)(e=>{var t;"delta"!==(t=e.type)&&"deltas"!==t&&eb(),ew(e)},[eb]);(0,r.useEffect)(()=>()=>ek(),[ek]),(0,r.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&eb()};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[eb]);let[e_,eT]=(0,r.useState)(!1),[eS,eA]=(0,r.useState)({}),[eE,eM]=(0,r.useState)([]),[eR,e$]=(0,r.useState)({}),[eN,eD]=(0,r.useState)({}),[eL,eU]=(0,r.useState)(null),[eP,ej]=(0,r.useState)("full"),[eO,eq]=(0,r.useState)([...V.SN]),[eF,eH]=(0,r.useState)([]),[eB,eW]=(0,r.useState)("auto"),[eJ,eK]=(0,r.useState)(null),[ez,eG]=(0,r.useState)(null),[eV,eY]=(0,r.useState)(null),[eQ,eX]=(0,r.useState)(null),[eZ,e0]=(0,r.useState)(null),[e1,e4]=(0,r.useState)(null),[e3,e5]=(0,r.useState)(!1),[e6,e2]=(0,r.useState)(null),[e8,e7]=(0,r.useState)(null),[e9,te]=(0,r.useState)(null),[tt,tn]=(0,r.useState)({steering:[],followUp:[]}),[tr,ta]=(0,r.useState)(null),ts=(0,r.useRef)(t?.id??null),to=function({sessionIdRef:e,onEvent:t,onReconnect:n,reconnectBaseMs:a=1e3,reconnectMaxMs:s=3e4}){let o=(0,r.useRef)(null),l=(0,r.useRef)({onEvent:t,onReconnect:n});l.current={onEvent:t,onReconnect:n};let i=(0,r.useCallback)(()=>{o.current?.close(),o.current=null},[]),u=(0,r.useCallback)(()=>{let e=o.current;return!!e&&"closed"!==e.state&&"error"!==e.state},[]),c=(0,r.useCallback)((t,n={})=>{o.current?.close(),o.current=null;let r=`/api/agent/${encodeURIComponent(t)}/events${n.replay?"?replay=1":""}`;return!function(e){let t=N(e);if("active"===t.snapshot.phase)return A(t,!0),M(t),t.snapshot;let n=Date.now();t.snapshot={..._(e),phase:"active",startedAt:n,lastEventAt:n,isStreaming:!0,streamingMessage:{role:"assistant",content:[]}},M(t),A(t,!0),t.snapshot}(t),new Promise((i,u)=>{let c=!1,d=!1,p=null,f=e=>{if(!c){if(c=!0,clearTimeout(m),e){p?.close(),o.current===p&&(o.current=null),u(e);return}i()}},m=setTimeout(()=>{n.requireConnected?f(Error("Timed out waiting for event stream connection")):f()},n.timeoutMs??3e4);o.current=p=function(e){let{url:t,onEvent:n,onStateChange:r,onFatalError:a,maxReconnectAttempts:s=1/0,reconnectBaseMs:o=1e3,reconnectMaxMs:l=3e4,autoReconnect:i=!0}=e,u="idle",c=new AbortController,d=0,p=null,f=null,m=!1,g=(e,t)=>{t&&(f=t),n(e,t)},h=e=>{u!==e&&(u=e,r?.(e))},y=()=>{null!==p&&(clearTimeout(p),p=null)},w=()=>{if(m)return;if(!i)return void h("error");if(d>=s){h("error"),a?.(Error(`Max reconnect attempts (${s}) reached`));return}let e=Math.min(l,o*2**d);d+=1,h("connecting"),p=setTimeout(()=>{p=null,C()},e)},C=async()=>{if(!m){y(),c=new AbortController,h("connecting");try{let e=await fetch(t,{signal:c.signal,headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...f?{"Last-Event-ID":f}:{}}});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 v(r,g,c.signal),c.signal.aborted)try{await r.cancel()}catch{}r.releaseLock(),h("closed"),!m&&i&&w()}catch(e){if(m||e instanceof DOMException&&"AbortError"===e.name)return void h("closed");h("error"),i&&w()}}};return{get state(){return u},connect:()=>{m=!1,d=0,y(),C()},close:()=>{m=!0,y(),c.abort(),h("closed")},get abortController(){return c}}}({url:r,onEvent:n=>{try{let r=JSON.parse(n);if("connected"===r.type&&f(),e.current!==t)return;l.current.onEvent(r)}catch{}},onStateChange:e=>{!function(e,t){let n=I().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()},M(n)),"connected"!==t&&"connected"===r&&R(n)}(t,e),"connected"===e&&(d&&(U(t),l.current.onReconnect?.(t)),d=!0)},reconnectBaseMs:a,reconnectMaxMs:s}),p.connect()})},[a,s,e]);return(0,r.useEffect)(()=>i,[i]),{connect:c,disconnect:i,isActive:u,readerRef:o}}({sessionIdRef:ts,onEvent:e=>t_.current?.(e),onReconnect:e=>tT.current?.(e,"sse_reconnected")}),{disconnect:tl,isActive:ti}=to,tu=to.readerRef,{statuses:tc,widgets:td,dialog:tp,notices:tf,applyFromState:tm,handleEvent:tg,respond:th,dismissNotice:ty}=function({chatInputRef:e,sessionIdRef:t,onError:n,noticeTtlMs:a=8e3}){let[s,o]=(0,r.useState)([]),[l,i]=(0,r.useState)([]),[u,c]=(0,r.useState)(null),[d,p]=(0,r.useState)([]),f=(0,r.useRef)(new Set),m=(0,r.useCallback)(()=>{for(let e of f.current)clearTimeout(e);f.current.clear()},[]);(0,r.useEffect)(()=>m,[m]);let g=(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(()=>{f.current.delete(r),p(e=>e.filter(e=>e.id!==n.id))},a);f.current.add(r)},[a]),h=(0,r.useCallback)(e=>{e&&(Array.isArray(e.extensionStatuses)&&o(e.extensionStatuses),Array.isArray(e.extensionWidgets)&&i(e.extensionWidgets))},[]),y=(0,r.useCallback)(t=>{if("extension_error"===t.type)return g("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 g(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 o(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,g]),v=(0,r.useCallback)(async(e,r)=>{let a=t.current;if(c(t=>t?.id===e?null:t),a)try{await w(a,{type:"extension_ui_response",id:e,...r})}catch(e){n(e instanceof Error?e.message:String(e))}},[n,t]);return{statuses:s,widgets:l,dialog:u,notices:d,applyFromState:h,handleEvent:y,respond:v,dismissNotice:(0,r.useCallback)(e=>{p(t=>t.filter(t=>t.id!==e))},[]),reset:(0,r.useCallback)(()=>{m(),o([]),i([]),c(null),p([])},[m])}}({chatInputRef:C,sessionIdRef:ts,onError:ta}),tw=(0,r.useRef)(!1),{live:tv,running:tC,isRunning:tk,begin:tb,finish:tI,handleEvent:tx}=function({onRunningChange:e,onDone:t,flushMs:n=60}={}){let[a,s]=(0,r.useState)(null),[o,l]=(0,r.useState)(!1),i=(0,r.useRef)(!1),u=(0,r.useRef)(""),c=(0,r.useRef)(null),d=(0,r.useRef)({onRunningChange:e,onDone:t});d.current={onRunningChange:e,onDone:t};let p=(0,r.useCallback)(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]);(0,r.useEffect)(()=>p,[p]);let f=(0,r.useCallback)(e=>{p(),u.current="",i.current=!0,l(!0),s({command:e,output:""}),d.current.onRunningChange?.(!0,e)},[p]),m=(0,r.useCallback)(()=>{p(),u.current="",i.current=!1,l(!1),s(null),d.current.onRunningChange?.(!1)},[p]);return{live:a,running:o,isRunning:(0,r.useCallback)(()=>i.current,[]),begin:f,finish:m,handleEvent:(0,r.useCallback)(e=>{if("bash_execution_start"===e.type){let t=String(e.command??"");return p(),u.current="",i.current=!0,l(!0),s({command:t,output:""}),d.current.onRunningChange?.(!0,t),!0}if("bash_execution_update"===e.type){let t="string"==typeof e.chunk?e.chunk:"";return!t||(u.current+=t,c.current||(c.current=setTimeout(()=>{c.current=null;let e=u.current;u.current="",e&&s(t=>t?{...t,output:t.output+e}:t)},n)),!0)}return"bash_done"===e.type&&(p(),u.current="",i.current=!1,l(!1),s(null),d.current.onRunningChange?.(!1),d.current.onDone?.(),!0)},[p,n])}}({onRunningChange:(e,t)=>{tw.current=e,eT(e),te(e?{kind:"running_tools",tools:[{id:"bash",name:"bash",args:t}]}:null)}}),t_=(0,r.useRef)(null),tT=(0,r.useRef)(null),tS=(0,r.useRef)(null),tA=(0,r.useRef)(!1),tE=(0,r.useRef)(null),tM=(0,r.useRef)(!1),tR=(0,r.useRef)(null),t$=(0,r.useRef)(null),tN=(0,r.useRef)(new Map),tD=(0,r.useRef)(new Map),tL=(0,r.useRef)(new Map),tU=(0,r.useRef)(new Map),tP=(0,r.useRef)(null),tj=(0,r.useRef)([]),tO=(0,r.useRef)(null),tq=(0,r.useRef)(0),tF=(0,r.useRef)(!1),tH=(0,r.useRef)(0),tB=(0,r.useRef)(!1),tW=(0,r.useRef)(!1),tJ=(0,r.useRef)(0),tK=(0,r.useRef)(null),tz=(0,r.useRef)(null),tG=(0,r.useRef)(0),tV=(0,r.useRef)(!1);(0,r.useEffect)(()=>{tP.current=es},[es]),(0,r.useEffect)(()=>{tV.current=ey.isStreaming},[ey.isStreaming]),(0,r.useEffect)(()=>{tU.current.clear()},[t?.id]);let tY=e.setNewSessionModel??eU,tQ=e.setToolPreset??ej,tX=e.setMemoryTools??eq,tZ=eZ??b?.context.model??e1??null,t0=k?eL:tZ,t1=(0,r.useCallback)(()=>(0,V.tE)(eP,eO),[eO,eP]),t4=(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"):"",[]),t3=(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})`)},[]),t5=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0};for(let t of el){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})(),t6=(0,r.useRef)(!1),t2=(0,r.useCallback)(async()=>{let e=ts.current;if(!e||t6.current||tB.current)return;t6.current=!0,tF.current=!0;let t=0,n=K(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(ts.current!==e)break;let a=r.context.messages,s=r.context.entryIds??[];if(0===a.length)break;ei(e=>[...a,...e]),ec(e=>{let t=[...s,...e];return tj.current=t,t});let o=t+a.length;if(eh(o),tH.current=o,em(r.hasMore??!1),z(e,a,s,r.hasMore??!1,o),t=o,!r.hasMore)break;await new Promise(e=>setTimeout(e,800))}catch{break}}finally{t6.current=!1,tB.current=!0,tF.current=!1}},[]),t8=(0,r.useCallback)(async(e,t=!1,n=!1,r=!1)=>{var a;let s=null;try{if(t&&W(!0),!n&&!tw.current&&!r){let n=K(e);if(n)return ep(n.totalMessages),em(n.hasMore),eh(n.loadedMessagesCount),ei(n.messages),tj.current=n.entryIds,ec(n.entryIds),tP.current=n.leafId,eo(n.leafId),tH.current=n.loadedMessagesCount,t&&W(!1),n.hasMore&&!tB.current&&setTimeout(()=>{t2()},1500),null}let o=n?`/api/sessions/${encodeURIComponent(e)}?includeState&deferThinking=1&deferMedia=1`:`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=0&deferThinking=1&deferMedia=1`,l=tz.current;if(l?.sid===e&&!t)return null;l?.controller.abort(Q("Session load superseded","AbortError"));let i=new AbortController;s=i,tz.current={sid:e,controller:i};let u=setTimeout(()=>{i.abort(Q("Session load timed out after 30 seconds","TimeoutError"))},3e4),c=await fetch(o,{signal:i.signal}).finally(()=>clearTimeout(u));if(ts.current&&ts.current!==e)return null;if(404===c.status)return t&&(x(null),tP.current=null,eo(null),ei([]),ea(null)),null;if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();n?(ep(d.totalMessages??d.context.messages.length),em(!1)):(ep(d.totalMessages??d.context.messages.length),em(d.hasMore??!1)),eh(d.context.messages.length),x(d),tP.current=d.leafId,eo(d.leafId);let p=d.context.messages,f=et(p),m=new Map,y=Date.now();for(let[t,n]of tN.current)if(n.sessionId===e){if(y-n.createdAt>12e4){tN.current.delete(t);continue}if(n.confirmKey){let e=f.get(n.confirmKey)??0,r=m.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(tN.current.delete(t),m.set(n.confirmKey,r+1))}}tD.current=f;let w=d.context.entryIds??[],v=[...tN.current.values()].filter(t=>en(t,e,w)).map(e=>e.message),C=v.length>0?[...p,...v]:p,k=function(e,t,n){if(0===t.size)return e;let r=!1,a=e.map(e=>{let a=h(e);if(!a)return e;let s=t.get(a);return s?n-s.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}}(s.message,e)?(t.delete(a),e):(r=!0,s.message):e});return r?a:e}(C,tU.current,Date.now()),b=tL.current.get(e);if(b){for(let[e,t]of b)y-t>12e4&&b.delete(e);0===b.size&&tL.current.delete(e)}let I=b?.size?b:null,_=I?new Set(w):null,T=!!I&&!!_&&[...I.keys()].some(e=>!_.has(e));I&&_&&!T&&tL.current.delete(e);let S=k.length;if(!n&&(tH.current>S||T))ep(d.totalMessages??d.context.messages.length),em(d.hasMore??!1);else{let t=tj.current;ei(e=>g(e,t,k,w)),tj.current=w,ec(w),n?tH.current=S:tH.current=Math.max(tH.current,S),a={sessionId:e,leafId:d.leafId,messages:k,entryIds:w,totalMessages:d.totalMessages??d.context.messages.length,hasMore:!n&&(d.hasMore??!1),loadedMessagesCount:d.context.messages.length},J().entries.set(e,{...a,loadedAt:Date.now()})}return e0(e=>{if(!e)return null;let t=d.context.model;return t?.provider===e.provider&&t.modelId===e.modelId?null:e}),ea(null),!d.agentState?.state?.thinkingLevel&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eW(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 ea(String(e)),null}finally{s&&tz.current?.controller===s&&(tz.current=null),t&&W(!1)}},[t2]),t7=(0,r.useRef)(!1),t9=(0,r.useCallback)(async()=>{if(t7.current)return;t7.current=!0;let e=ts.current;if(!e){t7.current=!1;return}try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}?limit=50&offset=${eg}&deferThinking=1&deferMedia=1`);if(!t.ok)return;let n=await t.json(),r=n.context.messages,a=n.context.entryIds??[];ei(e=>[...r,...e]),ec(e=>{let t=[...a,...e];return tj.current=t,t}),eh(e=>e+r.length),em(n.hasMore??!1),z(e,r,a,n.hasMore??!1,eg+r.length)}catch{}finally{t7.current=!1}},[eg]),ne=(0,r.useCallback)(async e=>{let t=ts.current;if(!t)return[];let n=tP.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(),s=a.groups?.find(t=>t.compactionEntryId===e);return s?.messages??[]}catch{return[]}},[]),nt=(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(),s=a.context.messages,o=a.context.entryIds??[],l=et(s),i=new Map,u=Date.now();for(let[t,n]of tN.current)if(n.sessionId===e){if(u-n.createdAt>12e4){tN.current.delete(t);continue}if(n.confirmKey){let e=l.get(n.confirmKey)??0,r=i.get(n.confirmKey)??0;e-r>n.confirmCountAtCreate&&(tN.current.delete(t),i.set(n.confirmKey,r+1))}}tD.current=l;let c=[...tN.current.values()].filter(t=>en(t,e,o)).map(e=>e.message),d=tj.current,p=c.length>0?[...s,...c]:s;ei(e=>g(e,d,p,o)),tj.current=o,ec(o)}catch(e){console.error("Failed to load context:",e)}},[]),nn=(0,r.useCallback)(async e=>{try{let t=await w(e,{type:"get_tools"});t&&(tQ((0,V.ES)(t)),tX((0,V.IB)(t)))}catch(e){console.error("Failed to load tools:",e)}},[tX,tQ]),nr=(0,r.useCallback)(async e=>{try{let t=await w(e,{type:"get_commands"});eH(Array.isArray(t?.commands)?t.commands:[])}catch{eH([])}},[]),na=to.connect,ns=(0,r.useCallback)(async(e,t="manual")=>{if(!e||ts.current!==e)return;let n=tq.current;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`),r=await t.json().catch(()=>({}));if(ts.current!==e||tq.current!==n)return;r.running?(tw.current=!0,eT(!0),te(a(r.state)),ti()||(U(e),na(e,{replay:!0}))):(tw.current=!1,tl(),L(e),eT(!1),te(null),eK(null),ex({type:"end"}),G(e),await t8(e,!1,!1,!0)),r.state?.contextUsage!==void 0&&eG(r.state.contextUsage??null),r.state?.systemPrompt!==void 0&&eY(r.state.systemPrompt??null),r.state?.isCompacting!==void 0&&e5(r.state.isCompacting),r.state?.thinkingLevel!==void 0&&eW(r.state.thinkingLevel??"auto"),r.state?.queuedMessages!==void 0&&tn(j(r.state.queuedMessages)),tm(r.state),r.state?.isBashRunning&&tb("")}catch{}},[na,t8,tm,tb,tl,ti,ex]);(0,r.useEffect)(()=>{tT.current=ns},[ns]),(0,r.useEffect)(()=>{tw.current=e_},[e_]);let no=(0,r.useRef)(P);no.current={runtime:e_?"running":"idle",phase:e9,retry:eJ,isCompacting:e3,compactError:e6,error:tr,queued:tt};let nl=(0,r.useCallback)(e=>{if(void 0!==e.runtime){let t="running"===e.runtime;tw.current=t,eT(t)}void 0!==e.phase&&te(e.phase),void 0!==e.retry&&eK(e.retry),void 0!==e.isCompacting&&e5(e.isCompacting),void 0!==e.compactError&&e2(e.compactError),void 0!==e.error&&ta(e.error),void 0!==e.queued&&tn(e.queued)},[]),ni=(0,r.useCallback)(e=>{tK.current&&clearTimeout(tK.current);let t=tq.current,n=0,r=async()=>{if(ts.current!==e||tw.current||tq.current!==t)return;G(e),await t8(e,!1,!1,!0);let a=Y[n++];void 0===a||ts.current!==e||tw.current||tq.current!==t||(tK.current=setTimeout(()=>{tK.current=null,r()},a))};r()},[t8]),nu=(0,r.useCallback)(e=>{fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eG(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eY(e.state.systemPrompt??null),e.state?.isCompacting!==void 0&&e5(e.state.isCompacting)}).catch(()=>{})},[]),nc=(0,r.useCallback)(e=>{for(let[t,n]of tN.current)n.sessionId===e&&"prompt"===n.kind&&tN.current.delete(t)},[]),nd=(0,r.useCallback)((e,t,n)=>{"assistant"===t.role&&"error"===t.stopReason&&t.errorMessage?.trim()&&ta(`Model response failed: ${t.errorMessage.trim()}`);let r=s(t),a=h(r);if(a&&tU.current.set(a,{observedAt:Date.now(),message:r}),!(n&&tj.current.includes(n))){if(e&&n){let t=tL.current.get(e)??new Map;t.set(n,Date.now()),tL.current.set(e,t)}ei(e=>e.some(e=>(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}})(e,r))?e:[...e,r]),n&&ec(e=>{if(e.includes(n))return e;let t=[...e,n];return tj.current=t,t})}},[]);t_.current=(0,r.useCallback)(e=>{let t=ts.current;"message_update"!==e.type&&eb(),t&&function(e,t){let n=N(e),r=Date.now();switch(t.type){case"agent_start":if("active"===n.snapshot.phase)return A(n,!0),n.snapshot;return $(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:[]}},M(n),A(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 A(n,!1),n.snapshot}case"tool_execution_start":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s=t.input??{};if(!e)return n.snapshot;let o=n.toolCalls.get(e);return n.toolCalls.set(e,{type:"toolCall",toolCallId:e,toolName:a,input:o&&Object.keys(o.input).length>0?o.input:s,startedAt:o?.startedAt??r}),n.activeToolId=e,$(n),n.activeToolId&&(n.toolProgressTimer=setInterval(()=>A(n,!0),1e3)),A(n,!0),n.snapshot}case"tool_execution_end":{let e="string"==typeof t.toolCallId?t.toolCallId:"",a="string"==typeof t.toolName?t.toolName:"tool",s="string"==typeof t.result?t.result:JSON.stringify(t.result??"");if(e){let o=n.toolCalls.get(e);o&&n.toolCalls.set(e,{...o,endedAt:r}),n.toolResults.set(e,{role:"toolResult",toolCallId:e,toolName:a,content:[{type:"text",text:s}],isError:!!t.isError,timestamp:r}),n.activeToolId===e&&(n.activeToolId=null,$(n))}return A(n,!0),n.snapshot}case"message_end":return S(n),A(n,!0),n.snapshot;case"agent_end":{if(S(n),$(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},M(n),T(e,{type:"snapshot-updated",snapshot:n.snapshot}),n.snapshot;R(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&&(tG.current=Date.now());let n=function(e,t,n){let r=n.sessionId;switch(t.type){case"prompt_admitted":case"agent_start":return{patch:{...O,error:null},streamAction:{type:"start"},effects:[]};case"agent_end":if(!0===t.willRetry)return{patch:O,effects:[]};return{patch:{...q,retry:null},streamAction:{type:"end"},effects:r?[{type:"completion-sync",sessionId:r},{type:"refresh-runtime",sessionId:r}]:[]};case"agent_settled":{let t={phase:null,retry:null};if("running"===e.runtime)return t.runtime="idle",{patch:t,streamAction:{type:"end"},effects:[]};return{patch:t,effects:[]}}case"message_start":case"message_update":{let n,r=t.message;if(r?.role==="user")return{patch:{},effects:[]};let a={};"idle"===e.runtime?(a.runtime="running",a.phase={kind:"waiting_model"}):a.phase=null;let s=t.assistantMessageEvent;return r?.role==="assistant"?n={type:"snapshot",message:r}:s&&(n={type:"delta",event:s}),{patch:a,streamAction:n,effects:[]}}case"message_end":{let n=t.message;if(!n||"user"===n.role)return{patch:{},effects:[]};let a=[{type:"completed-message",message:n,entryId:"string"==typeof t.__entryId?t.__entryId:null,sessionId:r}];if("running"===e.runtime)return{patch:{phase:{kind:"waiting_model"}},streamAction:{type:"reset"},effects:a};return{patch:{},effects:a}}case"replay_gap":return{patch:{},effects:r?[{type:"reload",sessionId:r,reason:"replay_gap"}]:[]};case"prompt_done":if("running"!==e.runtime||!r)return{patch:{},effects:[]};return{patch:{},effects:[{type:"reconcile",sessionId:r,reason:"prompt_done"}]};case"prompt_error":{let e="string"==typeof t.error&&t.error.trim()?t.error.trim():"The model request failed before producing a response.";return{patch:{...q,retry:null,error:`Model request failed: ${e}`},streamAction:{type:"end"},effects:r?[{type:"clear-stream",sessionId:r},{type:"reload",sessionId:r,reason:"prompt_error"}]:[]}}case"tool_execution_start":{let n="string"==typeof t.toolCallId?t.toolCallId:"",r="string"==typeof t.toolName?t.toolName:"tool",a=t.args,s="bash"===r&&"string"==typeof a?.command?a.command:void 0,o=e.phase?.kind==="running_tools"?[...e.phase.tools]:[];return n&&!o.some(e=>e.id===n)&&o.push({id:n,name:r,args:s}),{patch:{phase:{kind:"running_tools",tools:o}},effects:[]}}case"tool_execution_update":{let r="string"==typeof t.toolCallId?t.toolCallId:"";if(!r)return{patch:{},effects:[]};let a="string"==typeof t.toolName?t.toolName:"",s=n.toolProgress?.(t.partialResult),o=e.phase?.kind==="running_tools"?[...e.phase.tools]:[],l=o.find(e=>e.id===r),i={id:r,name:a||l?.name||"tool",args:l?.args,progress:s??l?.progress};return{patch:{phase:{kind:"running_tools",tools:[...o.filter(e=>e.id!==r),i]}},effects:[]}}case"tool_execution_end":{let n="string"==typeof t.toolCallId?t.toolCallId:"";if(e.phase?.kind!=="running_tools")return{patch:{},effects:[]};let r=e.phase.tools.filter(e=>e.id!==n);return{patch:{phase:0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}},effects:[]}}case"extension_ui_request":case"extension_error":return{patch:{},effects:[{type:"delegate-extension",event:t}]};case"bash_execution_start":case"bash_execution_update":return{patch:{},effects:[{type:"delegate-bash",event:t}]};case"bash_done":return{patch:{},effects:[{type:"delegate-bash",event:t},...r?[{type:"reload",sessionId:r,reason:"bash_done"}]:[]]};case"queue_update":return{patch:{queued:j({steering:Array.isArray(t.steering)?t.steering:[],followUp:Array.isArray(t.followUp)?t.followUp:[]})},effects:[]};case"auto_retry_start":return{patch:{...O,error:null,retry:{attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage}},effects:[]};case"auto_retry_end":if(!1===t.success&&"string"==typeof t.finalError&&t.finalError.trim())return{patch:{retry:null,error:`Model response failed after retries: ${t.finalError.trim()}`},effects:[]};return{patch:!0===t.success?{retry:null,error:null}:{retry:null},effects:[]};case"auto_compaction_start":case"compaction_start":return{patch:{isCompacting:!0,compactError:null},effects:[]};case"auto_compaction_end":case"compaction_end":{let e="string"==typeof t.errorMessage&&t.errorMessage.trim()?t.errorMessage:null,n=[];return!e&&!0!==t.aborted&&r&&n.push({type:"reload",sessionId:r,reason:"compaction_end"}),{patch:{isCompacting:!1,...e?{compactError:e}:{}},effects:n}}default:return{patch:{},effects:[]}}}(no.current,e,{sessionId:t,toolProgress:e=>(function(e){if(!f(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>f(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)??void 0});switch(nl(n.patch),n.streamAction?.type){case"start":ex({type:"start"});break;case"end":ex({type:"end"});break;case"reset":ex({type:"reset"});break;case"delta":eI(n.streamAction.event);break;case"snapshot":ex({type:"snapshot",message:s(n.streamAction.message)})}for(let e of n.effects)switch(e.type){case"completion-sync":ni(e.sessionId);break;case"refresh-runtime":nu(e.sessionId);break;case"reload":G(e.sessionId),t8(e.sessionId,!1,!1,!0);break;case"clear-stream":tl(),L(e.sessionId),nc(e.sessionId);break;case"reconcile":ns(e.sessionId,e.reason);break;case"delegate-extension":tg(e.event);break;case"delegate-bash":tx(e.event);break;case"completed-message":nd(e.sessionId,e.message,e.entryId)}n.effects.some(e=>"completion-sync"===e.type||"clear-stream"===e.type)&&l?.()},[t8,l,ns,tg,tx,tl,nl,ni,nu,nd,nc,eb,eI,ex]);let np=(0,r.useCallback)(async(e,r,a,s)=>{if(!e.trim()&&!r?.length&&!a?.length||e_)return;tq.current+=1;let o=t4(a),l=e.trim()?o?`${e}
|
|
5
|
+
|
|
6
|
+
Attached document text:
|
|
7
|
+
|
|
8
|
+
${o}`:e:o?`Attached document text:
|
|
9
|
+
|
|
10
|
+
${o}`:"",u=[],c=k?n:t?.cwd??b?.info?.cwd;if(r?.length&&c)try{u=await H(c,r)}catch(e){ta(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,F.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()},f=X(),m=k?null:t?.id??null;m&&G(m);let g=tP.current,h=ee(p.content);tN.current.set(f,{localId:f,sessionId:m??"__new__",leafId:g,message:p,createdAt:Date.now(),kind:"prompt",confirmKey:h,confirmCountAtCreate:k?0:h?tD.current.get(h)??0:0}),ei(e=>[...e,p]),ta(null),tw.current=!0,eT(!0),te({kind:"waiting_model"}),ex({type:"start"}),tM.current=!0;let v=eE.find(e=>e.provider===tZ?.provider&&e.id===tZ?.modelId)?.input,I=!v||0===v.length||v.includes("image")?r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0;try{if(k&&n){eL&&e4(eL);let t=s??t1(),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,...I?.length?{images:I}:{},...eL?{provider:eL.provider,modelId:eL.modelId}:{},..."auto"!==eB?{thinkingLevel:eB}:{}})}),a=await r.json().catch(()=>({}));if(!r.ok||a.error||!a.sessionId)throw Error(a.error??`HTTP ${r.status}`);let o=a.sessionId;ts.current=o;let u=tN.current.get(f);u&&(u.sessionId=o),tS.current?.(),tS.current=D(o,()=>{ts.current===o&&(eT(!1),te(null))}),tO.current=o,await na(o,{requireConnected:!0,timeoutMs:1e4}),await w(o,{type:"prompt",message:l,toolNames:t,...I?.length?{images:I}:{}}),i?.({id:o,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:e})}else if(t){let e=s??t1();await t3(t.id),tS.current?.(),tS.current=D(t.id,()=>{ts.current===t.id&&(eT(!1),te(null))}),await na(t.id,{requireConnected:!0,timeoutMs:1e4}),await w(t.id,{type:"prompt",message:l,toolNames:e,leafId:g,...tZ?{provider:tZ.provider,modelId:tZ.modelId}:{},..."auto"!==eB?{thinkingLevel:eB}:{},...I?.length?{images:I}:{}})}}catch(n){let t=ts.current;if(tN.current.delete(f),ei(e=>e.filter(e=>e!==p)),n instanceof y&&(409===n.status||"SESSION_BUSY"===n.code)){ta("This session is already running in another tab. Showing that active run instead."),tw.current=!0,eT(!0),te({kind:"waiting_model"}),ex({type:"start"}),t&&(tl(),U(t),na(t,{replay:!0}),tT.current?.(t,"prompt_conflict"));return}if(console.error("Failed to send message:",n),k&&ts.current){let e=ts.current;ts.current=null,tO.current=null,fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})}C?.current&&e.trim()&&C.current.insertIfEmpty(e),C?.current&&r?.length&&C.current.addBase64Images?.(r.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))),ta(n instanceof Error?n.message:String(n)),tl(),t&&L(t),tw.current=!1,eT(!1),te(null),ex({type:"end"})}},[k,n,eL,t1,eB,t,b?.info?.cwd,e_,na,i,t4,eE,tZ,t3,C,tl,ex]),nf=(0,r.useCallback)(async()=>{let e=ts.current;if(!e)return;let t=tk();tw.current=!1,tI(),ta(null),eT(!1),te(null),ex({type:"end"}),tl(),L(e),G(e);try{await w(e,{type:t?"abort_bash":"abort"}),await t8(e,!1,!1,!0)}catch(t){console.error("Failed to abort:",t),await t8(e,!1,!1,!0)}finally{t&&tI()}},[tI,tk,t8,tl,ex]),nm=(0,r.useCallback)(async(e,t)=>{let n=ts.current,r=e.trim();if(n&&r){ta(null),tb(r);try{await w(n,{type:"bash",command:r,excludeFromContext:t})}catch(e){ta(e instanceof Error?e.message:String(e))}finally{tI(),G(n),await t8(n,!1,!1,!0)}}},[tb,tI,t8]),ng=(0,r.useCallback)(async e=>{let t=ts.current;if(t){eX(e);try{let{cancelled:n,newSessionId:r}=await w(t,{type:"fork",entryId:e})??{};!n&&r&&u?.(r)}catch(e){console.error("Fork failed:",e)}finally{eX(null)}}},[u]),nh=(0,r.useCallback)(async e=>{let r=ts.current,a=b?.info?.cwd??t?.cwd??n??null;if(!r||!a)return{ok:!1,error:"No active session to fork"};if(tw.current)return{ok:!1,error:"Agent is still running"};try{let t=t1(),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,...tZ?{provider:tZ.provider,modelId:tZ.modelId}:{},..."auto"!==eB?{thinkingLevel:eB}:{}})}),s=await n.json().catch(()=>({}));if(!n.ok||s.error||!s.sessionId)return{ok:!1,error:s.error??`HTTP ${n.status}`};let o=s.sessionId;try{await w(o,{type:"append_message",message:e,customType:"fork_handoff",display:!0})}catch{}return i?.({id:o,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)}}},[b?.info?.cwd,t?.cwd,n,tZ,eB,t1,i]),ny=(0,r.useCallback)(async e=>{let t=ts.current;t&&(tL.current.delete(t),G(t),tP.current=e,eo(e),await nt(t,e))},[nt]),nw=(0,r.useCallback)(async e=>{tP.current=e,eo(e);let t=ts.current;t&&(tL.current.delete(t),G(t),await nt(t,e))},[nt]),nv=(0,r.useCallback)(async(e,t)=>{if(k)return void tY({provider:e,modelId:t});let n=ts.current;if(n)try{var r;ta(null);let a=await w(n,{type:"set_model",provider:e,modelId:t}),s={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)&&eW(a.thinkingLevel),e0(s),x(e=>e?{...e,context:{...e.context,model:s}}:e)}catch(t){let e=t instanceof Error?t.message:String(t);console.error("Failed to set model:",t),ta(e)}},[k,tY]),nC=(0,r.useCallback)(async()=>{let e=ts.current;if(e&&!e3){e5(!0),e2(null),e7(null);try{let t=await w(e,{type:"compact"});t?.reducedBy!=null&&e7(`Compacted ~${t.tokensBefore??"?"} → ~${t.tokensAfter??"?"} tokens (−${t.reducedBy})`),await t8(e,!0)}catch(e){e2(e instanceof Error?e.message:String(e))}finally{e5(!1)}}},[e3,t8]),nk=(0,r.useCallback)(async(e,t,n)=>{let r=ts.current;if(!r)return;G(r);let a=t4(n),s=e.trim()?a?`${e}
|
|
11
|
+
|
|
12
|
+
Attached document text:
|
|
13
|
+
|
|
14
|
+
${a}`:e:a?`Attached document text:
|
|
15
|
+
|
|
16
|
+
${a}`:"",o=eE.find(e=>e.provider===tZ?.provider&&e.id===tZ?.modelId)?.input,l=!o||0===o.length||o.includes("image")?t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0,i={role:"user",content:`[steer] ${s}`,timestamp:Date.now()},u=X(),c=Z(s,l?.length??0);tN.current.set(u,{localId:u,sessionId:r,leafId:tP.current,message:i,createdAt:Date.now(),kind:"steer",confirmKey:c,confirmCountAtCreate:c?tD.current.get(c)??0:0}),ei(e=>[...e,i]);try{await w(r,{type:"steer",message:s,...l?.length?{images:l}:{}})}catch(e){tN.current.delete(u),console.error("Failed to steer:",e)}},[t4,eE,tZ]),nb=(0,r.useCallback)(async(e,t,n)=>{let r=ts.current;if(!r)return;G(r);let a=t4(n),s=e.trim()?a?`${e}
|
|
17
|
+
|
|
18
|
+
Attached document text:
|
|
19
|
+
|
|
20
|
+
${a}`:e:a?`Attached document text:
|
|
21
|
+
|
|
22
|
+
${a}`:"",o=eE.find(e=>e.provider===tZ?.provider&&e.id===tZ?.modelId)?.input,l=!o||0===o.length||o.includes("image")?t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})):void 0,i={role:"user",content:s,timestamp:Date.now()},u=X(),c=Z(s,l?.length??0);tN.current.set(u,{localId:u,sessionId:r,leafId:tP.current,message:i,createdAt:Date.now(),kind:"follow_up",confirmKey:c,confirmCountAtCreate:c?tD.current.get(c)??0:0}),ei(e=>[...e,i]);try{await w(r,{type:"follow_up",message:s,...l?.length?{images:l}:{}})}catch(e){tN.current.delete(u),console.error("Failed to follow up:",e)}},[t4,eE,tZ]),nI=(0,r.useCallback)(async()=>{let e=ts.current;if(e)try{await w(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nx=(0,r.useCallback)(async e=>{if(eW(e),"auto"===e)return;let t=ts.current;if(t)try{await w(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),n_=(0,r.useCallback)(async e=>{tQ(e);let t=(0,V.tE)(e,eO),n=ts.current;if(n)try{await w(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[eO,tQ]),nT=(0,r.useCallback)(async e=>{tX(e);let t=(0,V.tE)(eP,e),n=ts.current;if(n)try{await w(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set memory tools:",e)}},[tX,eP]),nS=(0,r.useCallback)((e="smooth")=>{tR.current?.scrollIntoView({behavior:e})},[]),nA=(0,r.useCallback)(()=>{let e=t$.current,t=tE.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(ts.current=t.id,t.id===tO.current)return tO.current=null,()=>{tK.current&&clearTimeout(tK.current),tK.current=null,tl(),tS.current?.(),tS.current=null};tB.current=!1,tH.current=0;let r=(e=t.id,(n=I().get(e))&&"idle"!==n.snapshot.phase?n.snapshot:null);r?.phase==="active"&&(tw.current=!0,eT(!0),te({kind:"waiting_model"}),ex({type:"start"})),(async()=>{let e=await t8(t.id,!0,!0,!0);ts.current===t.id&&(await nn(t.id),nr(t.id),e?.running?(tw.current=!0,eT(!0),te(a(e.state)),ex({type:"start"}),na(t.id,{replay:!0}),tS.current?.(),tS.current=D(t.id,()=>{ts.current===t.id&&tT.current?.(t.id,"stream_watchdog")})):e&&r?.phase==="active"?(tw.current=!1,eT(!1),te(null),ex({type:"end"}),L(t.id)):e||r?.phase!=="active"||tT.current?.(t.id,"mount_state_load_failed"),e?.state&&(void 0!==e.state.isCompacting&&e5(e.state.isCompacting),void 0!==e.state.contextUsage&&eG(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eY(e.state.systemPrompt??null),void 0!==e.state.queuedMessages&&tn(j(e.state.queuedMessages)),tm(e.state),e.state.isBashRunning&&tb(""),void 0!==e.state.thinkingLevel&&eW(e.state.thinkingLevel??"auto")),e&&!tw.current&&e.state?.contextUsage===void 0&&tT.current?.(t.id,"mount_context_usage"))})()}return()=>{tO.current&&ts.current===tO.current||(tK.current&&clearTimeout(tK.current),tK.current=null,tz.current?.controller.abort(Q("Session changed","AbortError")),tz.current=null,tl(),tS.current?.(),tS.current=null)}},[na,t8,nn,nr,m,t,tm,tb,tl,ex]),(0,r.useEffect)(()=>{let e=()=>{let e=ts.current;e&&ns(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)}},[ns]),(0,r.useEffect)(()=>{let e=ts.current;if(e)return tW.current=!1,(0,B.O)(t=>{let n=t.includes(e),r=tW.current;tW.current=n,n&&!tw.current?(G(e),ns(e,"running_feed_start")):!n&&r&&(G(e),tw.current?ns(e,"running_feed_stop"):t8(e,!1,!1,!0))})},[t8,ns,t?.id]),(0,r.useEffect)(()=>{let e=window.setInterval(()=>{let e=ts.current;e&&(tw.current?(ns(e,"interval"),tV.current&&Date.now()-tG.current>25e3&&(tG.current=Date.now(),G(e),t8(e,!1,!1,!0))):Date.now()-tJ.current>=3e4?(tJ.current=Date.now(),G(e),t8(e,!1,!1,!0)):t8(e))},15e3);return()=>window.clearInterval(e)},[t8,ns]),(0,r.useEffect)(()=>{m&&m(b?.tree??[],es,nw)},[b?.tree,es,nw,m]),(0,r.useEffect)(()=>{el.length>0&&!tF.current&&(tM.current?(tM.current=!1,tA.current=!0,nA()):tA.current?tw.current||nS("smooth"):(tA.current=!0,nS("instant")))},[el.length,e_,nS,nA]),(0,r.useEffect)(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{if(eA(e.models),e.thinkingLevels&&e$(e.thinkingLevels),e.thinkingLevelMaps&&eD(e.thinkingLevelMaps),e.modelList&&(eM(e.modelList),k&&e.modelList.length>0)){let t=e.defaultModel,n=t&&e.modelList.find(e=>e.id===t.modelId&&e.provider===t.provider);tY(n?{provider:n.provider,modelId:n.id}:{provider:e.modelList[0].provider,modelId:e.modelList[0].id})}}).catch(()=>{})},[k,c,tY]),(0,r.useEffect)(()=>{if(!e6)return;let e=setTimeout(()=>e2(null),3e3);return()=>clearTimeout(e)},[e6]),(0,r.useEffect)(()=>{if(!e8)return;let e=setTimeout(()=>e7(null),6e3);return()=>clearTimeout(e)},[e8]);let nE=(0,r.useCallback)(async()=>{let e=ts.current;if(e)try{await w(e,{type:"clear_queue"}),tn({steering:[],followUp:[]})}catch(e){ta(e instanceof Error?e.message:String(e))}},[]);return{data:b,loading:E,error:er,activeLeafId:es,messages:el,entryIds:eu,streamState:ey,agentRunning:e_,modelNames:eS,modelList:eE,modelThinkingLevels:eR,modelThinkingLevelMaps:eN,newSessionModel:eL,toolPreset:eP,memoryTools:eO,thinkingLevel:eB,retryInfo:eJ,queuedMessages:tt,extensionStatuses:tc,extensionWidgets:td,extensionDialog:tp,extensionNotices:tf,bashLive:tv,bashRunning:tC,contextUsage:ez,systemPrompt:eV,forkingEntryId:eQ,isCompacting:e3,compactError:e6,compactInfo:e8,currentModel:tZ,displayModel:t0,sessionStats:t5,agentPhase:e9,agentError:tr,isNew:k,sessionIdRef:ts,sseReaderRef:tu,messagesEndRef:tR,scrollContainerRef:t$,lastUserMsgRef:tE,pendingScrollToUserRef:tM,initialScrollDoneRef:tA,handleSend:np,handleAbort:nf,handleFork:ng,handleNavigate:ny,handleModelChange:nv,handleCompact:nC,handleSteer:nk,handleFollowUp:nb,handleAbortCompaction:nI,handleToolPresetChange:n_,handleMemoryToolsChange:nT,handleThinkingLevelChange:nx,handleClearQueue:nE,handleBash:nm,respondToExtensionUi:th,dismissExtensionNotice:ty,loadTools:nn,loadSlashCommands:nr,slashCommands:eF,setActiveLeafId:eo,setData:x,setMessages:ei,dispatch:ew,setAgentRunning:eT,setForkingEntryId:eX,forkToNewSession:nh,loadMoreMessages:t9,hasMoreMessages:ef,totalMessages:ed,loadedMessagesCount:eg,loadShadowedMessages:ne,handleAgentEventRef:t_}}}}]);
|