openfox 1.6.35 → 1.6.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.
@@ -2,7 +2,7 @@ import {
2
2
  maybeAutoCompactContext,
3
3
  performManualContextCompaction,
4
4
  resolveCompactionStatsIdentity
5
- } from "./chunk-4O3C2JMB.js";
5
+ } from "./chunk-26PIZX2A.js";
6
6
  import "./chunk-NBU6KIOD.js";
7
7
  import "./chunk-574HZVLE.js";
8
8
  import "./chunk-D4ZLSV6P.js";
@@ -23,4 +23,4 @@ export {
23
23
  performManualContextCompaction,
24
24
  resolveCompactionStatsIdentity
25
25
  };
26
- //# sourceMappingURL=auto-compaction-7LK3QGPI.js.map
26
+ //# sourceMappingURL=auto-compaction-CQ66MD6K.js.map
@@ -10,8 +10,8 @@ import {
10
10
  } from "./chunk-AV45GQ7B.js";
11
11
  import {
12
12
  runChatTurn
13
- } from "./chunk-BOEXJCOD.js";
14
- import "./chunk-4O3C2JMB.js";
13
+ } from "./chunk-VFHCB5MC.js";
14
+ import "./chunk-26PIZX2A.js";
15
15
  import "./chunk-NBU6KIOD.js";
16
16
  import "./chunk-574HZVLE.js";
17
17
  import "./chunk-D4ZLSV6P.js";
@@ -62,7 +62,7 @@ async function startChatSession(sessionId, content, deps, options) {
62
62
  sessionManager.setRunning(sessionId, true);
63
63
  broadcastForSession(sessionId, createSessionRunningMessage(true));
64
64
  try {
65
- const { maybeAutoCompactContext } = await import("./auto-compaction-7LK3QGPI.js");
65
+ const { maybeAutoCompactContext } = await import("./auto-compaction-CQ66MD6K.js");
66
66
  await maybeAutoCompactContext({
67
67
  sessionManager,
68
68
  sessionId,
@@ -171,4 +171,4 @@ export {
171
171
  startChatSession,
172
172
  stopSessionExecution
173
173
  };
174
- //# sourceMappingURL=chat-handler-ZU74RXED.js.map
174
+ //# sourceMappingURL=chat-handler-EJR4GKYO.js.map
@@ -366,16 +366,20 @@ ${agentDef.prompt}${toolPermissions}
366
366
  }
367
367
  var BUILDER_KICKOFF_PROMPT = (criteriaCount) => `Implement the task and make sure you fulfil the ${criteriaCount} criteria.`;
368
368
  var VERIFIER_KICKOFF_PROMPT = 'Verify each criterion marked [NEEDS VERIFICATION]. Read the code, run tests if applicable, then call criterion with action "pass" or "fail" for each.';
369
- var COMPACTION_PROMPT = `Summarize the conversation history concisely, preserving:
370
- 1. All file modifications made (file paths and what changed)
371
- 2. All errors encountered and how they were resolved
372
- 3. Current progress on each task
373
- 4. Any important decisions or learnings
374
- 5. Next steps or pending actions that should be continued after compaction
375
- 6. The user's current question, prompt, or active request
369
+ var COMPACTION_PROMPT = `You are a helpful AI assistant tasked with summarizing conversations for continuation.
376
370
 
377
- Be thorough but concise. Output as a structured summary.
378
- You may use available tools to read files and verify changes if needed.`;
371
+ Summarize the conversation history concisely, preserving:
372
+ 1. What was done and what is currently being worked on
373
+ 2. All file modifications made (file paths and what changed)
374
+ 3. All errors encountered and how they were resolved
375
+ 4. Current progress on each task
376
+ 5. Important technical decisions and WHY they were made
377
+ 6. User constraints, preferences, or requirements that should persist
378
+ 7. Next steps or pending actions that should be continued after compaction
379
+ 8. The user's current question, prompt, or active request
380
+
381
+ Do not respond to any questions in the conversation, only output the summary.
382
+ Be thorough but concise. Output as a structured summary.`;
379
383
  var FORMAT_CORRECTION_PROMPT = `IMPORTANT: You MUST use the JSON function calling API. Do NOT output XML tags like <tool_call>, <function=>, or <parameter=>. Your previous attempt was stopped because you used the wrong format. Use the proper tool_calls format.`;
380
384
 
381
385
  // src/server/chat/request-context.ts
@@ -3347,7 +3351,7 @@ var callSubAgentTool = {
3347
3351
  };
3348
3352
  }
3349
3353
  try {
3350
- const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-CSV7G554.js");
3354
+ const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-25TQ5NQY.js");
3351
3355
  const toolRegistry = getToolRegistryForAgent2(agentDef);
3352
3356
  const turnMetrics = new TurnMetrics();
3353
3357
  const result = await executeSubAgent({
@@ -4476,4 +4480,4 @@ export {
4476
4480
  getToolRegistryForAgent,
4477
4481
  createToolRegistry
4478
4482
  };
4479
- //# sourceMappingURL=chunk-4O3C2JMB.js.map
4483
+ //# sourceMappingURL=chunk-26PIZX2A.js.map
@@ -6,7 +6,7 @@ import {
6
6
  createVerifierNudgeConfig,
7
7
  runBuilderTurn,
8
8
  runChatTurn
9
- } from "./chunk-BOEXJCOD.js";
9
+ } from "./chunk-VFHCB5MC.js";
10
10
  import {
11
11
  TurnMetrics,
12
12
  agentExists,
@@ -47,7 +47,7 @@ import {
47
47
  setSkillEnabled,
48
48
  skillExists,
49
49
  spawnShellProcess
50
- } from "./chunk-4O3C2JMB.js";
50
+ } from "./chunk-26PIZX2A.js";
51
51
  import {
52
52
  getPathSeparator,
53
53
  getPlatformShell,
@@ -5479,7 +5479,7 @@ function createTerminalRoutes() {
5479
5479
  }
5480
5480
 
5481
5481
  // src/constants.ts
5482
- var VERSION = "1.6.35";
5482
+ var VERSION = "1.6.36";
5483
5483
 
5484
5484
  // src/server/index.ts
5485
5485
  var __dirname2 = dirname5(fileURLToPath4(import.meta.url));
@@ -5781,7 +5781,7 @@ async function createServerHandle(config) {
5781
5781
  if (!callId || approved === void 0) {
5782
5782
  return res.status(400).json({ error: "callId and approved are required" });
5783
5783
  }
5784
- const { providePathConfirmation: providePathConfirmation2 } = await import("./tools-CSV7G554.js");
5784
+ const { providePathConfirmation: providePathConfirmation2 } = await import("./tools-25TQ5NQY.js");
5785
5785
  const result = providePathConfirmation2(callId, approved, alwaysAllow);
5786
5786
  if (!result.found) {
5787
5787
  return res.status(404).json({ error: "No pending path confirmation with that ID" });
@@ -5806,7 +5806,7 @@ async function createServerHandle(config) {
5806
5806
  if (!callId || !answer) {
5807
5807
  return res.status(400).json({ error: "callId and answer are required" });
5808
5808
  }
5809
- const { provideAnswer: provideAnswer2 } = await import("./tools-CSV7G554.js");
5809
+ const { provideAnswer: provideAnswer2 } = await import("./tools-25TQ5NQY.js");
5810
5810
  const found = provideAnswer2(callId, answer);
5811
5811
  if (!found) {
5812
5812
  return res.status(404).json({ error: "No pending question with that ID" });
@@ -5842,8 +5842,8 @@ async function createServerHandle(config) {
5842
5842
  if (!session) {
5843
5843
  return res.status(404).json({ error: "Session not found" });
5844
5844
  }
5845
- const { stopSessionExecution } = await import("./chat-handler-ZU74RXED.js");
5846
- const { cancelQuestionsForSession: cancelQuestionsForSession2, cancelPathConfirmationsForSession: cancelPathConfirmationsForSession2 } = await import("./tools-CSV7G554.js");
5845
+ const { stopSessionExecution } = await import("./chat-handler-EJR4GKYO.js");
5846
+ const { cancelQuestionsForSession: cancelQuestionsForSession2, cancelPathConfirmationsForSession: cancelPathConfirmationsForSession2 } = await import("./tools-25TQ5NQY.js");
5847
5847
  stopSessionExecution(sessionId, sessionManager);
5848
5848
  abortSession(sessionId);
5849
5849
  cancelQuestionsForSession2(sessionId, "Session stopped by user");
@@ -6302,7 +6302,7 @@ async function createServerHandle(config) {
6302
6302
  providerManager
6303
6303
  );
6304
6304
  const wss = wssExports.wss;
6305
- const { QueueProcessor } = await import("./processor-GAOK7TPI.js");
6305
+ const { QueueProcessor } = await import("./processor-7L64YPQC.js");
6306
6306
  const queueProcessor = new QueueProcessor({
6307
6307
  sessionManager,
6308
6308
  providerManager,
@@ -6375,4 +6375,4 @@ export {
6375
6375
  createServerHandle,
6376
6376
  createServer
6377
6377
  };
6378
- //# sourceMappingURL=chunk-NPSBNNGO.js.map
6378
+ //# sourceMappingURL=chunk-6JYCWE5P.js.map
@@ -154,7 +154,7 @@ async function runCli(options) {
154
154
  if (!configExists) {
155
155
  await runNetworkSetup(mode);
156
156
  }
157
- const { runServe } = await import("./serve-MMDVRY46.js");
157
+ const { runServe } = await import("./serve-OM263UOA.js");
158
158
  await runServe({
159
159
  mode,
160
160
  port: values.port ? parseInt(values.port) : void 0,
@@ -167,4 +167,4 @@ async function runCli(options) {
167
167
  export {
168
168
  runCli
169
169
  };
170
- //# sourceMappingURL=chunk-7EIVES5U.js.map
170
+ //# sourceMappingURL=chunk-TKL65AGO.js.map
@@ -13,7 +13,7 @@ import {
13
13
  getToolRegistryForAgent,
14
14
  loadAllAgentsDefault,
15
15
  runTopLevelAgentLoop
16
- } from "./chunk-4O3C2JMB.js";
16
+ } from "./chunk-26PIZX2A.js";
17
17
  import {
18
18
  getCurrentContextWindowId,
19
19
  getEventStore
@@ -293,4 +293,4 @@ export {
293
293
  runBuilderTurn,
294
294
  runVerifierTurn
295
295
  };
296
- //# sourceMappingURL=chunk-BOEXJCOD.js.map
296
+ //# sourceMappingURL=chunk-VFHCB5MC.js.map
package/dist/cli/dev.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runCli
4
- } from "../chunk-7EIVES5U.js";
4
+ } from "../chunk-TKL65AGO.js";
5
5
  import {
6
6
  logger
7
7
  } from "../chunk-PNBH3RAX.js";
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runCli
4
- } from "../chunk-7EIVES5U.js";
4
+ } from "../chunk-TKL65AGO.js";
5
5
  import {
6
6
  logger
7
7
  } from "../chunk-PNBH3RAX.js";
@@ -3,7 +3,7 @@ import {
3
3
  runBuilderTurn,
4
4
  runChatTurn,
5
5
  runVerifierTurn
6
- } from "./chunk-BOEXJCOD.js";
6
+ } from "./chunk-VFHCB5MC.js";
7
7
  import {
8
8
  TurnMetrics,
9
9
  createChatDoneEvent,
@@ -11,7 +11,7 @@ import {
11
11
  createMessageStartEvent,
12
12
  createToolCallEvent,
13
13
  createToolResultEvent
14
- } from "./chunk-4O3C2JMB.js";
14
+ } from "./chunk-26PIZX2A.js";
15
15
  import "./chunk-NBU6KIOD.js";
16
16
  import "./chunk-574HZVLE.js";
17
17
  import "./chunk-D4ZLSV6P.js";
@@ -39,4 +39,4 @@ export {
39
39
  runChatTurn,
40
40
  runVerifierTurn
41
41
  };
42
- //# sourceMappingURL=orchestrator-OE7WFEW6.js.map
42
+ //# sourceMappingURL=orchestrator-PCWZF3E5.js.map
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openfox",
3
- "version": "1.6.35",
3
+ "version": "1.6.36",
4
4
  "description": "Local-LLM-first agentic coding assistant",
5
5
  "type": "module",
6
6
  "bin": {
@@ -175,7 +175,7 @@ var QueueProcessor = class {
175
175
  backend: provider?.backend ?? llmClient.getBackend(),
176
176
  model: llmClient.getModel()
177
177
  };
178
- const { runChatTurn } = await import("./orchestrator-OE7WFEW6.js");
178
+ const { runChatTurn } = await import("./orchestrator-PCWZF3E5.js");
179
179
  const runChatTurnParams = buildRunChatTurnParams({
180
180
  sessionManager,
181
181
  sessionId,
@@ -208,4 +208,4 @@ var QueueProcessor = class {
208
208
  export {
209
209
  QueueProcessor
210
210
  };
211
- //# sourceMappingURL=processor-GAOK7TPI.js.map
211
+ //# sourceMappingURL=processor-7L64YPQC.js.map
@@ -6,10 +6,10 @@ import {
6
6
  import {
7
7
  VERSION,
8
8
  createServer
9
- } from "./chunk-NPSBNNGO.js";
9
+ } from "./chunk-6JYCWE5P.js";
10
10
  import "./chunk-AV45GQ7B.js";
11
- import "./chunk-BOEXJCOD.js";
12
- import "./chunk-4O3C2JMB.js";
11
+ import "./chunk-VFHCB5MC.js";
12
+ import "./chunk-26PIZX2A.js";
13
13
  import "./chunk-NBU6KIOD.js";
14
14
  import "./chunk-574HZVLE.js";
15
15
  import "./chunk-PYBB34ZK.js";
@@ -188,4 +188,4 @@ async function runServe(options) {
188
188
  export {
189
189
  runServe
190
190
  };
191
- //# sourceMappingURL=serve-MMDVRY46.js.map
191
+ //# sourceMappingURL=serve-OM263UOA.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  createServer,
3
3
  createServerHandle
4
- } from "../chunk-NPSBNNGO.js";
4
+ } from "../chunk-6JYCWE5P.js";
5
5
  import "../chunk-AV45GQ7B.js";
6
- import "../chunk-BOEXJCOD.js";
7
- import "../chunk-4O3C2JMB.js";
6
+ import "../chunk-VFHCB5MC.js";
7
+ import "../chunk-26PIZX2A.js";
8
8
  import "../chunk-NBU6KIOD.js";
9
9
  import "../chunk-574HZVLE.js";
10
10
  import "../chunk-PYBB34ZK.js";
@@ -11,7 +11,7 @@ import {
11
11
  requestPathAccess,
12
12
  stepDoneTool,
13
13
  validateToolAction
14
- } from "./chunk-4O3C2JMB.js";
14
+ } from "./chunk-26PIZX2A.js";
15
15
  import "./chunk-NBU6KIOD.js";
16
16
  import "./chunk-574HZVLE.js";
17
17
  import "./chunk-D4ZLSV6P.js";
@@ -48,4 +48,4 @@ export {
48
48
  stepDoneTool,
49
49
  validateToolAction
50
50
  };
51
- //# sourceMappingURL=tools-CSV7G554.js.map
51
+ //# sourceMappingURL=tools-25TQ5NQY.js.map
@@ -54,7 +54,7 @@ Error generating stack: `+h.message+`
54
54
  *
55
55
  * This source code is licensed under the MIT license found in the
56
56
  * LICENSE file in the root directory of this source tree.
57
- */var kx;function c1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),k=s({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function u1(){return Ex||(Ex=1,Od.exports=c1()),Od.exports}var d1=u1();const h1=JS.useInsertionEffect,f1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",p1=f1?H.useLayoutEffect:H.useEffect,m1=h1||p1,vb=e=>{const r=H.useRef([e,(...i)=>r[0](...i)]).current;return m1(()=>{r[0]=e}),r[1]},g1="popstate",jh="pushState",Nh="replaceState",x1="hashchange",jx=[g1,jh,Nh,x1],v1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>d1.useSyncExternalStore(v1,e,r),Nx=()=>location.search,b1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,y1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),_1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),S1=(e={})=>[y1(e),_1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const w1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,C1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,k1=(e="",r)=>w1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:S1,searchHook:b1,parser:l1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=H.createContext(_b),zs=()=>H.useContext(Sb),wb={},Cb=H.createContext(wb),E1=()=>H.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[k1(e.base,r),vb((s,c)=>e.aroundNav(i,C1(s,e.base),c))]},dr=()=>Ql(zs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(zs().parser,e,dr()[0]),j1=({children:e,...r})=>{var g,m,b;const i=zs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=H.useRef({}),d=l.current,p=d;for(let _ in s){const k=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&k!==p[_]&&(l.current=p={...p}),p[_]=k,(k!==s[_]||k!==c[_])&&(c=p)}return H.createElement(Sb.Provider,{value:c,children:e})},Rx=({children:e,component:r},i)=>r?H.createElement(r,{params:i}):typeof e=="function"?e(i):e,N1=e=>{let r=H.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=zs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=N1({...E1(),...l});if(!f)return null;const g=d?H.createElement(j1,{base:d},Rx(s,p)):Rx(s,p);return H.createElement(Cb.Provider,{value:p,children:g})},Mn=H.forwardRef((e,r)=>{const i=zs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===H.Fragment?r.props.children:r)):[e],T1=({children:e,location:r})=>{const i=zs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(H.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return H.cloneElement(c,{match:u})}return null},Lx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},A1=(e=>e?Lx(e):Lx),D1=e=>e;function R1(e,r=D1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=A1(e),i=s=>R1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function L1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class O1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);L1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const M1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new O1(M1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function I1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const B1=3e4;function z1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...I1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},B1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const H1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),P1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],F1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function U1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Rb=typeof Notification<"u"?Notification.permission:"denied";function $1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Rb=e,e))}const q1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},W1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function G1(e){typeof Notification>"u"||Rb==="granted"&&(document.hasFocus()||new Notification(q1[e],{body:W1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=U1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&G1(e)}const V1=e=>oo("complete",e),K1=e=>oo("phase_done",e),Y1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),X1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function Z1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function Q1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function J1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function ew(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function tw(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&V1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);K1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&Y1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&$t.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&$t.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{const i=r().connectionStatus;if(i==="connected"||i==="reconnecting")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{e({connectionStatus:c}),c==="connected"&&r().listSessions(void 0)});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"reconnecting"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,k,C,y,x,v,S,j,T,N,D,A,M,B,$,V,W;const s=r();tw(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:Q1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!Z1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(R=>R.isStreaming)??null,P=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],I=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:J1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:I,error:null,...P?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const R=At.getState();R.providers.find(Y=>Y.id===O.session.providerId)&&R.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:ew(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,P=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,isRunning:O.isRunning}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(P=>P.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(P=>{const Z=P.streamingMessage,G=F;if(Z&&Z.id===O.messageId){const I={...Z,...O.updates};return{messages:P.messages.map(R=>R.id===O.messageId?I:R),streamingMessageId:G?null:P.streamingMessageId,streamingMessage:G?null:{...Z,...O.updates}}}return{messages:P.messages.map(I=>I.id===O.messageId?{...I,...O.updates}:I),streamingMessageId:G?null:P.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);X1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const P=F.streamingMessage;return P&&P.id===O.messageId?{streamingMessage:{...P,preparingToolCalls:[...P.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=P=>{var I;const Z=(I=P.preparingToolCalls)==null?void 0:I.filter((R,z)=>{var Y;return R.name===O.tool?(Y=P.preparingToolCalls)==null?void 0:Y.slice(0,z).some(ie=>ie.name===O.tool):!0}),G=$t.toolOutput.filter(R=>R.callId===O.callId);return G.length>0&&($t.toolOutput=$t.toolOutput.filter(R=>R.callId!==O.callId)),{...P,toolCalls:[...P.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...G.length>0?{streamingOutput:G.map(R=>({stream:R.stream,content:R.content}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.tool_output":{if(!zt(i,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=P=>{var G;const Z=(G=P.toolCalls)==null?void 0:G.map(I=>I.id===O.callId?{...I,result:O.result}:I);return{...P,toolCalls:Z}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const P=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[P]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(P=>{const Z=P.streamingMessage,G=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:P.messages.map(I=>I.id===O.messageId?G??{...I,isStreaming:!1,stats:F??I.stats}:I),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(P=>P.id===F.streamingMessage.id?F.streamingMessage:P):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((M=r().currentSession)==null?void 0:M.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,P=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,phase:O.phase}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,(($=r().currentSession)==null?void 0:$.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,P=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const G=Z.sessions.map(R=>R.id===F?{...R,title:O.name,updatedAt:new Date().toISOString()}:R),I=P===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:G,currentSession:I}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Lb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function nw(){return Ce(e=>e.queuedMessages)}function rw(){return Ce(e=>e.abortInProgress)}function iw(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function sw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function aw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function ow({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function ur({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function uw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function hw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function fw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function pw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function mw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function gw({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function vw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Mb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Ib({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Bb=Ib,zb=Ib;function bw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function _w({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Sw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Cw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function kw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Hb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Ew({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Pb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Nw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const Tw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Hs=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Tw,title:"Edit",...e}));Hs.displayName="EditButton";const Aw="M6 18L18 6M6 6l12 12",Rh=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Aw,...e}));Rh.displayName="CloseButton";const Dw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),x=H.useCallback(()=>{k||_(!1),l==null||l()},[k,l]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${Dw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Rh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=H.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Rw({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:F1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(ur,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Lw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);H.useEffect(()=>{c()},[c]);const u=async()=>{await $1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:P1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Rw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Lh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Rr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Lh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=H.useState({id:null,type:null}),i=H.useCallback(u=>r({id:u,type:"delete"}),[]),s=H.useCallback(()=>r({id:null,type:null}),[]),c=H.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Hb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Ow({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Fb({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function Ub({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Hs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Mw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs(Ub,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function $b({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function qb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Wb(e={}){const{initialData:r={}}=e,[i,s]=H.useState("list"),[c,u]=H.useState(null),[f,l]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),l(""),u(null)},[r]),_=H.useCallback(x=>{s(x),x==="list"&&b()},[b]),k=H.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=H.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=H.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Mw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Iw({isOpen:e}){const r=Rr(O=>O.defaults),i=Rr(O=>O.userItems),s=Rr(O=>O.loading),c=Rr(O=>O.fetchSkills),u=Rr(O=>O.fetchSkill),f=Rr(O=>O.fetchDefaultContent),l=Rr(O=>O.createSkill),d=Rr(O=>O.updateSkill),p=Rr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Wb(),{clearConfirm:j}=Oh();H.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,P,Z)=>{v({name:Z??O.metadata.name,id:P??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(P=>P.id===O)){const P=await f(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}else{const P=await u(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}},D=async O=>{const P=r.some(G=>G.id===O)?await f(O):await u(O);if(!P)return;const Z=`${O}-copy-${Date.now()}`;T(P,!1,Z,`${P.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},M=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},$=async()=>{const O=m??k.id;if(!O||!k.name||!k.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:k.name,description:k.description,version:k.version},prompt:k.prompt},P=m?await d(m,F):await l(F);if(S(!1),!P.success){x(P.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:k.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:k.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:$,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Fb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs($b,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>M(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Bw({isOpen:e,onClose:r}){const[i,s]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Pw,{isOpen:e}),i==="skills"&&o.jsx(Iw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Lw,{})}),i==="display"&&o.jsx(Hw,{}),i==="advanced"&&o.jsx(zw,{onClose:r})]})})}function zw({onClose:e}){const[,r]=dr();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Hw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Pw({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Fw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var M=v.length-1;M>=0;M--)(N=v[M])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
57
+ */var kx;function c1(){if(kx)return Md;kx=1;var e=Zl();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var i=typeof Object.is=="function"?Object.is:r,s=e.useState,c=e.useEffect,u=e.useLayoutEffect,f=e.useDebugValue;function l(m,b){var _=b(),k=s({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),f(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!i(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:l;return Md.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Md}var Ex;function u1(){return Ex||(Ex=1,Od.exports=c1()),Od.exports}var d1=u1();const h1=JS.useInsertionEffect,f1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",p1=f1?H.useLayoutEffect:H.useEffect,m1=h1||p1,vb=e=>{const r=H.useRef([e,(...i)=>r[0](...i)]).current;return m1(()=>{r[0]=e}),r[1]},g1="popstate",jh="pushState",Nh="replaceState",x1="hashchange",jx=[g1,jh,Nh,x1],v1=e=>{for(const r of jx)addEventListener(r,e);return()=>{for(const r of jx)removeEventListener(r,e)}},bb=(e,r)=>d1.useSyncExternalStore(v1,e,r),Nx=()=>location.search,b1=({ssrSearch:e}={})=>bb(Nx,e!=null?()=>e:Nx),Tx=()=>location.pathname,y1=({ssrPath:e}={})=>bb(Tx,e!=null?()=>e:Tx),_1=(e,{replace:r=!1,state:i=null}={})=>history[r?Nh:jh](i,"",e),S1=(e={})=>[y1(e),_1],Ax=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ax]>"u"){for(const e of[jh,Nh]){const r=history[e];history[e]=function(){const i=r.apply(this,arguments),s=new Event(e);return s.arguments=arguments,dispatchEvent(s),i}}Object.defineProperty(window,Ax,{value:!0})}const w1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",yb=(e="")=>e==="/"?"":e,C1=(e,r)=>e[0]==="~"?e.slice(1):yb(r)+e,k1=(e="",r)=>w1(Dx(yb(e)),Dx(r)),Dx=e=>{try{return decodeURI(e)}catch{return e}},_b={hook:S1,searchHook:b1,parser:l1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,i)=>e(r,i)},Sb=H.createContext(_b),zs=()=>H.useContext(Sb),wb={},Cb=H.createContext(wb),E1=()=>H.useContext(Cb),Ql=e=>{const[r,i]=e.hook(e);return[k1(e.base,r),vb((s,c)=>e.aroundNav(i,C1(s,e.base),c))]},dr=()=>Ql(zs()),Th=(e,r,i,s)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",s),f=c.exec(i)||[],[l,...d]=f;return l!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):f.groups;let g={...d};return p&&Object.assign(g,p),g})(),...s?[l]:[]]:[!1,null]},Ah=e=>Th(zs().parser,e,dr()[0]),j1=({children:e,...r})=>{var g,m,b;const i=zs(),s=r.hook?_b:i;let c=s;const[u,f=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=f,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let l=H.useRef({}),d=l.current,p=d;for(let _ in s){const k=_==="base"?s[_]+(r[_]??""):r[_]??s[_];d===p&&k!==p[_]&&(l.current=p={...p}),p[_]=k,(k!==s[_]||k!==c[_])&&(c=p)}return H.createElement(Sb.Provider,{value:c,children:e})},Rx=({children:e,component:r},i)=>r?H.createElement(r,{params:i}):typeof e=="function"?e(i):e,N1=e=>{let r=H.useRef(wb);const i=r.current;return r.current=Object.keys(e).length!==Object.keys(i).length||Object.entries(e).some(([s,c])=>c!==i[s])?e:i},Oa=({path:e,nest:r,match:i,...s})=>{const c=zs(),[u]=Ql(c),[f,l,d]=i??Th(c.parser,e,u,r),p=N1({...E1(),...l});if(!f)return null;const g=d?H.createElement(j1,{base:d},Rx(s,p)):Rx(s,p);return H.createElement(Cb.Provider,{value:p,children:g})},Mn=H.forwardRef((e,r)=>{const i=zs(),[s,c]=Ql(i),{to:u="",href:f=u,onClick:l,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=vb(x=>{x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.button!==0||(l==null||l(x),x.defaultPrevented||(x.preventDefault(),c(f,e)))}),y=i.hrefs(f[0]==="~"?f.slice(1):i.base+f,i);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(s===f):g,children:p,ref:r})}),kb=e=>Array.isArray(e)?e.flatMap(r=>kb(r&&r.type===H.Fragment?r.props.children:r)):[e],T1=({children:e,location:r})=>{const i=zs(),[s]=Ql(i);for(const c of kb(e)){let u=0;if(H.isValidElement(c)&&(u=Th(i.parser,c.props.path,r||s,c.props.nest))[0])return H.cloneElement(c,{match:u})}return null},Lx=e=>{let r;const i=new Set,s=(p,g)=>{const m=typeof p=="function"?p(r):p;if(!Object.is(m,r)){const b=r;r=g??(typeof m!="object"||m===null)?m:Object.assign({},r,m),i.forEach(_=>_(r,b))}},c=()=>r,l={setState:s,getState:c,getInitialState:()=>d,subscribe:p=>(i.add(p),()=>i.delete(p))},d=r=e(s,c,l);return l},A1=(e=>e?Lx(e):Lx),D1=e=>e;function R1(e,r=D1){const i=dn.useSyncExternalStore(e.subscribe,dn.useCallback(()=>r(e.getState()),[e,r]),dn.useCallback(()=>r(e.getInitialState()),[e,r]));return dn.useDebugValue(i),i}const Ox=e=>{const r=A1(e),i=s=>R1(r,s);return Object.assign(i,r),i},Yn=(e=>e?Ox(e):Ox);async function ke(e,r={}){const i=localStorage.getItem("openfox_token"),s={...r.headers instanceof Headers?Object.fromEntries(r.headers.entries()):r.headers,...i?{"x-session-token":i}:{}};return fetch(e,{...r,headers:s})}function L1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Eb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class O1{constructor(r){ar(this,"ws",null);ar(this,"handlers",new Set);ar(this,"statusHandler",null);ar(this,"baseUrl");ar(this,"isReconnecting",!1);ar(this,"connectingPromise",null);ar(this,"lastCloseCode",0);ar(this,"reconnectAttempts",0);ar(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const i=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${i}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,i;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((i=this.ws)==null?void 0:i.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((s,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const f=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(f),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),s()},this.ws.onclose=l=>{var d,p,g;clearTimeout(f),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(f),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);L1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const s=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},s)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,i){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const s=Eb(),c={id:s,type:r,payload:i};return this.ws.send(JSON.stringify(c)),s}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const M1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,qt=new O1(M1),di=async(e,r,i)=>{try{const s=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return s.ok?{success:!0}:{success:!1,error:(await s.json()).error}}catch{return{success:!1,error:"Network error"}}};function jb(e){let r=null;function i(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return i}let El=[];const cr=Yn()((e,r)=>{function i(){if(El.length===0)return;const c=El;El=[],e(u=>({logs:[...u.logs,...c]}))}const s=jb(i);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:f,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:f.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const f=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:f,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const f=c.payload;if(f.workdir!==u)return;El.push({stream:f.stream,content:f.content}),s();break}case"devServer.state":{const f=c.payload;if(f.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:f.state,errorMessage:f.errorMessage}:l.status}));break}}}}});function I1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function Mx(e,r,i){const s=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok){const c=await s.json();throw new Error(c.error??"Failed to update model")}return s.json()}function Ix(e,r,i,s){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===i?{...u,...s,source:"user"}:u)}:c)}const B1=3e4;function z1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const At=Yn((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const i=await ke("/api/config");if(!i.ok)throw new Error("Failed to fetch config");const s=await i.json();e({version:s.version,model:s.model,maxContext:s.maxContext,llmUrl:s.llmUrl,llmStatus:s.llmStatus,backend:s.backend,providers:s.providers??[],activeProviderId:s.activeProviderId??null,defaultModelSelection:s.defaultModelSelection??null,loading:!1})}catch(i){e({error:i instanceof Error?i.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const i=await ke("/api/model/refresh",{method:"POST"});if(!i.ok)throw new Error("Failed to refresh model");const s=await i.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:s.llmStatus,backend:s.backend});return}e({model:s.model,llmStatus:s.llmStatus,backend:s.backend})}catch(i){console.error("Failed to refresh model:",i)}},activateProvider:async i=>{const{activeProviderId:s,providers:c}=r();if(i===s)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${i}/activate`,{method:"POST"});if(!u.ok){const l=await u.json();throw new Error(l.error??"Failed to activate provider")}const f=await u.json();return e({activeProviderId:f.activeProviderId,model:f.model,backend:f.backend,providers:c.map(l=>({...l,isActive:l.id===f.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(i,s)=>{const{providers:c}=r();e({activeProviderId:i,model:s,defaultModelSelection:`${i}/${s}`,providers:c.map(u=>({...u,isActive:u.id===i}))})},updateModelContext:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,{contextWindow:c}),{providers:f}=r();return e({providers:Ix(f,i,s,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(i,s,c)=>{e({activating:!0,error:null});try{const u=await Mx(i,s,c),{providers:f}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...I1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0})};return e({providers:Ix(f,i,s,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async i=>{e({activating:!0,error:null});try{const s=await ke(`/api/providers/${i}/refresh`,{method:"POST"});if(!s.ok){const f=await s.json();throw new Error(f.error??"Failed to refresh models")}const c=await s.json(),{providers:u}=r();return e({providers:u.map(f=>f.id===i?{...f,models:c.models}:f),activating:!1}),!0}catch(s){return e({error:s instanceof Error?s.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:i,refreshModel:s}=r();if(i)return;const c=setInterval(()=>{s()},B1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:i}=r();i&&(clearInterval(i),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:i,activeProviderId:s}=r();return i.find(c=>c.id===s)},getModelContext:i=>{const{providers:s,activeProviderId:c}=r(),u=s.find(l=>l.id===c);if(!u)return 2e5;const f=u.models.find(l=>l.id===i);return(f==null?void 0:f.contextWindow)??2e5}})),Vt=Yn((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const s=await(await ke("/api/projects")).json();e({projects:s.projects??[],loading:!1})}catch{e({loading:!1})}},createProject:async(i,s)=>{try{const c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:s})});if(!c.ok)return null;const u=await c.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async i=>{try{const s=await ke(`/api/projects/${i}`);if(!s.ok)return null;const c=await s.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(i,s)=>{var c;try{const u=await ke(`/api/projects/${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)return null;const f=await u.json();return((c=r().currentProject)==null?void 0:c.id)===i&&e({currentProject:f.project}),await r().listProjects(),f.project}catch{return null}},deleteProject:async i=>{var s;try{return(await ke(`/api/projects/${i}`,{method:"DELETE"})).ok?(await r().listProjects(),((s=r().currentProject)==null?void 0:s.id)===i&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let jl=[];const Va=Yn()((e,r)=>{function i(){if(jl.length===0)return;const c=jl;jl=[],e(u=>{const f={...u.logs};for(const l of c){const d=f[l.processId]??[];f[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:f}})}const s=jb(i);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(f=>({processes:f.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(f=>f.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([f])=>f!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,f)=>{jl.push({processId:c,stream:u,content:f}),s()},setLogs:(c,u)=>e(f=>({logs:{...f.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:f,name:l,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:f,sessionId:"",name:l,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const f=u.processId,l=u.stream,d=u.content;r().appendLog(f,l,d);break}case"backgroundProcess.exited":{const f=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===f?{...p,status:"exited",exitCode:l}:p)}));break}case"backgroundProcess.removed":{const f=u.processId;r().removeProcess(f);break}}}}}),Et={GLOBAL_INSTRUCTIONS:"global_instructions",NOTIFICATION_SETTINGS:"notification_settings",DISPLAY_SHOW_THINKING:"display.showThinking",DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT:"display.showVerboseToolOutput",DISPLAY_SHOW_STATS:"display.showStats",DISPLAY_SHOW_AGENT_DEFINITIONS:"display.showAgentDefinitions",DISPLAY_SHOW_WORKFLOW_BARS:"display.showWorkflowBars"};function Nl(e,r){return i=>({loading:{...i.loading,[e]:r}})}function Bx(e,r){return i=>({settings:{...i.settings,[e]:r},loading:{...i.loading,[e]:!1}})}const H1=[Et.DISPLAY_SHOW_THINKING,Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,Et.DISPLAY_SHOW_STATS,Et.DISPLAY_SHOW_AGENT_DEFINITIONS,Et.DISPLAY_SHOW_WORKFLOW_BARS];function Nb(){return{showThinking:en(e=>e.settings[Et.DISPLAY_SHOW_THINKING]??"true")==="true",showVerboseToolOutput:en(e=>e.settings[Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT]??"true")==="true",showStats:en(e=>e.settings[Et.DISPLAY_SHOW_STATS]??"true")==="true",showAgentDefinitions:en(e=>e.settings[Et.DISPLAY_SHOW_AGENT_DEFINITIONS]??"true")==="true",showWorkflowBars:en(e=>e.settings[Et.DISPLAY_SHOW_WORKFLOW_BARS]??"true")==="true"}}const en=Yn(e=>({settings:{},loading:{},getSetting:async r=>{e(Nl(r,!0));try{const s=await(await ke(`/api/settings/${r}`)).json();return e(Bx(r,s.value??"")),s.value}catch{return e(Nl(r,!1)),null}},setSetting:async(r,i)=>{e(Nl(r,!0));try{const c=await(await ke(`/api/settings/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:i})})).json();e(Bx(r,c.value??""))}catch{e(Nl(r,!1))}}})),P1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],F1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Tb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ci={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},Ab={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ch={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ci},waiting_for_user:{...ci},phase_done:{...ci},phase_blocked:{...ci},new_message:{...Ab}},agentOverrides:{}};function Db(e,r,i){var u;const s=e.events[r];if(!i)return s;const c=(u=e.agentOverrides[i])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??s.soundEnabled,browserNotification:c.browserNotification??s.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:s.customSoundUrl}:s}const Oi=Yn((e,r)=>({settings:ch,loaded:!1,load:()=>{en.getState().getSetting(Et.NOTIFICATION_SETTINGS);const s=en.subscribe(u=>{const f=u.settings[Et.NOTIFICATION_SETTINGS];if(f!==void 0)try{const l=JSON.parse(f);e({settings:zx(l),loaded:!0})}catch{e({loaded:!0})}}),c=en.getState().settings[Et.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:zx(u),loaded:!0})}catch{e({loaded:!0})}return s},update:i=>{e({settings:i}),Id(i)},updateEvent:(i,s)=>{const c=r().settings,u={...c,events:{...c.events,[i]:{...c.events[i],...s}}};e({settings:u}),Id(u)},updateAgentOverride:(i,s,c)=>{var d;const u=r().settings,f={...u.agentOverrides};if(c===null){if(f[i]){const p={...f[i]};delete p[s],Object.keys(p).length===0?delete f[i]:f[i]=p}}else f[i]={...f[i],[s]:{...((d=f[i])==null?void 0:d[s])??{},...c}};const l={...u,agentOverrides:f};e({settings:l}),Id(l)}}));function Id(e){en.getState().setSetting(Et.NOTIFICATION_SETTINGS,JSON.stringify(e))}function zx(e){var r,i,s,c,u;return{soundEnabled:e.soundEnabled??ch.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ch.browserNotificationEnabled,events:{complete:{...ci,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ci,...(i=e.events)==null?void 0:i.waiting_for_user},phase_done:{...ci,...(s=e.events)==null?void 0:s.phase_done},phase_blocked:{...ci,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Ab,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Hx=new Map;function U1(e){let r=Hx.get(e);return r||(r=new Audio(e),r.volume=.5,Hx.set(e,r)),r}let Rb=typeof Notification<"u"?Notification.permission:"denied";function $1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Rb=e,e))}const q1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},W1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function G1(e){typeof Notification>"u"||Rb==="granted"&&(document.hasFocus()||new Notification(q1[e],{body:W1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function oo(e,r){const{settings:i}=Oi.getState(),s=Db(i,e,r);if(i.soundEnabled&&s.soundEnabled){const c=s.customSoundUrl??Tb[e],u=U1(c);u.currentTime=0,u.play().catch(()=>{})}i.browserNotificationEnabled&&s.browserNotification&&G1(e)}const V1=e=>oo("complete",e),K1=e=>oo("phase_done",e),Y1=e=>oo("phase_blocked",e),Px=e=>oo("waiting_for_user",e),X1=e=>oo("new_message",e);let Ma=!1,or=null;const Bd=new Set,$t={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ms=null,un=null;function zd(){Ms===null&&(Ms=requestAnimationFrame(()=>{Ms=null,un==null||un()}))}function Ai(){Ms!==null&&(cancelAnimationFrame(Ms),Ms=null)}function zt(e,r){return r!==null&&e.sessionId===r}function Z1(e,r,i){return e.id!==void 0||zt(e,r)||i===!0&&e.sessionId!==void 0}function Q1(e,r){return e.includes(r)?e:[...e,r]}function Ia(e,r){return e.filter(i=>i!==r)}function J1(e,r){const i=e.find(c=>c.id===r.id),s=i?{...i,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return i?e.map(c=>c.id===r.id?s:c):[s,...e]}function ew(e,r,i){return e.map(s=>{const c=(i==null?void 0:i.id)===s.id?i:null,u=r.find(f=>f.id===s.id);return{...s,title:s.title??(u==null?void 0:u.title),mode:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??s.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??s.phase,isRunning:(c==null?void 0:c.isRunning)??(u==null?void 0:u.isRunning)??s.isRunning,messageCount:s.messageCount,recentUserPrompts:s.recentUserPrompts}})}const Fx=new Map;function Wa(e,r){var u;const i=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,s=e.sessions.find(f=>f.id===r),c=(i==null?void 0:i.mode)??(s==null?void 0:s.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function tw(e,r){if(e.type==="chat.done"){const i=e.payload,s=Wa(r,e.sessionId),c=i.agentType??s;i.reason==="complete"&&V1(c),i.reason==="waiting_for_user"&&Px(c);return}if(e.type==="chat.path_confirmation"){const i=Wa(r,e.sessionId);Px(i);return}if(e.type==="task.completed"){const i=Wa(r,e.sessionId);K1(i);return}if(e.type==="phase.changed"&&e.sessionId){const i=e.payload,s=Fx.get(e.sessionId)??null;if(Fx.set(e.sessionId,i.phase),s===i.phase)return;const c=Wa(r,e.sessionId);i.phase==="blocked"&&Y1(c)}}const Ce=Yn((e,r)=>(un=()=>{const i=$t;if(!i.messageId)return;const s=i.deltaContent.length>0,c=i.thinkingContent.length>0,u=i.toolOutput.length>0;if(!s&&!c&&!u)return;const f=i.deltaContent,l=i.thinkingContent,d=i.toolOutput;i.deltaContent="",i.thinkingContent="",i.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===i.messageId){let b={...g};if(s&&(b.content=b.content+f),c&&(b.thinkingContent=(b.thinkingContent??"")+l),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(x=>x.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(x=>({stream:x.stream,content:x.content}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&$t.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var x;if(C.id!==i.messageId)return C;const y=(x=C.toolCalls)==null?void 0:x.map(v=>{const S=d.filter(j=>j.callId===v.id);return S.length===0?v:(b.add(v.id),{...v,streamingOutput:[...v.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&$t.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let s=!1;try{s=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(s&&!qt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}qt.onStatusChange(c=>{e({connectionStatus:c}),c==="connected"&&r().listSessions(void 0)});try{if(await qt.connect(),!Ma){Ma=!0;const c=r().handleServerMessage;or=qt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=qt.getLastCloseCode();if(!qt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{qt.disconnect(),or&&(or(),or=null),Ma=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async i=>{try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})});if(!s.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:c}=await s.json();qt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Vt.getState(),{fetchConfig:f}=At.getState();u(),f(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{qt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(i,s)=>{try{e({pendingSessionCreate:!0});const c=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:i,title:s})});if(!c.ok)return e({pendingSessionCreate:!1}),null;const u=await c.json();return qt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async i=>{try{const s=r().currentSession;!s||s.id!==i?(Ai(),e({currentSession:null,unreadSessionIds:Ia(r().unreadSessionIds,i),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:Ia(r().unreadSessionIds,i)});const c=await ke(`/api/sessions/${i}`);if(!c.ok)return;const u=await c.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),qt.send("session.load",{sessionId:i});try{const f=await ke(`/api/sessions/${i}/background-processes`);if(f.ok){const l=await f.json();Va.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(i,s=20)=>{try{const c=new URLSearchParams;c.set("limit",String(s)),i&&c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e({sessions:f.sessions??[],sessionsHasMore:i?f.hasMore??!1:!0})}catch{}},loadMoreSessions:async i=>{const s=r();if(!(s.sessionsPaginationLoading||!s.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(s.sessions.length)),c.set("projectId",i);const f=await(await ke(`/api/sessions?${c.toString()}`)).json();e(l=>({sessions:[...l.sessions,...f.sessions??[]],sessionsHasMore:f.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async i=>{var s;try{return(await ke(`/api/sessions/${i}`,{method:"DELETE"})).ok?(await r().listSessions(),((s=r().currentSession)==null?void 0:s.id)===i&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async i=>{try{return(await ke(`/api/projects/${i}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Ai(),e(i=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:i.currentSession?Ia(i.unreadSessionIds,i.currentSession.id):i.unreadSessionIds}))},sendMessage:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},stopGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i&&!r().abortInProgress){Ai(),un==null||un(),e({abortInProgress:!0});try{await ke(`/api/sessions/${i}/stop`,{method:"POST"})}catch(c){console.error("Error stopping generation:",c)}}},continueGeneration:async()=>{var s;const i=(s=r().currentSession)==null?void 0:s.id;if(i){e({streamingMessageId:null});try{await ke(`/api/sessions/${i}/continue`,{method:"POST"})}catch(c){console.error("Error continuing generation:",c)}}},launchRunner:(i,s,c)=>{e({streamingMessageId:null});const u={};i!=null&&i.trim()&&(u.content=i),s&&s.length>0&&(u.attachments=s),c&&(u.workflowId=c),qt.send("runner.launch",u)},switchMode:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:i})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:i})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const f=await u.json();f.session&&e({currentSession:f.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(i,s,c)=>{e({streamingMessageId:null});const u={};i&&(u.workflowId=i),s!=null&&s.trim()&&(u.content=s),c&&c.length>0&&(u.attachments=c),qt.send("mode.accept",u)},editCriteria:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const u=await ke(`/api/sessions/${s}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:i})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{qt.send("context.compact",{})},setSessionProvider:async(i,s)=>{var c;try{const u=(c=r().currentSession)==null?void 0:c.id;if(!u)return null;const f=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:i,...s?{model:s}:{}})});if(!f.ok)return null;const l=await f.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:i=>{e({contextState:i})},updateSubAgentContextState:(i,s)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[i]:s}}))},clearSubAgentContextState:i=>{e(s=>{const c={...s.subAgentContextStates};return delete c[i],{subAgentContextStates:c}})},confirmPath:async(i,s,c=!1)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,approved:s,alwaysAllow:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(i,s)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:i,answer:s})})}catch(f){console.error("Error answering question:",f)}e({pendingQuestion:null})}},queueAsap:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(i,s,c)=>{var f;const u=(f=r().currentSession)==null?void 0:f.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,attachments:s,messageKind:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async i=>{var c;const s=(c=r().currentSession)==null?void 0:c.id;if(s)try{const f=await(await ke(`/api/sessions/${s}/queue/${i}`,{method:"DELETE"})).json();f.queueState&&e({queuedMessages:f.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:i=>{var f,l,d,p,g,m,b,_,k,C,y,x,v,S,j,T,N,D,A,M,B,$,V,W;const s=r();tw(i,s);const c=((f=s.currentSession)==null?void 0:f.id)??null,u=()=>{const O=i.sessionId;!O||O===c||e(F=>({unreadSessionIds:Q1(F.unreadSessionIds,O)}))};switch(i.type){case"session.state":{const O=i.payload;if(!Z1(i,c,s.pendingSessionCreate))break;Ai();const F=O.messages.find(R=>R.isStreaming)??null,P=r().pendingSessionCreate===!0,Z=O.pendingConfirmations??[],I=s.pendingPathConfirmation??(Z.length>0?Z[0]??null:null);if(e({currentSession:O.session,sessions:J1(r().sessions,O.session),unreadSessionIds:Ia(r().unreadSessionIds,O.session.id),messages:O.messages,streamingMessageId:(F==null?void 0:F.id)??null,streamingMessage:F,currentTodos:[],pendingPathConfirmation:I,error:null,...P?{pendingSessionCreate:O.session.id}:{}}),O.session.providerId&&O.session.providerModel){const R=At.getState();R.providers.find(Y=>Y.id===O.session.providerId)&&R.syncFromSession(O.session.providerId,O.session.providerModel)}break}case"session.list":{const O=i.payload;e(F=>({sessions:ew(O.sessions,F.sessions,F.currentSession)}));break}case"session.deleted":{const O=i.payload;e(F=>({unreadSessionIds:Ia(F.unreadSessionIds,O.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const O=i.payload,F=i.sessionId,P=(l=r().currentSession)==null?void 0:l.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,isRunning:O.isRunning}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,isRunning:O.isRunning}:null,...O.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!zt(i,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const O=i.payload;e(F=>F.messages.some(P=>P.id===O.message.id)?F:{messages:[...F.messages,O.message],streamingMessageId:O.message.isStreaming?O.message.id:F.streamingMessageId,streamingMessage:O.message.isStreaming?O.message:F.streamingMessage});break}case"chat.message_updated":{if(!zt(i,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const O=i.payload,F=O.updates.isStreaming===!1&&r().streamingMessageId===O.messageId;F&&(Ai(),un==null||un()),e(P=>{const Z=P.streamingMessage,G=F;if(Z&&Z.id===O.messageId){const I={...Z,...O.updates};return{messages:P.messages.map(R=>R.id===O.messageId?I:R),streamingMessageId:G?null:P.streamingMessageId,streamingMessage:G?null:{...Z,...O.updates}}}return{messages:P.messages.map(I=>I.id===O.messageId?{...I,...O.updates}:I),streamingMessageId:G?null:P.streamingMessageId}});break}case"chat.delta":{if(!zt(i,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const O=i.payload;if(!Bd.has(O.messageId)){Bd.add(O.messageId);const F=Wa(r(),i.sessionId);X1(F)}$t.messageId=O.messageId,$t.deltaContent+=O.content,zd();break}case"chat.thinking":{if(!zt(i,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.thinkingContent+=O.content,zd();break}case"chat.tool_preparing":{if(!zt(i,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const O=i.payload;e(F=>{const P=F.streamingMessage;return P&&P.id===O.messageId?{streamingMessage:{...P,preparingToolCalls:[...P.preparingToolCalls??[],{index:O.index,name:O.name}]}}:{messages:F.messages.map(Z=>Z.id===O.messageId?{...Z,preparingToolCalls:[...Z.preparingToolCalls??[],{index:O.index,name:O.name}]}:Z)}});break}case"chat.tool_call":{if(!zt(i,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const O=i.payload,F=P=>{var I;const Z=(I=P.preparingToolCalls)==null?void 0:I.filter((R,z)=>{var Y;return R.name===O.tool?(Y=P.preparingToolCalls)==null?void 0:Y.slice(0,z).some(ie=>ie.name===O.tool):!0}),G=$t.toolOutput.filter(R=>R.callId===O.callId);return G.length>0&&($t.toolOutput=$t.toolOutput.filter(R=>R.callId!==O.callId)),{...P,toolCalls:[...P.toolCalls??[],{id:O.callId,name:O.tool,arguments:O.args,startedAt:Date.now(),...G.length>0?{streamingOutput:G.map(R=>({stream:R.stream,content:R.content}))}:{}}],...Z&&Z.length>0?{preparingToolCalls:Z}:{preparingToolCalls:void 0}}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.tool_output":{if(!zt(i,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const O=i.payload;$t.messageId=O.messageId,$t.toolOutput.push({messageId:O.messageId,callId:O.callId,stream:O.stream,content:O.output}),zd();break}case"chat.tool_result":{if(!zt(i,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const O=i.payload,F=P=>{var G;const Z=(G=P.toolCalls)==null?void 0:G.map(I=>I.id===O.callId?{...I,result:O.result}:I);return{...P,toolCalls:Z}};e(P=>{const Z=P.streamingMessage;return Z&&Z.id===O.messageId?{streamingMessage:F(Z)}:{messages:P.messages.map(G=>G.id===O.messageId?F(G):G)}});break}case"chat.vision_fallback":{if(!zt(i,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const O=i.payload;e(F=>{const P=`${O.messageId}-${O.attachmentId}`,Z={...F.visionFallbackByMessage};return Z[P]={type:O.type,attachmentId:O.attachmentId,filename:O.filename,description:O.description},{visionFallbackByMessage:Z}});break}case"chat.todo":{if(!zt(i,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const O=i.payload;e({currentTodos:O.todos});break}case"chat.summary":{if(!zt(i,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,summary:O.summary}:null}));break}case"chat.progress":{if(!zt(i,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const O=i.payload;console.log("Progress:",O.message,O.phase);break}case"chat.format_retry":{if(!zt(i,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const O=i.payload;console.log("Format retry:",O.attempt,"/",O.maxAttempts);break}case"chat.done":{if(!zt(i,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Ai(),un==null||un();const O=i.payload,F=O.stats;$t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[],Bd.delete(O.messageId),e(P=>{const Z=P.streamingMessage,G=Z&&Z.id===O.messageId?{...Z,isStreaming:!1,stats:F??Z.stats}:null;return{messages:P.messages.map(I=>I.id===O.messageId?G??{...I,isStreaming:!1,stats:F??I.stats}:I),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!zt(i,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Ai(),un==null||un();const O=i.payload;console.error("Chat error:",O.error,"recoverable:",O.recoverable),O.recoverable||($t.messageId=null,$t.deltaContent="",$t.thinkingContent="",$t.toolOutput=[]),e(F=>({error:{code:"CHAT_ERROR",message:O.error},streamingMessageId:O.recoverable?F.streamingMessageId:null,...O.recoverable?{}:{messages:F.streamingMessage?F.messages.map(P=>P.id===F.streamingMessage.id?F.streamingMessage:P):F.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!zt(i,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const O=i.payload;e({pendingPathConfirmation:{callId:O.callId,tool:O.tool,paths:O.paths,workdir:O.workdir,reason:O.reason}});break}case"chat.ask_user":{if(!zt(i,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const O=i.payload;e({pendingQuestion:{callId:O.callId,question:O.question}});break}case"mode.changed":{if(!zt(i,((M=r().currentSession)==null?void 0:M.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,mode:O.mode}:null}));break}case"phase.changed":{const O=i.payload,F=i.sessionId,P=(B=r().currentSession)==null?void 0:B.id,Z=F&&F!==P;e(G=>({sessions:G.sessions.map(I=>I.id===F?{...I,phase:O.phase}:I)})),Z||e(G=>({currentSession:G.currentSession?{...G.currentSession,phase:O.phase}:null}));break}case"criteria.updated":{if(!zt(i,(($=r().currentSession)==null?void 0:$.id)??null)){u();break}const O=i.payload;e(F=>({currentSession:F.currentSession?{...F.currentSession,criteria:O.criteria}:null}));break}case"context.state":{const O=i.payload,F=zt(i,((V=r().currentSession)==null?void 0:V.id)??null);O.subAgentId?F&&r().updateSubAgentContextState(O.subAgentId,O.context):F?e({contextState:O.context}):u();break}case"session.name_generated":{const O=i.payload,F=i.sessionId,P=(W=r().currentSession)==null?void 0:W.id;e(Z=>{const G=Z.sessions.map(R=>R.id===F?{...R,title:O.name,updatedAt:new Date().toISOString()}:R),I=P===F?Z.currentSession?{...Z.currentSession,title:O.name,updatedAt:new Date().toISOString()}:null:Z.currentSession;return{sessions:G,currentSession:I}});break}case"queue.state":{const O=i.payload;e({queuedMessages:O.messages});break}case"devServer.output":case"devServer.state":{cr.getState().handleMessage(i);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{Va.getState().handleMessage(i.type,i.payload);break}case"error":{const O=i.payload;console.error("Server error:",O),e({error:{code:O.code,message:O.message},streamingMessageId:null});break}}}}));function Lb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function nw(){return Ce(e=>e.queuedMessages)}function rw(){return Ce(e=>e.abortInProgress)}function iw(){const e=Ce(s=>s.connect),r=Ce(s=>s.connectionStatus),i=Oi(s=>s.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&i()},[r,i]),{connectionStatus:r}}function sw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function Ob({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function aw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function ow({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Mr({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function ur({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function Jl({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function uw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Dh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function ec({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function Fl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function hw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function fw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function pw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function mw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Ux({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function gw({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function vw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Mb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Ib({className:e="",size:r="md"}){const i=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${i} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Bb=Ib,zb=Ib;function bw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function _w({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Sw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Cw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function kw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Hb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Ew({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Pb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Nw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function uh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function $x(e,r){const i=qt.ws;!i||i.readyState!==WebSocket.OPEN||i.send(JSON.stringify({id:uh(),type:e,payload:r}))}const Jn=Yn((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:i=>e({isOpen:i}),toggleOpen:()=>e(i=>({isOpen:!i.isOpen})),setWorkdir:i=>e({workdir:i}),fetchSessions:async()=>{try{const i=await ke("/api/terminals");if(i.ok){const s=await i.json();e({sessions:s});const c=qt.ws;if(c&&c.readyState===WebSocket.OPEN)for(const u of s)c.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async i=>{try{const s=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:i??r().workdir??void 0})});if(s.ok){const c=await s.json();e(f=>({sessions:[...f.sessions,c]}));const u=qt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:uh(),type:"terminal.subscribe",payload:{sessionId:c.id}}))}}catch(s){console.error("Failed to create terminal:",s)}},writeSession:(i,s)=>{$x("terminal.write",{sessionId:i,data:s})},resizeSession:(i,s,c)=>{$x("terminal.resize",{sessionId:i,cols:s,rows:c})},killSession:async i=>{try{(await ke(`/api/terminals/${i}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.sessions.filter(u=>u.id!==i)}))}catch(s){console.error("Failed to kill terminal:",s)}},handleMessage:i=>{switch(i.type){case"terminal.exit":{const{sessionId:s}=i.payload||{};s&&e(c=>{const u=c.sessions.filter(f=>f.id!==s);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));qt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&Jn.getState().handleMessage(e)});var tc=xb();const nc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:i="",...s},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${i}`,...s,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));nc.displayName="IconButton";const Tw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",Hs=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Tw,title:"Edit",...e}));Hs.displayName="EditButton";const Aw="M6 18L18 6M6 6l12 12",Rh=H.forwardRef((e,r)=>o.jsx(nc,{ref:r,icon:Aw,...e}));Rh.displayName="CloseButton";const Dw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:i="md",minHeight:s,children:c,footer:u,className:f,onClose:l,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),x=H.useCallback(()=>{k||_(!1),l==null||l()},[k,l]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,x,g]);const v=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:f,children:e}):o.jsx("span",{onClick:y,className:f,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[v,C&&(typeof document<"u"?tc.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?x:void 0}),o.jsxs("div",{className:`relative w-full ${Dw[i]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Rh,{onClick:x,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:s?{minHeight:s}:void 0,children:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const it=H.forwardRef(({variant:e="secondary",size:r="md",className:i="",children:s,...c},u)=>{const f="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={primary:"bg-accent-primary/25 text-white hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${f} ${l[e]} ${d[r]} ${i}`,...c,children:s})});it.displayName="Button";function Rw({value:e,defaultUrl:r,disabled:i,onChange:s}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,disabled:i,onChange:u=>{const f=u.target.value;s(f===r?null:f)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:F1.map(({url:u,label:f})=>o.jsx("option",{value:u,title:f,children:f.split(" ")[0]},u))}),o.jsx(ur,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const qx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Lw(){const e=Oi(d=>d.settings),r=Oi(d=>d.update),i=Oi(d=>d.updateEvent),s=Oi(d=>d.updateAgentOverride),c=Oi(d=>d.load);H.useEffect(()=>{c()},[c]);const u=async()=>{await $1()==="granted"&&r({...e,browserNotificationEnabled:!0})},f=(d,p,g,m)=>{d==="general"?i(p,{[g]:m}):s(d,p,{[g]:m})},l=(d,p,g)=>{d==="general"?i(p,{customSoundUrl:g}):s(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(Wx,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(Wx,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),qx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:P1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),qx.map(p=>{const g=Db(e,d.key,p.key==="general"?void 0:p.key),m=Tb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>f(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>f(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Rw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>l(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function Wx({label:e,description:r,checked:i,onChange:s}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${i?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:c=>{c.preventDefault(),s(!i)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${i?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Lh(e,r){r({loading:!0});try{const s=await(await ke(e)).json();r({defaults:s.defaults??[],userItems:s.userItems??[],loading:!1})}catch{r({loading:!1})}}const Rr=Yn((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Lh("/api/skills",e)},toggleSkill:async i=>{try{const c=await(await ke(`/api/skills/${i}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(f=>f.id===i?{...f,enabled:c.enabled}:f),userItems:u.userItems.map(f=>f.id===i?{...f,enabled:c.enabled}:f)}))}catch{}},fetchSkill:async i=>{try{const s=await ke(`/api/skills/${i}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async i=>{try{const s=await ke(`/api/skills/defaults/${i}`);return s.ok?await s.json():null}catch{return null}},createSkill:async i=>{const s=await di("POST","/api/skills",i);return s.success&&await r().fetchSkills(),s},updateSkill:async(i,s)=>{const c=await di("PUT",`/api/skills/${i}`,s);return c.success&&await r().fetchSkills(),c},deleteSkill:async i=>{try{const s=await ke(`/api/skills/${i}`,{method:"DELETE"}),c=await s.json();return s.ok?(e(u=>({userItems:u.userItems.filter(f=>f.id!==i)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async i=>{try{const s=await ke(`/api/skills/${i}/duplicate`,{method:"POST"}),c=await s.json();return s.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Oh(){const[e,r]=H.useState({id:null,type:null}),i=H.useCallback(u=>r({id:u,type:"delete"}),[]),s=H.useCallback(()=>r({id:null,type:null}),[]),c=H.useCallback((u,f)=>e.id===u&&e.type===f,[e.id,e.type]);return{requestDelete:i,clearConfirm:s,isConfirming:c}}function Mh({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function Ih({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Hb,{})})}function Qa({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(Jl,{})})}function Mi({label:e,value:r,onChange:i,placeholder:s,readOnly:c,hint:u,mono:f}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:l=>i(l.target.value),readOnly:c,placeholder:s,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"font-mono":""} ${c?"opacity-60":""}`})]})}function Ow({onCancel:e,onSave:r,saving:i,saveDisabled:s}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(it,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(it,{variant:"primary",onClick:r,disabled:i||s,children:i?"Saving...":"Save"})]})}function Bh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Fb({description:e,onNew:r,newLabel:i="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(it,{variant:"primary",size:"sm",onClick:r,children:i})})]})}function Ub({isBuiltIn:e,isConfirmingDelete:r,onView:i,onEdit:s,onDuplicate:c,onDelete:u,children:f}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:f}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&i&&o.jsx("button",{onClick:i,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(ec,{})}),o.jsx(Qa,{onClick:c}),!e&&s&&o.jsx(Hs,{onClick:s}),!e&&(r?o.jsx(Mh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Ih,{onClick:()=>u==null?void 0:u()}))]})]})}function Mw({id:e,name:r,description:i,isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d}){return o.jsxs(Ub,{isBuiltIn:s,isConfirmingDelete:c,onView:u,onEdit:f,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),i&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:i})]})}function $b({loading:e,hasItems:r,loadingLabel:i,emptyLabel:s,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:i}):r?o.jsx("div",{className:"space-y-4",children:c}):s?o.jsx("div",{className:"text-text-muted text-sm",children:s}):null}function qb({name:e,id:r,nameLabel:i="Name",idLabel:s="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:f,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:i,value:e,onChange:p,placeholder:c,hint:f}),o.jsx(Mi,{label:s,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Wb(e={}){const{initialData:r={}}=e,[i,s]=H.useState("list"),[c,u]=H.useState(null),[f,l]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),l(""),u(null)},[r]),_=H.useCallback(x=>{s(x),x==="list"&&b()},[b]),k=H.useCallback(x=>{m(v=>typeof x=="function"?x(v):x)},[]),C=H.useCallback((x,v={})=>{u(x),s("edit"),m({...v}),l("")},[]),y=H.useCallback(()=>{u(null),s("edit"),m(r),l("")},[r]);return{view:i,editingId:c,formError:f,saving:d,formData:g,setView:_,setEditingId:u,setFormError:l,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function zh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function Gx({skill:e,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f}){return o.jsx(Mw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:i,onView:s,onEdit:c,onDuplicate:u,onDelete:f})}function Iw({isOpen:e}){const r=Rr(O=>O.defaults),i=Rr(O=>O.userItems),s=Rr(O=>O.loading),c=Rr(O=>O.fetchSkills),u=Rr(O=>O.fetchSkill),f=Rr(O=>O.fetchDefaultContent),l=Rr(O=>O.createSkill),d=Rr(O=>O.updateSkill),p=Rr(O=>O.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:x,setFormData:v,setSaving:S}=Wb(),{clearConfirm:j}=Oh();H.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const T=(O,F,P,Z)=>{v({name:Z??O.metadata.name,id:P??O.metadata.id,description:O.metadata.description??"",version:O.metadata.version??"1.0.0",prompt:O.prompt,isReadOnly:F})},N=async O=>{if(r.some(P=>P.id===O)){const P=await f(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}else{const P=await u(O);if(!P)return;T(P,!0),y(O),x(""),C("edit")}},D=async O=>{const P=r.some(G=>G.id===O)?await f(O):await u(O);if(!P)return;const Z=`${O}-copy-${Date.now()}`;T(P,!1,Z,`${P.metadata.name} (copy)`),y(null),x(""),C("edit")},A=()=>{v({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},M=async O=>{const F=await u(O);F&&(T(F,!1),y(O),x(""),C("edit"))},B=async O=>{await p(O),j()},$=async()=>{const O=m??k.id;if(!O||!k.name||!k.prompt){x("Name, ID, and prompt are required.");return}S(!0),x("");const F={metadata:{id:O,name:k.name,description:k.description,version:k.version},prompt:k.prompt},P=m?await d(m,F):await l(F);if(S(!1),!P.success){x(P.error??"Failed to save skill.");return}C("list")},V=O=>{v(F=>({...F,name:O})),m||v(F=>({...F,id:O.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Bh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(qb,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:V,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Mi,{label:"Description",value:k.description,onChange:O=>v(F=>({...F,description:O})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Mi,{label:"Version",value:k.version,onChange:O=>v(F=>({...F,version:O})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:O=>v(F=>({...F,prompt:O.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(it,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(it,{variant:"primary",onClick:()=>{v(O=>({...O,name:O.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(it,{variant:"primary",onClick:$,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Fb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs($b,{loading:s,hasItems:r.length>0||i.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(O.id),onDuplicate:()=>D(O.id)},O.id))})]}),i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:i.map(O=>o.jsx(Gx,{skill:O,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(O.id),onEdit:()=>M(O.id),onDuplicate:()=>D(O.id),onDelete:()=>B(O.id)},O.id))})]})]})]})}function Bw({isOpen:e,onClose:r}){const[i,s]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(Ba,{label:"Instructions",active:i==="instructions",onClick:()=>s("instructions")}),o.jsx(Ba,{label:"Skills",active:i==="skills",onClick:()=>s("skills")}),o.jsx(Ba,{label:"Notifications",active:i==="notifications",onClick:()=>s("notifications")}),o.jsx(Ba,{label:"Display",active:i==="display",onClick:()=>s("display")}),o.jsx(Ba,{label:"Advanced",active:i==="advanced",onClick:()=>s("advanced")})]}),i==="instructions"&&o.jsx(Pw,{isOpen:e}),i==="skills"&&o.jsx(Iw,{isOpen:e}),i==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Lw,{})}),i==="display"&&o.jsx(Hw,{}),i==="advanced"&&o.jsx(zw,{onClose:r})]})})}function zw({onClose:e}){const[,r]=dr();function i(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(it,{variant:"secondary",onClick:i,children:"Launch Onboarding"})]})})}function Hw(){const e=en(g=>g.settings),r=en(g=>g.loading),i=en(g=>g.getSetting),s=en(g=>g.setSetting),c=r[Et.DISPLAY_SHOW_THINKING]??!1,u=[{key:Et.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:Et.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:Et.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:Et.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:Et.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],f=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[l,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>i(g.key))},[i]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,f[g.key]==="true"])))},[JSON.stringify(f)]);const p=async g=>{const m=String(!l[g]);d(b=>({...b,[g]:!b[g]})),await s(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})})}function Ba({label:e,active:r,onClick:i}){return o.jsx("button",{onClick:i,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Pw({isOpen:e}){const r=en(y=>y.settings),i=en(y=>y.loading),s=en(y=>y.getSetting),c=en(y=>y.setSetting),u=r[Et.GLOBAL_INSTRUCTIONS]??"",f=i[Et.GLOBAL_INSTRUCTIONS]??!1,[l,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&s(Et.GLOBAL_INSTRUCTIONS)},[e,s]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),c(Et.GLOBAL_INSTRUCTIONS,l),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=f||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(zh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(it,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(it,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var Hd={exports:{}},Vx;function Fw(){return Vx||(Vx=1,(function(e,r){(function(i,s){e.exports=s()})(globalThis,(()=>(()=>{var i={4567:function(f,l,d){var p=this&&this.__decorate||function(v,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(v,S,j,T);else for(var M=v.length-1;M>=0;M--)(N=v[M])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(v,S){return function(j,T){S(j,T,v)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let x=l.AccessibilityManager=class extends _.Disposable{constructor(v,S,j,T){super(),this._terminal=v,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
58
58
  `)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,_.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(v){for(let S=0;S<v;S++)this._handleChar(" ")}_handleChar(v){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==v&&(this._charsToAnnounce+=v):this._charsToAnnounce+=v,v===`
59
59
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(v){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(v)||this._charsToConsume.push(v)}_refreshRows(v,S){this._liveRegionDebouncer.refresh(v,S,this._terminal.rows)}_renderRows(v,S){const j=this._terminal.buffer,T=j.lines.length.toString();for(let N=v;N<=S;N++){const D=j.lines.get(j.ydisp+N),A=[],M=(D==null?void 0:D.translateToString(!0,void 0,void 0,A))||"",B=(j.ydisp+N+1).toString(),$=this._rowElements[N];$&&(M.length===0?($.innerText=" ",this._rowColumns.set($,[0,1])):($.textContent=M,this._rowColumns.set($,A)),$.setAttribute("aria-posinset",B),$.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(v,S){const j=v.target,T=this._rowElements[S===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||v.relatedTarget!==T)return;let N,D;if(S===0?(N=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(N=this._rowElements.shift(),D=j,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),v.preventDefault(),v.stopImmediatePropagation()}_handleSelectionChange(){var M;if(this._rowElements.length===0)return;const v=document.getSelection();if(!v)return;if(v.isCollapsed)return void(this._rowContainer.contains(v.anchorNode)&&this._terminal.clearSelection());if(!v.anchorNode||!v.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:v.anchorNode,offset:v.anchorOffset},j={node:v.focusNode,offset:v.focusOffset};if((S.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===j.node&&S.offset>j.offset)&&([S,j]=[j,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const T=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(T)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:T,offset:((M=T.textContent)==null?void 0:M.length)??0}),!this._rowContainer.contains(j.node))return;const N=({node:B,offset:$})=>{const V=B instanceof Text?B.parentNode:B;let W=parseInt(V==null?void 0:V.getAttribute("aria-posinset"),10)-1;if(isNaN(W))return console.warn("row is invalid. Race condition?"),null;const O=this._rowColumns.get(V);if(!O)return console.warn("columns is null. Race condition?"),null;let F=$<O.length?O[$]:O.slice(-1)[0]+1;return F>=this._terminal.cols&&(++W,F=0),{row:W,column:F}},D=N(S),A=N(j);if(D&&A){if(D.row>A.row||D.row===A.row&&D.column>=A.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(A.row-D.row)*this._terminal.cols-D.column+A.column)}}_handleResize(v){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>v;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const v=this._coreBrowserService.mainDocument.createElement("div");return v.setAttribute("role","listitem"),v.tabIndex=-1,this._refreshRowDimensions(v),v}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let v=0;v<this._terminal.rows;v++)this._refreshRowDimensions(this._rowElements[v])}}_refreshRowDimensions(v){v.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=x=p([g(1,C.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],x)},3614:(f,l)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function p(b,_){return _?"\x1B[200~"+b+"\x1B[201~":b}function g(b,_,k,C){b=p(b=d(b),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(b,!0),_.value=""}function m(b,_,k){const C=k.getBoundingClientRect(),y=b.clientX-C.left-10,x=b.clientY-C.top-10;_.style.width="20px",_.style.height="20px",_.style.left=`${y}px`,_.style.top=`${x}px`,_.style.zIndex="1000",_.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=d,l.bracketTextForPaste=p,l.copyHandler=function(b,_){b.clipboardData&&b.clipboardData.setData("text/plain",_.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,_,k,C){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),_,k,C)},l.paste=g,l.moveTextAreaUnderMouseCursor=m,l.rightClickHandler=function(b,_,k,C,y){m(b,_,k),y&&C.rightClickSelect(b),_.value=C.selectionText,_.select()}},7239:(f,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const p=d(1505);l.ColorContrastCache=class{constructor(){this._color=new p.TwoKeyMap,this._css=new p.TwoKeyMap}setCss(g,m,b){this._css.set(g,m,b)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,b){this._color.set(g,m,b)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(d,p,g,m){d.addEventListener(p,g,m);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(p,g,m))}}}},3551:function(f,l,d){var p=this&&this.__decorate||function(x,v,S,j){var T,N=arguments.length,D=N<3?v:j===null?j=Object.getOwnPropertyDescriptor(v,S):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(x,v,S,j);else for(var A=x.length-1;A>=0;A--)(T=x[A])&&(D=(N<3?T(D):N>3?T(v,S,D):T(v,S))||D);return N>3&&D&&Object.defineProperty(v,S,D),D},g=this&&this.__param||function(x,v){return function(S,j){v(S,j,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const m=d(3656),b=d(8460),_=d(844),k=d(2585),C=d(4725);let y=l.Linkifier=class extends _.Disposable{get currentLink(){return this._currentLink}constructor(x,v,S,j,T){super(),this._element=x,this._mouseService=v,this._renderService=S,this._bufferService=j,this._linkProviderService=T,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,_.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,_.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(x){this._lastMouseEvent=x;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);if(!v)return;this._isMouseOut=!1;const S=x.composedPath();for(let j=0;j<S.length;j++){const T=S[j];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&v.x===this._lastBufferCell.x&&v.y===this._lastBufferCell.y||(this._handleHover(v),this._lastBufferCell=v)}_handleHover(x){if(this._activeLine!==x.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(x,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,x)||(this._clearCurrentLink(),this._askForLink(x,!0))}_askForLink(x,v){var j,T;this._activeProviderReplies&&v||((j=this._activeProviderReplies)==null||j.forEach((N=>{N==null||N.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=x.y);let S=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())v?(T=this._activeProviderReplies)!=null&&T.get(N)&&(S=this._checkLinkProviderResult(N,x,S)):D.provideLinks(x.y,(A=>{var B,$;if(this._isMouseOut)return;const M=A==null?void 0:A.map((V=>({link:V})));(B=this._activeProviderReplies)==null||B.set(N,M),S=this._checkLinkProviderResult(N,x,S),(($=this._activeProviderReplies)==null?void 0:$.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(x.y,this._activeProviderReplies)}))}_removeIntersectingLinks(x,v){const S=new Set;for(let j=0;j<v.size;j++){const T=v.get(j);if(T)for(let N=0;N<T.length;N++){const D=T[N],A=D.link.range.start.y<x?0:D.link.range.start.x,M=D.link.range.end.y>x?this._bufferService.cols:D.link.range.end.x;for(let B=A;B<=M;B++){if(S.has(B)){T.splice(N--,1);break}S.add(B)}}}}_checkLinkProviderResult(x,v,S){var N;if(!this._activeProviderReplies)return S;const j=this._activeProviderReplies.get(x);let T=!1;for(let D=0;D<x;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(T=!0);if(!T&&j){const D=j.find((A=>this._linkAtPosition(A.link,v)));D&&(S=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let D=0;D<this._activeProviderReplies.size;D++){const A=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((M=>this._linkAtPosition(M.link,v)));if(A){S=!0,this._handleNewLink(A);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(x){if(!this._currentLink)return;const v=this._positionFromMouseEvent(x,this._element,this._mouseService);v&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,v)&&this._currentLink.link.activate(x,this._currentLink.link.text)}_clearCurrentLink(x,v){this._currentLink&&this._lastMouseEvent&&(!x||!v||this._currentLink.link.range.start.y>=x&&this._currentLink.link.range.end.y<=v)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,_.disposeArray)(this._linkCacheDisposables))}_handleNewLink(x){if(!this._lastMouseEvent)return;const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._linkAtPosition(x.link,v)&&(this._currentLink=x,this._currentLink.state={decorations:{underline:x.link.decorations===void 0||x.link.decorations.underline,pointerCursor:x.link.decorations===void 0||x.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,x.link,this._lastMouseEvent),x.link.decorations={},Object.defineProperties(x.link.decorations,{pointerCursor:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.pointerCursor},set:S=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.underline},set:S=>{var j,T,N;(j=this._currentLink)!=null&&j.state&&((N=(T=this._currentLink)==null?void 0:T.state)==null?void 0:N.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(x.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const j=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=T&&(this._clearCurrentLink(j,T),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!0),this._currentLink.state.decorations.pointerCursor&&x.classList.add("xterm-cursor-pointer")),v.hover&&v.hover(S,v.text)}_fireUnderlineEvent(x,v){const S=x.range,j=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-j-1,S.end.x,S.end.y-j-1,void 0);(v?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(x,v,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(v,!1),this._currentLink.state.decorations.pointerCursor&&x.classList.remove("xterm-cursor-pointer")),v.leave&&v.leave(S,v.text)}_linkAtPosition(x,v){const S=x.range.start.y*this._bufferService.cols+x.range.start.x,j=x.range.end.y*this._bufferService.cols+x.range.end.x,T=v.y*this._bufferService.cols+v.x;return S<=T&&T<=j}_positionFromMouseEvent(x,v,S){const j=S.getCoords(x,v,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(x,v,S,j,T){return{x1:x,y1:v,x2:S,y2:j,cols:this._bufferService.cols,fg:T}}};l.Linkifier=y=p([g(1,C.IMouseService),g(2,C.IRenderService),g(3,k.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(f,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(f,l,d){var p=this&&this.__decorate||function(C,y,x,v){var S,j=arguments.length,T=j<3?y:v===null?v=Object.getOwnPropertyDescriptor(y,x):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(C,y,x,v);else for(var N=C.length-1;N>=0;N--)(S=C[N])&&(T=(j<3?S(T):j>3?S(y,x,T):S(y,x))||T);return j>3&&T&&Object.defineProperty(y,x,T),T},g=this&&this.__param||function(C,y){return function(x,v){y(x,v,C)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const m=d(511),b=d(2585);let _=l.OscLinkProvider=class{constructor(C,y,x){this._bufferService=C,this._optionsService=y,this._oscLinkService=x}provideLinks(C,y){var M;const x=this._bufferService.buffer.lines.get(C-1);if(!x)return void y(void 0);const v=[],S=this._optionsService.rawOptions.linkHandler,j=new m.CellData,T=x.getTrimmedLength();let N=-1,D=-1,A=!1;for(let B=0;B<T;B++)if(D!==-1||x.hasContent(B)){if(x.loadCell(B,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=B,N=j.extended.urlId;continue}A=j.extended.urlId!==N}else D!==-1&&(A=!0);if(A||D!==-1&&B===T-1){const $=(M=this._oscLinkService.getLinkData(N))==null?void 0:M.uri;if($){const V={start:{x:D+1,y:C},end:{x:B+(A||B!==T-1?0:1),y:C}};let W=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const O=new URL($);["http:","https:"].includes(O.protocol)||(W=!0)}catch{W=!0}W||v.push({text:$,range:V,activate:(O,F)=>S?S.activate(O,F,V):k(0,F),hover:(O,F)=>{var P;return(P=S==null?void 0:S.hover)==null?void 0:P.call(S,O,F,V)},leave:(O,F)=>{var P;return(P=S==null?void 0:S.leave)==null?void 0:P.call(S,O,F,V)}})}A=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=B,N=j.extended.urlId):(D=-1,N=-1)}}y(v)}};function k(C,y){if(confirm(`Do you want to navigate to ${y}?
60
60
 
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/png" href="/assets/openfox.png" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height" />
7
7
  <title>OpenFox</title>
8
- <script type="module" crossorigin src="/assets/index-DH6wDW66.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-BOmvIO84.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-DTKU-xoU.css">
10
10
  <link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head>
11
11
  <body class="bg-bg-primary text-text-primary font-mono">
package/dist/web/sw.js CHANGED
@@ -1 +1 @@
1
- if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let o={};const l=e=>i(e,t),u={module:{uri:t},exports:o,require:l};s[t]=Promise.all(n.map(e=>u[e]||l(e))).then(e=>(r(...e),o))}}define(["./workbox-8c29f6e4"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"b8578c18ab89662a2106ff04f2645ee5"},{url:"assets/index-DTKU-xoU.css",revision:null},{url:"assets/index-DH6wDW66.js",revision:null},{url:"assets/html2canvas.esm-QH1iLAAe.js",revision:null},{url:"assets/openfox-192.png",revision:"79feeb86d692c274854e37959a7dae67"},{url:"assets/openfox-512.png",revision:"fee24b214220594b4f595a467e73036e"},{url:"manifest.webmanifest",revision:"c25f372c782e623ab1e768a8dfe350ca"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))});
1
+ if(!self.define){let e,s={};const i=(i,n)=>(i=new URL(i+".js",n).href,s[i]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=i,e.onload=s,document.head.appendChild(e)}else e=i,importScripts(i),s()}).then(()=>{let e=s[i];if(!e)throw new Error(`Module ${i} didn’t register its module`);return e}));self.define=(n,r)=>{const t=e||("document"in self?document.currentScript.src:"")||location.href;if(s[t])return;let o={};const l=e=>i(e,t),u={module:{uri:t},exports:o,require:l};s[t]=Promise.all(n.map(e=>u[e]||l(e))).then(e=>(r(...e),o))}}define(["./workbox-8c29f6e4"],function(e){"use strict";self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"index.html",revision:"8933f3ebb3f1d5b4d1a9b1fc8ae3b8db"},{url:"assets/index-DTKU-xoU.css",revision:null},{url:"assets/index-BOmvIO84.js",revision:null},{url:"assets/html2canvas.esm-QH1iLAAe.js",revision:null},{url:"assets/openfox-192.png",revision:"79feeb86d692c274854e37959a7dae67"},{url:"assets/openfox-512.png",revision:"fee24b214220594b4f595a467e73036e"},{url:"manifest.webmanifest",revision:"c25f372c782e623ab1e768a8dfe350ca"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html")))});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openfox",
3
- "version": "1.6.35",
3
+ "version": "1.6.36",
4
4
  "description": "Local-LLM-first agentic coding assistant",
5
5
  "type": "module",
6
6
  "bin": {