@hydra-acp/browser 0.1.35 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/ui/index.html +25 -1
  2. package/package.json +1 -1
@@ -124,6 +124,30 @@ input, select, textarea {
124
124
  input, select, textarea { font-size: max(16px, 1em); }
125
125
  }
126
126
  input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
127
+
128
+ /* Themed scrollbars, desktop only. Touch platforms already draw thin
129
+ overlay scrollbars that disappear when idle and cost no layout width,
130
+ so restyling there would only make them worse; a fine pointer gets the
131
+ chunky always-present kind that reads as browser chrome sitting inside
132
+ the app. Gated on pointer, not width, since a touch tablet can be as
133
+ wide as a laptop.
134
+
135
+ The thumb's transparent border plus background-clip is what makes it
136
+ look slim without shrinking the hit area — the track stays a
137
+ comfortable target while the visible bar is a few px. */
138
+ @media (hover: hover) and (pointer: fine) {
139
+ * { scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
140
+ ::-webkit-scrollbar { width: 11px; height: 11px; }
141
+ ::-webkit-scrollbar-track { background: transparent; }
142
+ ::-webkit-scrollbar-thumb {
143
+ background: var(--border);
144
+ background-clip: content-box;
145
+ border: 3px solid transparent;
146
+ border-radius: 999px;
147
+ }
148
+ ::-webkit-scrollbar-thumb:hover { background: var(--muted); background-clip: content-box; }
149
+ ::-webkit-scrollbar-corner { background: transparent; }
150
+ }
127
151
  a { color: var(--accent); text-decoration: none; }
128
152
  a:hover { text-decoration: underline; }
129
153
  code { background: var(--panel-2); padding: 0.1rem 0.4rem; border-radius: 4px; font-family: ui-monospace, "SFMono-Regular", Menlo, monospace; font-size: 0.9em; }
@@ -570,7 +594,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),P=h,O=A),T===void 0&&(
570
594
  `),r),s=!1,o=[],r="",f++;continue}o.push(p),f++;continue}if(/^```/.test(p)){u(),d(),s=!0,r=p.slice(3).trim(),f++;continue}if(f+1<t.length&&p.includes("|")){let m=Bn(p),y=uc(t[f+1]);if(m&&y&&m.length>0&&y.length>0){u(),d();let S=Math.max(m.length,y.length),v=[];for(let E=0;E<S;E++)v.push(y[E]??null);n+="<table><thead>",n+=Hr(m,v,"th"),n+="</thead><tbody>";let b=f+2;for(;b<t.length;){let E=Bn(t[b]);if(!E)break;n+=Hr(E,v,"td"),b++}n+="</tbody></table>",f=b;continue}}if(/^\s*$/.test(p)){u(),d(),f++;continue}let g;if(g=p.match(/^(#{1,3})\s+(.+)$/)){u(),d();let m=g[1].length;n+=`<h${m}>${Ge(ae(g[2]))}</h${m}>`,f++;continue}if(g=p.match(/^\s*[-*]\s+(.*)$/)){u(),a!=="ul"&&(d(),n+="<ul>",a="ul"),n+=`<li>${Ge(ae(g[1]))}</li>`,f++;continue}if(g=p.match(/^\s*\d+\.\s+(.*)$/)){u(),a!=="ol"&&(d(),n+="<ol>",a="ol"),n+=`<li>${Ge(ae(g[1]))}</li>`,f++;continue}if(g=p.match(/^\s*>\s?(.*)$/)){u(),d(),n+=`<blockquote>${Ge(ae(g[1]))}</blockquote>`,f++;continue}d(),c.push(ae(p)),f++}return s&&(n+=Br(o.join(`
571
595
  `),r)),u(),d(),n}function ct(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(ct).join("");if(e&&typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.content=="string")return t.content}return""}function $r(e){let t=e.content;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=typeof r.oldText=="string"?r.oldText:void 0,a=typeof r.newText=="string"?r.newText:void 0;if(o===void 0&&a===void 0)continue;let c=typeof r.path=="string"?r.path:void 0;return{...c!==void 0?{path:c}:{},oldText:o??"",newText:a??""}}let n=e.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Ur(e){let t=e.oldText.split(`
572
596
  `),n=e.newText.split(`
573
- `);return t.length>0&&t[t.length-1]===""&&t.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:t,newLines:n}}var dc=1e6;function fc(e,t){let n=e.length,s=t.length;if(n===0||s===0||n*s>dc){let u=[];for(let d of e)u.push({op:"-",text:d});for(let d of t)u.push({op:"+",text:d});return u}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let u=n-1;u>=0;u--)for(let d=s-1;d>=0;d--)e[u]===t[d]?r[u][d]=r[u+1][d+1]+1:r[u][d]=Math.max(r[u+1][d],r[u][d+1]);let o=[],a=0,c=0;for(;a<n&&c<s;)e[a]===t[c]?(o.push({op:"=",text:e[a]}),a++,c++):r[a+1][c]>=r[a][c+1]?(o.push({op:"-",text:e[a]}),a++):(o.push({op:"+",text:t[c]}),c++);for(;a<n;)o.push({op:"-",text:e[a]}),a++;for(;c<s;)o.push({op:"+",text:t[c]}),c++;return o}function qr(e,t){let n=0,s=Math.min(e.length,t.length);for(;n<s&&e[n]===t[n];)n++;let r=e.length,o=t.length;for(;r>n&&o>n&&e[r-1]===t[o-1];)r--,o--;let a=[];for(let c=0;c<n;c++)a.push({op:"=",text:e[c]});a.push(...fc(e.slice(n,r),t.slice(n,o)));for(let c=r;c<e.length;c++)a.push({op:"=",text:e[c]});return a}function Kr(e){let{oldLines:t,newLines:n}=Ur(e),s=0,r=0;for(let o of qr(t,n))o.op==="+"?s++:o.op==="-"&&r++;return{added:s,removed:r}}function zr(e,t={}){let n=t.maxLines??40,s=t.contextLines??3,{oldLines:r,newLines:o}=Ur(e),a=qr(r,o),c=[];if(Number.isFinite(s)){if(!a.some(g=>g.op!=="="))return[];let f=new Array(a.length).fill(!1);for(let g=0;g<a.length;g++)if(a[g].op!=="="){let m=Math.max(0,g-s),y=Math.min(a.length-1,g+s);for(let S=m;S<=y;S++)f[S]=!0}let p=0;for(;p<a.length;){if(f[p]){c.push({op:a[p].op,text:a[p].text}),p++;continue}let g=p;for(;g<a.length&&!f[g];)g++;let m=g-p;c.push({op:"gap",text:`\u22EF ${m} unchanged line${m===1?"":"s"}`}),p=g}}else for(let d of a)c.push({op:d.op,text:d.text});let u=[];for(let d=0;d<c.length;d++){if(u.length>=n-1&&d<c.length-1){let p=c.length-d;u.push({op:"gap",text:`\u2026 ${p} more line${p===1?"":"s"}`});break}u.push(c[d])}return u}var pc="hydra-acp-history-cache",gc=3,le="sessions",mc=6e6,Wr=10,hc=2e3,Bt=null;function Hn(){return Bt||(Bt=new Promise(e=>{if(!("indexedDB"in window)){e(null);return}let t;try{t=indexedDB.open(pc,gc)}catch{e(null);return}t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(le)&&t.result.deleteObjectStore(le),t.result.createObjectStore(le,{keyPath:"sessionId"})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null)}),Bt)}function bc(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}async function Qr(e){let t=await Hn();return t?new Promise(n=>{let s;try{s=t.transaction(le,"readwrite")}catch{n(null);return}let r=s.objectStore(le),o=r.get(e);o.onsuccess=()=>{let a=o.result;if(!a){n(null);return}a.lastAccessed=Date.now(),r.put(a),n({lastSeenMessageId:a.lastSeenMessageId,frames:_e("cache-read-map",()=>a.frames.map(c=>c.frame))})},o.onerror=()=>n(null)}):null}async function Xr(e){let t=await Hn();return t?new Promise(n=>{let s;try{s=t.transaction(le,"readonly")}catch{n("unreadable");return}let r=s.objectStore(le).get(e);r.onsuccess=()=>{let o=r.result;if(!o){n("empty");return}let a=new Map;for(let u of o.frames){let d=u.frame.params?.update,f=typeof d?.sessionUpdate=="string"?d.sessionUpdate:"?";a.set(f,(a.get(f)??0)+1)}let c=[...a.entries()].sort((u,d)=>d[1]-u[1]).map(([u,d])=>`${u.replace(/_chunk$/,"")}:${d}`).join(" ");n(`${o.frames.length}f ${(o.totalBytes/1e6).toFixed(1)}MB \u2014 ${c}`)},r.onerror=()=>n("unreadable")}):"unavailable"}var ke=new Map,Ht=new Map,Ye;function Ft(e,t,n){let s=ke.get(e)??[];s.push(t),ke.set(e,s),Ht.set(e,n),Ye===void 0&&(Ye=setTimeout(()=>{Ye=void 0,Vr()},hc))}var Gr=Promise.resolve();function Vr(){Gr=Gr.then(Ec).catch(()=>{})}function Yr(){Ye!==void 0&&(clearTimeout(Ye),Ye=void 0),Vr()}async function Ec(){if(ke.size===0)return;let e=Array.from(ke.keys()),t=await Hn();if(!t){ke.clear(),Ht.clear();return}for(let n of e){let s=ke.get(n),r=Ht.get(n);ke.delete(n),Ht.delete(n),!(!s||!r)&&await yc(t,n,s,r)}await _c(t)}function yc(e,t,n,s){return new Promise(r=>{let o;try{o=e.transaction(le,"readwrite")}catch{r();return}let a=o.objectStore(le),c=a.get(t);c.onsuccess=()=>{let u=c.result,d=_e("cache-size",()=>n.map(m=>({frame:m,bytes:bc(m)}))),f=[...u?.frames??[],...d],p=(u?.totalBytes??0)+d.reduce((m,y)=>m+y.bytes,0);for(;f.length>1&&p>mc;){let m=f.shift();m&&(p-=m.bytes)}let g={sessionId:t,lastSeenMessageId:s,frames:f,totalBytes:p,lastAccessed:Date.now()};_e("cache-put",()=>a.put(g)),r()},c.onerror=()=>r()})}function _c(e){return new Promise(t=>{let n;try{n=e.transaction(le,"readwrite")}catch{t();return}let s=n.objectStore(le),r=s.getAll();r.onsuccess=()=>{let o=r.result??[];if(o.length<=Wr){t();return}o.sort((c,u)=>c.lastAccessed-u.lastAccessed);let a=o.slice(0,o.length-Wr);for(let c of a)s.delete(c.sessionId);t()},r.onerror=()=>t()})}typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pagehide",Yr),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Yr()}));typeof navigator<"u"&&navigator.storage?.persist&&navigator.storage.persist();function qt(e){i.current&&i.current.log.push(e)}var vc=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]);function Kt(e){e.log=[],e.toolCalls=new Map,e.pendingPermissions=new Map,e.spinner=null,e.plan=null,e.mode=null,e.model=null,e.modes=[],e.models=[],e.contextUsed=null,e.contextSize=null,e.cost=null,e.busy=!1,e.recentOwnPrompts=[],e.promptQueue=[],e.queueByMessageId=new Map,e.ownPromptIds=new Map,e.inTurn=!1,e.unsolicitedTurnOpen=new Set,e.currentPlanEntry=null,e.daemonSupportsAmend=!1,e.ownClientId=void 0,e.currentHeadMessageId=void 0,e.lastSeenMessageId=void 0,e.spinnerOwner=void 0}function wc(e){if(!e||typeof e!="object")return;let t=e._meta;if(!t||typeof t!="object")return;let n=t["hydra-acp"];if(!n||typeof n!="object")return;let s=n.recordedAt;return typeof s=="number"&&Number.isFinite(s)?s:void 0}function Sc(e){if(e.kind!=="stream"||e.role!=="user"||!e.queueEntry)return!1;let t=e.queueEntry.status;return t==="queued"||t==="editing"}function $n(){if(!i.current)return 0;let e=i.current.log;for(let t=0;t<e.length;t++)if(Sc(e[t]))return t;return e.length}function ge(e){i.current&&i.current.log.splice($n(),0,e)}function Un(e){if(!(!i.current||e.messageId===void 0)){for(let t of i.current.log)if(t.kind==="stream"&&t.queueEntry===e){t.messageId=e.messageId,Ic(e);return}}}function Tc(e,t){let n=i.current?.spinnerOwner;!i.current||n===void 0||Ft(i.current.sessionId,{method:"session/update",params:{sessionId:i.current.sessionId,update:{sessionUpdate:"turn_complete",messageId:`${n}:turn_complete`,...e!==void 0?{stopReason:e}:{}},_meta:{"hydra-acp":{recordedAt:t??Date.now()}}}},`${n}:turn_complete`)}function Ic(e){!i.current||e.messageId===void 0||Ft(i.current.sessionId,{method:"session/update",params:{sessionId:i.current.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:[{type:"text",text:e.text}]},_meta:{"hydra-acp":{recordedAt:Date.now()}}}},e.messageId)}function fe(){i.current&&(i.current.inTurn=!0)}function Ac(){if(!i.current)return;i.current.inTurn=!1;let e=i.current.idleListeners;i.current.idleListeners=[];for(let t of e)try{t()}catch{}}function Fn(e,t,n=!1,s){if(!i.current)return;let r=ct(t);if(!r)return;let o=i.current.log,a=$n(),c;for(let u=a-1;u>=0;u--){let d=o[u];if(d.kind!=="spinner"){c=d;break}}if(c&&c.kind==="stream"&&c.role===e&&!c.closed&&!!c.synthetic===n){c.text+=r,s!==void 0&&(c.messageId=s);return}o.splice(a,0,{kind:"stream",role:e,text:r,synthetic:n||void 0,messageId:s})}function Xe(){if(i.current)for(let e=i.current.log.length-1;e>=0;e--){let t=i.current.log[e];if(t.kind==="stream"&&!t.closed){t.closed=!0;return}}}function Zr(e){if(!i.current)return!1;let t=ct(e);if(!t)return!1;let n=i.current.recentOwnPrompts;for(let s=0;s<n.length;s++)if(n[s].text===t)return n.splice(s,1),!0;return!1}function $t(e){if(!e)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map($t).join("");if(typeof e=="object"){let t=e;if(t.text)return String(t.text);if(t.content)return $t(t.content);if(t.diff)return String(t.diff);try{return JSON.stringify(e,null,2)}catch{return String(e)}}return""}function me(e){if(!i.current)return;let t=i.current;if(t.spinner){t.log.some(n=>n.kind==="spinner")||ge({kind:"spinner",spinner:t.spinner});return}t.spinner={toolCallIds:[],expanded:!1,startedAt:e??Date.now()},t.spinnerOwner=void 0,ge({kind:"spinner",spinner:t.spinner})}function jr(e,t){if(!i.current)return;let n=i.current,s=n.spinner;if(s){let r=n.log.findIndex(o=>o.kind==="spinner");r>=0&&(n.log[r]={kind:"turn-stamp",elapsedMs:Math.max(0,(e??Date.now())-s.startedAt),toolCount:s.toolCallIds.length,stopReason:t})}n.spinner=null,n.spinnerOwner=void 0,n.log=n.log.filter(r=>r.kind!=="spinner")}function lt(e,t){if(!i.current)return;let n=i.current;jr(e),n.spinner={toolCallIds:[],expanded:!1,startedAt:e??Date.now()},n.spinnerOwner=t,ge({kind:"spinner",spinner:n.spinner})}function kc(e){return typeof e!="string"||!e?!1:e.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode"}function xc(e){let t=e.rawInput;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.plan;return typeof n!="string"||n.length===0?null:n}function Mc(e){if(!i.current)return null;let t=i.current.log;for(let n=0;n<t.length;n++){let s=t[n];if(s.kind==="exit-plan-mode"&&s.toolCallId===e)return{idx:n,item:s}}return null}function Jr(e){if(!i.current)return!1;let t=String(e.toolCallId??"");if(!t)return!1;let n=e.name??e.title,s=Mc(t);if(!kc(n)&&!s)return!1;let r=xc(e),o=typeof e.status=="string"?e.status:void 0;if(s)return r!==null&&(s.item.plan=r),o!==void 0&&(s.item.status=o),!0;if(r===null)return!1;Xe();let a={kind:"exit-plan-mode",toolCallId:t,plan:r};return o!==void 0&&(a.status=o),ge(a),!0}function Nc(e){if(!i.current)return null;let t=i.current.log;for(let n=0;n<t.length;n++){let s=t[n];if(s.kind==="edit-diff"&&s.toolCallId===e)return{idx:n,item:s}}return null}function ei(e){if(!i.current)return!1;let t=String(e.toolCallId??"");if(!t)return!1;let n=Nc(t),s=$r(e),r=typeof e.status=="string"?e.status:void 0;if(n)return s!==null&&(n.item.diff=s),r!==void 0&&(n.item.status=r),!0;if(s===null)return!1;Xe();let o={kind:"edit-diff",toolCallId:t,diff:s,expanded:!1};return r!==void 0&&(o.status=r),ge(o),!0}function Cc(e){if(!i.current)return;if(Xe(),Jr(e)){Qe(String(e.toolCallId),typeof e.status=="string"?e.status:void 0);return}if(ei(e)){Qe(String(e.toolCallId),typeof e.status=="string"?e.status:void 0);return}let t={toolCallId:String(e.toolCallId),title:String(e.title??e.kind??"tool"),kind:String(e.kind??""),status:String(e.status??"in_progress"),content:$t(e.content)};i.current.toolCalls.set(t.toolCallId,t),me(),i.current.spinner?.toolCallIds.push(t.toolCallId),Qe(t.toolCallId,t.status)}function Rc(e){if(!i.current)return;if(Jr(e)){typeof e.status=="string"&&Qe(String(e.toolCallId),e.status);return}if(ei(e)){typeof e.status=="string"&&Qe(String(e.toolCallId),e.status);return}let t=i.current.toolCalls.get(String(e.toolCallId));t&&(typeof e.status=="string"&&(t.status=e.status,Qe(t.toolCallId,e.status)),typeof e.title=="string"&&(t.title=e.title),e.content!==void 0&&(t.content=(t.content||"")+$t(e.content)))}function xe(e,t,n=!1){if(i.current){n&&Tc(e,t),jr(t,e),Xe();for(let s of i.current.promptQueue)s.status==="processing"&&(s.status=e==="cancelled"?"cancelled":"done");for(let s of i.current.promptQueue)s.reseatAfterCurrentTurn&&s.status!=="done"&&s.status!=="cancelled"&&(s.reseatAfterCurrentTurn=void 0,zt(i.current,s));i.current.currentPlanEntry=null,i.current.currentHeadMessageId=void 0,Ac()}}function Oc(e,t){if(!i.current)return;let s=(Array.isArray(e.prompt)?e.prompt:[]).map(a=>ct(a)).join("");if(!s)return;let r=typeof e.messageId=="string"?e.messageId:void 0;if(r&&i.current.queueByMessageId.has(r)||r&&i.current.log.some(a=>a.kind==="stream"&&a.role==="user"&&a.messageId===r)||Zr({text:s}))return;let o=i.current.promptQueue.find(a=>a.text===s&&(a.status==="pending"||a.status==="queued"||a.status==="processing"));if(o){r!==void 0&&o.messageId===void 0&&(o.messageId=r,i.current.queueByMessageId.set(r,o),Un(o),i.current.spinnerOwner===o.id&&(i.current.spinnerOwner=r));return}Xe(),ge({kind:"stream",role:"user",text:s,closed:!0,messageId:r,attachments:qn(e.prompt)}),lt(t,r),fe()}function ti(e){if(i.current)for(let t of e){if(!t||typeof t!="object")continue;let n=t,s=typeof n.messageId=="string"?n.messageId:"";if(!s)continue;let r=typeof n.position=="number"?n.position:0,o=i.current.queueByMessageId.get(s);if(o){r===0?(i.current.currentHeadMessageId=s,(o.status==="queued"||o.status==="pending")&&(o.status="processing")):o.status==="pending"&&(o.status="queued");continue}let a=ni(n.prompt);if(!a)continue;let c=i.current.promptQueue.find(d=>d.messageId===void 0&&d.text===a&&(d.status==="pending"||d.status==="queued"||d.status==="cancelled"));if(c){c.messageId=s,i.current.queueByMessageId.set(s,c),Un(c),c.aheadAtEnqueue=Math.max(0,r),c.status=r===0?"processing":"queued",r===0&&(i.current.currentHeadMessageId=s);continue}let u={id:"snap_"+Math.random().toString(36).slice(2,10),text:a,status:r===0?"processing":"queued",aheadAtEnqueue:Math.max(0,r),messageId:s};if(i.current.queueByMessageId.set(s,u),r===0){i.current.currentHeadMessageId=s;let d=Lc(a);if(d){d.queueEntry=u;continue}}i.current.log.push({kind:"stream",role:"user",text:a,closed:!0,queueEntry:u,attachments:qn(n.prompt)})}}function Lc(e){if(!i.current)return null;let t=i.current.log;for(let n=t.length-1;n>=0;n--){let s=t[n];if(s.kind==="stream"&&s.role==="user"&&!s.queueEntry&&s.text===e)return s}return null}function ni(e){let t=Array.isArray(e)?e:[],n="";for(let s of t)if(s&&typeof s=="object"){let r=s;r.type==="text"&&typeof r.text=="string"&&(n+=r.text)}return n}function qn(e){let t=Array.isArray(e)?e:[],n=[];for(let s of t){if(!s||typeof s!="object")continue;let r=s;r.type!=="image"||typeof r.data!="string"||n.push({mimeType:typeof r.mimeType=="string"?r.mimeType:"image/png",data:r.data,sizeBytes:Math.round(r.data.length*3/4)})}return n.length>0?n:void 0}function Dc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let s=(e._meta??{})["hydra-acp"]??{},r=typeof s.amending=="string"?s.amending:void 0,o=e.originator??{},a=typeof o.clientId=="string"?o.clientId:"",c=!!i.current.ownClientId&&a===i.current.ownClientId,u=ni(e.prompt);if(c){let y=i.current.promptQueue.filter(E=>E.messageId===void 0&&(E.status==="pending"||E.status==="queued"||E.status==="editing")),v=(u.length>0?y.find(E=>E.text===u):void 0)??y[0]??i.current.promptQueue.find(E=>E.messageId===void 0&&E.status==="cancelled"&&E.text===u);if(!v)return;v.messageId=t,i.current.queueByMessageId.set(t,v),Un(v),i.current.spinnerOwner===v.id&&(i.current.spinnerOwner=t),r!==void 0&&(v.amendsMessageId=r,Ut(r,t));let b=typeof e.position=="number"?e.position:1;if(v.aheadAtEnqueue=Math.max(0,b),b===0)v.status="processing";else if(v.status==="pending"||v.status==="cancelled"){v.status="queued",i.current.spinnerOwner!==void 0&&i.current.spinnerOwner===v.id&&i.current.spinner&&(i.current.spinner=null,i.current.spinnerOwner=void 0,i.current.log=i.current.log.filter(x=>x.kind!=="spinner"));let E=i.current.log,M=E.findIndex(x=>x.kind==="stream"&&x.queueEntry===v);if(M>=0){let[x]=E.splice(M,1),R=$n();R>M?E.splice(R,0,x):E.splice(M,0,x)}}return}let d=u;if(!d)return;let f=typeof e.position=="number"?e.position:0,p=typeof e.queueDepth=="number"?e.queueDepth:1,g={id:"peer_"+Math.random().toString(36).slice(2,10),text:d,status:f===0?"processing":"queued",aheadAtEnqueue:Math.max(0,f),messageId:t};r!==void 0&&(g.amendsMessageId=r,Ut(r,t)),i.current.queueByMessageId.set(t,g),Xe();let m={kind:"stream",role:"user",text:d,closed:!0,queueEntry:g,messageId:t,attachments:qn(e.prompt)};f===0?ge(m):i.current.log.push(m)}function Pc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);if(!n)return;let s=Array.isArray(e.prompt)?e.prompt:[],r="";for(let o of s)if(o&&typeof o=="object"){let a=o;a.type==="text"&&typeof a.text=="string"&&(r+=a.text)}if(r){n.text=r;for(let o of i.current.log)if(o.kind==="stream"&&o.role==="user"&&o.queueEntry===n){o.text=r;break}}}function zt(e,t){let n=e.log.findIndex(r=>r.kind==="stream"&&r.queueEntry===t);if(n<0||n===e.log.length-1)return;let[s]=e.log.splice(n,1);s&&e.log.push(s)}function Bc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=typeof e.reason=="string"?e.reason:"";n==="started"&&(i.current.currentHeadMessageId=t);let s=i.current.queueByMessageId.get(t);s&&(n==="started"?(s.status="processing",s.reseatAfterCurrentTurn=void 0,i.current.spinnerOwner!==void 0&&(i.current.spinnerOwner===s.id||i.current.spinnerOwner===t)?i.current.spinnerOwner=t:lt(void 0,t),fe()):(n==="cancelled"||n==="abandoned")&&(s.amendedByMessageId!==void 0?s.status="amended":s.status="cancelled",i.current.queueByMessageId.delete(t)))}function Hc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);n&&(n.held=!0)}function Fc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);n&&(n.held=!1)}function $c(e){i.current&&typeof e.count=="number"&&(i.current.armedTasks=e.count,i.current.armedSince=e.count>0&&typeof e.since=="number"?e.since:void 0,i.current.armedTaskList=Kn(e.tasks))}function Kn(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let s=n;typeof s.label!="string"||typeof s.since!="number"||t.push({label:s.label,since:s.since,taskId:typeof s.taskId=="string"?s.taskId:void 0,taskType:typeof s.taskType=="string"?s.taskType:void 0,toolCallId:typeof s.toolCallId=="string"?s.toolCallId:void 0})}return t}function Uc(e){if(!i.current)return;switch(typeof e.phase=="string"?e.phase:""){case"started":case"iteration":i.current.compactionPhase="running";break;case"deferred":i.current.compactionPhase="deferred";break;case"swapped":i.current.compactionPhase=void 0,C({banner:{kind:"good",text:"Context compacted."}});break;case"failed":i.current.compactionPhase=void 0,C({banner:{kind:"bad",text:"Context compaction failed."}});break;case"rolled_back":i.current.compactionPhase=void 0,C({banner:{kind:"warn",text:"Compaction rolled back."}});break;default:break}}function qc(e){if(!i.current)return;let t=typeof e.cancelledMessageId=="string"?e.cancelledMessageId:"",n=typeof e.newMessageId=="string"?e.newMessageId:"";if(!t||!n)return;Ut(t,n);let s=i.current.queueByMessageId.get(n);s&&s.amendsMessageId===void 0&&(s.amendsMessageId=t)}function Ut(e,t){if(!i.current)return;let n=i.current.queueByMessageId.get(e)??i.current.promptQueue.find(s=>s.messageId===e);n&&(n.amendedByMessageId=t,n.status==="cancelled"&&(n.status="amended"))}function Kc(e){if(!i.current)return;let t=e.entries??e.plan??null;if(i.current.plan=t,i.current.currentPlanEntry){i.current.currentPlanEntry.entries=t;return}let n={kind:"plan",entries:t};ge(n),i.current.currentPlanEntry=n}function zc(e){if(!i.current)return;let t=typeof e?.toolCallId=="string"?e.toolCallId:void 0;t&&si(t)}function si(e){i.current&&(i.current.pendingPermissions.delete(e),i.current.log=i.current.log.filter(t=>!(t.kind==="perm"&&t.toolCallId===e)))}function Qe(e,t){!i.current||!e||!t||t==="pending"||i.current.pendingPermissions.has(e)&&si(e)}function Wt(e,t=!1){if(i.current?.cold&&(i.current.cold=!1,i.current.ready=!0),e.method==="hydra-acp/prompt_queue/added"){Dc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/updated"){Pc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/removed"){Bc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/held"){Hc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/released"){Fc(e.params??{});return}if(e.method==="hydra-acp/session/armed_tasks_updated"){$c(e.params??{});return}if(e.method==="hydra-acp/prompt/amended"){qc(e.params??{});return}if(e.method!=="session/update")return;let n=e.params?.update??null;if(!n||typeof n!="object")return;let s=String(n.sessionUpdate??"");if(i.current&&s&&!vc.has(s)&&typeof n.messageId=="string"&&(i.current.lastSeenMessageId=n.messageId,t||Ft(i.current.sessionId,e,n.messageId)),s==="permission_resolved"){zc(n);return}let o=(n._meta??{})["hydra-acp"]??{},a=s==="agent_message_chunk"&&o.synthetic===!0,c=typeof n.messageId=="string"?n.messageId:void 0,u=wc(e.params);switch(s){case"prompt_received":case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":case"tool_call":case"tool_call_update":case"plan":a||fe();break;default:break}switch(s){case"user_message_chunk":{if(o.compatFor==="prompt_received")break;Zr(n.content)||Fn("user",n.content,!1,c);break}case"agent_message_chunk":Fn("agent",n.content,a,c);break;case"agent_thought_chunk":Fn("thought",n.content,!1,c);break;case"tool_call":Cc(n);break;case"tool_call_update":Rc(n);break;case"current_mode_update":i.current&&(i.current.mode=n.modeId??n.currentModeId??null,Array.isArray(n.availableModes)&&(i.current.modes=n.availableModes),_());break;case"available_modes_update":i.current&&Array.isArray(n.availableModes)&&(i.current.modes=n.availableModes,_());break;case"current_model_update":i.current&&(i.current.model=n.modelId??n.currentModelId??null,Array.isArray(n.availableModels)&&(i.current.models=n.availableModels),_());break;case"config_option_update":i.current&&Array.isArray(n.configOptions)&&(i.current.configOptions=n.configOptions,_());break;case"usage_update":if(i.current){let d=n.used??n.contextUsed,f=n.size??n.contextSize;typeof d=="number"&&(i.current.contextUsed=d),typeof f=="number"&&(i.current.contextSize=f),n.cost&&(i.current.cost=n.cost)}break;case"plan":Kc(n);break;case"prompt_received":Oc(n,u);break;case"stop":case"turn_complete":{let p=((n._meta??{})["hydra-acp"]??{}).amended;if(p){let m=typeof p.cancelledMessageId=="string"?p.cancelledMessageId:"",y=typeof p.newMessageId=="string"?p.newMessageId:"";m&&y&&Ut(m,y)}let g=typeof n.stopReason=="string"?n.stopReason:void 0;xe(g,u);break}case"turn_started":{if(!i.current)break;let f=(n._meta??{})["hydra-acp"]??{};if(f.unsolicited!==!0)break;let p=typeof n.messageId=="string"?n.messageId:void 0;if(!p||i.current.unsolicitedTurnOpen.has(p))break;i.current.unsolicitedTurnOpen.add(p),fe();let g=f.cause??{},m=typeof g.label=="string"?g.label:void 0;ge({kind:"system",text:m?`agent resumed on its own: background task finished (${m})`:"agent resumed on its own"});break}case"turn_ended":{if(!i.current)break;let f=(n._meta??{})["hydra-acp"]??{};if(f.unsolicited!==!0)break;let p=typeof n.startedMessageId=="string"?n.startedMessageId:void 0;if(!p||!i.current.unsolicitedTurnOpen.has(p)||(i.current.unsolicitedTurnOpen.delete(p),f.reason==="superseded")||i.current.unsolicitedTurnOpen.size>0)break;xe(void 0,u);break}case"session_info_update":i.current&&typeof n.title=="string"&&(i.current.title=n.title);break;case"hydra_compaction":Uc(n);break;default:break}i.current?.inTurn&&me(u)}function ri(e){if(i.current){if(e.method==="session/request_permission"){let t=e.params??{},n=t.toolCall??{},s=typeof n.toolCallId=="string"?n.toolCallId:"";if(!s){i.current.ws?.send(JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"missing toolCall.toolCallId"}}));return}i.current.pendingPermissions.set(s,{requestId:e.id,toolCallId:s,toolCall:n,options:t.options??[]}),qt({kind:"perm",toolCallId:s});return}i.current.ws?.send(JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`method not handled: ${String(e.method)}`}}))}}var Wc="hydra-acp-draft:";function Gt(e){return Wc+e}function oi(e){try{return localStorage.getItem(Gt(e))??""}catch{return""}}var Yt=new Map,Me;function Ve(e,t){Yt.set(e,t),Me!==void 0&&clearTimeout(Me),Me=setTimeout(()=>{Me=void 0,ai()},400)}function Qt(e){Yt.delete(e);try{localStorage.removeItem(Gt(e))}catch{}}function ai(){for(let[e,t]of Yt)try{t?localStorage.setItem(Gt(e),t):localStorage.removeItem(Gt(e))}catch{}Yt.clear()}function ii(){Me!==void 0&&(clearTimeout(Me),Me=void 0),ai()}typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pagehide",ii),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&ii()}));var Gc="hydra-acp-offline-queue";var Ne="sessions",Xt=null;function zn(){return Xt||(Xt=new Promise(e=>{if(!("indexedDB"in window)){e(null);return}let t;try{t=indexedDB.open(Gc,1)}catch{e(null);return}t.onupgradeneeded=()=>{t.result.createObjectStore(Ne,{keyPath:"sessionId"})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null)}),Xt)}async function ci(e){let t=await zn();return t?new Promise(n=>{let s;try{s=t.transaction(Ne,"readonly")}catch{n([]);return}let r=s.objectStore(Ne).get(e);r.onsuccess=()=>{let o=r.result;n(o?.entries??[])},r.onerror=()=>n([])}):[]}async function Wn(e,t){let n=await zn();if(n)return new Promise(s=>{let r;try{r=n.transaction(Ne,"readwrite")}catch{s();return}let o=r.objectStore(Ne),a=o.get(e);a.onsuccess=()=>{let c=a.result??{sessionId:e,entries:[]},u=c.entries.findIndex(d=>d.id===t.id);u>=0?c.entries[u]=t:c.entries.push(t),o.put(c),s()},a.onerror=()=>s()})}async function Vt(e,t){let n=await zn();if(n)return new Promise(s=>{let r;try{r=n.transaction(Ne,"readwrite")}catch{s();return}let o=r.objectStore(Ne),a=o.get(e);a.onsuccess=()=>{let c=a.result;if(!c){s();return}c.entries=c.entries.filter(u=>u.id!==t),c.entries.length===0?o.delete(e):o.put(c),s()},a.onerror=()=>s()})}function dt(e,t){let n=[];e&&n.push({type:"text",text:e});for(let s of t)n.push({type:"image",data:s.data,mimeType:s.mimeType});return n}function ft(){let e=i.current;if(!e)return;let t=e.composerValue.trim(),n=e.attachments;!t&&n.length===0||(Yn(e,t,{attachments:n})&&(e.composerValue="",e.attachments=[],Qt(e.sessionId)),_())}function ui(e){let t=i.current;t&&(Yn(t,`/hydra workspace ${e}`,{addToHistory:!1}),_())}function di(){let e=i.current;e&&(Yn(e,"/hydra compact",{addToHistory:!1}),_())}function Yn(e,t,n={}){let s=n.attachments??[],r=!e.connectionHealthy||!navigator.onLine||!e.ws||e.ws.readyState!==WebSocket.OPEN,o=e.promptQueue.filter(p=>p.status==="queued"||p.status==="pending"||p.status==="processing").length,a=e.inTurn&&!e.promptQueue.some(p=>p.status==="processing"),c=r?0:o+(a?1:0),u={id:"p_"+Math.random().toString(36).slice(2,10),text:t,status:r?"offline":c>0?"queued":"pending",aheadAtEnqueue:c,attachments:s.length>0?s:void 0};e.promptQueue.push(u),e.log.push({kind:"stream",role:"user",text:t,closed:!0,queueEntry:u,attachments:u.attachments}),e.recentOwnPrompts.push({text:t,at:Date.now()});let d=Date.now()-6e4;if(e.recentOwnPrompts=e.recentOwnPrompts.filter(p=>p.at>=d).slice(-16),r)return Wn(e.sessionId,{id:u.id,text:t,attachments:u.attachments}),ut(e),(n.addToHistory??!0)&&Gn(e,t),!0;let f=ue("session/prompt",{sessionId:e.sessionId,prompt:dt(t,s)});return f!==void 0&&e.ownPromptIds.set(String(f),u),u.status==="pending"?lt(void 0,u.id):me(),fe(),ut(e),(n.addToHistory??!0)&&Gn(e,t),!0}function fi(e){let t=!1,n=null;for(let s of e.promptQueue){if(s.status!=="offline")continue;if(!e.ws||e.ws.readyState!==WebSocket.OPEN)break;t=!0;let r=e.promptQueue.filter(u=>u.status==="queued"||u.status==="pending"||u.status==="processing").length,o=e.inTurn&&!e.promptQueue.some(u=>u.status==="processing"),a=r+(o?1:0);s.aheadAtEnqueue=a,s.status=a>0?"queued":"pending",!n&&s.status==="pending"&&(n=s);let c=ue("session/prompt",{sessionId:e.sessionId,prompt:dt(s.text,s.attachments??[])});c!==void 0&&e.ownPromptIds.set(String(c),s),Vt(e.sessionId,s.id),zt(e,s),e.inTurn&&(s.reseatAfterCurrentTurn=!0)}t&&(n?lt(void 0,n.id):me(),fe())}var li=100;function Gn(e,t){e.history[0]!==t&&(e.history.unshift(t),e.history.length>li&&(e.history.length=li)),e.historyIndex=null,e.historyDraft=null}function jt(e){let t=i.current;if(t){if(e.messageId!==void 0){ue("hydra-acp/prompt/cancel",{sessionId:t.sessionId,messageId:e.messageId});return}e.status==="offline"&&Vt(t.sessionId,e.id),e.status="cancelled",_()}}function pi(e){let t=i.current;if(!t||!t.daemonSupportsAmend||t.currentHeadMessageId===void 0||e.messageId===void 0||e.status!=="queued")return;if(!t.connectionHealthy||!navigator.onLine||!t.ws||t.ws.readyState!==WebSocket.OPEN){C({banner:{kind:"warn",text:"Not connected \u2014 still queued, try again in a moment."}});return}let n=t.currentHeadMessageId,s=e.messageId;t.queueByMessageId.delete(s),e.messageId=void 0,e.status="pending",e.amendsMessageId=n,e.aheadAtEnqueue=0,zt(t,e),ue("hydra-acp/prompt/cancel",{sessionId:t.sessionId,messageId:s}),hi(e,e.text,n,e.text),ut(t),_()}function gi(e,t){let n=i.current;if(!n)return;let s=t.trim();if(s){if(e.status==="offline"){e.text=s,Wn(n.sessionId,{id:e.id,text:s,attachments:e.attachments}),_();return}if(e.messageId===void 0){e.text=s,_();return}ue("hydra-acp/prompt/update",{sessionId:n.sessionId,messageId:e.messageId,prompt:dt(s,e.attachments??[])})}}function mi(){let e=i.current;if(!e)return;let t=e.composerValue.trim(),n=e.attachments;if(!t&&n.length===0)return;if(!e.connectionHealthy||!navigator.onLine||!e.ws||e.ws.readyState!==WebSocket.OPEN){e.log.push({kind:"error",text:"Not connected to session \u2014 prompt not sent."}),e.composerValue="",e.attachments=[],Qt(e.sessionId),_();return}if(!e.daemonSupportsAmend||e.currentHeadMessageId===void 0){ft();return}let s=e.currentHeadMessageId,r=e.composerValue;e.composerValue="",e.attachments=[],Qt(e.sessionId),Gn(e,t);let o={id:"p_"+Math.random().toString(36).slice(2,10),text:t,status:"pending",aheadAtEnqueue:0,amendsMessageId:s,attachments:n.length>0?n:void 0};e.promptQueue.push(o),e.log.push({kind:"stream",role:"user",text:t,closed:!0,queueEntry:o,attachments:o.attachments}),e.recentOwnPrompts.push({text:t,at:Date.now()});let a=Date.now()-6e4;e.recentOwnPrompts=e.recentOwnPrompts.filter(c=>c.at>=a).slice(-16),me(),fe(),ut(e),hi(o,r,s,t),_()}function hi(e,t,n,s){let r=i.current;if(!r)return;let o=ue("_session/steering",{sessionId:r.sessionId,prompt:dt(s,e.attachments??[])});o!==void 0&&r.responseHandlers.set(String(o),a=>{Yc(e,t,n,s,a)})}function Yc(e,t,n,s,r){let o=i.current;if(!o)return;if(r.error){if(r.error?.code===-32601){Qc(e,t,n,s);return}Zt(o,e,t),C({banner:{kind:"bad",text:`steering failed: ${bi(r.error)}`}});return}let a=r.result??{};if(a.outcome==="injected"){e.status="processing",_();return}a.outcome!=="startedNewTurn"&&(Zt(o,e,t),C({banner:{kind:"warn",text:"steering failed"}}))}function Qc(e,t,n,s){let r=i.current;if(!r)return;let o=ue("hydra-acp/prompt/amend",{sessionId:r.sessionId,targetMessageId:n,prompt:dt(s,e.attachments??[])});o!==void 0&&r.responseHandlers.set(String(o),a=>{Xc(e,t,a)})}function Xc(e,t,n){let s=i.current;if(!s)return;if(n.error){Zt(s,e,t),C({banner:{kind:"bad",text:`amend failed: ${bi(n.error)}`}});return}let r=n.result??{};if(r.amended&&r.reason==="ok")return;Zt(s,e,t);let o="amend rejected";r.reason==="target_completed"?o="previous response finished \u2014 press Send to send as a new turn":r.reason==="target_cancelled"?o="amend skipped \u2014 previous turn was cancelled":r.reason==="target_not_found"&&(o="amend skipped \u2014 no matching prompt"),C({banner:{kind:"warn",text:o}})}function Zt(e,t,n){let s=e.promptQueue.indexOf(t);s>=0&&e.promptQueue.splice(s,1),e.log=e.log.filter(r=>!(r.kind==="stream"&&r.role==="user"&&r.queueEntry===t)),e.composerValue=n,e.attachments=t.attachments??[],Ve(e.sessionId,n),_()}function bi(e){if(e&&typeof e=="object"&&"message"in e){let t=e.message;if(typeof t=="string")return t}return"unknown error"}function Ei(){let e=i.current;!e||!e.inTurn||Ze("session/cancel",{sessionId:e.sessionId})}function yi(){let e=i.current;if(!e)return;let t=!1;for(let n of e.promptQueue)(n.status==="queued"||n.status==="pending")&&(jt(n),t=!0);e.inTurn&&Ze("session/cancel",{sessionId:e.sessionId}),t&&_()}function _i(e){i.current&&ue("session/set_mode",{sessionId:i.current.sessionId,modeId:e})}function vi(e){i.current&&ue("session/set_model",{sessionId:i.current.sessionId,modelId:e})}function wi(e,t){let n=i.current;if(!n)return;let s=ue("session/set_config_option",{sessionId:n.sessionId,configId:e,value:t});s!==void 0&&n.responseHandlers.set(String(s),r=>{let o=r.result?.configOptions;Array.isArray(o)&&i.current===n&&(n.configOptions=o,_())})}function Si(e){for(let t of e.promptQueue)t.status!=="done"&&t.status!=="cancelled"&&(t.status==="offline"&&Vt(e.sessionId,t.id),t.status="cancelled",t.messageId!==void 0&&e.queueByMessageId.delete(t.messageId))}function Ti(e){for(let t of e.promptQueue)t.messageId===void 0&&t.status!=="done"&&t.status!=="cancelled"&&t.status!=="offline"&&(t.status="cancelled")}var Jt=null;async function je(){if(Jt)return Jt;if(!("serviceWorker"in navigator))return null;try{return Jt=await navigator.serviceWorker.register("/sw.js"),Jt}catch{return null}}async function Ii(){return typeof Notification>"u"||!await je()?!1:Notification.permission==="granted"?!0:Notification.permission==="denied"?!1:await Notification.requestPermission()==="granted"}function Ai(){return document.visibilityState!=="visible"||!document.hasFocus()}async function ki(){let e=await je();return!e||!("pushManager"in e)?void 0:(await e.pushManager.getSubscription())?.endpoint}function Vc(e){let t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),s=atob(n);return Uint8Array.from(s,r=>r.charCodeAt(0))}async function en(){let e=await je();if(!(!e||!("pushManager"in e)))try{let{publicKey:t}=await se("/api/push/vapid-public-key"),n=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Vc(t)});await se("/api/push/subscribe",{method:"POST",body:JSON.stringify(n.toJSON())})}catch(t){console.warn("push subscribe failed:",t)}}async function xi(){let e=await je();if(!(!e||!("pushManager"in e)))try{let t=await e.pushManager.getSubscription();if(!t)return;let n=t.endpoint;await t.unsubscribe(),await se("/api/push/unsubscribe",{method:"POST",body:JSON.stringify({endpoint:n})})}catch(t){console.warn("push unsubscribe failed:",t)}}function ue(e,t){let n=i.current;if(!n||!n.ws||n.ws.readyState!==WebSocket.OPEN)return;let s=n.nextId=n.nextId??1;return n.nextId=s+1,n.ws.send(JSON.stringify({jsonrpc:"2.0",id:s,method:e,params:t})),s}function Ze(e,t){let n=i.current;!n||!n.ws||n.ws.readyState!==WebSocket.OPEN||n.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t}))}function pt(){Ze("bridge/visibility",{visible:!Ai()})}function Je(){ki().then(e=>{Ze("bridge/push-endpoint",{endpoint:e??null})})}var Zc=1e4,jc=5e3;function Mi(e){e.heartbeatTimer=setTimeout(()=>Jc(e),Zc)}function Jc(e){i.current!==e||!e.ws||e.ws.readyState!==WebSocket.OPEN||(Ze("bridge/ping",{}),e.heartbeatDeadline=setTimeout(()=>{e.connectionHealthy=!1,_();try{e.ws?.close()}catch{}},jc))}function el(e){e.connectionHealthy=!0,e.heartbeatDeadline!==void 0&&(clearTimeout(e.heartbeatDeadline),e.heartbeatDeadline=void 0),Mi(e)}function tl(e){tn(e),e.connectionHealthy=!0,Mi(e)}function tn(e){e.heartbeatTimer!==void 0&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=void 0),e.heartbeatDeadline!==void 0&&(clearTimeout(e.heartbeatDeadline),e.heartbeatDeadline=void 0)}function nl(e,t){let n=i.current;!n||!n.ws||n.ws.readyState!==WebSocket.OPEN||n.ws.send(JSON.stringify({jsonrpc:"2.0",id:e,result:t}))}function Ni(e){if(i.current){if(e.method==="bridge/replay_policy"){e.params?.policy!=="after_message"&&Kt(i.current);return}if(e.method==="bridge/ready"){i.current.ready=!0,i.current.cold=!1,i.banner=null,i.current.reconnectAttempt=0;let t=e.params??{};typeof t.clientId=="string"&&(i.current.ownClientId=t.clientId),Array.isArray(t.configOptions)&&(i.current.configOptions=t.configOptions);let s=t._meta?.["hydra-acp"];if(s?.busy===!1&&i.current.inTurn&&xe(),s?.busy===!0){fe();let c=s.turnStartedAt;typeof c=="number"&&Number.isFinite(c)?(i.current.spinner||me(),i.current.spinner&&i.current.spinnerOwner===void 0&&(i.current.spinner.startedAt=c)):i.current.spinner||me()}let r=s?.queue;Array.isArray(r)&&ti(r),s?.prompt?.amending===!0&&(i.current.daemonSupportsAmend=!0),typeof s?.armedTasks=="number"&&(i.current.armedTasks=s.armedTasks,i.current.armedSince=s.armedTasks>0&&typeof s.armedSince=="number"?s.armedSince:void 0,i.current.armedTaskList=Kn(s.armedTaskList));let a=i.current.readyListeners;i.current.readyListeners=[];for(let c of a)try{c()}catch{}pt(),Je(),tl(i.current),fi(i.current),_();return}if(e.method==="bridge/pong"){i.current&&el(i.current);return}if(e.method==="bridge/error"){qt({kind:"error",text:`Bridge error: ${e.params?.message??"?"}`}),_();return}if(e.method==="hydra-acp/session/closed"){i.current&&(i.current.ready=!1,i.current.cold=!0,Si(i.current),xe()),_();return}if(e.method&&"id"in e){ri(e),i.current.ready&&_();return}if(e.method){Wt(e),i.current.ready&&_();return}if("id"in e&&e.id!==void 0&&i.current.ownPromptIds.has(String(e.id))){let t=i.current.ownPromptIds.get(String(e.id));if(i.current.ownPromptIds.delete(String(e.id)),i.current.cold&&(i.current.cold=!1,i.current.ready=!0),e.error){let a=e.error;qt({kind:"error",text:`Prompt failed: ${a.message??"unknown error"}`}),xe(),_();return}let n=e.result,s=typeof n?.stopReason=="string"?n.stopReason:void 0,r=i.current.spinnerOwner;t===void 0||r===void 0||r===t.id||t.messageId!==void 0&&r===t.messageId?xe(s,void 0,!0):s==="cancelled"&&t.status!=="amended"&&(t.status="cancelled"),_();return}if("id"in e&&e.id!==void 0){let t=i.current.responseHandlers.get(String(e.id));t&&(i.current.responseHandlers.delete(String(e.id)),t({result:e.result,error:e.error}))}}}function Qn(e,t){if(!i.current)return;let n=i.current.pendingPermissions.get(e);n&&(i.current.pendingPermissions.delete(e),i.current.log=i.current.log.filter(s=>!(s.kind==="perm"&&s.toolCallId===e)),nl(n.requestId,{outcome:t==="__cancel__"?{outcome:"cancelled"}:{outcome:"selected",optionId:t}}),_())}var Ci=[1e3,2e3,4e3,8e3,16e3,3e4],sl=5;function Ri(e,t){let n=encodeURIComponent(e);return t?`#/session/${n}?load=true`:`#/session/${n}`}function Oi(){let t=new URLSearchParams(window.location.search).get("protocol_launch");if(!t)return;history.replaceState(null,"",window.location.pathname+window.location.hash);let n;try{n=new URL(t)}catch{return}if(n.protocol!=="web+hydra:"||n.hostname!=="sessions")return;let s=decodeURIComponent(n.pathname.replace(/^\/+/,""));s&&(window.location.hash=Ri(s,!0))}var Xn=!1,Vn=!1;function rl(){try{return window.matchMedia?.("(display-mode: standalone)").matches===!0||navigator.standalone===!0}catch{return!1}}function Li(e){if(window.location.hash===e)return;Xn=!0;let t=Vn||rl()?history.replaceState:history.pushState;Vn=!1;try{t.call(history,null,"",e||window.location.pathname+window.location.search)}finally{queueMicrotask(()=>{Xn=!1})}}function Zn(){if(Xn)return;let t=window.location.hash.match(/^#\/session\/([^?]+)(?:\?(.*))?$/);if(t){let n=decodeURIComponent(t[1]),r=new URLSearchParams(t[2]??"").get("load")==="true";if(i.view==="chat"&&i.current?.sessionId===n)return;Ce(n,r);return}i.view!=="list"&&Re()}function Ce(e,t){Li(Ri(e,t)),Jn();let n=i.sessions.find(r=>r.sessionId===e),s={sessionId:e,title:n?.title??"",cwd:n?.cwd||"",agentId:n?.agentId||"",ws:null,ready:!1,log:[],toolCalls:new Map,pendingPermissions:new Map,pendingRequestById:new Map,responseHandlers:new Map,spinner:null,plan:null,mode:null,model:null,modes:[],models:[],contextUsed:null,contextSize:null,cost:null,fileOverlay:null,composerValue:oi(e),attachments:[],busy:!1,recentOwnPrompts:[],history:[],historyIndex:null,historyDraft:null,_lastMetaFp:n?`${n.title}|${n.cwd}|${n.agentId}`:"",promptQueue:[],queueByMessageId:new Map,ownPromptIds:new Map,inTurn:!1,idleListeners:[],readyListeners:[],currentPlanEntry:null,daemonSupportsAmend:!1,loadOnConnect:t,reconnectAttempt:0,headerExpanded:!1,unsolicitedTurnOpen:new Set,configOptions:[],connectionHealthy:!0};i.current=s,C({view:"chat",listHighlightedSessionId:e,lastSessionId:e}),il(s)}async function il(e){let t=await Qr(e.sessionId);if(i.current!==e)return;t&&(_e("cache-replay",()=>{for(let s of t.frames)try{Wt(s,!0)}catch(r){console.error("[hydra] cached frame failed to replay",r,s)}}),e.lastSeenMessageId=e.lastSeenMessageId??t.lastSeenMessageId,e.historyIsPartial=!0);let n=await ci(e.sessionId);if(i.current===e){for(let s of n){let r={id:s.id,text:s.text,status:"offline",aheadAtEnqueue:0,attachments:s.attachments};e.promptQueue.push(r),e.log.push({kind:"stream",role:"user",text:s.text,closed:!0,queueEntry:r,attachments:r.attachments})}(t||n.length>0)&&_(),jn(e)}}function Di(e){if(i.current!==e)return;let t=document.querySelector(".chat-body");if(t){let n=t.getBoundingClientRect().top;for(let s of t.querySelectorAll("[data-message-id]"))if(s.getBoundingClientRect().bottom>n){e.scrollRestoreMessageId=s.dataset.messageId;break}}Jn(),Pi(e),Kt(e),e.historyIsPartial=!1,_(),jn(e)}function jn(e){let t=new URL("/ws",location.href);t.protocol=location.protocol==="https:"?"wss:":"ws:",t.searchParams.set("session",e.sessionId),e.loadOnConnect&&t.searchParams.set("load","true"),e.lastSeenMessageId!==void 0&&t.searchParams.set("afterMessageId",e.lastSeenMessageId);let n=new WebSocket(t.toString());e.ws=n,n.addEventListener("open",()=>{}),n.addEventListener("message",s=>{if(!i.current||i.current.ws!==n)return;let r;try{r=JSON.parse(String(s.data))}catch{return}Ni(r)}),n.addEventListener("close",()=>{!i.current||i.current.ws!==n||ol(i.current)}),n.addEventListener("error",()=>{})}function ol(e){e.ready=!1,Ti(e);let t=e.reconnectAttempt??0,n=Ci[Math.min(t,Ci.length-1)],s=t>=sl;C({banner:s?{kind:"bad",text:"Still disconnected \u2014 retrying\u2026"}:{kind:"warn",text:"Reconnecting\u2026"}}),e.reconnectTimer=setTimeout(()=>{!i.current||i.current!==e||(e.reconnectTimer=void 0,e.reconnectAttempt=t+1,Pi(e),_(),jn(e))},n)}function Pi(e){e.ws=null,e.ready=!1,e.pendingRequestById=new Map,e.responseHandlers=new Map,e.ownPromptIds=new Map,e.idleListeners=[],e.readyListeners=[],e.nextId=void 0,tn(e)}function Bi(){if(i.view==="chat")return;let e=i.lastSessionId;if(!e||(C({listHighlightedSessionId:e}),!te()))return;let t=n=>{if(i.view==="chat")return;let s=i.sessions.find(r=>r.sessionId===e);if(s){s.status!=="cold"&&(Vn=!0,Ce(e,!1));return}n<20&&setTimeout(()=>t(n+1),250)};t(0)}function Re(){Li(""),Jn();let e=i.current?.sessionId??i.lastSessionId;C({view:"list",current:null,lastSessionId:e,listHighlightedSessionId:e??i.listHighlightedSessionId}),gt()}function Hi(){if(i.current?.ws)try{i.current.ws.close()}catch{}}function Jn(){if(i.current&&(i.current.reconnectTimer&&(clearTimeout(i.current.reconnectTimer),i.current.reconnectTimer=void 0),tn(i.current),i.current.ws)){try{i.current.ws.close()}catch{}i.current.ws=null}}var Fi="(prefers-color-scheme: dark)";function al(){return i.theme==="system"?window.matchMedia(Fi).matches?"dark":"light":i.theme}function sn(){document.documentElement.style.fontSize=`${16*i.fontScale}px`}function nn(){let e=al();document.documentElement.setAttribute("data-theme",e),document.querySelector('meta[name="theme-color"]')?.setAttribute("content",e==="light"?"#ffffff":"#0e1116")}function $i(){nn(),window.matchMedia(Fi).addEventListener("change",()=>{i.theme==="system"&&nn()})}var Ui=10*1024*1024,mt=new WeakSet;function ss(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e>=1024?`${(e/1024).toFixed(0)}KB`:`${e}B`}function cl(e,t){for(let n of t){if(n.size>Ui){C({banner:{kind:"warn",text:`pasted image is ${ss(n.size)}, max ${ss(Ui)}`}});continue}let s=new FileReader;s.onload=()=>{let r=s.result;if(typeof r!="string")return;let o=r.indexOf(",");o<0||(e.attachments.push({mimeType:n.type||"image/png",data:r.slice(o+1),sizeBytes:n.size}),_())},s.readAsDataURL(n)}}function Ji(e){return`data:${e.mimeType};base64,${e.data}`}function ll(e){return e.attachments.length===0?null:l("div",{class:"attachment-chips"},...e.attachments.map((t,n)=>l("span",{class:"attachment-chip",title:ss(t.sizeBytes)},l("img",{class:"attachment-thumb",src:Ji(t)}),l("button",{class:"attachment-remove",title:"Remove image",...I(()=>{e.attachments.splice(n,1),_()})},"\xD7"))))}function eo(e){return"untitled"}function he(e){return e.replace(/^hydra_session_/,"")}function ul(e){if(!e)return;let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}function dl(e,t){let n=e||"?",s=ul(t);return s?`${n}\u2022${s}`:n}function to(e){let t=Math.floor(Math.max(0,e)/1e3);if(t<60)return"<1m";let n=Math.floor(t/60);if(n<60)return`${n}m`;let s=Math.floor(n/60);if(s<24)return`${s}h`;let r=Math.floor(s/24);if(r<14)return`${r}d`;let o=Math.floor(r/7);if(o<9)return`${o}w`;let a=Math.floor(r/30);return a<12?`${a}mo`:`${Math.floor(r/365)}y`}function fl(e,t=Date.now()){if(!e)return"?";let n=Date.parse(e);return Number.isNaN(n)?"?":to(t-n)}function qi(e){return Number.isFinite(e)?e<1e3?String(e):e<1e6?(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")+"k":(e/1e6).toFixed(2).replace(/\.?0+$/,"")+"M":"?"}function Ki(e){let t=null,n="USD";if(typeof e=="number")t=e;else if(e&&typeof e=="object"){let r=e;if(typeof r.amount=="number")t=r.amount;else if(typeof r.total=="number")t=r.total;else if(r.total&&typeof r.total=="object"){let o=r.total;typeof o.amount=="number"&&(t=o.amount),typeof o.currency=="string"&&(n=o.currency)}typeof r.currency=="string"&&(n=r.currency)}if(t===null)return null;let s=t<.01?4:t<1?3:2;return n==="USD"?`$${t.toFixed(s)}`:`${t.toFixed(s)} ${n}`}function no(e,t){t.banner&&e.appendChild(l("div",{class:"banner "+t.banner.kind},t.banner.text)),te()?e.appendChild(hl(t)):t.view==="list"?(e.appendChild(io()),e.appendChild(ro()),e.appendChild(lo())):t.view==="chat"&&t.current&&(e.appendChild(ln(t.current)),t.current.fileOverlay&&e.appendChild(Eo(t.current))),t.modal&&(t.modal.kind==="session"?e.appendChild(Fl(t.modal)):t.modal.kind==="modes"&&t.current?e.appendChild(Gi("Mode",t.current.modes,t.current.mode,n=>_i(n.id))):t.modal.kind==="models"&&t.current?e.appendChild(Gi("Model",t.current.models,t.current.model,n=>vi(n.id))):t.modal.kind==="options"&&e.appendChild(Ml()))}function so(){return[io(),ro(),lo()]}function pl(){let e=l("div",{class:"rail",tabindex:"-1","data-focus-key":"list-rail"},...so());return i.railWidth!==null&&(e.style.flex=`0 0 ${rs(i.railWidth)}px`),ls(),e}function gl(e){if(!_o())return;let t=e.querySelector(".list"),n=t?t.scrollTop:null,s=document.activeElement,r=s&&e.contains(s)?s.dataset.focusKey??null:null,o=r?s.selectionStart:null,a=r?s.selectionEnd:null;if(e.replaceChildren(...so()),ls(),r){let c=e.querySelector(`[data-focus-key="${CSS.escape(r)}"]`);if(c){c.focus();let u=c;if(o!==null&&typeof u.setSelectionRange=="function")try{u.setSelectionRange(o,a)}catch{}}}if(n!==null){let c=e.querySelector(".list");c&&(c.scrollTop=n)}}function rs(e){let t=Math.max(280,Math.min(window.innerWidth*.6,window.innerWidth-360));return Math.round(Math.max(240,Math.min(e,t)))}function ml(){let e=l("div",{class:"splitter",title:"Drag to resize"});return e.addEventListener("pointerdown",t=>{let n=e.previousElementSibling;if(!n)return;t.preventDefault();let s=t.clientX,r=n.getBoundingClientRect().width;e.setPointerCapture(t.pointerId),e.classList.add("dragging");let o=c=>{n.style.flex=`0 0 ${rs(r+(c.clientX-s))}px`},a=()=>{e.releasePointerCapture(t.pointerId),e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",a),e.removeEventListener("pointercancel",a),C({railWidth:rs(n.getBoundingClientRect().width)})};e.addEventListener("pointermove",o),e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a)}),e}function hl(e){let t=l("div",{class:"split-detail"});return e.current?(t.appendChild(ln(e.current)),e.current.fileOverlay&&t.appendChild(Eo(e.current))):t.appendChild(l("div",{class:"split-detail-empty"},"Select a session from the list")),l("div",{class:"split"},pl(),ml(),t)}function as(){let e=document.querySelector('[data-focus-key="list-rail"]');e&&(i.current&&C({listHighlightedSessionId:i.current.sessionId}),e.focus())}function ro(){let e=i.sessionSearch.length>0?l("button",{class:"session-search-clear",title:"Clear filter",...I(()=>C({sessionSearch:""}))},"\xD7"):null;return l("div",{class:"session-search-row"},l("input",{class:"session-search",type:"text",placeholder:"Filter sessions\u2026",value:i.sessionSearch,"data-focus-key":"session-search",autocomplete:"off",autocapitalize:"off",autocorrect:"off",spellcheck:"false",oninput:t=>{C({sessionSearch:t.target.value})},onkeydown:t=>{t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),i.sessionSearch.length>0?C({sessionSearch:""}):t.target.blur())}}),e)}function io(){return l("div",{class:"topbar"},l("span",{class:"pill clickable",title:"Click to toggle grouping by project/recent",...I(()=>C({groupBy:i.groupBy==="project"?"recent":"project"}))},i.groupBy),l("span",{class:"pill clickable",title:"Click to toggle showing disk-only sessions",...I(()=>{C({showCold:!i.showCold})})},i.showCold?"all":"warm"),bl(),l("span",{class:"spacer"}),l("button",{...I(uo),title:"Options"},"\u2699"),l("button",{...I(Dl),title:"Import a *.hydra bundle from disk"},"\u{1F4E5}"),l("button",{...I(go),title:"New Session"},"\uFF0B"))}function bl(){let e=new Set;for(let r of i.sessions)r.importedFromMachine&&!r.upstreamSessionId&&e.add(r.importedFromMachine);let t=[...e].sort(),n=l("select",{class:"host-select",title:"Filter sessions by origin host",onchange:r=>{let o=r.target.value;C({hostFilter:o})}}),s=(r,o)=>{let a=document.createElement("option");a.value=r,a.textContent=o,i.hostFilter===r&&(a.selected=!0),n.appendChild(a)};s("__local","local");for(let r of t)s(r,r);return s("__all","all"),i.hostFilter!=="__local"&&i.hostFilter!=="__all"&&!t.includes(i.hostFilter)&&(n.value=i.hostFilter),n}function El(e,t){if(t.length===0)return!0;let n=t.toLowerCase();return[he(e.sessionId),e.upstreamSessionId??"",e.agentId??"",e.title??"",e.cwd,e.cwd.replace(/^\/(?:home|Users)\/[^/]+/,"~")].some(r=>r.toLowerCase().includes(n))}function oo(){let e=i.showCold?i.sessions:i.sessions.filter(n=>n.status!=="cold");i.hostFilter==="__local"?e=e.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):i.hostFilter!=="__all"&&(e=e.filter(n=>n.importedFromMachine===i.hostFilter&&!n.upstreamSessionId));let t=i.sessionSearch.trim();return t.length>0&&(e=e.filter(n=>El(n,t))),e}function yl(){return fo(oo(),i.groupBy).flatMap(e=>e.sessions.map(t=>t.sessionId))}function ao(){document.querySelector('[data-focus-key="composer"]')?.focus()}function is(e,t){if(te()&&i.current?.sessionId===e){ao();return}Ce(e,t)}function co(e){let t=document.activeElement?.dataset.focusKey==="list-rail";if(i.view!=="list"&&!(te()&&t)||ve(document.activeElement))return;if(e.key==="Escape"){if(te()&&i.current){e.preventDefault(),C({listHighlightedSessionId:i.current.sessionId}),ao();return}let u=i.lastSessionId,d=u?i.sessions.find(f=>f.sessionId===u):void 0;if(!d)return;e.preventDefault(),is(d.sessionId,d.status==="cold");return}if(e.key.toLowerCase()==="c"&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),go();return}let n=!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey,s=e.key==="ArrowDown"||e.key==="n"&&n,r=e.key==="ArrowUp"||e.key==="p"&&n;if(!s&&!r&&e.key!=="Enter")return;let o=yl();if(o.length===0)return;if(e.key==="Enter"){let u=i.listHighlightedSessionId;if(!u||!o.includes(u))return;let d=i.sessions.find(f=>f.sessionId===u);if(!d)return;e.preventDefault(),is(d.sessionId,d.status==="cold");return}e.preventDefault();let a=i.listHighlightedSessionId?o.indexOf(i.listHighlightedSessionId):-1,c=a===-1?0:s?Math.min(o.length-1,a+1):Math.max(0,a-1);C({listHighlightedSessionId:o[c]})}function lo(){let e=oo(),t=i.showCold?0:i.sessions.filter(r=>r.status==="cold").length,n=fo(e,i.groupBy),s=l("div",{class:"list"});if(i.listHighlightedSessionId&&queueMicrotask(()=>{document.querySelector(".card.highlighted")?.scrollIntoView({block:"nearest"})}),e.length===0){let r;i.sessionSearch.trim().length>0?r=`No sessions match \u201C${i.sessionSearch.trim()}\u201D.`:i.sessions.length===0?r="No sessions. Use + to create one, or run `hydra-acp launch <agent>` from your editor.":i.hostFilter==="__local"?r="No local sessions. Switch the host filter to see imported sessions.":i.hostFilter!=="__all"?r=`No sessions from ${i.hostFilter}. Try a different host.`:r=`No warm sessions. ${t} cold session${t===1?"":"s"} hidden \u2014 click "warm" to switch to "all".`,s.appendChild(l("div",{class:"empty"},r))}for(let r of n){let o=l("div",{class:"group"});r.label&&o.appendChild(l("h2",null,r.label));for(let a of r.sessions)o.appendChild(Cl(a,r.label===null));s.appendChild(o)}return s}function zi(e,t){let n=r=>{let o=r.status==="warm";return o&&r.busy&&r.awaitingInput?4:o&&r.busy?3:o&&r.awaitingInput?2:o?1:0},s=n(t)-n(e);return s!==0?s:String(t.updatedAt||"").slice(0,16).localeCompare(String(e.updatedAt||"").slice(0,16))}function un(e){return e.replace(/^\/(home|Users)\/[^/]+/,"~")}function es(e,t){return l("div",{class:"detail"},l("span",{class:"k"},e),l("code",null,t))}function _l(e){let t=(n,s)=>l("button",{class:"ghost",...I(()=>ui(n))},s);return e?l("div",{class:"detail"},l("span",{class:"k"},"workspace"),l("code",null,`${e.label}${e.clean===!1?" \xB7 dirty":""}`),t("sync","Sync"),t("stop","Stop"),t("apply","Apply")):l("div",{class:"detail"},l("span",{class:"k"},"workspace"),t("start","Start workspace"))}function vl(){return l("div",{class:"detail"},l("span",{class:"k"},"hide thoughts"),l("label",{class:"checkbox-label"},l("input",{type:"checkbox",checked:i.hideThoughts?"":void 0,onchange:e=>{C({hideThoughts:e.target.checked})}})))}function wl(){return l("div",{class:"detail"},l("span",{class:"k"},"notify"),l("label",{class:"checkbox-label"},l("input",{type:"checkbox",checked:i.notifyOnTurnEnd?"":void 0,onchange:e=>{if(!e.target.checked){C({notifyOnTurnEnd:!1}),xi().then(()=>Je());return}Ii().then(n=>{if(!n){C({banner:{kind:"warn",text:"Notifications blocked \u2014 enable them for this site in your browser settings."}});return}C({notifyOnTurnEnd:!0}),en().then(()=>Je())})}})))}function uo(){let e=i.current?.sessionId;i.cacheInfo=e?"\u2026":"no session open",e&&Xr(e).then(t=>{i.cacheInfo=t,_()}),C({modal:{kind:"options"}})}var Sl=[{value:"system",label:"system"},{value:"dark",label:"dark"},{value:"light",label:"light"}],Tl=[{value:.85,label:"smaller"},{value:.95,label:"small"},{value:1,label:"normal"},{value:1.15,label:"large"},{value:1.3,label:"larger"},{value:1.5,label:"largest"}];function Il(){let e=l("select",{onchange:t=>{C({fontScale:Number(t.target.value)}),sn()}},...Tl.map(t=>l("option",{value:String(t.value)},t.label)));return e.value=String(i.fontScale),l("div",{class:"detail"},l("span",{class:"k"},"text size"),e)}function on(e,t){let n=l("span",{class:"diag-value"},t);return l("div",{class:"detail diag-copy",title:"Tap to copy",...I(()=>{let r=()=>{let a=n.textContent;n.textContent="copied",setTimeout(()=>{n.textContent=a},1200)},o=`${e}: ${t}`;navigator.clipboard?.writeText?navigator.clipboard.writeText(o).then(r,()=>Wi(n)):Wi(n)})},l("span",{class:"k"},e),n)}function Wi(e){let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n?.removeAllRanges(),n?.addRange(t)}function Al(){return on("cache",i.cacheInfo??"\u2026")}function kl(){return on("build","2026-08-26 16:23Z")}function xl(){let e=l("select",{onchange:t=>{C({theme:t.target.value}),nn()}},...Sl.map(t=>{let n=l("option",{value:t.value},t.label);return t.value===i.theme&&n.setAttribute("selected",""),n}));return e.value=i.theme,l("div",{class:"detail"},l("span",{class:"k"},"theme"),e)}function Ml(){return l("div",{class:"modal-bg",...I(e=>{e.target.classList.contains("modal-bg")&&be()})},l("div",{class:"modal"},l("h2",null,"Options"),xl(),Il(),vl(),wl(),l("div",{class:"diagnostics"},kl(),Al(),on("slow",vs()),on("paths",_s())),l("div",{class:"actions"},l("button",{class:"primary",...I(be)},"Close"))))}function Nl(e){let t=l("select",{onchange:n=>{wi(e.id,n.target.value)}},...e.options.map(n=>{let s=l("option",{value:n.value},n.name||n.value);return n.value===e.currentValue&&s.setAttribute("selected",""),s}));return t.value=e.currentValue,l("div",{class:"detail"},l("span",{class:"k",title:e.description??""},e.name||e.id),t)}function fo(e,t){if(t==="recent")return[{label:null,sessions:e.slice().sort(zi)}];let n=new Map;for(let r of e){let o=r.cwd||"(unknown)";n.has(o)||n.set(o,[]),n.get(o).push(r)}let s=[];for(let[r,o]of[...n.entries()].sort((a,c)=>a[0].localeCompare(c[0])))o.sort(zi),s.push({label:un(r),sessions:o});return s}function Cl(e,t){let n=e.title||eo(e.sessionId),s=[he(e.sessionId),dl(e.agentId,e.currentModel),`age ${fl(e.updatedAt)}`].join(" \xB7 "),r=!e.busy&&(e.armedTasks??0)>0;return l("div",{class:e.sessionId===i.listHighlightedSessionId?"card highlighted":"card",...I(o=>{o.target.closest("button")||is(e.sessionId,e.status==="cold")})},l("div",{class:"row1"},n),l("div",{class:"card-body"},l("div",{class:"meta"},l("div",{class:"row2"},s)),l("div",{class:"badges"},e.status==="cold"||!(e.busy||e.awaitingInput||r)?l("span",{class:`badge ${e.status==="cold"?"cold":"warm"}`,title:e.status==="cold"?"Disk-only \u2014 opening will resurrect the session":"Live in-memory session"},e.status==="cold"?"cold":"warm"):null,e.busy||r?l("span",{class:"badge busy",title:e.busy?"Agent is working":"Agent has a background task running. It may resume on its own."},"busy"):null,e.awaitingInput?l("span",{class:"badge blocked",title:"Waiting on you \u2014 a permission request or other prompt is pending"},"blocked"):null,...e.importedFromMachine&&!e.upstreamSessionId?[l("span",{class:"badge imported",title:`Passive mirror imported from ${e.importedFromMachine} \u2014 attach to start working on it here.`},`\u2190 ${e.importedFromMachine}`)]:[])),t?l("div",{class:"row3"},e.cwd?un(e.cwd):"?"):null,e.status!=="cold"?l("button",{class:"card-kill",title:"Kill this session",...I(()=>{Rl(e)})},"\xD7"):null)}async function Rl(e){if(confirm(`Kill session ${e.title?`"${e.title}" (${he(e.sessionId)})`:he(e.sessionId)}?`))try{await se("/api/kill",{method:"POST",body:JSON.stringify({sessionId:e.sessionId})}),Oe()}catch(t){C({banner:{kind:"bad",text:"kill failed: "+t.message}})}}function Ol(e){e.compactionPhase||confirm("Compact this session's context now? The agent will summarize history and continue from the summary.")&&di()}function Ll(e){let t=document.createElement("a");t.href=`/api/sessions/${encodeURIComponent(e)}/export`,t.download="",t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function Dl(){let e=document.createElement("input");e.type="file",e.accept=".hydra,application/json",e.style.display="none",e.onchange=()=>{let t=e.files&&e.files[0];document.body.removeChild(e),t&&Pl(t)},document.body.appendChild(e),e.click()}async function Pl(e){let t;try{let s=await e.text();t=JSON.parse(s)}catch(s){C({banner:{kind:"bad",text:"import: bundle is not valid JSON: "+s.message}});return}let n=await wo(t);if(n.ok){let s=n.result;C({banner:{kind:"good",text:s.replaced?`Replaced ${he(s.sessionId)} from bundle`:`Imported as ${he(s.sessionId)}`}}),Oe();return}if(n.status===409&&n.existingSessionId){let s=n.existingSessionId;if(!confirm(`This session is already imported locally as ${he(s)}.
597
+ `);return t.length>0&&t[t.length-1]===""&&t.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:t,newLines:n}}var dc=1e6;function fc(e,t){let n=e.length,s=t.length;if(n===0||s===0||n*s>dc){let u=[];for(let d of e)u.push({op:"-",text:d});for(let d of t)u.push({op:"+",text:d});return u}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let u=n-1;u>=0;u--)for(let d=s-1;d>=0;d--)e[u]===t[d]?r[u][d]=r[u+1][d+1]+1:r[u][d]=Math.max(r[u+1][d],r[u][d+1]);let o=[],a=0,c=0;for(;a<n&&c<s;)e[a]===t[c]?(o.push({op:"=",text:e[a]}),a++,c++):r[a+1][c]>=r[a][c+1]?(o.push({op:"-",text:e[a]}),a++):(o.push({op:"+",text:t[c]}),c++);for(;a<n;)o.push({op:"-",text:e[a]}),a++;for(;c<s;)o.push({op:"+",text:t[c]}),c++;return o}function qr(e,t){let n=0,s=Math.min(e.length,t.length);for(;n<s&&e[n]===t[n];)n++;let r=e.length,o=t.length;for(;r>n&&o>n&&e[r-1]===t[o-1];)r--,o--;let a=[];for(let c=0;c<n;c++)a.push({op:"=",text:e[c]});a.push(...fc(e.slice(n,r),t.slice(n,o)));for(let c=r;c<e.length;c++)a.push({op:"=",text:e[c]});return a}function Kr(e){let{oldLines:t,newLines:n}=Ur(e),s=0,r=0;for(let o of qr(t,n))o.op==="+"?s++:o.op==="-"&&r++;return{added:s,removed:r}}function zr(e,t={}){let n=t.maxLines??40,s=t.contextLines??3,{oldLines:r,newLines:o}=Ur(e),a=qr(r,o),c=[];if(Number.isFinite(s)){if(!a.some(g=>g.op!=="="))return[];let f=new Array(a.length).fill(!1);for(let g=0;g<a.length;g++)if(a[g].op!=="="){let m=Math.max(0,g-s),y=Math.min(a.length-1,g+s);for(let S=m;S<=y;S++)f[S]=!0}let p=0;for(;p<a.length;){if(f[p]){c.push({op:a[p].op,text:a[p].text}),p++;continue}let g=p;for(;g<a.length&&!f[g];)g++;let m=g-p;c.push({op:"gap",text:`\u22EF ${m} unchanged line${m===1?"":"s"}`}),p=g}}else for(let d of a)c.push({op:d.op,text:d.text});let u=[];for(let d=0;d<c.length;d++){if(u.length>=n-1&&d<c.length-1){let p=c.length-d;u.push({op:"gap",text:`\u2026 ${p} more line${p===1?"":"s"}`});break}u.push(c[d])}return u}var pc="hydra-acp-history-cache",gc=3,le="sessions",mc=6e6,Wr=10,hc=2e3,Bt=null;function Hn(){return Bt||(Bt=new Promise(e=>{if(!("indexedDB"in window)){e(null);return}let t;try{t=indexedDB.open(pc,gc)}catch{e(null);return}t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(le)&&t.result.deleteObjectStore(le),t.result.createObjectStore(le,{keyPath:"sessionId"})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null)}),Bt)}function bc(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}async function Qr(e){let t=await Hn();return t?new Promise(n=>{let s;try{s=t.transaction(le,"readwrite")}catch{n(null);return}let r=s.objectStore(le),o=r.get(e);o.onsuccess=()=>{let a=o.result;if(!a){n(null);return}a.lastAccessed=Date.now(),r.put(a),n({lastSeenMessageId:a.lastSeenMessageId,frames:_e("cache-read-map",()=>a.frames.map(c=>c.frame))})},o.onerror=()=>n(null)}):null}async function Xr(e){let t=await Hn();return t?new Promise(n=>{let s;try{s=t.transaction(le,"readonly")}catch{n("unreadable");return}let r=s.objectStore(le).get(e);r.onsuccess=()=>{let o=r.result;if(!o){n("empty");return}let a=new Map;for(let u of o.frames){let d=u.frame.params?.update,f=typeof d?.sessionUpdate=="string"?d.sessionUpdate:"?";a.set(f,(a.get(f)??0)+1)}let c=[...a.entries()].sort((u,d)=>d[1]-u[1]).map(([u,d])=>`${u.replace(/_chunk$/,"")}:${d}`).join(" ");n(`${o.frames.length}f ${(o.totalBytes/1e6).toFixed(1)}MB \u2014 ${c}`)},r.onerror=()=>n("unreadable")}):"unavailable"}var ke=new Map,Ht=new Map,Ye;function Ft(e,t,n){let s=ke.get(e)??[];s.push(t),ke.set(e,s),Ht.set(e,n),Ye===void 0&&(Ye=setTimeout(()=>{Ye=void 0,Vr()},hc))}var Gr=Promise.resolve();function Vr(){Gr=Gr.then(Ec).catch(()=>{})}function Yr(){Ye!==void 0&&(clearTimeout(Ye),Ye=void 0),Vr()}async function Ec(){if(ke.size===0)return;let e=Array.from(ke.keys()),t=await Hn();if(!t){ke.clear(),Ht.clear();return}for(let n of e){let s=ke.get(n),r=Ht.get(n);ke.delete(n),Ht.delete(n),!(!s||!r)&&await yc(t,n,s,r)}await _c(t)}function yc(e,t,n,s){return new Promise(r=>{let o;try{o=e.transaction(le,"readwrite")}catch{r();return}let a=o.objectStore(le),c=a.get(t);c.onsuccess=()=>{let u=c.result,d=_e("cache-size",()=>n.map(m=>({frame:m,bytes:bc(m)}))),f=[...u?.frames??[],...d],p=(u?.totalBytes??0)+d.reduce((m,y)=>m+y.bytes,0);for(;f.length>1&&p>mc;){let m=f.shift();m&&(p-=m.bytes)}let g={sessionId:t,lastSeenMessageId:s,frames:f,totalBytes:p,lastAccessed:Date.now()};_e("cache-put",()=>a.put(g)),r()},c.onerror=()=>r()})}function _c(e){return new Promise(t=>{let n;try{n=e.transaction(le,"readwrite")}catch{t();return}let s=n.objectStore(le),r=s.getAll();r.onsuccess=()=>{let o=r.result??[];if(o.length<=Wr){t();return}o.sort((c,u)=>c.lastAccessed-u.lastAccessed);let a=o.slice(0,o.length-Wr);for(let c of a)s.delete(c.sessionId);t()},r.onerror=()=>t()})}typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pagehide",Yr),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&Yr()}));typeof navigator<"u"&&navigator.storage?.persist&&navigator.storage.persist();function qt(e){i.current&&i.current.log.push(e)}var vc=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction","_hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]);function Kt(e){e.log=[],e.toolCalls=new Map,e.pendingPermissions=new Map,e.spinner=null,e.plan=null,e.mode=null,e.model=null,e.modes=[],e.models=[],e.contextUsed=null,e.contextSize=null,e.cost=null,e.busy=!1,e.recentOwnPrompts=[],e.promptQueue=[],e.queueByMessageId=new Map,e.ownPromptIds=new Map,e.inTurn=!1,e.unsolicitedTurnOpen=new Set,e.currentPlanEntry=null,e.daemonSupportsAmend=!1,e.ownClientId=void 0,e.currentHeadMessageId=void 0,e.lastSeenMessageId=void 0,e.spinnerOwner=void 0}function wc(e){if(!e||typeof e!="object")return;let t=e._meta;if(!t||typeof t!="object")return;let n=t["hydra-acp"];if(!n||typeof n!="object")return;let s=n.recordedAt;return typeof s=="number"&&Number.isFinite(s)?s:void 0}function Sc(e){if(e.kind!=="stream"||e.role!=="user"||!e.queueEntry)return!1;let t=e.queueEntry.status;return t==="queued"||t==="editing"}function $n(){if(!i.current)return 0;let e=i.current.log;for(let t=0;t<e.length;t++)if(Sc(e[t]))return t;return e.length}function ge(e){i.current&&i.current.log.splice($n(),0,e)}function Un(e){if(!(!i.current||e.messageId===void 0)){for(let t of i.current.log)if(t.kind==="stream"&&t.queueEntry===e){t.messageId=e.messageId,Ic(e);return}}}function Tc(e,t){let n=i.current?.spinnerOwner;!i.current||n===void 0||Ft(i.current.sessionId,{method:"session/update",params:{sessionId:i.current.sessionId,update:{sessionUpdate:"turn_complete",messageId:`${n}:turn_complete`,...e!==void 0?{stopReason:e}:{}},_meta:{"hydra-acp":{recordedAt:t??Date.now()}}}},`${n}:turn_complete`)}function Ic(e){!i.current||e.messageId===void 0||Ft(i.current.sessionId,{method:"session/update",params:{sessionId:i.current.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:[{type:"text",text:e.text}]},_meta:{"hydra-acp":{recordedAt:Date.now()}}}},e.messageId)}function fe(){i.current&&(i.current.inTurn=!0)}function Ac(){if(!i.current)return;i.current.inTurn=!1;let e=i.current.idleListeners;i.current.idleListeners=[];for(let t of e)try{t()}catch{}}function Fn(e,t,n=!1,s){if(!i.current)return;let r=ct(t);if(!r)return;let o=i.current.log,a=$n(),c;for(let u=a-1;u>=0;u--){let d=o[u];if(d.kind!=="spinner"){c=d;break}}if(c&&c.kind==="stream"&&c.role===e&&!c.closed&&!!c.synthetic===n){c.text+=r,s!==void 0&&(c.messageId=s);return}o.splice(a,0,{kind:"stream",role:e,text:r,synthetic:n||void 0,messageId:s})}function Xe(){if(i.current)for(let e=i.current.log.length-1;e>=0;e--){let t=i.current.log[e];if(t.kind==="stream"&&!t.closed){t.closed=!0;return}}}function Zr(e){if(!i.current)return!1;let t=ct(e);if(!t)return!1;let n=i.current.recentOwnPrompts;for(let s=0;s<n.length;s++)if(n[s].text===t)return n.splice(s,1),!0;return!1}function $t(e){if(!e)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map($t).join("");if(typeof e=="object"){let t=e;if(t.text)return String(t.text);if(t.content)return $t(t.content);if(t.diff)return String(t.diff);try{return JSON.stringify(e,null,2)}catch{return String(e)}}return""}function me(e){if(!i.current)return;let t=i.current;if(t.spinner){t.log.some(n=>n.kind==="spinner")||ge({kind:"spinner",spinner:t.spinner});return}t.spinner={toolCallIds:[],expanded:!1,startedAt:e??Date.now()},t.spinnerOwner=void 0,ge({kind:"spinner",spinner:t.spinner})}function jr(e,t){if(!i.current)return;let n=i.current,s=n.spinner;if(s){let r=n.log.findIndex(o=>o.kind==="spinner");r>=0&&(n.log[r]={kind:"turn-stamp",elapsedMs:Math.max(0,(e??Date.now())-s.startedAt),toolCount:s.toolCallIds.length,stopReason:t})}n.spinner=null,n.spinnerOwner=void 0,n.log=n.log.filter(r=>r.kind!=="spinner")}function lt(e,t){if(!i.current)return;let n=i.current;jr(e),n.spinner={toolCallIds:[],expanded:!1,startedAt:e??Date.now()},n.spinnerOwner=t,ge({kind:"spinner",spinner:n.spinner})}function kc(e){return typeof e!="string"||!e?!1:e.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode"}function xc(e){let t=e.rawInput;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.plan;return typeof n!="string"||n.length===0?null:n}function Mc(e){if(!i.current)return null;let t=i.current.log;for(let n=0;n<t.length;n++){let s=t[n];if(s.kind==="exit-plan-mode"&&s.toolCallId===e)return{idx:n,item:s}}return null}function Jr(e){if(!i.current)return!1;let t=String(e.toolCallId??"");if(!t)return!1;let n=e.name??e.title,s=Mc(t);if(!kc(n)&&!s)return!1;let r=xc(e),o=typeof e.status=="string"?e.status:void 0;if(s)return r!==null&&(s.item.plan=r),o!==void 0&&(s.item.status=o),!0;if(r===null)return!1;Xe();let a={kind:"exit-plan-mode",toolCallId:t,plan:r};return o!==void 0&&(a.status=o),ge(a),!0}function Nc(e){if(!i.current)return null;let t=i.current.log;for(let n=0;n<t.length;n++){let s=t[n];if(s.kind==="edit-diff"&&s.toolCallId===e)return{idx:n,item:s}}return null}function ei(e){if(!i.current)return!1;let t=String(e.toolCallId??"");if(!t)return!1;let n=Nc(t),s=$r(e),r=typeof e.status=="string"?e.status:void 0;if(n)return s!==null&&(n.item.diff=s),r!==void 0&&(n.item.status=r),!0;if(s===null)return!1;Xe();let o={kind:"edit-diff",toolCallId:t,diff:s,expanded:!1};return r!==void 0&&(o.status=r),ge(o),!0}function Cc(e){if(!i.current)return;if(Xe(),Jr(e)){Qe(String(e.toolCallId),typeof e.status=="string"?e.status:void 0);return}if(ei(e)){Qe(String(e.toolCallId),typeof e.status=="string"?e.status:void 0);return}let t={toolCallId:String(e.toolCallId),title:String(e.title??e.kind??"tool"),kind:String(e.kind??""),status:String(e.status??"in_progress"),content:$t(e.content)};i.current.toolCalls.set(t.toolCallId,t),me(),i.current.spinner?.toolCallIds.push(t.toolCallId),Qe(t.toolCallId,t.status)}function Rc(e){if(!i.current)return;if(Jr(e)){typeof e.status=="string"&&Qe(String(e.toolCallId),e.status);return}if(ei(e)){typeof e.status=="string"&&Qe(String(e.toolCallId),e.status);return}let t=i.current.toolCalls.get(String(e.toolCallId));t&&(typeof e.status=="string"&&(t.status=e.status,Qe(t.toolCallId,e.status)),typeof e.title=="string"&&(t.title=e.title),e.content!==void 0&&(t.content=(t.content||"")+$t(e.content)))}function xe(e,t,n=!1){if(i.current){n&&Tc(e,t),jr(t,e),Xe();for(let s of i.current.promptQueue)s.status==="processing"&&(s.status=e==="cancelled"?"cancelled":"done");for(let s of i.current.promptQueue)s.reseatAfterCurrentTurn&&s.status!=="done"&&s.status!=="cancelled"&&(s.reseatAfterCurrentTurn=void 0,zt(i.current,s));i.current.currentPlanEntry=null,i.current.currentHeadMessageId=void 0,Ac()}}function Oc(e,t){if(!i.current)return;let s=(Array.isArray(e.prompt)?e.prompt:[]).map(a=>ct(a)).join("");if(!s)return;let r=typeof e.messageId=="string"?e.messageId:void 0;if(r&&i.current.queueByMessageId.has(r)||r&&i.current.log.some(a=>a.kind==="stream"&&a.role==="user"&&a.messageId===r)||Zr({text:s}))return;let o=i.current.promptQueue.find(a=>a.text===s&&(a.status==="pending"||a.status==="queued"||a.status==="processing"));if(o){r!==void 0&&o.messageId===void 0&&(o.messageId=r,i.current.queueByMessageId.set(r,o),Un(o),i.current.spinnerOwner===o.id&&(i.current.spinnerOwner=r));return}Xe(),ge({kind:"stream",role:"user",text:s,closed:!0,messageId:r,attachments:qn(e.prompt)}),lt(t,r),fe()}function ti(e){if(i.current)for(let t of e){if(!t||typeof t!="object")continue;let n=t,s=typeof n.messageId=="string"?n.messageId:"";if(!s)continue;let r=typeof n.position=="number"?n.position:0,o=i.current.queueByMessageId.get(s);if(o){r===0?(i.current.currentHeadMessageId=s,(o.status==="queued"||o.status==="pending")&&(o.status="processing")):o.status==="pending"&&(o.status="queued");continue}let a=ni(n.prompt);if(!a)continue;let c=i.current.promptQueue.find(d=>d.messageId===void 0&&d.text===a&&(d.status==="pending"||d.status==="queued"||d.status==="cancelled"));if(c){c.messageId=s,i.current.queueByMessageId.set(s,c),Un(c),c.aheadAtEnqueue=Math.max(0,r),c.status=r===0?"processing":"queued",r===0&&(i.current.currentHeadMessageId=s);continue}let u={id:"snap_"+Math.random().toString(36).slice(2,10),text:a,status:r===0?"processing":"queued",aheadAtEnqueue:Math.max(0,r),messageId:s};if(i.current.queueByMessageId.set(s,u),r===0){i.current.currentHeadMessageId=s;let d=Lc(a);if(d){d.queueEntry=u;continue}}i.current.log.push({kind:"stream",role:"user",text:a,closed:!0,queueEntry:u,attachments:qn(n.prompt)})}}function Lc(e){if(!i.current)return null;let t=i.current.log;for(let n=t.length-1;n>=0;n--){let s=t[n];if(s.kind==="stream"&&s.role==="user"&&!s.queueEntry&&s.text===e)return s}return null}function ni(e){let t=Array.isArray(e)?e:[],n="";for(let s of t)if(s&&typeof s=="object"){let r=s;r.type==="text"&&typeof r.text=="string"&&(n+=r.text)}return n}function qn(e){let t=Array.isArray(e)?e:[],n=[];for(let s of t){if(!s||typeof s!="object")continue;let r=s;r.type!=="image"||typeof r.data!="string"||n.push({mimeType:typeof r.mimeType=="string"?r.mimeType:"image/png",data:r.data,sizeBytes:Math.round(r.data.length*3/4)})}return n.length>0?n:void 0}function Dc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let s=(e._meta??{})["hydra-acp"]??{},r=typeof s.amending=="string"?s.amending:void 0,o=e.originator??{},a=typeof o.clientId=="string"?o.clientId:"",c=!!i.current.ownClientId&&a===i.current.ownClientId,u=ni(e.prompt);if(c){let y=i.current.promptQueue.filter(E=>E.messageId===void 0&&(E.status==="pending"||E.status==="queued"||E.status==="editing")),v=(u.length>0?y.find(E=>E.text===u):void 0)??y[0]??i.current.promptQueue.find(E=>E.messageId===void 0&&E.status==="cancelled"&&E.text===u);if(!v)return;v.messageId=t,i.current.queueByMessageId.set(t,v),Un(v),i.current.spinnerOwner===v.id&&(i.current.spinnerOwner=t),r!==void 0&&(v.amendsMessageId=r,Ut(r,t));let b=typeof e.position=="number"?e.position:1;if(v.aheadAtEnqueue=Math.max(0,b),b===0)v.status="processing";else if(v.status==="pending"||v.status==="cancelled"){v.status="queued",i.current.spinnerOwner!==void 0&&i.current.spinnerOwner===v.id&&i.current.spinner&&(i.current.spinner=null,i.current.spinnerOwner=void 0,i.current.log=i.current.log.filter(x=>x.kind!=="spinner"));let E=i.current.log,M=E.findIndex(x=>x.kind==="stream"&&x.queueEntry===v);if(M>=0){let[x]=E.splice(M,1),R=$n();R>M?E.splice(R,0,x):E.splice(M,0,x)}}return}let d=u;if(!d)return;let f=typeof e.position=="number"?e.position:0,p=typeof e.queueDepth=="number"?e.queueDepth:1,g={id:"peer_"+Math.random().toString(36).slice(2,10),text:d,status:f===0?"processing":"queued",aheadAtEnqueue:Math.max(0,f),messageId:t};r!==void 0&&(g.amendsMessageId=r,Ut(r,t)),i.current.queueByMessageId.set(t,g),Xe();let m={kind:"stream",role:"user",text:d,closed:!0,queueEntry:g,messageId:t,attachments:qn(e.prompt)};f===0?ge(m):i.current.log.push(m)}function Pc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);if(!n)return;let s=Array.isArray(e.prompt)?e.prompt:[],r="";for(let o of s)if(o&&typeof o=="object"){let a=o;a.type==="text"&&typeof a.text=="string"&&(r+=a.text)}if(r){n.text=r;for(let o of i.current.log)if(o.kind==="stream"&&o.role==="user"&&o.queueEntry===n){o.text=r;break}}}function zt(e,t){let n=e.log.findIndex(r=>r.kind==="stream"&&r.queueEntry===t);if(n<0||n===e.log.length-1)return;let[s]=e.log.splice(n,1);s&&e.log.push(s)}function Bc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=typeof e.reason=="string"?e.reason:"";n==="started"&&(i.current.currentHeadMessageId=t);let s=i.current.queueByMessageId.get(t);s&&(n==="started"?(s.status="processing",s.reseatAfterCurrentTurn=void 0,i.current.spinnerOwner!==void 0&&(i.current.spinnerOwner===s.id||i.current.spinnerOwner===t)?i.current.spinnerOwner=t:lt(void 0,t),fe()):(n==="cancelled"||n==="abandoned")&&(s.amendedByMessageId!==void 0?s.status="amended":s.status="cancelled",i.current.queueByMessageId.delete(t)))}function Hc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);n&&(n.held=!0)}function Fc(e){if(!i.current)return;let t=typeof e.messageId=="string"?e.messageId:"";if(!t)return;let n=i.current.queueByMessageId.get(t);n&&(n.held=!1)}function $c(e){i.current&&typeof e.count=="number"&&(i.current.armedTasks=e.count,i.current.armedSince=e.count>0&&typeof e.since=="number"?e.since:void 0,i.current.armedTaskList=Kn(e.tasks))}function Kn(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let s=n;typeof s.label!="string"||typeof s.since!="number"||t.push({label:s.label,since:s.since,taskId:typeof s.taskId=="string"?s.taskId:void 0,taskType:typeof s.taskType=="string"?s.taskType:void 0,toolCallId:typeof s.toolCallId=="string"?s.toolCallId:void 0})}return t}function Uc(e){if(!i.current)return;switch(typeof e.phase=="string"?e.phase:""){case"started":case"iteration":i.current.compactionPhase="running";break;case"deferred":i.current.compactionPhase="deferred";break;case"swapped":i.current.compactionPhase=void 0,C({banner:{kind:"good",text:"Context compacted."}});break;case"failed":i.current.compactionPhase=void 0,C({banner:{kind:"bad",text:"Context compaction failed."}});break;case"rolled_back":i.current.compactionPhase=void 0,C({banner:{kind:"warn",text:"Compaction rolled back."}});break;default:break}}function qc(e){if(!i.current)return;let t=typeof e.cancelledMessageId=="string"?e.cancelledMessageId:"",n=typeof e.newMessageId=="string"?e.newMessageId:"";if(!t||!n)return;Ut(t,n);let s=i.current.queueByMessageId.get(n);s&&s.amendsMessageId===void 0&&(s.amendsMessageId=t)}function Ut(e,t){if(!i.current)return;let n=i.current.queueByMessageId.get(e)??i.current.promptQueue.find(s=>s.messageId===e);n&&(n.amendedByMessageId=t,n.status==="cancelled"&&(n.status="amended"))}function Kc(e){if(!i.current)return;let t=e.entries??e.plan??null;if(i.current.plan=t,i.current.currentPlanEntry){i.current.currentPlanEntry.entries=t;return}let n={kind:"plan",entries:t};ge(n),i.current.currentPlanEntry=n}function zc(e){if(!i.current)return;let t=typeof e?.toolCallId=="string"?e.toolCallId:void 0;t&&si(t)}function si(e){i.current&&(i.current.pendingPermissions.delete(e),i.current.log=i.current.log.filter(t=>!(t.kind==="perm"&&t.toolCallId===e)))}function Qe(e,t){!i.current||!e||!t||t==="pending"||i.current.pendingPermissions.has(e)&&si(e)}function Wt(e,t=!1){if(i.current?.cold&&(i.current.cold=!1,i.current.ready=!0),e.method==="hydra-acp/prompt_queue/added"){Dc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/updated"){Pc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/removed"){Bc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/held"){Hc(e.params??{});return}if(e.method==="hydra-acp/prompt_queue/released"){Fc(e.params??{});return}if(e.method==="hydra-acp/session/armed_tasks_updated"){$c(e.params??{});return}if(e.method==="hydra-acp/prompt/amended"){qc(e.params??{});return}if(e.method!=="session/update")return;let n=e.params?.update??null;if(!n||typeof n!="object")return;let s=String(n.sessionUpdate??"");if(i.current&&s&&!vc.has(s)&&typeof n.messageId=="string"&&(i.current.lastSeenMessageId=n.messageId,t||Ft(i.current.sessionId,e,n.messageId)),s==="permission_resolved"){zc(n);return}let o=(n._meta??{})["hydra-acp"]??{},a=s==="agent_message_chunk"&&o.synthetic===!0,c=typeof n.messageId=="string"?n.messageId:void 0,u=wc(e.params);switch(s){case"prompt_received":case"user_message_chunk":case"agent_message_chunk":case"agent_thought_chunk":case"tool_call":case"tool_call_update":case"plan":a||fe();break;default:break}switch(s){case"user_message_chunk":{if(o.compatFor==="prompt_received")break;Zr(n.content)||Fn("user",n.content,!1,c);break}case"agent_message_chunk":Fn("agent",n.content,a,c);break;case"agent_thought_chunk":Fn("thought",n.content,!1,c);break;case"tool_call":Cc(n);break;case"tool_call_update":Rc(n);break;case"current_mode_update":i.current&&(i.current.mode=n.modeId??n.currentModeId??null,Array.isArray(n.availableModes)&&(i.current.modes=n.availableModes),_());break;case"_hydra_available_modes_update":i.current&&Array.isArray(n.availableModes)&&(i.current.modes=n.availableModes,_());break;case"_hydra_current_model_update":i.current&&(i.current.model=n.modelId??n.currentModelId??null,Array.isArray(n.availableModels)&&(i.current.models=n.availableModels),_());break;case"config_option_update":i.current&&Array.isArray(n.configOptions)&&(i.current.configOptions=n.configOptions,_());break;case"usage_update":if(i.current){let d=n.used??n.contextUsed,f=n.size??n.contextSize;typeof d=="number"&&(i.current.contextUsed=d),typeof f=="number"&&(i.current.contextSize=f),n.cost&&(i.current.cost=n.cost)}break;case"plan":Kc(n);break;case"prompt_received":Oc(n,u);break;case"stop":case"turn_complete":{let p=((n._meta??{})["hydra-acp"]??{}).amended;if(p){let m=typeof p.cancelledMessageId=="string"?p.cancelledMessageId:"",y=typeof p.newMessageId=="string"?p.newMessageId:"";m&&y&&Ut(m,y)}let g=typeof n.stopReason=="string"?n.stopReason:void 0;xe(g,u);break}case"_hydra_turn_started":{if(!i.current)break;let f=(n._meta??{})["hydra-acp"]??{};if(f.unsolicited!==!0)break;let p=typeof n.messageId=="string"?n.messageId:void 0;if(!p||i.current.unsolicitedTurnOpen.has(p))break;i.current.unsolicitedTurnOpen.add(p),fe();let g=f.cause??{},m=typeof g.label=="string"?g.label:void 0;ge({kind:"system",text:m?`agent resumed on its own: background task finished (${m})`:"agent resumed on its own"});break}case"_hydra_turn_ended":{if(!i.current)break;let f=(n._meta??{})["hydra-acp"]??{};if(f.unsolicited!==!0)break;let p=typeof n.startedMessageId=="string"?n.startedMessageId:void 0;if(!p||!i.current.unsolicitedTurnOpen.has(p)||(i.current.unsolicitedTurnOpen.delete(p),f.reason==="superseded")||i.current.unsolicitedTurnOpen.size>0)break;xe(void 0,u);break}case"session_info_update":i.current&&typeof n.title=="string"&&(i.current.title=n.title);break;case"_hydra_compaction":Uc(n);break;default:break}i.current?.inTurn&&me(u)}function ri(e){if(i.current){if(e.method==="session/request_permission"){let t=e.params??{},n=t.toolCall??{},s=typeof n.toolCallId=="string"?n.toolCallId:"";if(!s){i.current.ws?.send(JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"missing toolCall.toolCallId"}}));return}i.current.pendingPermissions.set(s,{requestId:e.id,toolCallId:s,toolCall:n,options:t.options??[]}),qt({kind:"perm",toolCallId:s});return}i.current.ws?.send(JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`method not handled: ${String(e.method)}`}}))}}var Wc="hydra-acp-draft:";function Gt(e){return Wc+e}function oi(e){try{return localStorage.getItem(Gt(e))??""}catch{return""}}var Yt=new Map,Me;function Ve(e,t){Yt.set(e,t),Me!==void 0&&clearTimeout(Me),Me=setTimeout(()=>{Me=void 0,ai()},400)}function Qt(e){Yt.delete(e);try{localStorage.removeItem(Gt(e))}catch{}}function ai(){for(let[e,t]of Yt)try{t?localStorage.setItem(Gt(e),t):localStorage.removeItem(Gt(e))}catch{}Yt.clear()}function ii(){Me!==void 0&&(clearTimeout(Me),Me=void 0),ai()}typeof window<"u"&&typeof document<"u"&&(window.addEventListener("pagehide",ii),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&ii()}));var Gc="hydra-acp-offline-queue";var Ne="sessions",Xt=null;function zn(){return Xt||(Xt=new Promise(e=>{if(!("indexedDB"in window)){e(null);return}let t;try{t=indexedDB.open(Gc,1)}catch{e(null);return}t.onupgradeneeded=()=>{t.result.createObjectStore(Ne,{keyPath:"sessionId"})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null)}),Xt)}async function ci(e){let t=await zn();return t?new Promise(n=>{let s;try{s=t.transaction(Ne,"readonly")}catch{n([]);return}let r=s.objectStore(Ne).get(e);r.onsuccess=()=>{let o=r.result;n(o?.entries??[])},r.onerror=()=>n([])}):[]}async function Wn(e,t){let n=await zn();if(n)return new Promise(s=>{let r;try{r=n.transaction(Ne,"readwrite")}catch{s();return}let o=r.objectStore(Ne),a=o.get(e);a.onsuccess=()=>{let c=a.result??{sessionId:e,entries:[]},u=c.entries.findIndex(d=>d.id===t.id);u>=0?c.entries[u]=t:c.entries.push(t),o.put(c),s()},a.onerror=()=>s()})}async function Vt(e,t){let n=await zn();if(n)return new Promise(s=>{let r;try{r=n.transaction(Ne,"readwrite")}catch{s();return}let o=r.objectStore(Ne),a=o.get(e);a.onsuccess=()=>{let c=a.result;if(!c){s();return}c.entries=c.entries.filter(u=>u.id!==t),c.entries.length===0?o.delete(e):o.put(c),s()},a.onerror=()=>s()})}function dt(e,t){let n=[];e&&n.push({type:"text",text:e});for(let s of t)n.push({type:"image",data:s.data,mimeType:s.mimeType});return n}function ft(){let e=i.current;if(!e)return;let t=e.composerValue.trim(),n=e.attachments;!t&&n.length===0||(Yn(e,t,{attachments:n})&&(e.composerValue="",e.attachments=[],Qt(e.sessionId)),_())}function ui(e){let t=i.current;t&&(Yn(t,`/hydra workspace ${e}`,{addToHistory:!1}),_())}function di(){let e=i.current;e&&(Yn(e,"/hydra compact",{addToHistory:!1}),_())}function Yn(e,t,n={}){let s=n.attachments??[],r=!e.connectionHealthy||!navigator.onLine||!e.ws||e.ws.readyState!==WebSocket.OPEN,o=e.promptQueue.filter(p=>p.status==="queued"||p.status==="pending"||p.status==="processing").length,a=e.inTurn&&!e.promptQueue.some(p=>p.status==="processing"),c=r?0:o+(a?1:0),u={id:"p_"+Math.random().toString(36).slice(2,10),text:t,status:r?"offline":c>0?"queued":"pending",aheadAtEnqueue:c,attachments:s.length>0?s:void 0};e.promptQueue.push(u),e.log.push({kind:"stream",role:"user",text:t,closed:!0,queueEntry:u,attachments:u.attachments}),e.recentOwnPrompts.push({text:t,at:Date.now()});let d=Date.now()-6e4;if(e.recentOwnPrompts=e.recentOwnPrompts.filter(p=>p.at>=d).slice(-16),r)return Wn(e.sessionId,{id:u.id,text:t,attachments:u.attachments}),ut(e),(n.addToHistory??!0)&&Gn(e,t),!0;let f=ue("session/prompt",{sessionId:e.sessionId,prompt:dt(t,s)});return f!==void 0&&e.ownPromptIds.set(String(f),u),u.status==="pending"?lt(void 0,u.id):me(),fe(),ut(e),(n.addToHistory??!0)&&Gn(e,t),!0}function fi(e){let t=!1,n=null;for(let s of e.promptQueue){if(s.status!=="offline")continue;if(!e.ws||e.ws.readyState!==WebSocket.OPEN)break;t=!0;let r=e.promptQueue.filter(u=>u.status==="queued"||u.status==="pending"||u.status==="processing").length,o=e.inTurn&&!e.promptQueue.some(u=>u.status==="processing"),a=r+(o?1:0);s.aheadAtEnqueue=a,s.status=a>0?"queued":"pending",!n&&s.status==="pending"&&(n=s);let c=ue("session/prompt",{sessionId:e.sessionId,prompt:dt(s.text,s.attachments??[])});c!==void 0&&e.ownPromptIds.set(String(c),s),Vt(e.sessionId,s.id),zt(e,s),e.inTurn&&(s.reseatAfterCurrentTurn=!0)}t&&(n?lt(void 0,n.id):me(),fe())}var li=100;function Gn(e,t){e.history[0]!==t&&(e.history.unshift(t),e.history.length>li&&(e.history.length=li)),e.historyIndex=null,e.historyDraft=null}function jt(e){let t=i.current;if(t){if(e.messageId!==void 0){ue("hydra-acp/prompt/cancel",{sessionId:t.sessionId,messageId:e.messageId});return}e.status==="offline"&&Vt(t.sessionId,e.id),e.status="cancelled",_()}}function pi(e){let t=i.current;if(!t||!t.daemonSupportsAmend||t.currentHeadMessageId===void 0||e.messageId===void 0||e.status!=="queued")return;if(!t.connectionHealthy||!navigator.onLine||!t.ws||t.ws.readyState!==WebSocket.OPEN){C({banner:{kind:"warn",text:"Not connected \u2014 still queued, try again in a moment."}});return}let n=t.currentHeadMessageId,s=e.messageId;t.queueByMessageId.delete(s),e.messageId=void 0,e.status="pending",e.amendsMessageId=n,e.aheadAtEnqueue=0,zt(t,e),ue("hydra-acp/prompt/cancel",{sessionId:t.sessionId,messageId:s}),hi(e,e.text,n,e.text),ut(t),_()}function gi(e,t){let n=i.current;if(!n)return;let s=t.trim();if(s){if(e.status==="offline"){e.text=s,Wn(n.sessionId,{id:e.id,text:s,attachments:e.attachments}),_();return}if(e.messageId===void 0){e.text=s,_();return}ue("hydra-acp/prompt/update",{sessionId:n.sessionId,messageId:e.messageId,prompt:dt(s,e.attachments??[])})}}function mi(){let e=i.current;if(!e)return;let t=e.composerValue.trim(),n=e.attachments;if(!t&&n.length===0)return;if(!e.connectionHealthy||!navigator.onLine||!e.ws||e.ws.readyState!==WebSocket.OPEN){e.log.push({kind:"error",text:"Not connected to session \u2014 prompt not sent."}),e.composerValue="",e.attachments=[],Qt(e.sessionId),_();return}if(!e.daemonSupportsAmend||e.currentHeadMessageId===void 0){ft();return}let s=e.currentHeadMessageId,r=e.composerValue;e.composerValue="",e.attachments=[],Qt(e.sessionId),Gn(e,t);let o={id:"p_"+Math.random().toString(36).slice(2,10),text:t,status:"pending",aheadAtEnqueue:0,amendsMessageId:s,attachments:n.length>0?n:void 0};e.promptQueue.push(o),e.log.push({kind:"stream",role:"user",text:t,closed:!0,queueEntry:o,attachments:o.attachments}),e.recentOwnPrompts.push({text:t,at:Date.now()});let a=Date.now()-6e4;e.recentOwnPrompts=e.recentOwnPrompts.filter(c=>c.at>=a).slice(-16),me(),fe(),ut(e),hi(o,r,s,t),_()}function hi(e,t,n,s){let r=i.current;if(!r)return;let o=ue("_session/steering",{sessionId:r.sessionId,prompt:dt(s,e.attachments??[])});o!==void 0&&r.responseHandlers.set(String(o),a=>{Yc(e,t,n,s,a)})}function Yc(e,t,n,s,r){let o=i.current;if(!o)return;if(r.error){if(r.error?.code===-32601){Qc(e,t,n,s);return}Zt(o,e,t),C({banner:{kind:"bad",text:`steering failed: ${bi(r.error)}`}});return}let a=r.result??{};if(a.outcome==="injected"){e.status="processing",_();return}a.outcome!=="startedNewTurn"&&(Zt(o,e,t),C({banner:{kind:"warn",text:"steering failed"}}))}function Qc(e,t,n,s){let r=i.current;if(!r)return;let o=ue("hydra-acp/prompt/amend",{sessionId:r.sessionId,targetMessageId:n,prompt:dt(s,e.attachments??[])});o!==void 0&&r.responseHandlers.set(String(o),a=>{Xc(e,t,a)})}function Xc(e,t,n){let s=i.current;if(!s)return;if(n.error){Zt(s,e,t),C({banner:{kind:"bad",text:`amend failed: ${bi(n.error)}`}});return}let r=n.result??{};if(r.amended&&r.reason==="ok")return;Zt(s,e,t);let o="amend rejected";r.reason==="target_completed"?o="previous response finished \u2014 press Send to send as a new turn":r.reason==="target_cancelled"?o="amend skipped \u2014 previous turn was cancelled":r.reason==="target_not_found"&&(o="amend skipped \u2014 no matching prompt"),C({banner:{kind:"warn",text:o}})}function Zt(e,t,n){let s=e.promptQueue.indexOf(t);s>=0&&e.promptQueue.splice(s,1),e.log=e.log.filter(r=>!(r.kind==="stream"&&r.role==="user"&&r.queueEntry===t)),e.composerValue=n,e.attachments=t.attachments??[],Ve(e.sessionId,n),_()}function bi(e){if(e&&typeof e=="object"&&"message"in e){let t=e.message;if(typeof t=="string")return t}return"unknown error"}function Ei(){let e=i.current;!e||!e.inTurn||Ze("session/cancel",{sessionId:e.sessionId})}function yi(){let e=i.current;if(!e)return;let t=!1;for(let n of e.promptQueue)(n.status==="queued"||n.status==="pending")&&(jt(n),t=!0);e.inTurn&&Ze("session/cancel",{sessionId:e.sessionId}),t&&_()}function _i(e){i.current&&ue("session/set_mode",{sessionId:i.current.sessionId,modeId:e})}function vi(e){i.current&&ue("session/set_model",{sessionId:i.current.sessionId,modelId:e})}function wi(e,t){let n=i.current;if(!n)return;let s=ue("session/set_config_option",{sessionId:n.sessionId,configId:e,value:t});s!==void 0&&n.responseHandlers.set(String(s),r=>{let o=r.result?.configOptions;Array.isArray(o)&&i.current===n&&(n.configOptions=o,_())})}function Si(e){for(let t of e.promptQueue)t.status!=="done"&&t.status!=="cancelled"&&(t.status==="offline"&&Vt(e.sessionId,t.id),t.status="cancelled",t.messageId!==void 0&&e.queueByMessageId.delete(t.messageId))}function Ti(e){for(let t of e.promptQueue)t.messageId===void 0&&t.status!=="done"&&t.status!=="cancelled"&&t.status!=="offline"&&(t.status="cancelled")}var Jt=null;async function je(){if(Jt)return Jt;if(!("serviceWorker"in navigator))return null;try{return Jt=await navigator.serviceWorker.register("/sw.js"),Jt}catch{return null}}async function Ii(){return typeof Notification>"u"||!await je()?!1:Notification.permission==="granted"?!0:Notification.permission==="denied"?!1:await Notification.requestPermission()==="granted"}function Ai(){return document.visibilityState!=="visible"||!document.hasFocus()}async function ki(){let e=await je();return!e||!("pushManager"in e)?void 0:(await e.pushManager.getSubscription())?.endpoint}function Vc(e){let t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),s=atob(n);return Uint8Array.from(s,r=>r.charCodeAt(0))}async function en(){let e=await je();if(!(!e||!("pushManager"in e)))try{let{publicKey:t}=await se("/api/push/vapid-public-key"),n=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Vc(t)});await se("/api/push/subscribe",{method:"POST",body:JSON.stringify(n.toJSON())})}catch(t){console.warn("push subscribe failed:",t)}}async function xi(){let e=await je();if(!(!e||!("pushManager"in e)))try{let t=await e.pushManager.getSubscription();if(!t)return;let n=t.endpoint;await t.unsubscribe(),await se("/api/push/unsubscribe",{method:"POST",body:JSON.stringify({endpoint:n})})}catch(t){console.warn("push unsubscribe failed:",t)}}function ue(e,t){let n=i.current;if(!n||!n.ws||n.ws.readyState!==WebSocket.OPEN)return;let s=n.nextId=n.nextId??1;return n.nextId=s+1,n.ws.send(JSON.stringify({jsonrpc:"2.0",id:s,method:e,params:t})),s}function Ze(e,t){let n=i.current;!n||!n.ws||n.ws.readyState!==WebSocket.OPEN||n.ws.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t}))}function pt(){Ze("bridge/visibility",{visible:!Ai()})}function Je(){ki().then(e=>{Ze("bridge/push-endpoint",{endpoint:e??null})})}var Zc=1e4,jc=5e3;function Mi(e){e.heartbeatTimer=setTimeout(()=>Jc(e),Zc)}function Jc(e){i.current!==e||!e.ws||e.ws.readyState!==WebSocket.OPEN||(Ze("bridge/ping",{}),e.heartbeatDeadline=setTimeout(()=>{e.connectionHealthy=!1,_();try{e.ws?.close()}catch{}},jc))}function el(e){e.connectionHealthy=!0,e.heartbeatDeadline!==void 0&&(clearTimeout(e.heartbeatDeadline),e.heartbeatDeadline=void 0),Mi(e)}function tl(e){tn(e),e.connectionHealthy=!0,Mi(e)}function tn(e){e.heartbeatTimer!==void 0&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=void 0),e.heartbeatDeadline!==void 0&&(clearTimeout(e.heartbeatDeadline),e.heartbeatDeadline=void 0)}function nl(e,t){let n=i.current;!n||!n.ws||n.ws.readyState!==WebSocket.OPEN||n.ws.send(JSON.stringify({jsonrpc:"2.0",id:e,result:t}))}function Ni(e){if(i.current){if(e.method==="bridge/replay_policy"){e.params?.policy!=="after_message"&&Kt(i.current);return}if(e.method==="bridge/ready"){i.current.ready=!0,i.current.cold=!1,i.banner=null,i.current.reconnectAttempt=0;let t=e.params??{};typeof t.clientId=="string"&&(i.current.ownClientId=t.clientId),Array.isArray(t.configOptions)&&(i.current.configOptions=t.configOptions);let s=t._meta?.["hydra-acp"];if(s?.busy===!1&&i.current.inTurn&&xe(),s?.busy===!0){fe();let c=s.turnStartedAt;typeof c=="number"&&Number.isFinite(c)?(i.current.spinner||me(),i.current.spinner&&i.current.spinnerOwner===void 0&&(i.current.spinner.startedAt=c)):i.current.spinner||me()}let r=s?.queue;Array.isArray(r)&&ti(r),s?.prompt?.amending===!0&&(i.current.daemonSupportsAmend=!0),typeof s?.armedTasks=="number"&&(i.current.armedTasks=s.armedTasks,i.current.armedSince=s.armedTasks>0&&typeof s.armedSince=="number"?s.armedSince:void 0,i.current.armedTaskList=Kn(s.armedTaskList));let a=i.current.readyListeners;i.current.readyListeners=[];for(let c of a)try{c()}catch{}pt(),Je(),tl(i.current),fi(i.current),_();return}if(e.method==="bridge/pong"){i.current&&el(i.current);return}if(e.method==="bridge/error"){qt({kind:"error",text:`Bridge error: ${e.params?.message??"?"}`}),_();return}if(e.method==="hydra-acp/session/closed"){i.current&&(i.current.ready=!1,i.current.cold=!0,Si(i.current),xe()),_();return}if(e.method&&"id"in e){ri(e),i.current.ready&&_();return}if(e.method){Wt(e),i.current.ready&&_();return}if("id"in e&&e.id!==void 0&&i.current.ownPromptIds.has(String(e.id))){let t=i.current.ownPromptIds.get(String(e.id));if(i.current.ownPromptIds.delete(String(e.id)),i.current.cold&&(i.current.cold=!1,i.current.ready=!0),e.error){let a=e.error;qt({kind:"error",text:`Prompt failed: ${a.message??"unknown error"}`}),xe(),_();return}let n=e.result,s=typeof n?.stopReason=="string"?n.stopReason:void 0,r=i.current.spinnerOwner;t===void 0||r===void 0||r===t.id||t.messageId!==void 0&&r===t.messageId?xe(s,void 0,!0):s==="cancelled"&&t.status!=="amended"&&(t.status="cancelled"),_();return}if("id"in e&&e.id!==void 0){let t=i.current.responseHandlers.get(String(e.id));t&&(i.current.responseHandlers.delete(String(e.id)),t({result:e.result,error:e.error}))}}}function Qn(e,t){if(!i.current)return;let n=i.current.pendingPermissions.get(e);n&&(i.current.pendingPermissions.delete(e),i.current.log=i.current.log.filter(s=>!(s.kind==="perm"&&s.toolCallId===e)),nl(n.requestId,{outcome:t==="__cancel__"?{outcome:"cancelled"}:{outcome:"selected",optionId:t}}),_())}var Ci=[1e3,2e3,4e3,8e3,16e3,3e4],sl=5;function Ri(e,t){let n=encodeURIComponent(e);return t?`#/session/${n}?load=true`:`#/session/${n}`}function Oi(){let t=new URLSearchParams(window.location.search).get("protocol_launch");if(!t)return;history.replaceState(null,"",window.location.pathname+window.location.hash);let n;try{n=new URL(t)}catch{return}if(n.protocol!=="web+hydra:"||n.hostname!=="sessions")return;let s=decodeURIComponent(n.pathname.replace(/^\/+/,""));s&&(window.location.hash=Ri(s,!0))}var Xn=!1,Vn=!1;function rl(){try{return window.matchMedia?.("(display-mode: standalone)").matches===!0||navigator.standalone===!0}catch{return!1}}function Li(e){if(window.location.hash===e)return;Xn=!0;let t=Vn||rl()?history.replaceState:history.pushState;Vn=!1;try{t.call(history,null,"",e||window.location.pathname+window.location.search)}finally{queueMicrotask(()=>{Xn=!1})}}function Zn(){if(Xn)return;let t=window.location.hash.match(/^#\/session\/([^?]+)(?:\?(.*))?$/);if(t){let n=decodeURIComponent(t[1]),r=new URLSearchParams(t[2]??"").get("load")==="true";if(i.view==="chat"&&i.current?.sessionId===n)return;Ce(n,r);return}i.view!=="list"&&Re()}function Ce(e,t){Li(Ri(e,t)),Jn();let n=i.sessions.find(r=>r.sessionId===e),s={sessionId:e,title:n?.title??"",cwd:n?.cwd||"",agentId:n?.agentId||"",ws:null,ready:!1,log:[],toolCalls:new Map,pendingPermissions:new Map,pendingRequestById:new Map,responseHandlers:new Map,spinner:null,plan:null,mode:null,model:null,modes:[],models:[],contextUsed:null,contextSize:null,cost:null,fileOverlay:null,composerValue:oi(e),attachments:[],busy:!1,recentOwnPrompts:[],history:[],historyIndex:null,historyDraft:null,_lastMetaFp:n?`${n.title}|${n.cwd}|${n.agentId}`:"",promptQueue:[],queueByMessageId:new Map,ownPromptIds:new Map,inTurn:!1,idleListeners:[],readyListeners:[],currentPlanEntry:null,daemonSupportsAmend:!1,loadOnConnect:t,reconnectAttempt:0,headerExpanded:!1,unsolicitedTurnOpen:new Set,configOptions:[],connectionHealthy:!0};i.current=s,C({view:"chat",listHighlightedSessionId:e,lastSessionId:e}),il(s)}async function il(e){let t=await Qr(e.sessionId);if(i.current!==e)return;t&&(_e("cache-replay",()=>{for(let s of t.frames)try{Wt(s,!0)}catch(r){console.error("[hydra] cached frame failed to replay",r,s)}}),e.lastSeenMessageId=e.lastSeenMessageId??t.lastSeenMessageId,e.historyIsPartial=!0);let n=await ci(e.sessionId);if(i.current===e){for(let s of n){let r={id:s.id,text:s.text,status:"offline",aheadAtEnqueue:0,attachments:s.attachments};e.promptQueue.push(r),e.log.push({kind:"stream",role:"user",text:s.text,closed:!0,queueEntry:r,attachments:r.attachments})}(t||n.length>0)&&_(),jn(e)}}function Di(e){if(i.current!==e)return;let t=document.querySelector(".chat-body");if(t){let n=t.getBoundingClientRect().top;for(let s of t.querySelectorAll("[data-message-id]"))if(s.getBoundingClientRect().bottom>n){e.scrollRestoreMessageId=s.dataset.messageId;break}}Jn(),Pi(e),Kt(e),e.historyIsPartial=!1,_(),jn(e)}function jn(e){let t=new URL("/ws",location.href);t.protocol=location.protocol==="https:"?"wss:":"ws:",t.searchParams.set("session",e.sessionId),e.loadOnConnect&&t.searchParams.set("load","true"),e.lastSeenMessageId!==void 0&&t.searchParams.set("afterMessageId",e.lastSeenMessageId);let n=new WebSocket(t.toString());e.ws=n,n.addEventListener("open",()=>{}),n.addEventListener("message",s=>{if(!i.current||i.current.ws!==n)return;let r;try{r=JSON.parse(String(s.data))}catch{return}Ni(r)}),n.addEventListener("close",()=>{!i.current||i.current.ws!==n||ol(i.current)}),n.addEventListener("error",()=>{})}function ol(e){e.ready=!1,Ti(e);let t=e.reconnectAttempt??0,n=Ci[Math.min(t,Ci.length-1)],s=t>=sl;C({banner:s?{kind:"bad",text:"Still disconnected \u2014 retrying\u2026"}:{kind:"warn",text:"Reconnecting\u2026"}}),e.reconnectTimer=setTimeout(()=>{!i.current||i.current!==e||(e.reconnectTimer=void 0,e.reconnectAttempt=t+1,Pi(e),_(),jn(e))},n)}function Pi(e){e.ws=null,e.ready=!1,e.pendingRequestById=new Map,e.responseHandlers=new Map,e.ownPromptIds=new Map,e.idleListeners=[],e.readyListeners=[],e.nextId=void 0,tn(e)}function Bi(){if(i.view==="chat")return;let e=i.lastSessionId;if(!e||(C({listHighlightedSessionId:e}),!te()))return;let t=n=>{if(i.view==="chat")return;let s=i.sessions.find(r=>r.sessionId===e);if(s){s.status!=="cold"&&(Vn=!0,Ce(e,!1));return}n<20&&setTimeout(()=>t(n+1),250)};t(0)}function Re(){Li(""),Jn();let e=i.current?.sessionId??i.lastSessionId;C({view:"list",current:null,lastSessionId:e,listHighlightedSessionId:e??i.listHighlightedSessionId}),gt()}function Hi(){if(i.current?.ws)try{i.current.ws.close()}catch{}}function Jn(){if(i.current&&(i.current.reconnectTimer&&(clearTimeout(i.current.reconnectTimer),i.current.reconnectTimer=void 0),tn(i.current),i.current.ws)){try{i.current.ws.close()}catch{}i.current.ws=null}}var Fi="(prefers-color-scheme: dark)";function al(){return i.theme==="system"?window.matchMedia(Fi).matches?"dark":"light":i.theme}function sn(){document.documentElement.style.fontSize=`${16*i.fontScale}px`}function nn(){let e=al();document.documentElement.setAttribute("data-theme",e),document.querySelector('meta[name="theme-color"]')?.setAttribute("content",e==="light"?"#ffffff":"#0e1116")}function $i(){nn(),window.matchMedia(Fi).addEventListener("change",()=>{i.theme==="system"&&nn()})}var Ui=10*1024*1024,mt=new WeakSet;function ss(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e>=1024?`${(e/1024).toFixed(0)}KB`:`${e}B`}function cl(e,t){for(let n of t){if(n.size>Ui){C({banner:{kind:"warn",text:`pasted image is ${ss(n.size)}, max ${ss(Ui)}`}});continue}let s=new FileReader;s.onload=()=>{let r=s.result;if(typeof r!="string")return;let o=r.indexOf(",");o<0||(e.attachments.push({mimeType:n.type||"image/png",data:r.slice(o+1),sizeBytes:n.size}),_())},s.readAsDataURL(n)}}function Ji(e){return`data:${e.mimeType};base64,${e.data}`}function ll(e){return e.attachments.length===0?null:l("div",{class:"attachment-chips"},...e.attachments.map((t,n)=>l("span",{class:"attachment-chip",title:ss(t.sizeBytes)},l("img",{class:"attachment-thumb",src:Ji(t)}),l("button",{class:"attachment-remove",title:"Remove image",...I(()=>{e.attachments.splice(n,1),_()})},"\xD7"))))}function eo(e){return"untitled"}function he(e){return e.replace(/^hydra_session_/,"")}function ul(e){if(!e)return;let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)}function dl(e,t){let n=e||"?",s=ul(t);return s?`${n}\u2022${s}`:n}function to(e){let t=Math.floor(Math.max(0,e)/1e3);if(t<60)return"<1m";let n=Math.floor(t/60);if(n<60)return`${n}m`;let s=Math.floor(n/60);if(s<24)return`${s}h`;let r=Math.floor(s/24);if(r<14)return`${r}d`;let o=Math.floor(r/7);if(o<9)return`${o}w`;let a=Math.floor(r/30);return a<12?`${a}mo`:`${Math.floor(r/365)}y`}function fl(e,t=Date.now()){if(!e)return"?";let n=Date.parse(e);return Number.isNaN(n)?"?":to(t-n)}function qi(e){return Number.isFinite(e)?e<1e3?String(e):e<1e6?(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")+"k":(e/1e6).toFixed(2).replace(/\.?0+$/,"")+"M":"?"}function Ki(e){let t=null,n="USD";if(typeof e=="number")t=e;else if(e&&typeof e=="object"){let r=e;if(typeof r.amount=="number")t=r.amount;else if(typeof r.total=="number")t=r.total;else if(r.total&&typeof r.total=="object"){let o=r.total;typeof o.amount=="number"&&(t=o.amount),typeof o.currency=="string"&&(n=o.currency)}typeof r.currency=="string"&&(n=r.currency)}if(t===null)return null;let s=t<.01?4:t<1?3:2;return n==="USD"?`$${t.toFixed(s)}`:`${t.toFixed(s)} ${n}`}function no(e,t){t.banner&&e.appendChild(l("div",{class:"banner "+t.banner.kind},t.banner.text)),te()?e.appendChild(hl(t)):t.view==="list"?(e.appendChild(io()),e.appendChild(ro()),e.appendChild(lo())):t.view==="chat"&&t.current&&(e.appendChild(ln(t.current)),t.current.fileOverlay&&e.appendChild(Eo(t.current))),t.modal&&(t.modal.kind==="session"?e.appendChild(Fl(t.modal)):t.modal.kind==="modes"&&t.current?e.appendChild(Gi("Mode",t.current.modes,t.current.mode,n=>_i(n.id))):t.modal.kind==="models"&&t.current?e.appendChild(Gi("Model",t.current.models,t.current.model,n=>vi(n.id))):t.modal.kind==="options"&&e.appendChild(Ml()))}function so(){return[io(),ro(),lo()]}function pl(){let e=l("div",{class:"rail",tabindex:"-1","data-focus-key":"list-rail"},...so());return i.railWidth!==null&&(e.style.flex=`0 0 ${rs(i.railWidth)}px`),ls(),e}function gl(e){if(!_o())return;let t=e.querySelector(".list"),n=t?t.scrollTop:null,s=document.activeElement,r=s&&e.contains(s)?s.dataset.focusKey??null:null,o=r?s.selectionStart:null,a=r?s.selectionEnd:null;if(e.replaceChildren(...so()),ls(),r){let c=e.querySelector(`[data-focus-key="${CSS.escape(r)}"]`);if(c){c.focus();let u=c;if(o!==null&&typeof u.setSelectionRange=="function")try{u.setSelectionRange(o,a)}catch{}}}if(n!==null){let c=e.querySelector(".list");c&&(c.scrollTop=n)}}function rs(e){let t=Math.max(280,Math.min(window.innerWidth*.6,window.innerWidth-360));return Math.round(Math.max(240,Math.min(e,t)))}function ml(){let e=l("div",{class:"splitter",title:"Drag to resize"});return e.addEventListener("pointerdown",t=>{let n=e.previousElementSibling;if(!n)return;t.preventDefault();let s=t.clientX,r=n.getBoundingClientRect().width;e.setPointerCapture(t.pointerId),e.classList.add("dragging");let o=c=>{n.style.flex=`0 0 ${rs(r+(c.clientX-s))}px`},a=()=>{e.releasePointerCapture(t.pointerId),e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",a),e.removeEventListener("pointercancel",a),C({railWidth:rs(n.getBoundingClientRect().width)})};e.addEventListener("pointermove",o),e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a)}),e}function hl(e){let t=l("div",{class:"split-detail"});return e.current?(t.appendChild(ln(e.current)),e.current.fileOverlay&&t.appendChild(Eo(e.current))):t.appendChild(l("div",{class:"split-detail-empty"},"Select a session from the list")),l("div",{class:"split"},pl(),ml(),t)}function as(){let e=document.querySelector('[data-focus-key="list-rail"]');e&&(i.current&&C({listHighlightedSessionId:i.current.sessionId}),e.focus())}function ro(){let e=i.sessionSearch.length>0?l("button",{class:"session-search-clear",title:"Clear filter",...I(()=>C({sessionSearch:""}))},"\xD7"):null;return l("div",{class:"session-search-row"},l("input",{class:"session-search",type:"text",placeholder:"Filter sessions\u2026",value:i.sessionSearch,"data-focus-key":"session-search",autocomplete:"off",autocapitalize:"off",autocorrect:"off",spellcheck:"false",oninput:t=>{C({sessionSearch:t.target.value})},onkeydown:t=>{t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),i.sessionSearch.length>0?C({sessionSearch:""}):t.target.blur())}}),e)}function io(){return l("div",{class:"topbar"},l("span",{class:"pill clickable",title:"Click to toggle grouping by project/recent",...I(()=>C({groupBy:i.groupBy==="project"?"recent":"project"}))},i.groupBy),l("span",{class:"pill clickable",title:"Click to toggle showing disk-only sessions",...I(()=>{C({showCold:!i.showCold})})},i.showCold?"all":"warm"),bl(),l("span",{class:"spacer"}),l("button",{...I(uo),title:"Options"},"\u2699"),l("button",{...I(Dl),title:"Import a *.hydra bundle from disk"},"\u{1F4E5}"),l("button",{...I(go),title:"New Session"},"\uFF0B"))}function bl(){let e=new Set;for(let r of i.sessions)r.importedFromMachine&&!r.upstreamSessionId&&e.add(r.importedFromMachine);let t=[...e].sort(),n=l("select",{class:"host-select",title:"Filter sessions by origin host",onchange:r=>{let o=r.target.value;C({hostFilter:o})}}),s=(r,o)=>{let a=document.createElement("option");a.value=r,a.textContent=o,i.hostFilter===r&&(a.selected=!0),n.appendChild(a)};s("__local","local");for(let r of t)s(r,r);return s("__all","all"),i.hostFilter!=="__local"&&i.hostFilter!=="__all"&&!t.includes(i.hostFilter)&&(n.value=i.hostFilter),n}function El(e,t){if(t.length===0)return!0;let n=t.toLowerCase();return[he(e.sessionId),e.upstreamSessionId??"",e.agentId??"",e.title??"",e.cwd,e.cwd.replace(/^\/(?:home|Users)\/[^/]+/,"~")].some(r=>r.toLowerCase().includes(n))}function oo(){let e=i.showCold?i.sessions:i.sessions.filter(n=>n.status!=="cold");i.hostFilter==="__local"?e=e.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):i.hostFilter!=="__all"&&(e=e.filter(n=>n.importedFromMachine===i.hostFilter&&!n.upstreamSessionId));let t=i.sessionSearch.trim();return t.length>0&&(e=e.filter(n=>El(n,t))),e}function yl(){return fo(oo(),i.groupBy).flatMap(e=>e.sessions.map(t=>t.sessionId))}function ao(){document.querySelector('[data-focus-key="composer"]')?.focus()}function is(e,t){if(te()&&i.current?.sessionId===e){ao();return}Ce(e,t)}function co(e){let t=document.activeElement?.dataset.focusKey==="list-rail";if(i.view!=="list"&&!(te()&&t)||ve(document.activeElement))return;if(e.key==="Escape"){if(te()&&i.current){e.preventDefault(),C({listHighlightedSessionId:i.current.sessionId}),ao();return}let u=i.lastSessionId,d=u?i.sessions.find(f=>f.sessionId===u):void 0;if(!d)return;e.preventDefault(),is(d.sessionId,d.status==="cold");return}if(e.key.toLowerCase()==="c"&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),go();return}let n=!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey,s=e.key==="ArrowDown"||e.key==="n"&&n,r=e.key==="ArrowUp"||e.key==="p"&&n;if(!s&&!r&&e.key!=="Enter")return;let o=yl();if(o.length===0)return;if(e.key==="Enter"){let u=i.listHighlightedSessionId;if(!u||!o.includes(u))return;let d=i.sessions.find(f=>f.sessionId===u);if(!d)return;e.preventDefault(),is(d.sessionId,d.status==="cold");return}e.preventDefault();let a=i.listHighlightedSessionId?o.indexOf(i.listHighlightedSessionId):-1,c=a===-1?0:s?Math.min(o.length-1,a+1):Math.max(0,a-1);C({listHighlightedSessionId:o[c]})}function lo(){let e=oo(),t=i.showCold?0:i.sessions.filter(r=>r.status==="cold").length,n=fo(e,i.groupBy),s=l("div",{class:"list"});if(i.listHighlightedSessionId&&queueMicrotask(()=>{document.querySelector(".card.highlighted")?.scrollIntoView({block:"nearest"})}),e.length===0){let r;i.sessionSearch.trim().length>0?r=`No sessions match \u201C${i.sessionSearch.trim()}\u201D.`:i.sessions.length===0?r="No sessions. Use + to create one, or run `hydra-acp launch <agent>` from your editor.":i.hostFilter==="__local"?r="No local sessions. Switch the host filter to see imported sessions.":i.hostFilter!=="__all"?r=`No sessions from ${i.hostFilter}. Try a different host.`:r=`No warm sessions. ${t} cold session${t===1?"":"s"} hidden \u2014 click "warm" to switch to "all".`,s.appendChild(l("div",{class:"empty"},r))}for(let r of n){let o=l("div",{class:"group"});r.label&&o.appendChild(l("h2",null,r.label));for(let a of r.sessions)o.appendChild(Cl(a,r.label===null));s.appendChild(o)}return s}function zi(e,t){let n=r=>{let o=r.status==="warm";return o&&r.busy&&r.awaitingInput?4:o&&r.busy?3:o&&r.awaitingInput?2:o?1:0},s=n(t)-n(e);return s!==0?s:String(t.updatedAt||"").slice(0,16).localeCompare(String(e.updatedAt||"").slice(0,16))}function un(e){return e.replace(/^\/(home|Users)\/[^/]+/,"~")}function es(e,t){return l("div",{class:"detail"},l("span",{class:"k"},e),l("code",null,t))}function _l(e){let t=(n,s)=>l("button",{class:"ghost",...I(()=>ui(n))},s);return e?l("div",{class:"detail"},l("span",{class:"k"},"workspace"),l("code",null,`${e.label}${e.clean===!1?" \xB7 dirty":""}`),t("sync","Sync"),t("stop","Stop"),t("apply","Apply")):l("div",{class:"detail"},l("span",{class:"k"},"workspace"),t("start","Start workspace"))}function vl(){return l("div",{class:"detail"},l("span",{class:"k"},"hide thoughts"),l("label",{class:"checkbox-label"},l("input",{type:"checkbox",checked:i.hideThoughts?"":void 0,onchange:e=>{C({hideThoughts:e.target.checked})}})))}function wl(){return l("div",{class:"detail"},l("span",{class:"k"},"notify"),l("label",{class:"checkbox-label"},l("input",{type:"checkbox",checked:i.notifyOnTurnEnd?"":void 0,onchange:e=>{if(!e.target.checked){C({notifyOnTurnEnd:!1}),xi().then(()=>Je());return}Ii().then(n=>{if(!n){C({banner:{kind:"warn",text:"Notifications blocked \u2014 enable them for this site in your browser settings."}});return}C({notifyOnTurnEnd:!0}),en().then(()=>Je())})}})))}function uo(){let e=i.current?.sessionId;i.cacheInfo=e?"\u2026":"no session open",e&&Xr(e).then(t=>{i.cacheInfo=t,_()}),C({modal:{kind:"options"}})}var Sl=[{value:"system",label:"system"},{value:"dark",label:"dark"},{value:"light",label:"light"}],Tl=[{value:.85,label:"smaller"},{value:.95,label:"small"},{value:1,label:"normal"},{value:1.15,label:"large"},{value:1.3,label:"larger"},{value:1.5,label:"largest"}];function Il(){let e=l("select",{onchange:t=>{C({fontScale:Number(t.target.value)}),sn()}},...Tl.map(t=>l("option",{value:String(t.value)},t.label)));return e.value=String(i.fontScale),l("div",{class:"detail"},l("span",{class:"k"},"text size"),e)}function on(e,t){let n=l("span",{class:"diag-value"},t);return l("div",{class:"detail diag-copy",title:"Tap to copy",...I(()=>{let r=()=>{let a=n.textContent;n.textContent="copied",setTimeout(()=>{n.textContent=a},1200)},o=`${e}: ${t}`;navigator.clipboard?.writeText?navigator.clipboard.writeText(o).then(r,()=>Wi(n)):Wi(n)})},l("span",{class:"k"},e),n)}function Wi(e){let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n?.removeAllRanges(),n?.addRange(t)}function Al(){return on("cache",i.cacheInfo??"\u2026")}function kl(){return on("build","2026-08-26 22:24Z")}function xl(){let e=l("select",{onchange:t=>{C({theme:t.target.value}),nn()}},...Sl.map(t=>{let n=l("option",{value:t.value},t.label);return t.value===i.theme&&n.setAttribute("selected",""),n}));return e.value=i.theme,l("div",{class:"detail"},l("span",{class:"k"},"theme"),e)}function Ml(){return l("div",{class:"modal-bg",...I(e=>{e.target.classList.contains("modal-bg")&&be()})},l("div",{class:"modal"},l("h2",null,"Options"),xl(),Il(),vl(),wl(),l("div",{class:"diagnostics"},kl(),Al(),on("slow",vs()),on("paths",_s())),l("div",{class:"actions"},l("button",{class:"primary",...I(be)},"Close"))))}function Nl(e){let t=l("select",{onchange:n=>{wi(e.id,n.target.value)}},...e.options.map(n=>{let s=l("option",{value:n.value},n.name||n.value);return n.value===e.currentValue&&s.setAttribute("selected",""),s}));return t.value=e.currentValue,l("div",{class:"detail"},l("span",{class:"k",title:e.description??""},e.name||e.id),t)}function fo(e,t){if(t==="recent")return[{label:null,sessions:e.slice().sort(zi)}];let n=new Map;for(let r of e){let o=r.cwd||"(unknown)";n.has(o)||n.set(o,[]),n.get(o).push(r)}let s=[];for(let[r,o]of[...n.entries()].sort((a,c)=>a[0].localeCompare(c[0])))o.sort(zi),s.push({label:un(r),sessions:o});return s}function Cl(e,t){let n=e.title||eo(e.sessionId),s=[he(e.sessionId),dl(e.agentId,e.currentModel),`age ${fl(e.updatedAt)}`].join(" \xB7 "),r=!e.busy&&(e.armedTasks??0)>0;return l("div",{class:e.sessionId===i.listHighlightedSessionId?"card highlighted":"card",...I(o=>{o.target.closest("button")||is(e.sessionId,e.status==="cold")})},l("div",{class:"row1"},n),l("div",{class:"card-body"},l("div",{class:"meta"},l("div",{class:"row2"},s)),l("div",{class:"badges"},e.status==="cold"||!(e.busy||e.awaitingInput||r)?l("span",{class:`badge ${e.status==="cold"?"cold":"warm"}`,title:e.status==="cold"?"Disk-only \u2014 opening will resurrect the session":"Live in-memory session"},e.status==="cold"?"cold":"warm"):null,e.busy||r?l("span",{class:"badge busy",title:e.busy?"Agent is working":"Agent has a background task running. It may resume on its own."},"busy"):null,e.awaitingInput?l("span",{class:"badge blocked",title:"Waiting on you \u2014 a permission request or other prompt is pending"},"blocked"):null,...e.importedFromMachine&&!e.upstreamSessionId?[l("span",{class:"badge imported",title:`Passive mirror imported from ${e.importedFromMachine} \u2014 attach to start working on it here.`},`\u2190 ${e.importedFromMachine}`)]:[])),t?l("div",{class:"row3"},e.cwd?un(e.cwd):"?"):null,e.status!=="cold"?l("button",{class:"card-kill",title:"Kill this session",...I(()=>{Rl(e)})},"\xD7"):null)}async function Rl(e){if(confirm(`Kill session ${e.title?`"${e.title}" (${he(e.sessionId)})`:he(e.sessionId)}?`))try{await se("/api/kill",{method:"POST",body:JSON.stringify({sessionId:e.sessionId})}),Oe()}catch(t){C({banner:{kind:"bad",text:"kill failed: "+t.message}})}}function Ol(e){e.compactionPhase||confirm("Compact this session's context now? The agent will summarize history and continue from the summary.")&&di()}function Ll(e){let t=document.createElement("a");t.href=`/api/sessions/${encodeURIComponent(e)}/export`,t.download="",t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function Dl(){let e=document.createElement("input");e.type="file",e.accept=".hydra,application/json",e.style.display="none",e.onchange=()=>{let t=e.files&&e.files[0];document.body.removeChild(e),t&&Pl(t)},document.body.appendChild(e),e.click()}async function Pl(e){let t;try{let s=await e.text();t=JSON.parse(s)}catch(s){C({banner:{kind:"bad",text:"import: bundle is not valid JSON: "+s.message}});return}let n=await wo(t);if(n.ok){let s=n.result;C({banner:{kind:"good",text:s.replaced?`Replaced ${he(s.sessionId)} from bundle`:`Imported as ${he(s.sessionId)}`}}),Oe();return}if(n.status===409&&n.existingSessionId){let s=n.existingSessionId;if(!confirm(`This session is already imported locally as ${he(s)}.
574
598
 
575
599
  Replace it? (Any live attach will be closed.)`)){C({banner:{kind:"warn",text:"Import cancelled."}});return}try{let o=await vo(t,{replace:!0});C({banner:{kind:"good",text:`Replaced ${he(o.sessionId)} from bundle`}}),Oe()}catch(o){C({banner:{kind:"bad",text:"import failed: "+o.message}})}return}C({banner:{kind:"bad",text:"import failed: "+n.message}})}var po="hydra-acp-browser:lastCwd";function Bl(){try{return localStorage.getItem(po)}catch{return null}}function Hl(e){try{localStorage.setItem(po,e)}catch{}}function go(){C({modal:{kind:"session",cwd:Bl()??i.defaultCwd??"",agentId:"",name:"",prompt:"",err:null,busy:!1}})}function Fl(e){return l("div",{class:"modal-bg",...I(t=>{t.target.classList.contains("modal-bg")&&be()})},l("div",{class:"modal"},l("h2",null,"New session"),l("div",{class:"field"},l("label",{for:"f-cwd"},"cwd"),l("input",{id:"f-cwd","data-focus-key":"session-modal-cwd",value:e.cwd,placeholder:"/home/you/dev/project",oninput:t=>{e.cwd=t.target.value}})),l("div",{class:"field"},l("label",{for:"f-agent"},"agent"),$l(e)),l("div",{class:"field"},l("label",{for:"f-name"},"name (optional)"),l("input",{id:"f-name","data-focus-key":"session-modal-name",value:e.name,placeholder:"feature-x",oninput:t=>{e.name=t.target.value}})),l("div",{class:"field"},l("label",{for:"f-prompt"},"first prompt (optional)"),l("textarea",{id:"f-prompt","data-focus-key":"session-modal-prompt",rows:"4",placeholder:"What should the agent do first?",autocapitalize:"off",oninput:t=>{e.prompt=t.target.value}},e.prompt)),e.err?l("div",{class:"err"},e.err):null,l("div",{class:"actions"},l("button",{...I(be)},"Cancel"),l("button",{class:"primary",...I(Ul),disabled:e.busy},e.busy?"Creating\u2026":"Create"))))}function $l(e){let t=l("select",{id:"f-agent","data-focus-key":"session-modal-agent",onchange:s=>{e.agentId=s.target.value}}),n=l("option",{value:""},"<default>");e.agentId===""&&n.setAttribute("selected",""),t.appendChild(n);for(let s of i.agents){let r=l("option",{value:s.id},s.id);s.id===e.agentId&&r.setAttribute("selected",""),t.appendChild(r)}return t}async function Ul(){let e=i.modal;if(!(!e||e.kind!=="session")){if(!e.cwd){e.err="cwd is required",_();return}e.busy=!0,e.err=null,_();try{let t={cwd:e.cwd};e.agentId&&(t.agentId=e.agentId),e.name&&(t.name=e.name),e.prompt&&(t.prompt=e.prompt);let n=await se("/api/sessions",{method:"POST",body:JSON.stringify(t),timeoutMs:6e4});if(Hl(e.cwd),Oe(),i.modal!==e)return;be(),n&&n.sessionId&&Ce(n.sessionId,!1)}catch(t){if(i.modal!==e)return;e.err=t.message,e.busy=!1,_()}}}function be(){C({modal:null})}function ql(){!i.current?.models||i.current.models.length===0||C({modal:{kind:"models"}})}function Gi(e,t,n,s){return l("div",{class:"modal-bg",...I(r=>{r.target.classList.contains("modal-bg")&&be()})},l("div",{class:"modal"},l("h2",null,e),...t.map(r=>l("div",{class:"card",...I(()=>{s(r),be()})},l("div",{class:"meta"},l("div",{class:"row1"},r.name||r.id),l("div",{class:"row2"},r.id)),r.id===n?l("span",{class:"badge warm"},"current"):null))))}var ts=5;function Kl(e){let t=e.armedTaskList;if(!t||t.length===0)return document.createTextNode("");let n=t.slice(0,ts),s=Date.now();return l("div",{class:"armed-tasks"},...n.map(r=>l("div",{class:"armed-task"},l("span",{class:"dot"},"\u25D0"),l("span",{class:"label"},r.label.length>0?r.label:r.taskType??"background task"),l("span",{class:"elapsed"},to(s-r.since)))),t.length>ts?l("div",{class:"armed-tasks-more"},`+${t.length-ts} more`):null)}var ns=200,os=450,zl=250;function ht(e){if(!e.stickToBottom||e.touchActive)return;let t=performance.now();if(t-e.lastTouchEndAt<os||t-e.lastScrollAt<zl)return;let n=e.body,s=n.scrollHeight-n.clientHeight;Math.abs(n.scrollTop-s)>1&&(n.scrollTop=n.scrollHeight)}var et=new WeakMap;function Wl(e){let t=et.get(e);if(t)return t;let n=l("div",{class:"chat-body"}),s=l("button",{class:"jump-to-latest-btn",...I(()=>{n.scrollTop=n.scrollHeight,c.classList.remove("visible")})},"\u2193 Bottom"),r=l("button",{class:"jump-to-latest-btn icon",...I(()=>cn("prev")),title:"Previous turn (Cmd/Ctrl+PageUp)"},"\u25B2"),o=l("button",{class:"jump-to-latest-btn icon",...I(()=>cn("next")),title:"Next turn (Cmd/Ctrl+PageDown)"},"\u25BC"),a=l("div",{class:"turn-toast"}),c=l("div",{class:"jump-to-latest"},r,a,o,s),u=0;n.addEventListener("scroll",()=>{t.lastScrollAt=performance.now();let E=n.scrollHeight-n.scrollTop-n.clientHeight<50;t.stickToBottom=E,u&&cancelAnimationFrame(u),u=requestAnimationFrame(()=>{u=0,c.classList.toggle("visible",!E),cs(n,a)})},{passive:!0});let d=0;n.addEventListener("touchstart",()=>{t.touchActive=!0,d=n.scrollHeight},{passive:!0});let f=E=>{E.touches.length>0||(t.touchActive=!1,t.lastTouchEndAt=performance.now(),n.scrollHeight!==d&&(setTimeout(()=>ht(t),os+50),setTimeout(()=>ht(t),os+900)))};n.addEventListener("touchend",f,{passive:!0}),n.addEventListener("touchcancel",f,{passive:!0});let p=0,g=0;n.addEventListener("pointerdown",E=>{p=E.clientX,g=E.clientY},{passive:!0}),n.addEventListener("pointerup",E=>{if(ve(E.target)||Math.hypot(E.clientX-p,E.clientY-g)>Tn)return;let M=document.activeElement;(M instanceof HTMLTextAreaElement||M instanceof HTMLInputElement)&&M.blur()},{passive:!0});let m=l("div",{class:"chat-slot"}),y=l("div",{class:"chat-slot"}),S=l("div",{class:"chat-slot"}),v=l("div",{class:"chat-slot"});{let x=null,R=null,L=!1,G=!1,B=()=>{let H=document.activeElement;G&&(H instanceof HTMLTextAreaElement||H instanceof HTMLInputElement)&&H.blur(),x=null,R=null,L=!1,G=!1};v.addEventListener("touchstart",H=>{x=null,R=null,L=!1,G=!1;let Y=document.activeElement;if(!(Y instanceof HTMLTextAreaElement||Y instanceof HTMLInputElement))return;let V=H.touches[0];V&&(x=V.clientX,R=V.clientY)},{passive:!0}),v.addEventListener("touchmove",H=>{if(x===null||R===null)return;let Y=H.touches[0];if(!Y)return;let V=Y.clientX-x,Z=Y.clientY-R;if(!L){if(Math.abs(V)<10&&Math.abs(Z)<10)return;if(Math.abs(V)>Math.abs(Z)||Z<0){x=null,R=null;return}L=!0}G=Z>=50},{passive:!0}),v.addEventListener("touchend",B,{passive:!0}),v.addEventListener("touchcancel",B,{passive:!0})}return t={root:l("div",{class:"chat"},m,y,S,n,v),body:n,jump:c,headerSlot:m,detailsSlot:y,armedSlot:S,composerSlot:v,stickToBottom:!0,touchActive:!1,lastTouchEndAt:0,lastScrollAt:0,turnToast:a},et.set(e,t),t}var Yi=new WeakMap;function Gl(e){if(e.kind==="stream"){let t=e.queueEntry;return[e.text,e.role,e.synthetic??!1,e.closed??!1,mt.has(e),t?.status,t?.amendedByMessageId,t?.amendsMessageId,e.attachments?.length??0]}return e.kind==="system"||e.kind==="error"?[e.text]:e.kind==="edit-diff"?[e.diff,e.expanded,e.status]:e.kind==="exit-plan-mode"?[e.plan,e.status]:e.kind==="turn-stamp"?[e.elapsedMs,e.toolCount,e.stopReason]:null}var Qi="pre, table";function Yl(e,t){if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement))return;let n=e.querySelectorAll(Qi);if(n.length===0)return;let s=[];n.forEach((r,o)=>{(r.scrollLeft!==0||r.scrollTop!==0)&&s.push([o,r.scrollLeft])}),s.length!==0&&queueMicrotask(()=>{let r=t.querySelectorAll(Qi);for(let[o,a]of s){let c=r[o];c&&(c.scrollLeft=a)}})}function Ql(e){let t=Gl(e);if(t===null)return Vi(e);let n=Yi.get(e);if(n&&n.sig.length===t.length&&n.sig.every((r,o)=>r===t[o]))return $e("node-hit"),n.node;$e(n?"node-resig":"node-new");let s=Vi(e);return n&&Yl(n.node,s),Yi.set(e,{node:s,sig:t}),s}function Xl(e,t){let n=new Set(t);for(let s=e.childNodes.length-1;s>=0;s--){let r=e.childNodes[s];n.has(r)||e.removeChild(r)}for(let s=0;s<t.length;s++){let r=t[s],o=e.childNodes[s]??null;o!==r&&e.insertBefore(r,o)}for(;e.childNodes.length>t.length;)e.removeChild(e.lastChild)}function Vl(e,t){let n=t.body,s=!e.renderAllHistory&&e.log.length>ns,r=s?e.log.length-ns:0;if(s){let c=Math.max(0,e.log.length-ns*2);for(let u=r;u>=c;u--){let d=e.log[u];if(d&&d.kind==="stream"&&d.role==="user"){r=u;break}}}let o=s?e.log.slice(r):e.log,a=[];if(e.historyIsPartial&&!s&&a.push(l("button",{class:"show-earlier",...I(()=>Di(e))},"Load full history")),s){let c=r;a.push(l("button",{class:"show-earlier",...I(()=>{e.renderAllHistory=!0,_()})},`Show ${c} earlier message${c===1?"":"s"}`))}for(let c of o)i.hideThoughts&&c.kind==="stream"&&c.role==="thought"||a.push(Ql(c));a.push(t.jump),Xl(n,a),ht(t)}function an(e){let t=i.current?.scrollRestoreMessageId;if(!t)return!1;let n=e.querySelector(`[data-message-id="${CSS.escape(t)}"]`);return n?(n.scrollIntoView({block:"start"}),i.current.scrollRestoreMessageId=void 0,!0):!1}function mo(e,t){if(t.view!=="chat"||!t.current||t.banner||t.modal||t.current.fileOverlay)return!1;let n=et.get(t.current);if(!n)return!1;if(te()){if(e.childNodes.length!==1)return!1;let s=e.firstElementChild;if(!s||!s.classList.contains("split"))return!1;let r=s.querySelector(":scope > .rail"),o=s.querySelector(":scope > .split-detail");return!r||!o||o.childNodes.length!==1||o.firstChild!==n.root?!1:(gl(r),ln(t.current),an(n.body),!0)}return e.childNodes.length!==1||e.firstChild!==n.root?!1:(ln(t.current),an(n.body),!0)}function ho(e){let t=et.get(e);t&&ht(t)}function ut(e){let t=et.get(e);t&&(t.stickToBottom=!0,ht(t))}function cs(e,t){let n=Array.from(e.querySelectorAll(".msg.user"));if(n.length===0){t.textContent="";return}let s=e.getBoundingClientRect().top,r=1,o=-1;for(let a=n.length-1;a>=0;a--)if(n[a].getBoundingClientRect().top<s+r){o=a;break}t.textContent=o===-1?"Start":`Turn ${o+1} of ${n.length}`}function cn(e){let t=document.querySelector(".chat-body");if(!t)return;let n=Array.from(t.querySelectorAll(".msg.user"));if(n.length===0){let u=t.clientHeight*.9;t.scrollBy({top:e==="next"?u:-u,behavior:"smooth"});return}let s=i.current?et.get(i.current):void 0,r=t.getBoundingClientRect().top,o=1,a=null,c=-1;if(e==="prev"){for(let u=n.length-1;u>=0;u--)if(n[u].getBoundingClientRect().top<r-o){a=n[u],c=u;break}a?(a.scrollIntoView({block:"start",behavior:"smooth"}),s&&(s.turnToast.textContent=`Turn ${c+1} of ${n.length}`)):(t.scrollTo({top:0,behavior:"smooth"}),s&&(s.turnToast.textContent="Start"));return}for(let u=0;u<n.length;u++)if(n[u].getBoundingClientRect().top>r+o){a=n[u],c=u;break}a?(a.scrollIntoView({block:"start",behavior:"smooth"}),s&&(s.turnToast.textContent=`Turn ${c+1} of ${n.length}`)):t.scrollTo({top:t.scrollHeight,behavior:"smooth"})}function ln(e){let t=i.sessions.find(b=>b.sessionId===e.sessionId),n=t?.title||e.title||eo(e.sessionId),s=t?.cwd||e.cwd,r=()=>{e.headerExpanded=!e.headerExpanded,_()},o=l("div",{class:"chat-header"},l("div",{class:"chat-title-row"},te()?null:l("button",{class:"chat-back",title:"Back to session list",...I(()=>Re())},"\u2190"),l("div",{class:"chat-title clickable",title:"Click for session details",...I(r)},n)),l("div",{class:"chat-header-row"},!e.ready&&e.cold?l("span",{class:"pill cold clickable",title:"Session closed cold \u2014 sending a prompt will resurrect it",...I(r)},"cold"):e.ready?e.inTurn?l("span",{class:"pill working clickable",title:"Agent is working",...I(r)},l("span",{class:"dot"},"\u25CF"),"thinking"):e.armedTasks&&e.armedTasks>0?l("span",{class:"pill waiting clickable",title:e.armedSince?`Agent has a background task running (armed ${Math.max(1,Math.floor((Date.now()-e.armedSince)/6e4))}m ago). It may resume on its own.`:"Agent has a background task running. It may resume on its own.",...I(r)},l("span",{class:"dot"},"\u25CF"),"waiting"):l("span",{class:"pill ready clickable",title:"Ready for a prompt",...I(r)},l("span",{class:"dot"},"\u25CF"),"ready"):l("span",{class:"pill clickable",title:"Click for session details",...I(r)},"connecting\u2026"),t?.workspace?l("span",{class:"pill clickable",title:`In workspace "${t.workspace.label}" (source: ${un(t.workspace.sourceCwd)})`,...I(r)},"\u2387 "+t.workspace.label):null,e.model?l("span",{class:"pill clickable",title:"Model (click to change)",...I(ql)},e.model):null,e.contextUsed!=null&&e.contextSize?l("span",{class:e.compactionPhase?"pill clickable compacting":"pill clickable",title:e.compactionPhase?e.compactionPhase==="deferred"?"Compaction queued \u2014 will run once the session is idle.":"Compacting\u2026":`${e.contextUsed.toLocaleString()} / ${e.contextSize.toLocaleString()} context tokens \u2014 click to compact`,...I(()=>Ol(e))},e.compactionPhase?e.compactionPhase==="deferred"?"\u23F3 queued":"\u25D0 compacting\u2026":`${qi(e.contextUsed)}/${qi(e.contextSize)}`):null,Ki(e.cost)?l("span",{class:"pill",title:"Session cost so far"},Ki(e.cost)):null,te()?null:l("button",{...I(uo),title:"Options"},"\u2699"),l("button",{...I(uu),title:"Files"},"\u{1F4C1}"),l("button",{title:"Export this session as a *.hydra bundle",...I(()=>Ll(e.sessionId))},"\u2B07"),l("div",{class:"info clickable",title:"Click for session details",...I(r)}))),a=e.headerExpanded?l("div",{class:"chat-details"},es("title",n),es("session",he(e.sessionId)),es("directory",s||"?"),_l(t?.workspace),...e.configOptions.map(Nl)):null,c=Wl(e),u=b=>{b.style.height="auto",b.style.height=b.scrollHeight+"px"},d=(b,E)=>{b.value=E,e.composerValue=E,Ve(e.sessionId,E),u(b),b.setSelectionRange(E.length,E.length)},f=b=>{if(b.isComposing)return;if(b.key==="Escape"&&te()&&!i.modal){b.preventDefault(),b.stopPropagation(),as();return}let E=b.target;if(b.key==="ArrowUp"&&!b.shiftKey&&!b.altKey&&!b.ctrlKey&&!b.metaKey&&E.selectionStart===0&&E.selectionEnd===0&&e.history.length>0){let M=e.historyIndex===null?0:Math.min(e.history.length-1,e.historyIndex+1);e.historyIndex===null&&(e.historyDraft=e.composerValue),e.historyIndex=M,b.preventDefault(),d(E,e.history[M]);return}if(b.key==="ArrowDown"&&!b.shiftKey&&!b.altKey&&!b.ctrlKey&&!b.metaKey&&E.selectionStart===E.value.length&&E.selectionEnd===E.value.length&&e.historyIndex!==null){if(b.preventDefault(),e.historyIndex>0)e.historyIndex-=1,d(E,e.history[e.historyIndex]);else{let M=e.historyDraft??"";e.historyIndex=null,e.historyDraft=null,d(E,M)}return}if(b.key==="Enter"&&!b.shiftKey){if(b.altKey||b.ctrlKey||b.metaKey){b.preventDefault(),hu(E,`
576
600
  `);return}b.preventDefault(),ft()}},p=()=>l("textarea",{"data-focus-key":"composer",placeholder:e.ready?"Message\u2026":e.cold?"Message\u2026 (wakes the session)":"Connecting\u2026",rows:"1",autocapitalize:"off",onkeydown:f,onpaste:b=>{let E=b.clipboardData?.items;if(!E)return;let M=[];for(let x of E){if(x.kind!=="file"||!x.type.startsWith("image/"))continue;let R=x.getAsFile();R&&M.push(R)}M.length!==0&&(b.preventDefault(),cl(e,M))},oninput:b=>{yo();let E=b.target;e.composerValue=E.value,Ve(e.sessionId,E.value),e.historyIndex!==null&&(e.historyIndex=null,e.historyDraft=null),u(E);let M=E.value.trim().length>0||e.attachments.length>0,x=E.closest(".composer")?.querySelectorAll(".content-gated")??[];for(let R of x)R.classList.toggle("empty",!M)}},e.composerValue),g=c.composerTextarea;if(g||(g=p(),c.composerTextarea=g),g.placeholder=e.ready?"Message\u2026":e.cold?"Message\u2026 (wakes the session)":"Connecting\u2026",g.value!==e.composerValue){g.value=e.composerValue;let b=g;queueMicrotask(()=>u(b))}if(e.composerValue&&e.composerValue.length>0){let b=g;queueMicrotask(()=>u(b))}!e.composerAutoFocused&&Ss()&&(e.composerAutoFocused=!0,queueMicrotask(()=>g.focus()));let m=e.composerValue.trim().length>0||e.attachments.length>0,y=[];e.inTurn?(e.daemonSupportsAmend&&e.currentHeadMessageId!==void 0&&y.push(l("button",{class:`content-gated${m?"":" empty"}`,...I(mi),title:"Cancel the current turn and replace its prompt"},"Amend")),y.push(l("button",{class:`primary content-gated${m?"":" empty"}`,...I(ft),title:"Queue this prompt to run after the current turn"},"Enqueue"))):y.push(l("button",{class:`primary content-gated${m?"":" empty"}`,...I(ft)},"Send"));let S=l("div",{class:"composer"},ll(e),g,l("div",{class:"composer-buttons"},l("button",{class:"stop",disabled:!e.inTurn&&!e.promptQueue.some(b=>b.status==="queued"||b.status==="pending"),...I(yi),title:"Cancel current turn"},"Stop"),...y));return c.headerSlot.replaceChildren(o),a!==null&&document.activeElement!==null&&c.detailsSlot.contains(document.activeElement)||(a?c.detailsSlot.replaceChildren(a):c.detailsSlot.replaceChildren()),c.armedSlot.replaceChildren(Kl(e)),c.composerSlot.replaceChildren(S),Vl(e,c),c.root}var Xi=new WeakMap;function bo(e,t){let n=Xi.get(e);if(n&&n.text===t)return n.html;let s=Fr(t);return Xi.set(e,{text:t,html:s}),s}function Vi(e){if(e.kind==="stream"){let t=e.role==="thought",n=e.role==="user"?"msg user":t?"msg system":"msg agent",s=t&&mt.has(e),r=l("div",{class:s?n+" collapsed":n,"data-message-id":e.messageId});t&&r.addEventListener("click",()=>{if(!!mt.has(e)){mt.delete(e),_();return}let c=document.querySelector(".chat-body"),u=c?.getBoundingClientRect(),d=r.getBoundingClientRect(),f=d.top-(u?.top??0)+(c?.scrollTop??0),g=!u||d.top>=u.top&&d.top<u.bottom?c?.scrollTop??0:f;mt.add(e),_(),requestAnimationFrame(()=>{let m=document.querySelector(".chat-body");m&&(m.scrollTop=g)})});let o=e.queueEntry;if(o&&o.amendedByMessageId!==void 0&&o.status==="amended"&&r.classList.add("amended-target"),o&&(o.status==="queued"||o.status==="pending"||o.status==="cancelled"||o.status==="editing"||o.status==="amended"||o.status==="offline")&&r.appendChild(su(o)),o&&o.amendsMessageId!==void 0&&r.appendChild(l("span",{class:"amend-badge",title:"Merged amend \u2014 replaces the previous, cancelled prompt"},"+")),o&&o.status==="editing")r.classList.add("bubble-editing"),r.appendChild(ru(o,a=>{e.text=a}));else{e.attachments&&e.attachments.length>0&&r.appendChild(l("div",{class:"attachment-thumbs"},...e.attachments.map(c=>l("img",{class:"attachment-thumb",src:Ji(c)}))));let a=l("div",{class:e.synthetic?"body raw":"body"});e.synthetic?a.textContent=e.text:a.innerHTML=bo(e,e.text),o&&o.status==="cancelled"&&(a.style.textDecoration="line-through",a.style.opacity="0.6"),r.appendChild(a)}return r}if(e.kind==="system")return l("div",{class:"msg system"},e.text);if(e.kind==="error")return l("div",{class:"msg error"},e.text);if(e.kind==="spinner")return ou(e.spinner);if(e.kind==="turn-stamp")return iu(e);if(e.kind==="perm"){if(!i.current)return document.createTextNode("");let t=i.current.pendingPermissions.get(e.toolCallId);return t?cu(t):document.createTextNode("")}return e.kind==="plan"?lu(e.entries):e.kind==="exit-plan-mode"?tu(e):e.kind==="edit-diff"?eu(e):document.createTextNode("")}function Zl(e){return e==="+"?"diff-line hljs-addition":e==="-"?"diff-line hljs-deletion":e==="gap"?"diff-line diff-gap":"diff-line"}function jl(e){return e==="+"?"+ ":e==="-"?"- ":e==="gap"?"":" "}var Zi=new WeakMap;function Jl(e){let t=Zi.get(e);return t||(t={counts:Kr(e)},Zi.set(e,t)),t}function eu(e){let t=Jl(e.diff),n=t.counts,s=e.diff.path?un(e.diff.path):"file",r=[];n.added>0&&r.push(l("span",{class:"add"},`+${n.added}`)),n.removed>0&&r.push(l("span",{class:"del"},`-${n.removed}`));let o=l("div",{class:"head",...I(()=>{e.expanded=!e.expanded,_()})},l("span",null,e.expanded?"\u25BE":"\u25B8"),l("span",{class:"title"},`Edited ${s}`),r.length>0?l("span",{class:"kind edit-summary"},r):null),a=l("div",{class:e.expanded?"toolcard open":"toolcard"},o);if(e.expanded){let c=t.lines??(t.lines=zr(e.diff));a.appendChild(l("div",{class:"body"},l("pre",null,l("code",{class:"diff-body"},c.map(u=>l("div",{class:Zl(u.op)},jl(u.op)+u.text))))))}return a}function tu(e){let t=l("div",{class:"msg agent plan-markdown"});t.appendChild(l("div",{class:"plan-header"},"\u{1F4CB} Plan"));let n=l("div",{class:"body"});n.innerHTML=bo(e,e.plan),t.appendChild(n);let s=nu(e.status);return s!==null&&t.appendChild(s),t}function nu(e){if(e===void 0)return null;switch(e){case"completed":case"succeeded":case"ok":return l("div",{class:"plan-status plan-status-ok"},"\u2713 Approved");case"failed":case"error":case"rejected":return l("div",{class:"plan-status plan-status-fail"},"\u2717 Rejected");case"cancelled":return l("div",{class:"plan-status plan-status-cancelled"},"\u229D Cancelled");case"pending":case"in_progress":case"running":case"updated":return l("div",{class:"plan-status plan-status-pending"},"awaiting approval\u2026");default:return null}}function su(e){if(e.status==="queued"||e.status==="pending"){let t=e.status==="pending"?"sending\u2026":`queued \xB7 ${Math.max(1,e.aheadAtEnqueue)} ahead`+(e.held?" \xB7 held: agent resumed":""),n=e.status==="queued"&&e.messageId!==void 0&&i.current!==null&&i.current.daemonSupportsAmend&&i.current.currentHeadMessageId!==void 0&&i.current.inTurn;return l("div",{class:"queue-chip queue-queued"},l("span",null,t),n?l("button",{class:"queue-edit",...I(()=>pi(e)),title:"Send now \u2014 amends the running turn instead of waiting"},l("span",{class:"queue-btn-glyph"},"+")):null,l("button",{class:"queue-edit",...I(()=>{e.status="editing",_()}),title:"Edit before sending"},l("span",{class:"queue-btn-glyph"},"\u270E")),l("button",{class:"queue-cancel",...I(()=>jt(e)),title:"Cancel before sending"},l("span",{class:"queue-btn-glyph"},"\xD7")))}return e.status==="editing"?l("div",{class:"queue-chip queue-editing"},l("span",null,"editing \u2014 Save or Cancel below")):e.status==="processing"?l("div",{class:"queue-chip queue-processing"},l("span",{class:"dot"}),l("span",null,"processing")):e.status==="cancelled"?l("div",{class:"queue-chip queue-cancelled"},l("span",null,"cancelled")):e.status==="amended"?l("div",{class:"queue-chip queue-amended"},l("span",null,"amended \u2014 merged into the next prompt")):e.status==="offline"?l("div",{class:"queue-chip queue-offline"},l("span",null,"pending"),l("button",{class:"queue-edit",...I(()=>{e.editReturnStatus="offline",e.status="editing",_()}),title:"Edit before sending"},l("span",{class:"queue-btn-glyph"},"\u270E")),l("button",{class:"queue-cancel",...I(()=>jt(e)),title:"Discard, this was never sent"},l("span",{class:"queue-btn-glyph"},"\xD7"))):document.createTextNode("")}function ru(e,t){let n=l("textarea",{class:"queue-edit-area",rows:"1",autocapitalize:"off"});n.value=e.text;let s=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",s);let r=()=>{e.status=e.editReturnStatus??"queued",e.editReturnStatus=void 0},o=()=>{let c=n.value;e.text=c,t(c),r(),gi(e,c),_()},a=()=>{r(),_()};return n.addEventListener("keydown",c=>{c.key==="Enter"&&!c.shiftKey?(c.preventDefault(),o()):c.key==="Escape"&&(c.preventDefault(),a())}),queueMicrotask(()=>{s(),n.focus(),n.setSelectionRange(n.value.length,n.value.length)}),l("div",{class:"queue-editor"},n,l("div",{class:"queue-editor-actions"},l("button",{class:"ghost",...I(a)},"Cancel"),l("button",{class:"primary",...I(o)},"Save")))}function rn(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function iu(e){let t=e.stopReason!==void 0&&e.stopReason!=="end_turn",n=t?`stopped (${e.stopReason}) \xB7 ${rn(e.elapsedMs)}`:e.toolCount>0?`${e.toolCount} tool${e.toolCount===1?"":"s"} \xB7 took ${rn(e.elapsedMs)}`:`thought \xB7 ${rn(e.elapsedMs)}`;return l("div",{class:t?"turn-stamp bad":"turn-stamp"},n)}function ou(e){let t=l("button",{class:"queue-cancel",...I(()=>Ei()),title:"Cancel this turn"},l("span",{class:"queue-btn-glyph"},"\xD7")),n=rn(Date.now()-e.startedAt);if(!e.expanded)return l("div",{class:"spinner",...I(()=>{e.expanded=!0,_()})},l("div",{class:"head"},l("span",{class:"dot"}),l("span",null,e.toolCallIds.length===0?`thinking \xB7 ${n}`:`working \u2014 ${e.toolCallIds.length} tool call${e.toolCallIds.length===1?"":"s"} \xB7 ${n}`),t));let s=e.toolCallIds.map(r=>{let o=i.current?.toolCalls.get(r);if(!o)return null;let a=o.status==="completed"||o.status==="success"?"\u2705":o.status==="failed"||o.status==="error"?"\u274C":"\u25B6";return l("li",null,l("span",{class:"icon"},a),document.createTextNode(" "+o.title))});return l("div",{class:"spinner expanded",...I(()=>{e.expanded=!1,_()})},l("div",{class:"head"},l("span",{class:"dot"}),l("span",null,`working \xB7 ${n}`),t),l("ul",null,s))}function au(e){let t=f=>typeof f=="string"&&f.length>0?f:void 0,n=[],s=(f,p)=>l("div",{class:"detail"},l("span",{class:"k"},f),l("code",null,p)),r=t(e.kind);r&&n.push(s("kind",r));let o=new Set,a=[],c=f=>{let p=t(f);p&&!o.has(p)&&(o.add(p),a.push(p))},u=e.locations;if(Array.isArray(u))for(let f of u)f&&typeof f=="object"&&c(f.path);let d=e.rawInput&&typeof e.rawInput=="object"?e.rawInput:void 0;d&&(c(d.file_path),c(d.filePath),c(d.path));for(let f of a)n.push(s("path",f));if(d){let f=t(d.command);f&&n.push(s("command",f));let p=t(d.url);p&&n.push(s("url",p));let g=t(d.description);g&&n.push(l("div",{class:"detail note"},g))}return n}function cu(e){let t=e.toolCall||{};return l("div",{class:"perm"},l("div",{class:"title"},"\u{1F512} Permission requested"),l("div",{class:"desc"},t.title||t.name||"tool call"),au(t),l("div",{class:"opts"},...e.options.map(n=>l("button",{class:n.kind?.startsWith("allow")?"primary":n.kind?.startsWith("reject")?"danger":"",...I(()=>Qn(e.toolCallId,n.optionId))},n.name||n.optionId)),l("button",{...I(()=>Qn(e.toolCallId,"__cancel__"))},"Cancel")))}function lu(e){return Array.isArray(e)?l("div",{class:"msg agent"},l("div",{class:"body"},l("strong",null,"Plan")),l("ul",null,...e.map(t=>l("li",null,`${t.status==="completed"?"\u2713":t.status==="in_progress"?"\u25B8":"\xB7"} ${t.content||t.title||""}`)))):document.createTextNode("")}function uu(){i.current&&(i.current.fileOverlay={path:"",entries:[],preview:null,err:null},_(),bt(""))}async function bt(e){if(i.current)try{let t=await se("/api/files/list",{method:"POST",body:JSON.stringify({sessionId:i.current.sessionId,path:e})});i.current.fileOverlay={path:t.path,entries:t.entries??[],preview:null,err:null},_()}catch(t){i.current.fileOverlay={path:e,entries:[],preview:null,err:t.message},_()}}async function du(e){if(i.current)try{let t=await se("/api/files/read",{method:"POST",body:JSON.stringify({sessionId:i.current.sessionId,path:e})}),n=i.current.fileOverlay;i.current.fileOverlay={path:n.path,entries:n.entries,preview:{path:e,content:t.content},err:null},_()}catch(t){i.current.fileOverlay&&(i.current.fileOverlay={...i.current.fileOverlay,err:t.message}),_()}}function ji(){i.current&&(i.current.fileOverlay=null,_())}function fu(e){if(!i.current?.fileOverlay)return;let t=i.current.fileOverlay,n=t.path?`${t.path}/${e.name}`:e.name;e.kind==="dir"?bt(n):e.kind==="file"&&du(n)}function pu(e){let t=e?e.split("/").filter(Boolean):[],n=[l("span",{class:"crumb",...I(()=>bt(""))},".")],s="";for(let r of t){s=s?`${s}/${r}`:r;let o=s;n.push(document.createTextNode(" / ")),n.push(l("span",{class:"crumb",...I(()=>bt(o))},r))}return l("div",{class:"crumbs"},n)}function gu(e,t){if(!i.current)return;let n=`${e}:${t}`,s=i.current.composerValue;i.current.composerValue=s?`${s} ${n}`:n,Ve(i.current.sessionId,i.current.composerValue),_()}function mu(){i.current?.fileOverlay&&(i.current.fileOverlay.preview=null,_())}function Eo(e){let t=e.fileOverlay;if(!t)return document.createTextNode("");let n;if(t.preview){let{path:s,content:r}=t.preview,o=Dr(r,s)??ae(r),a=r.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydra-acp/browser",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
4
4
  "description": "Browser-based UI for hydra-acp sessions.",
5
5
  "license": "MIT",
6
6
  "type": "module",