mycode-cli 0.15.0__py3-none-any.whl → 0.16.0__py3-none-any.whl
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.
- mycode_cli/config.py +16 -0
- mycode_cli/main.py +9 -8
- mycode_cli/runtime.py +1 -0
- mycode_cli/server/run_manager.py +23 -18
- mycode_cli/server/static/assets/{index-DzNDonIR.js → index-CT9f_Z06.js} +2 -2
- mycode_cli/server/static/index.html +1 -1
- mycode_cli/tui/chat.py +0 -1
- mycode_cli/tui/render.py +36 -31
- {mycode_cli-0.15.0.dist-info → mycode_cli-0.16.0.dist-info}/METADATA +2 -2
- {mycode_cli-0.15.0.dist-info → mycode_cli-0.16.0.dist-info}/RECORD +13 -13
- {mycode_cli-0.15.0.dist-info → mycode_cli-0.16.0.dist-info}/WHEEL +0 -0
- {mycode_cli-0.15.0.dist-info → mycode_cli-0.16.0.dist-info}/entry_points.txt +0 -0
- {mycode_cli-0.15.0.dist-info → mycode_cli-0.16.0.dist-info}/licenses/LICENSE +0 -0
mycode_cli/config.py
CHANGED
|
@@ -71,6 +71,9 @@ class ProviderConfig:
|
|
|
71
71
|
# Opt-in for generic openai_chat endpoints that accept the standard
|
|
72
72
|
# top-level reasoning_effort param. Ignored for other provider types.
|
|
73
73
|
supports_reasoning_effort: bool = False
|
|
74
|
+
# Opt-in for generic openai_chat endpoints that only implement the legacy
|
|
75
|
+
# max_tokens field. Ignored for other provider types.
|
|
76
|
+
legacy_max_tokens: bool = False
|
|
74
77
|
|
|
75
78
|
|
|
76
79
|
@dataclass(frozen=True)
|
|
@@ -119,6 +122,7 @@ class ResolvedProvider:
|
|
|
119
122
|
provider_name: str | None = None
|
|
120
123
|
model_config: ModelConfig | None = None
|
|
121
124
|
supports_reasoning_effort: bool = False
|
|
125
|
+
legacy_max_tokens: bool = False
|
|
122
126
|
reasoning_efforts: tuple[str, ...] = ()
|
|
123
127
|
|
|
124
128
|
|
|
@@ -434,6 +438,12 @@ def _validate_provider_config(name: str, raw: Any) -> dict[str, Any]:
|
|
|
434
438
|
raise ValueError(f"provider {name!r}: supports_reasoning_effort must be a boolean")
|
|
435
439
|
out["supports_reasoning_effort"] = supports_effort
|
|
436
440
|
|
|
441
|
+
legacy_max_tokens = raw.get("legacy_max_tokens")
|
|
442
|
+
if legacy_max_tokens is not None:
|
|
443
|
+
if not isinstance(legacy_max_tokens, bool):
|
|
444
|
+
raise ValueError(f"provider {name!r}: legacy_max_tokens must be a boolean")
|
|
445
|
+
out["legacy_max_tokens"] = legacy_max_tokens
|
|
446
|
+
|
|
437
447
|
raw_models = raw.get("models")
|
|
438
448
|
if raw_models is not None:
|
|
439
449
|
models = _validate_model_config_entries(name, raw_models)
|
|
@@ -519,6 +529,8 @@ def get_settings(cwd: str | None = None) -> Settings:
|
|
|
519
529
|
merged["base_url"] = raw["base_url"]
|
|
520
530
|
if "supports_reasoning_effort" in raw:
|
|
521
531
|
merged["supports_reasoning_effort"] = raw["supports_reasoning_effort"]
|
|
532
|
+
if "legacy_max_tokens" in raw:
|
|
533
|
+
merged["legacy_max_tokens"] = raw["legacy_max_tokens"]
|
|
522
534
|
|
|
523
535
|
raw_providers[name] = merged
|
|
524
536
|
|
|
@@ -623,6 +635,7 @@ def _build_providers(raw_providers: dict[str, dict[str, Any]]) -> dict[str, Prov
|
|
|
623
635
|
api_key_env_var=raw.get("api_key_env_var") or None,
|
|
624
636
|
base_url=raw.get("base_url") or None,
|
|
625
637
|
supports_reasoning_effort=raw.get("supports_reasoning_effort") is True,
|
|
638
|
+
legacy_max_tokens=raw.get("legacy_max_tokens") is True,
|
|
626
639
|
)
|
|
627
640
|
|
|
628
641
|
return providers
|
|
@@ -815,6 +828,8 @@ def _resolve_provider_runtime(
|
|
|
815
828
|
supports_effort = adapter.supports_reasoning_effort or bool(
|
|
816
829
|
provider_config and provider_config.supports_reasoning_effort and isinstance(adapter, OpenAIChatAdapter)
|
|
817
830
|
)
|
|
831
|
+
# The legacy max_tokens opt-in only applies to generic openai_chat providers.
|
|
832
|
+
legacy_max_tokens = bool(provider_config and provider_config.legacy_max_tokens and provider_type == "openai_chat")
|
|
818
833
|
resolved_api_key = api_key
|
|
819
834
|
if not resolved_api_key and provider_config:
|
|
820
835
|
if env_name := provider_config.api_key_env_var:
|
|
@@ -841,5 +856,6 @@ def _resolve_provider_runtime(
|
|
|
841
856
|
reasoning_effort=None,
|
|
842
857
|
model_config=model_config,
|
|
843
858
|
supports_reasoning_effort=supports_effort,
|
|
859
|
+
legacy_max_tokens=legacy_max_tokens,
|
|
844
860
|
reasoning_efforts=reasoning_efforts,
|
|
845
861
|
)
|
mycode_cli/main.py
CHANGED
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import asyncio
|
|
6
6
|
import os
|
|
7
7
|
import sys
|
|
8
|
-
from contextlib import suppress
|
|
8
|
+
from contextlib import aclosing, suppress
|
|
9
9
|
from dataclasses import dataclass, replace
|
|
10
10
|
from typing import TYPE_CHECKING, Annotated, Any, Literal
|
|
11
11
|
from uuid import uuid4
|
|
@@ -107,13 +107,14 @@ async def run_noninteractive(agent: Agent, message: str, *, store: SessionStore,
|
|
|
107
107
|
latest_assistant = payload
|
|
108
108
|
|
|
109
109
|
error_message = ""
|
|
110
|
-
async
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
110
|
+
async with aclosing(agent.achat(message, on_persist=track)) as stream:
|
|
111
|
+
async for event in stream:
|
|
112
|
+
if event.type == "error":
|
|
113
|
+
error_message = str(event.data.get("message") or "agent error")
|
|
114
|
+
elif event.type == "tool_done" and event.data.get("is_error"):
|
|
115
|
+
output = str(event.data.get("output") or "")
|
|
116
|
+
if output in {PERMISSION_DENIED_OUTPUT, PERMISSION_DENIED_BY_USER_OUTPUT}:
|
|
117
|
+
error_message = output
|
|
117
118
|
|
|
118
119
|
reply = ""
|
|
119
120
|
if latest_assistant:
|
mycode_cli/runtime.py
CHANGED
|
@@ -54,6 +54,7 @@ def build_agent(
|
|
|
54
54
|
api_base=resolved_provider.api_base,
|
|
55
55
|
reasoning_effort=resolved_provider.reasoning_effort,
|
|
56
56
|
supports_reasoning_effort=resolved_provider.supports_reasoning_effort,
|
|
57
|
+
legacy_max_tokens=resolved_provider.legacy_max_tokens,
|
|
57
58
|
max_tokens=model_config.max_output_tokens if model_config else None,
|
|
58
59
|
context_window=model_config.context_window if model_config else None,
|
|
59
60
|
supports_image_input=model_config.supports_image_input if model_config else None,
|
mycode_cli/server/run_manager.py
CHANGED
|
@@ -6,7 +6,7 @@ import asyncio
|
|
|
6
6
|
import copy
|
|
7
7
|
import time
|
|
8
8
|
from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable
|
|
9
|
-
from contextlib import asynccontextmanager
|
|
9
|
+
from contextlib import aclosing, asynccontextmanager
|
|
10
10
|
from dataclasses import dataclass, field
|
|
11
11
|
from typing import Any, Literal, Protocol
|
|
12
12
|
from uuid import uuid4
|
|
@@ -47,7 +47,7 @@ class RunAgent(Protocol):
|
|
|
47
47
|
|
|
48
48
|
def cancel(self) -> None: ...
|
|
49
49
|
|
|
50
|
-
def achat(self, user_input: str | ConversationMessage) ->
|
|
50
|
+
def achat(self, user_input: str | ConversationMessage) -> AsyncGenerator[Event, None]: ...
|
|
51
51
|
|
|
52
52
|
def acompact(self) -> Awaitable[ConversationMessage]: ...
|
|
53
53
|
|
|
@@ -355,12 +355,14 @@ class RunManager:
|
|
|
355
355
|
async def _run(self, state: RunState) -> None:
|
|
356
356
|
"""Run the agent and store streamed events."""
|
|
357
357
|
|
|
358
|
-
#
|
|
358
|
+
# A run can be stopped before the SDK operation has started.
|
|
359
359
|
if state.cancel_requested:
|
|
360
|
+
await self._append_event(state, Event("cancelled", {}))
|
|
360
361
|
await self._finish_run(state, status="cancelled")
|
|
361
362
|
return
|
|
362
363
|
|
|
363
364
|
last_error: str | None = None
|
|
365
|
+
cancelled = False
|
|
364
366
|
|
|
365
367
|
try:
|
|
366
368
|
if state.kind == "compact":
|
|
@@ -371,29 +373,32 @@ class RunManager:
|
|
|
371
373
|
await self._append_event(state, Event("compact", {}), compact_cost=sum_session_cost([marker]))
|
|
372
374
|
else:
|
|
373
375
|
assert state.user_message is not None
|
|
374
|
-
async
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
376
|
+
async with aclosing(state.agent.achat(state.user_message)) as stream:
|
|
377
|
+
async for event in stream:
|
|
378
|
+
if event.type == "retry":
|
|
379
|
+
continue
|
|
380
|
+
if event.type == "error":
|
|
381
|
+
last_error = str(event.data.get("message") or "unknown error")
|
|
382
|
+
elif event.type == "cancelled":
|
|
383
|
+
cancelled = True
|
|
384
|
+
continue
|
|
385
|
+
await self._append_event(state, event)
|
|
380
386
|
except asyncio.CancelledError:
|
|
381
|
-
#
|
|
382
|
-
|
|
383
|
-
# leaks (next /api/chat returns 409).
|
|
384
|
-
last_error = "cancelled"
|
|
387
|
+
# Manual compaction and external task cancellation both end the run.
|
|
388
|
+
cancelled = True
|
|
385
389
|
except Exception as exc:
|
|
386
390
|
# Reached by compact failures (e.g. nothing to compact, provider
|
|
387
|
-
# errors)
|
|
391
|
+
# errors) and by persist/cleanup failures during a chat turn.
|
|
388
392
|
last_error = str(exc)
|
|
389
393
|
await self._append_event(state, Event("error", {"message": last_error}))
|
|
390
394
|
|
|
391
|
-
if
|
|
392
|
-
await self._finish_run(state, status="
|
|
395
|
+
if last_error is not None:
|
|
396
|
+
await self._finish_run(state, status="failed", error=last_error)
|
|
393
397
|
return
|
|
394
398
|
|
|
395
|
-
if
|
|
396
|
-
await self.
|
|
399
|
+
if cancelled or state.cancel_requested:
|
|
400
|
+
await self._append_event(state, Event("cancelled", {}))
|
|
401
|
+
await self._finish_run(state, status="cancelled")
|
|
397
402
|
return
|
|
398
403
|
|
|
399
404
|
await self._finish_run(state, status="completed")
|
|
@@ -364,5 +364,5 @@ l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
|
|
|
364
364
|
`)){t+=`$$${i}$$`,n=r+2;continue}}}t+=e[n],n+=1}return t}var iX=(0,E.memo)(function({content:e}){return(0,L.jsx)(`div`,{className:`prose max-w-none`,children:(0,L.jsx)(VL,{remarkPlugins:eX,rehypePlugins:tX,components:nX,children:rX(e)})})});function aX(e){let t=Math.max(.1,e/1e3);if(t<60)return`${t.toFixed(1)}s`;let n=Math.round(t),r=Math.floor(n/60),i=n%60;return i===0?`${r}m`:`${r}m ${i}s`}var oX=(0,E.memo)(function({content:e,isStreaming:t,durationMs:n}){let[r,i]=(0,E.useState)(null);if(!e)return null;let a=r??!!t,o=t?`Thinking…`:n==null?`Thought`:`Thought for ${aX(n)}`;return(0,L.jsxs)(`div`,{className:`group/thinking`,children:[(0,L.jsx)(`button`,{type:`button`,className:`block select-none cursor-pointer text-left`,"aria-expanded":a,onClick:()=>i(!a),children:(0,L.jsx)(`span`,{className:li(`text-[12px] text-muted-foreground transition-colors duration-200 group-hover/thinking:text-foreground/80`,t&&`animate-thinking`),children:o})}),(0,L.jsx)(`div`,{"data-expanded":a,className:li(`chat-collapsible-body grid transition-[grid-template-rows,opacity] duration-250 ease-out-strong`,a?`grid-rows-[1fr] opacity-100`:`grid-rows-[0fr] opacity-0`),children:(0,L.jsx)(`div`,{className:`overflow-hidden`,children:(0,L.jsx)(`div`,{className:`mt-2 border-l border-border pl-3 text-[13px] text-muted-foreground whitespace-pre-wrap leading-relaxed`,children:e})})})]})}),sX=(0,E.lazy)(()=>g(()=>import(`./EditDiff-DOjxGJl-.js`),__vite__mapDeps([4,2,5,1,3])));function cX(e){return typeof e==`string`?e:``}function lX(e){return typeof e==`number`?e:null}function uX(e){let t=e?.edits;return Array.isArray(t)?t:null}function dX(e){let t=e?.patch;return typeof t==`string`&&t?t:null}function fX(e){let t=e,n=lX(t?.added_lines),r=lX(t?.removed_lines);return n==null||r==null?null:{added:n,removed:r}}function pX({edits:e}){return(0,L.jsx)(`div`,{className:`rounded-md bg-code shadow-hairline px-3 py-2 font-mono text-[13px] leading-normal overflow-x-auto scrollbar-subtle whitespace-pre-wrap`,children:e.map((e,t)=>(0,L.jsxs)(`div`,{children:[t>0&&(0,L.jsx)(`div`,{className:`text-center text-muted-foreground/20 select-none text-xs py-0.5`,children:`···`}),e.oldText&&(0,L.jsx)(`div`,{className:`diff-line-removed px-1`,children:e.oldText}),e.newText&&(0,L.jsx)(`div`,{className:`diff-line-added px-1`,children:e.newText})]},t))})}var mX={bash:tf,read:Rd,write:qd,edit:Qd,webfetch:Vd,websearch:Xd};function hX({head:e,body:t}){return!e&&!t?null:(0,L.jsxs)(`div`,{className:`rounded-md bg-code shadow-hairline overflow-hidden font-mono text-[13px]`,children:[e&&(0,L.jsx)(`div`,{className:`px-3 py-2 leading-normal max-h-60 overflow-auto scrollbar-subtle`,children:e}),t&&(0,L.jsx)(`div`,{className:`px-3 py-2 leading-relaxed text-muted-foreground whitespace-pre-wrap overflow-auto scrollbar-subtle max-h-60`,children:t})]})}function gX(e,t){if(!t)return``;switch(e){case`bash`:return cX(t.command);case`read`:case`write`:case`edit`:return cX(t.path);case`webfetch`:return cX(t.url);case`websearch`:return cX(t.query);default:{let e=[];for(let[n,r]of Object.entries(t))n===`content`||n===`prompt`||e.push(typeof r==`object`?`…`:String(r));return e.join(` `)}}}function _X(e){let t=e,n=lX(t?.offset),r=lX(t?.limit);return n!=null&&r!=null?`:${n}-${n+r}`:n==null?r==null?``:`:1-${r}`:`:${n}`}function vX(e){let t=cX(e?.content);return t?`${t.split(`
|
|
365
365
|
`).length} lines`:``}function yX({name:e,args:t,metadata:n}){if(e===`edit`){let e=fX(n);return!e||e.added===0&&e.removed===0?null:(0,L.jsxs)(`span`,{className:`shrink-0 text-[12px] font-mono tabular-nums`,children:[(0,L.jsxs)(`span`,{className:`text-diff-added`,children:[`+`,e.added]}),(0,L.jsxs)(`span`,{className:`text-diff-removed ml-1`,children:[`−`,e.removed]})]})}if(e===`websearch`){let e=lX(n?.results);return e==null?null:(0,L.jsxs)(`span`,{className:`shrink-0 text-[12px] font-mono tabular-nums text-muted-foreground/60`,children:[e,` results`]})}let r=e===`read`?_X(t):e===`write`?vX(t):``;return r?(0,L.jsx)(`span`,{className:`shrink-0 text-[12px] font-mono tabular-nums text-muted-foreground/60`,children:r}):null}function bX({args:e,display:t}){let n=cX(e?.command);return(0,L.jsx)(hX,{head:n&&(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-muted-foreground/40 select-none`,children:`$ `}),(0,L.jsx)(`span`,{className:`text-foreground whitespace-pre-wrap break-all`,children:n})]}),body:t})}function xX({args:e,display:t,isError:n}){let r=cX(e?.content);return(0,L.jsx)(hX,{head:r&&(0,L.jsx)(`span`,{className:`text-foreground/75 whitespace-pre-wrap`,children:r}),body:n?t:null})}function SX({args:e,metadata:t,display:n,isError:r}){let i=uX(e);if(i?.length){let e=dX(t);return(0,L.jsxs)(`div`,{className:`space-y-2`,children:[e?(0,L.jsx)(E.Suspense,{fallback:(0,L.jsx)(pX,{edits:i}),children:(0,L.jsx)(sX,{patch:e})}):(0,L.jsx)(pX,{edits:i}),r&&(0,L.jsx)(hX,{body:n})]})}return(0,L.jsx)(hX,{head:e&&Object.keys(e).length>0&&(0,L.jsx)(CX,{args:e}),body:n})}function CX({args:e}){return Object.entries(e).map(([e,t])=>(0,L.jsxs)(`div`,{children:[(0,L.jsxs)(`span`,{className:`text-accent/80`,children:[e,`: `]}),(0,L.jsx)(`span`,{className:`text-foreground/75 break-all whitespace-pre-wrap`,children:typeof t==`object`?JSON.stringify(t,null,2):String(t)})]},e))}var wX=(0,E.memo)(function({name:e,args:t,output:n,finalOutput:r,metadata:i,pending:a,isError:o}){let s=typeof r==`string`?r:typeof n==`string`?n:``,c=!!o||typeof r==`string`&&r.startsWith(`error:`),[l,u]=(0,E.useState)(!1),d=a?`pending`:c?`error`:`success`,f=mX[e]??tf,p=gX(e,t),m=e===`bash`?(0,L.jsx)(bX,{args:t,display:s}):e===`read`||e===`webfetch`||e===`websearch`?(0,L.jsx)(hX,{body:s}):e===`write`?(0,L.jsx)(xX,{args:t,display:s,isError:c}):e===`edit`?(0,L.jsx)(SX,{args:t,metadata:i,display:s,isError:c}):(0,L.jsx)(hX,{head:t&&Object.keys(t).length>0&&(0,L.jsx)(CX,{args:t}),body:s});return(0,L.jsxs)(`div`,{className:`group/tool`,children:[(0,L.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-1.5 select-none cursor-pointer text-left`,"aria-expanded":l,onClick:()=>u(e=>!e),children:[(0,L.jsx)(f,{className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:li(`text-[13px] shrink-0 tracking-tight transition-colors duration-200`,d===`error`?`text-destructive/90 group-hover/tool:text-destructive`:`text-foreground/90 group-hover/tool:text-foreground`,d===`pending`&&`animate-thinking`),children:e}),p&&(0,L.jsx)(`span`,{className:`min-w-0 text-[13px] font-mono text-muted-foreground/60 truncate`,children:p}),(0,L.jsx)(yX,{name:e,args:t,metadata:i})]}),(0,L.jsx)(`div`,{"data-expanded":l,className:li(`chat-collapsible-body grid transition-[grid-template-rows,opacity] duration-250 ease-out-strong`,l?`grid-rows-[1fr] opacity-100`:`grid-rows-[0fr] opacity-0`),children:(0,L.jsx)(`div`,{className:`overflow-hidden`,children:(0,L.jsx)(`div`,{className:`mt-2 ml-5`,children:m})})})]})});function TX(e){let t=e.meta?.duration_ms;return typeof t==`number`?t:void 0}function EX(e){return e.meta}function DX(e,t){if(e===t)return!0;if(e.type!==t.type)return!1;if(e.type===`text`&&t.type===`text`)return e.text===t.text&&EX(e)?.attachment===EX(t)?.attachment&&EX(e)?.path===EX(t)?.path;if(e.type===`thinking`&&t.type===`thinking`)return e.text===t.text&&TX(e)===TX(t);if(e.type===`tool_use`&&t.type===`tool_use`){let n=e.runtime,r=t.runtime;return e.id===t.id&&e.name===t.name&&e.input===t.input&&n?.pending===r?.pending&&n?.output===r?.output&&n?.finalOutput===r?.finalOutput&&n?.metadata===r?.metadata&&n?.isError===r?.isError}return e.type===`image`&&t.type===`image`||e.type===`document`&&t.type===`document`?e.data===t.data&&e.mime_type===t.mime_type&&e.name===t.name:e.type===`tool_result`&&t.type===`tool_result`&&e.tool_use_id===t.tool_use_id&&e.output===t.output&&e.metadata===t.metadata&&e.is_error===t.is_error}function OX(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(!r||!i||!DX(r,i))return!1}return!0}function kX(e,t){return e===t?!0:!e||!t?!1:e.input_tokens===t.input_tokens&&e.total_tokens===t.total_tokens&&e.output_tokens===t.output_tokens&&e.cache_read_tokens===t.cache_read_tokens&&e.cache_write_tokens===t.cache_write_tokens&&e.reasoning_tokens===t.reasoning_tokens&&e.context_tokens===t.context_tokens&&e.context_window===t.context_window&&e.cost?.total===t.cost?.total&&e.cost?.input===t.cost?.input&&e.cost?.cache_read===t.cost?.cache_read&&e.cost?.cache_write===t.cost?.cache_write&&e.cost?.output===t.cost?.output&&e.cost?.reasoning===t.cost?.reasoning}function AX(e,t){return e.role!==t.role||e.sourceIndex!==t.sourceIndex||e.isStreaming!==t.isStreaming||e.model!==t.model||!kX(e.stats,t.stats)||e.onRewindAndSend!==t.onRewindAndSend||e.role===`user`&&e.isLoading!==t.isLoading?!1:OX(e.blocks,t.blocks)}var jX=class extends E.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error(`Chat block render failed:`,e)}render(){return this.state.hasError?this.props.fallback:this.props.children}},MX=(0,L.jsx)(`div`,{className:`rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive/80`,children:`Failed to render this block.`});function NX({model:e,stats:t}){let n=[e,t?.cost?df(t.cost.total):null].filter(Boolean).join(` · `);if(!n)return null;let r=t?.cost?.input!==void 0&&t.cost.output!==void 0,i=[],a=(e,t,n)=>{if(t===void 0)return;let r={label:e,tokens:t};n!==void 0&&(r.cost=n),i.push(r)};a(`Input`,t?.input_tokens===void 0?void 0:t.input_tokens-(t.cache_read_tokens??0)-(t.cache_write_tokens??0),t?.cost?.input),t?.cache_read_tokens&&a(`Cache read`,t.cache_read_tokens,t.cost?.cache_read),t?.cache_write_tokens&&a(`Cache write`,t.cache_write_tokens,t.cost?.cache_write),a(`Output`,t?.output_tokens,t?.cost?(t.cost.output??0)+(t.cost.reasoning??0):void 0);let o=t?.total_tokens??(t?.input_tokens!==void 0&&t.output_tokens!==void 0?t.input_tokens+t.output_tokens:void 0);return i.length===0&&o===void 0?(0,L.jsx)(`span`,{className:`cursor-default text-xs tabular-nums text-muted-foreground/50`,children:n}):(0,L.jsx)(Mj,{trigger:n,children:(0,L.jsxs)(`span`,{className:li(`grid items-baseline gap-x-5 gap-y-1`,r?`grid-cols-[max-content_max-content_max-content]`:`grid-cols-[max-content_max-content]`),children:[i.map(e=>(0,L.jsxs)(E.Fragment,{children:[(0,L.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),(0,L.jsx)(`span`,{className:`text-right tabular-nums`,children:e.tokens.toLocaleString()}),r?(0,L.jsx)(`span`,{className:`text-right tabular-nums`,children:df(e.cost??0)}):null]},e.label)),o===void 0?null:(0,L.jsxs)(`span`,{className:`col-span-full mt-1 grid grid-cols-subgrid items-baseline border-t border-border/50 pt-1.5 font-medium`,children:[(0,L.jsx)(`span`,{children:`Total`}),(0,L.jsx)(`span`,{className:`text-right tabular-nums`,children:o.toLocaleString()}),r?(0,L.jsx)(`span`,{className:`text-right tabular-nums`,children:df(t.cost?.total??0)}):null]})]})})}function PX({label:e,value:t}){return(0,L.jsxs)(`div`,{className:`min-w-32 max-w-xs rounded-lg border border-border/40 bg-muted/50 px-3 py-2 text-sm text-foreground/80`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(Rd,{className:`size-4 shrink-0 text-accent/80`}),(0,L.jsx)(`span`,{className:`font-medium`,children:e})]}),(0,L.jsx)(`div`,{className:`mt-1 break-all text-xs text-muted-foreground`,children:t})]})}var FX=(0,E.memo)(function({role:e,blocks:t,sourceIndex:n,isStreaming:r,isLoading:i,model:a,stats:o,onRewindAndSend:s}){let c=e===`user`,[l,u]=(0,E.useState)(!1),[d,f]=(0,E.useState)(!1),[p,m]=(0,E.useState)(``),h=(0,E.useRef)(null),{textContent:g,textAttachmentBlocks:_,imageBlocks:v,documentBlocks:y}=(0,E.useMemo)(()=>{let e=[],n=[],r=[],i=[];for(let a of t)a&&(a.type===`text`?EX(a)?.attachment?n.push(a):e.push(a.text):a.type===`image`?r.push(a):a.type===`document`&&i.push(a));return{textContent:e.join(`
|
|
366
366
|
|
|
367
|
-
`),textAttachmentBlocks:n,imageBlocks:r,documentBlocks:i}},[t]);(0,E.useEffect)(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]);let b=(0,E.useCallback)(async()=>{if(g)try{await Hj(g),u(!0),h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{u(!1),h.current=null},2e3)}catch{}},[g]),x=c&&!!g&&v.length===0&&y.length===0&&_.length===0&&typeof n==`number`&&!i&&s,S=(0,E.useCallback)(()=>{m(g),f(!0)},[g]),C=(0,E.useCallback)(e=>{e&&(e.focus(),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]),w=(0,E.useCallback)(()=>{let e=p.trim();!e||!s||typeof n!=`number`||(f(!1),s(n,e))},[p,s,n]),T=(0,E.useCallback)(()=>{f(!1)},[]),D=(0,E.useCallback)(e=>{e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),w()):e.key===`Escape`&&T()},[w,T]);return c?d?(0,L.jsx)(`div`,{className:`flex justify-end px-5 max-md:px-4`,children:(0,L.jsxs)(`div`,{className:`max-w-[85%] w-full flex flex-col gap-2`,children:[(0,L.jsx)(`textarea`,{ref:C,name:`edit-message`,"aria-label":`Edit message`,value:p,onChange:e=>{m(e.target.value),e.target.style.height=`auto`,e.target.style.height=`${Math.min(e.target.scrollHeight,300)}px`},onKeyDown:D,className:`w-full resize-none rounded-lg bg-muted px-3.5 py-2 text-base md:text-sm leading-relaxed text-foreground border border-border/60 focus:outline-none focus:border-accent/60 max-h-75`}),(0,L.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:T,className:`px-3 py-1 text-xs rounded-lg text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:`Cancel`}),(0,L.jsx)(`button`,{type:`button`,onClick:w,disabled:!p.trim(),className:li(`px-3 py-1 text-xs rounded-lg transition-[color,background-color,filter,scale] duration-150`,p.trim()?`bg-accent text-accent-foreground hover:brightness-105 hover:saturate-[.9] active:scale-95`:`text-muted-foreground/40`),children:`Send`})]})]})}):(0,L.jsxs)(`div`,{className:`group/user flex justify-end px-5 max-md:px-4`,children:[x&&(0,L.jsx)(`button`,{type:`button`,"aria-label":`Edit message`,onClick:S,className:`self-end mr-2 mb-0.5 opacity-0 group-hover/user:opacity-100 max-md:opacity-60 active:scale-95 transition-[color,opacity,scale] duration-150 size-6 flex items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground`,title:`Edit & resend`,children:(0,L.jsx)(Jd,{className:`size-3`})}),(0,L.jsxs)(`div`,{className:`max-w-[85%] flex flex-col gap-1.5 items-end`,children:[v.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:v.map(e=>e.data?(0,L.jsx)(`img`,{src:`data:${e.mime_type};base64,${e.data}`,alt:e.name??`Image`,className:`max-h-64 max-w-full rounded-lg`},e.renderKey):(0,L.jsx)(PX,{label:`Image`,value:e.name??`image`},e.renderKey))}),y.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:y.map(e=>(0,L.jsx)(PX,{label:`PDF`,value:e.name??`document.pdf`},e.renderKey))}),_.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:_.map(e=>{let t=EX(e)?.path;return(0,L.jsx)(PX,{label:`Text`,value:typeof t==`string`?t:`attached-file`},e.renderKey)})}),g&&(0,L.jsx)(`div`,{className:`rounded-lg bg-muted px-3.5 py-2 text-sm leading-relaxed text-foreground whitespace-pre-wrap wrap-anywhere`,children:g})]})]}):(0,L.jsxs)(`div`,{className:`group/msg relative px-5 max-md:px-4`,children:[(0,L.jsxs)(`div`,{className:`flex flex-col gap-3 text-foreground/90 leading-relaxed text-sm`,children:[t.map((e,n)=>{if(e.type===`thinking`){let i=e.renderKey||`thinking:${e.text||`block`}`,a=TX(e);return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(oX,{content:e.text,durationMs:a,isStreaming:r&&a==null&&n===t.length-1})},i)}if(e.type===`text`){let t=e.renderKey||`text:${e.text||`block`}`;return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(iX,{content:e.text})},t)}if(e.type===`tool_use`){let t=e.renderKey||e.id||`tool:${e.name||`tool`}`;return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(wX,{name:e.name,args:e.input,output:e.runtime?.output,finalOutput:e.runtime?.finalOutput,metadata:e.runtime?.metadata,pending:e.runtime?.pending,isError:e.runtime?.isError})},t)}return null}),r&&(0,L.jsx)(`span`,{className:`inline-block w-[1.5px] h-4 bg-foreground/40 ml-0.5 align-middle`})]}),!c&&g&&!r&&(0,L.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 max-md:opacity-60 opacity-0 group-hover/msg:opacity-100 transition-opacity duration-150`,children:[(0,L.jsx)(`button`,{type:`button`,"aria-label":`Copy to clipboard`,onClick:b,className:li(`flex items-center justify-center size-6 rounded-sm active:scale-95 transition-[color,scale] duration-150`,l?`text-accent`:`text-muted-foreground/50 hover:text-foreground`),title:`Copy`,children:l?(0,L.jsx)(Md,{className:`size-3.5`}):(0,L.jsx)(Id,{className:`size-3.5`})}),(a||o)&&(0,L.jsx)(NX,{model:a,stats:o})]})]})},AX),IX=120,LX=`__draft__`,RX=60,zX=30,BX=160,VX=(0,E.memo)(function({sessionId:e,messages:t,loading:n,compacting:r,compactError:i,onRewindAndSend:a,emptyStateFooter:o}){let s=e||LX,c=t.length===0?`empty`:`ready`;return(0,L.jsx)(WX,{messages:t,loading:n,compacting:r,compactError:i,onRewindAndSend:a,emptyStateFooter:o},`${s}:${c}`)});function HX(e){return Math.max(0,e-RX)}function UX(e){let t=e.querySelectorAll(`.chat-message-shell`);for(let e of t)e.style.setProperty(`--chat-message-intrinsic-size`,`${Math.ceil(e.getBoundingClientRect().height)}px`)}function WX({messages:e,loading:t,compacting:n,compactError:r,onRewindAndSend:i,emptyStateFooter:a}){let o=(0,E.useRef)(null),s=(0,E.useRef)(!0),c=(0,E.useRef)(``),l=(0,E.useRef)(null),u=(0,E.useRef)(null),[d,f]=(0,E.useState)(!1),[p,m]=(0,E.useState)(()=>HX(e.length)),h=Math.min(p,HX(e.length)),g=(0,E.useMemo)(()=>e.slice(h),[h,e]),_=e.at(-1),v=n&&(!_||!Bj(_)),y=!_||Bj(_)?0:_.content.length,b=!_||Bj(_)?0:_.content.reduce((e,t)=>t.type!==`text`&&t.type!==`thinking`?e:e+(t.text?.length??0),0),x=`${e.length}:${y}:${b}:${n}:${r??``}`,S=(0,E.useCallback)(e=>e.scrollHeight-e.scrollTop-e.clientHeight<IX,[]),C=(0,E.useCallback)(()=>{let e=o.current;e&&(e.scrollTop=e.scrollHeight)},[]),w=(0,E.useCallback)(()=>{u.current!==null&&window.cancelAnimationFrame(u.current),u.current=window.requestAnimationFrame(()=>{u.current=null;let e=o.current;e&&UX(e),f(!0)})},[]),T=(0,E.useCallback)(()=>{let e=o.current;e&&(s.current=S(e),!(e.scrollTop>BX||h===0)&&(l.current={scrollHeight:e.scrollHeight,scrollTop:e.scrollTop},f(!1),m(Math.max(0,h-zX))))},[h,S]);return(0,E.useLayoutEffect)(()=>{s.current=!0,C(),w()},[w,C]),(0,E.useLayoutEffect)(()=>()=>{u.current!==null&&window.cancelAnimationFrame(u.current)},[]),(0,E.useLayoutEffect)(()=>{let e=l.current;if(e==null)return;let t=o.current;t&&(t.scrollTop=t.scrollHeight-e.scrollHeight+e.scrollTop,l.current=null,s.current=S(t),w())},[S,w]),(0,E.useLayoutEffect)(()=>{!d||!s.current||(l.current??C())},[d,C]),(0,E.useLayoutEffect)(()=>{c.current!==x&&(c.current=x,s.current&&l.current==null&&C())},[x,C]),(0,L.jsx)(`div`,{ref:o,onScroll:T,className:`min-h-0 flex-1 overflow-y-auto pb-4 pt-6 [overflow-anchor:none] [scrollbar-gutter:stable_both-edges]`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex min-h-full max-w-4xl flex-col gap-6 max-md:max-w-none max-md:gap-5`,children:[e.length===0&&(0,L.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center p-8 text-center`,children:[(0,L.jsxs)(`h1`,{className:`font-display text-3xl tracking-[-0.022em] text-foreground/70`,children:[`mycode`,(0,L.jsx)(`span`,{className:`ml-0.5 inline-block h-6 w-0.5 animate-cursor-blink bg-accent/60 align-middle`})]}),a&&(0,L.jsx)(`div`,{className:`mt-8`,children:a})]}),g.map((n,r)=>{let a=h+r,o=n.renderKey||`msg-${a}`,s=t&&a===e.length-1&&!Bj(n)&&n.role===`assistant`;return Bj(n)?(0,L.jsx)(`div`,{className:`chat-message-shell`,"data-layout-optimized":d,children:(0,L.jsx)(Vj,{})},o):(0,L.jsx)(`div`,{className:`chat-message-shell`,"data-layout-optimized":d,children:(0,L.jsx)(FX,{role:n.role,blocks:n.content,sourceIndex:n.sourceIndex,isStreaming:s,isLoading:t,model:n.meta?.model,stats:n.stats,onRewindAndSend:i})},o)}),v&&(0,L.jsx)(`div`,{className:`chat-message-shell`,children:(0,L.jsx)(Vj,{pending:!0})}),!n&&r&&(0,L.jsx)(`div`,{role:`status`,title:r,className:`flex select-none items-center justify-center px-2 py-1`,children:(0,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-[0.18em] text-muted-foreground/50`,children:r===`nothing to compact`?`nothing to compact`:`compaction failed`})}),(e.length>0||v||r)&&(0,L.jsx)(`div`,{className:`h-4`})]})})}var GX={bash:tf,read:Rd,write:qd,edit:Qd,webfetch:Vd,websearch:Xd},KX={bash:`Run this command?`,read:`Read this file?`,write:`Write this file?`,edit:`Edit this file?`,webfetch:`Fetch this page?`,websearch:`Run this search?`};function qX({toolName:e,preview:t}){let n=e===`bash`,r=e===`websearch`;return(0,L.jsxs)(`div`,{className:li(`rounded-md bg-code px-3 py-2 leading-normal text-foreground/80`,r?`text-[13px]`:`font-mono text-[12.5px]`,n&&`max-h-24 overflow-y-auto scrollbar-subtle whitespace-pre-wrap break-words`,!n&&!r&&`break-all`),children:[n&&(0,L.jsx)(`span`,{className:`select-none text-muted-foreground/40`,children:`$ `}),r?`“${t}”`:t]})}var JX=(0,E.memo)(function({request:e,onDecide:t}){let n=(0,E.useCallback)(e=>{e?.focus()},[]),r=e=>{e.key===`Enter`?(e.preventDefault(),t(`allow`)):e.key===`Escape`&&(e.preventDefault(),t(`deny`))},i=GX[e.tool_name]??tf,a=KX[e.tool_name]??`Run this tool?`;return(0,L.jsx)(`div`,{className:`mx-auto max-w-4xl max-md:max-w-none px-5 max-md:px-3 pt-3 max-md:pt-2 pb-1`,children:(0,L.jsxs)(`div`,{ref:n,role:`dialog`,"aria-label":`Tool permission request`,tabIndex:-1,onKeyDown:r,className:`flex flex-col gap-3 rounded-lg bg-card px-3.5 py-3 shadow-card animate-fade-in-up focus:outline-none`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`grid size-6 shrink-0 place-items-center rounded-md bg-accent/10 text-accent`,children:(0,L.jsx)(i,{className:`size-3.5`,"aria-hidden":`true`})}),(0,L.jsx)(`span`,{className:`text-sm text-foreground/90`,children:a})]}),e.preview&&(0,L.jsx)(qX,{toolName:e.tool_name,preview:e.preview}),(0,L.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,L.jsxs)(`button`,{type:`button`,onClick:()=>t(`allow`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-accent px-3 text-[12.5px] font-medium text-accent-foreground transition-[filter,scale] duration-150 hover:brightness-105 hover:saturate-[.9] active:scale-95`,children:[`Allow`,(0,L.jsx)(Ld,{className:`size-3 opacity-70`,"aria-hidden":`true`})]}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>t(`deny`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-muted/70 px-3 text-[12.5px] text-muted-foreground transition-[color,background-color,scale] duration-150 hover:bg-muted hover:text-foreground active:scale-95`,children:[`Deny`,(0,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-wider`,"aria-hidden":`true`,children:`esc`})]})]})]},e.request_id)})});function YX({children:e}){return(0,L.jsx)(`div`,{className:li(`flex h-screen min-h-0 w-full flex-col overflow-hidden supports-[height:100dvh]:h-dvh bg-background font-sans text-foreground antialiased`,`transition-colors duration-150`),children:e})}function XX({title:e,onMenuToggle:t,onCreateSession:n}){return(0,L.jsxs)(`header`,{className:`flex md:hidden h-12 shrink-0 items-center justify-between px-4 border-b border-border/40 bg-background`,children:[(0,L.jsx)(`button`,{type:`button`,"aria-label":`Toggle menu`,onClick:t,className:`flex items-center justify-center size-10 -ml-2 text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:(0,L.jsx)(Wd,{className:`size-5`})}),(0,L.jsx)(`span`,{className:`text-xs text-foreground/70 truncate max-w-[60%] text-center`,children:e||`mycode`}),(0,L.jsx)(`button`,{type:`button`,"aria-label":`New chat`,onClick:n,className:`flex items-center justify-center size-10 -mr-2 text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:(0,L.jsx)(Yd,{className:`size-5`})})]})}function ZX({...e}){return(0,L.jsx)(hd,{"data-slot":`dialog`,...e})}function QX({...e}){return(0,L.jsx)($u,{"data-slot":`dialog-portal`,...e})}function $X({className:e,...t}){return(0,L.jsx)(Ai,{"data-slot":`dialog-overlay`,className:li(`fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}function eZ({className:e,children:t,showCloseButton:n=!0,...r}){return(0,L.jsxs)(QX,{children:[(0,L.jsx)($X,{}),(0,L.jsxs)(Xu,{"data-slot":`dialog-content`,className:li(`fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-md bg-background p-4 text-sm text-foreground shadow-overlay duration-100 ease-out-strong outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r,children:[t,n&&(0,L.jsxs)(Gi,{"data-slot":`dialog-close`,render:(0,L.jsx)(di,{variant:`ghost`,className:`absolute top-2 right-2`,size:`icon-sm`}),children:[(0,L.jsx)(rf,{}),(0,L.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function tZ({className:e,...t}){return(0,L.jsx)(gd,{"data-slot":`dialog-title`,className:li(`text-base leading-none font-medium`,e),...t})}function nZ({label:e,hint:t,children:n}){return(0,L.jsxs)(`div`,{className:li(`flex flex-col gap-1.5`,`md:grid md:grid-cols-[110px_1fr] md:gap-x-3 md:gap-y-0 md:items-start`),children:[(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/80 select-none md:pt-2`,children:e}),(0,L.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0`,children:[n,t&&(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/70 leading-relaxed`,children:t})]})]})}function rZ({title:e,children:t}){return(0,L.jsxs)(`section`,{className:`flex flex-col gap-3.5`,children:[(0,L.jsx)(`h3`,{className:`text-[14px] font-semibold text-foreground select-none`,children:e}),(0,L.jsx)(`div`,{className:`flex flex-col gap-2.5`,children:t})]})}function iZ({value:e,options:t,onChange:n,ariaLabel:r,size:i=`md`}){return(0,L.jsx)(`div`,{role:`radiogroup`,"aria-label":r,className:`inline-flex items-center rounded-md border border-border/50 bg-muted/30 p-0.5`,children:t.map(t=>{let r=t.value===e;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,onClick:()=>n(t.value),className:li(`inline-flex items-center justify-center gap-1.5 rounded-sm font-medium transition-colors`,i===`sm`?`h-7 px-2.5 text-[12px]`:`h-7 px-3 text-[12px]`,r?`bg-background text-foreground`:`text-muted-foreground/80 hover:text-foreground`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent/60`),children:[t.icon,t.label]},t.value)})})}function aZ({className:e,invalid:t,...n}){return(0,L.jsx)(`input`,{...n,className:li(`h-9 w-full bg-transparent px-2`,`text-[13px] font-mono`,`border-b border-border/60`,`transition-colors`,`placeholder:text-muted-foreground/50`,`hover:border-border`,`focus:border-accent focus:outline-none`,`disabled:opacity-50 disabled:hover:border-border/60`,t&&`border-destructive/70 focus:border-destructive`,e)})}function oZ({className:e,children:t,...n}){return(0,L.jsxs)(`div`,{className:`relative inline-flex w-full min-w-0`,children:[(0,L.jsx)(`select`,{...n,className:li(`appearance-none w-full h-9 pl-2 pr-7`,`text-[13px] font-mono bg-transparent`,`border-b border-border/60`,`transition-colors`,`hover:border-border`,`focus:border-accent focus:outline-none`,e),children:t}),(0,L.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground/60`,children:`▾`})]})}function sZ(e){if(!e)return null;for(let t of e.elements){let e=t.tagName;if(e===`BUTTON`||e===`INPUT`){let e=t;if(e.type===`submit`)return e}}return null}var cZ=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.indeterminate=`data-indeterminate`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),lZ=function(e){return e.disabled=`data-disabled`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),uZ={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},dZ={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},fZ={disabled:!1,...dZ},pZ={valid(e){return e===null?null:e?{[lZ.valid]:``}:{[lZ.invalid]:``}}};function mZ(e){return E.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[cZ.checked]:``}:{[cZ.unchecked]:``}},...pZ}),[e.indeterminate])}var hZ={invalid:void 0,name:void 0,validityData:{state:uZ,errors:[],error:``,value:``,initialValue:null},setValidityData:_n,disabled:void 0,touched:dZ.touched,setTouched:_n,dirty:dZ.dirty,setDirty:_n,filled:dZ.filled,setFilled:_n,focused:dZ.focused,setFocused:_n,validate:()=>null,validationMode:`onSubmit`,validationDebounceTime:0,shouldValidateOnChange:()=>!1,state:fZ,markedDirtyRef:{current:!1},registerFieldControl:_n,validation:{getValidationProps:(e,t=yn)=>t,inputRef:{current:null},registerInput:_n,commit:async()=>{},change:_n}},gZ=E.createContext(hZ);function _Z(e=!0){let t=E.useContext(gZ);if(t.setValidityData===_n&&!e)throw Error(en(28));return t}function vZ(e,t,n,r,i=!0,a){let{registerFieldControl:o}=_Z(),s=E.useRef(null);s.current||=Symbol(),It(()=>{let c=s.current;if(!(!c||!i))return o(c,{controlRef:e,getValue:r,id:t,name:a,value:n}),()=>{o(c,void 0)}},[e,i,r,t,a,o,n])}var yZ=E.createContext({disabled:!1});function bZ(){return E.useContext(yZ)}var xZ=E.createContext({formRef:{current:{fields:new Map}},errors:{},clearErrors:_n,validationMode:`onSubmit`,submitAttemptedRef:{current:!1}});function SZ(){return E.useContext(xZ)}var CZ=E.createContext({controlId:void 0,registerControlId:_n,labelId:void 0,setLabelId:_n,messageIds:[],setMessageIds:_n,getDescriptionProps:e=>e});function wZ(){return E.useContext(CZ)}function TZ(e,t,n,r=!0,i){let[a,o]=E.useState(),s=Xi(i?`${i}-label`:void 0),c=e??t??a;return It(()=>{let i=e||t||!r?void 0:EZ(n.current,s);a!==i&&o(i)}),c}function EZ(e,t){let n=DZ(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function DZ(e){if(!e)return;let t=e.parentElement;if(t&&t.tagName===`LABEL`)return t;let n=e.id;if(n){let t=e.nextElementSibling;if(t&&t.htmlFor===n)return t}let r=e.labels;return r&&r[0]}var OZ=E.createContext(void 0);function kZ(e=!0){let t=E.useContext(OZ);if(t===void 0&&!e)throw Error(en(3));return t}var AZ=E.createContext(void 0);function jZ(){let e=E.useContext(AZ);if(e===void 0)throw Error(en(14));return e}var MZ=`data-parent`,NZ=E.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i=!1,"aria-labelledby":a,disabled:o=!1,form:s,id:c,indeterminate:l=!1,inputRef:u,name:d,onCheckedChange:f,parent:p=!1,readOnly:m=!1,render:h,required:g=!1,uncheckedValue:_,value:v,nativeButton:y=!1,style:b,...x}=e,{clearErrors:S}=SZ(),{disabled:C,name:w,setDirty:T,setFilled:D,setFocused:O,setTouched:k,state:A,validationMode:j,validityData:M,validation:N}=_Z(),P=bZ(),{labelId:F,controlId:I,registerControlId:ee,getDescriptionProps:te}=wZ(),ne=kZ(),re=ne?.parent,ie=re&&ne.allValues,ae=C||P.disabled||ne?.disabled||o,oe=w??d,se=v??oe,ce=Xi(),le=Xi(),ue=I;ie?ue=p?le:`${re.id}-${se}`:c&&(ue=c);let de={};ie&&(p?de=ne.parent.getParentProps():se&&(de=ne.parent.getChildProps(se)));let{checked:fe=n,indeterminate:pe=l,onCheckedChange:me,...he}=de,ge=ne?.value,_e=ne?.setValue,ve=ne?.defaultValue,ye=E.useRef(null),be=At(()=>Symbol(`checkbox-control`)),xe=E.useRef(!1),{getButtonProps:Se,buttonRef:Ce}=an({disabled:ae,native:y}),we=ne?.validation??N,[Te,Ee]=Kk({controlled:se&&ge&&!p?ge.includes(se):fe,default:se&&ve&&!p?ve.includes(se):i,name:`Checkbox`,state:`checked`}),De=ie?!!fe:Te,Oe=ie&&pe||l;It(()=>{ee!==_n&&(xe.current=!0,ee(be.current,ue))},[ue,ee,be]),E.useEffect(()=>{let e=be.current;return()=>{!xe.current||ee===_n||(xe.current=!1,ee(e,void 0))}},[ee,be]),vZ(ye,ce,Te,void 0,!ne&&!ae,d);let ke=E.useRef(null),Ae=cn(u,ke,we.inputRef,we.registerInput),je=TZ(a,F,ke,!y,ue??void 0);It(()=>{ke.current&&(ke.current.indeterminate=Oe,Te&&D(!0))},[Te,Oe,D]),vd(Te,()=>{ne||(S(oe),D(Te),T(Te!==M.initialValue),we.change(Te))});let Me=zt({checked:Te,disabled:ae,form:s,name:p?void 0:oe,id:y?void 0:ue??void 0,required:g,ref:Ae,style:oe?to:eo,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(m){e.preventDefault();return}let t=e.currentTarget.checked,n=Wi(ji,e.nativeEvent);if(f?.(t,n),!n.isCanceled&&(me?.(t,n),!n.isCanceled&&(Ee(t),se&&ge&&_e&&!p&&!ie))){let e=t?[...ge,se]:ge.filter(e=>e!==se);_e(e,n)}},onFocus(){ye.current?.focus()}},v===void 0?yn:{value:(ne?Te&&v:v)||``},te,e=>we.getValidationProps(ae,e));E.useEffect(()=>{if(!re||!se)return;let e=re.disabledStatesRef.current;return e.set(se,ae),()=>{e.delete(se)}},[re,ae,se]);let Ne=E.useMemo(()=>({...A,checked:De,disabled:ae,readOnly:m,required:g,indeterminate:Oe}),[A,De,ae,m,g,Oe]),Pe=mZ(Ne),Fe=Cn(`span`,e,{state:Ne,ref:[Ce,ye,t,ne?.registerControlRef],props:[{id:y?ue??void 0:ce,role:`checkbox`,"aria-checked":Oe?`mixed`:De,"aria-readonly":m||void 0,"aria-required":g||void 0,"aria-labelledby":je,[MZ]:p?``:void 0,onFocus(){ae||O(!0)},onBlur(){let e=ke.current;e&&(k(!0),O(!1),j===`onBlur`&&we.commit(ne?ge:e.checked))},onKeyDown(e){if(e.key!==`Enter`||(e.preventBaseUIHandler(),e.defaultPrevented))return;let t=ke.current?.form??null,n=e.currentTarget,r=e.nativeEvent,i=e.preventDefault,a=r.preventDefault,o=!1;e.preventDefault=()=>{o=!0,i.call(e)},r.preventDefault=()=>{o=!0,a.call(r)},a.call(r),at(n).queueMicrotask(()=>{e.preventDefault=i,r.preventDefault=a,o||sZ(t)?.click()})},onClick(e){if(m||ae)return;e.preventDefault();let t=ke.current;t&&t.dispatchEvent(new(at(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},x,he,Se,te,e=>we.getValidationProps(ae,e)],stateAttributesMapping:Pe});return(0,L.jsxs)(AZ.Provider,{value:Ne,children:[Fe,!Te&&!ne&&oe&&!p&&_!==void 0&&(0,L.jsx)(`input`,{type:`hidden`,form:s,name:oe,value:_,disabled:ae}),(0,L.jsx)(`input`,{...Me,suppressHydrationWarning:!0})]})}),PZ=E.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=jZ(),c=s.checked||s.indeterminate,{mounted:l,transitionStatus:u,setMounted:d}=Ll(c),f=E.useRef(null),p={...s,transitionStatus:u};zl({open:c,ref:f,onComplete(){c||d(!1)}});let m={...mZ(s),...vi,...pZ},h=a||l,g=Cn(`span`,e,{ref:[t,f],state:p,stateAttributesMapping:m,props:o});return h?g:null}),FZ=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,IZ=(0,E.memo)(function({draft:e,providerTypes:t,envByName:n,providerTypeEnvVars:r,providerTypeDefaultModels:i,usedTypesByOthers:a,duplicateName:o,onChange:s,onRemove:c}){let[l,u]=(0,E.useState)(``),d=(0,E.useId)(),f=t=>s({...e,...t}),p=t=>{if(!(e.name===``||e.name===e.type)){f({type:t});return}let n=a.has(t);f({type:t,name:n?``:t})},m=()=>{let t=l.trim();if(t){if(e.models.includes(t)){u(``);return}f({models:[...e.models,t]}),u(``)}},h=t=>f({models:e.models.filter(e=>e!==t)}),g=t=>{if(t.key===`Enter`||t.key===`,`)t.preventDefault(),m();else if(t.key===`Backspace`&&!l&&e.models.length){t.preventDefault();let n=e.models[e.models.length-1];n&&h(n)}},_=LZ(e,n,r);return(0,L.jsxs)(`div`,{className:li(`relative rounded-lg bg-card shadow-card px-4 py-3.5`,`transition-colors hover:border-border/60`),children:[(0,L.jsx)(`button`,{type:`button`,onClick:()=>c(e.id),"aria-label":`Remove provider ${e.name||`untitled`}`,className:li(`absolute right-2 top-2 inline-flex items-center justify-center rounded-sm size-7`,`text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-destructive/60`),children:(0,L.jsx)(rf,{className:`size-3.5`})}),(0,L.jsxs)(`div`,{className:`flex flex-col gap-2.5 pr-8`,children:[(0,L.jsxs)(nZ,{label:`Name`,hint:RZ(e,a,o),children:[(0,L.jsx)(aZ,{value:e.name,onChange:e=>f({name:e.target.value}),placeholder:`e.g. anthropic`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,invalid:o||!e.name.trim()}),o&&(0,L.jsx)(`span`,{className:`text-[12px] text-destructive/80`,children:`duplicate name`})]}),(0,L.jsx)(nZ,{label:`Type`,children:(0,L.jsx)(oZ,{value:e.type,onChange:e=>p(e.target.value),children:t.map(e=>(0,L.jsx)(`option`,{value:e,children:e},e))})}),(0,L.jsx)(nZ,{label:`Base URL`,children:(0,L.jsx)(aZ,{value:e.base_url,onChange:e=>f({base_url:e.target.value}),placeholder:`(provider default)`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`})}),e.type===`openai_chat`&&(0,L.jsx)(nZ,{label:`Reasoning effort`,hint:`Enable if this endpoint accepts a reasoning effort level.`,children:(0,L.jsxs)(NZ,{checked:e.supports_reasoning_effort,onCheckedChange:e=>f({supports_reasoning_effort:e}),"aria-label":`Reasoning effort supported`,className:li(`group flex h-9 items-center gap-2.5 px-2 cursor-pointer select-none`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent/60`),children:[(0,L.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-border/60 transition-colors group-hover:border-border group-data-[checked]:border-accent group-data-[checked]:bg-accent`,children:(0,L.jsx)(PZ,{children:(0,L.jsx)(Md,{className:`size-3 text-accent-foreground`,strokeWidth:3})})}),(0,L.jsx)(`span`,{className:`text-[13px] text-foreground/90`,children:`Supported`})]})}),(0,L.jsx)(nZ,{label:`API key`,hint:_,children:(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(aZ,{id:d,value:e.api_key_input,onChange:e=>f({api_key_input:e.target.value,api_key_dirty:!0}),placeholder:e.api_key_saved&&!e.api_key_dirty?`•••••• saved · type to replace`:"paste a key, or use ${ENV_VAR}",spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,autoComplete:`off`,type:`text`}),e.api_key_saved&&!e.api_key_dirty&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>f({api_key_input:``,api_key_dirty:!0}),className:li(`shrink-0 text-[12px]`,`text-muted-foreground/70 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`,`h-9 px-2`),"aria-label":`Clear saved API key`,children:`clear`})]})}),(0,L.jsx)(nZ,{label:`Models`,hint:e.models.length===0?zZ(i[e.type]):void 0,children:(0,L.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[e.models.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.models.map(e=>(0,L.jsxs)(`span`,{className:li(`group inline-flex items-center gap-1 rounded-sm h-7 pl-2.5 pr-1`,`bg-muted/60 text-foreground/90 text-[12px] font-mono`),children:[e,(0,L.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:li(`inline-flex items-center justify-center rounded-sm size-5`,`text-muted-foreground/60 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`),"aria-label":`Remove model ${e}`,children:(0,L.jsx)(rf,{className:`size-3`})})]},e))}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:g,"aria-label":`Add model`,placeholder:e.models.length===0?`add a model id…`:`add another…`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,className:li(`flex-1 min-w-0 bg-transparent h-9 px-2`,`text-[13px] font-mono`,`border-b border-border/60`,`transition-colors`,`placeholder:text-muted-foreground/50`,`hover:border-border focus:border-accent focus:outline-none`)}),l&&(0,L.jsx)(`button`,{type:`button`,onClick:m,className:li(`shrink-0 inline-flex items-center justify-center rounded-sm size-9`,`text-muted-foreground/70 hover:text-foreground hover:bg-muted/50 active:scale-95 transition-[color,background-color,scale] duration-150`),"aria-label":`Add model`,children:(0,L.jsx)(Yd,{className:`size-4`})})]})]})})]})]})});function LZ(e,t,n){if(e.original_name!==``&&e.original_name!==e.name.trim()&&e.api_key_saved&&!e.api_key_dirty)return(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`renamed from `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.original_name}),`: saved key won't carry over, paste it again`]});let r=e.api_key_input.trim().match(FZ);if(r){let e=r[1];return t[e]??!1?(0,L.jsxs)(L.Fragment,{children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:e}),` is set`]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:e}),` is not set`]})}if(!e.api_key_input.trim()&&!e.api_key_saved){let r=n[e.type]||[];if(r.length===0)return(0,L.jsx)(`span`,{className:`text-destructive/80`,children:`API key required. Paste a key or use an environment variable`});let i=r[0];return t[i]??!1?(0,L.jsxs)(L.Fragment,{children:[`using env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i})]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i}),` not set. Paste a key or set the env`]})}}function RZ(e,t,n){if(n)return;let r=e.name.trim();if(!r)return t.has(e.type)?(0,L.jsxs)(L.Fragment,{children:[`type `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.type}),` already used. pick an alias name`]}):void 0;if(r===e.type)return(0,L.jsxs)(L.Fragment,{children:[`overrides built-in `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.type})]})}function zZ(e){return!e||e.length===0?`add at least one model id`:(0,L.jsxs)(L.Fragment,{children:[`uses built-in:`,` `,e.map((t,n)=>(0,L.jsxs)(`span`,{children:[(0,L.jsx)(`code`,{className:`font-mono`,children:t}),n<e.length-1?`, `:``]},t))]})}var BZ=`~/.mycode/config.json`,VZ={default_provider:``,default_model:``,compact_threshold:``,permission_level:`safe`,permission_mode:`ask`,web_fetch:`local`,web_search:`off`,web_tavily:{api_key_input:``,api_key_dirty:!1,api_key_saved:!1},web_exa:{api_key_input:``,api_key_dirty:!1,api_key_saved:!1},providers:[]},HZ=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,UZ=[{value:`readonly`,label:`readonly`},{value:`safe`,label:`safe`},{value:`standard`,label:`standard`},{value:`yolo`,label:`yolo`}],WZ=[{value:`ask`,label:`ask`},{value:`deny`,label:`deny`}],GZ=li(`inline-flex items-center justify-center rounded-md text-[13px]`,`text-muted-foreground hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),KZ=li(`inline-flex items-center justify-center gap-1.5 rounded-md text-[13px] font-medium`,`bg-accent text-accent-foreground hover:brightness-105 hover:saturate-[.9] active:scale-95 transition-[color,filter,scale] duration-150`,`disabled:opacity-40 disabled:pointer-events-none`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`),qZ=[{value:`system`,label:`system`,icon:(0,L.jsx)(Hd,{className:`size-3.5`})},{value:`light`,label:`light`,icon:(0,L.jsx)(ef,{className:`size-3.5`})},{value:`dark`,label:`dark`,icon:(0,L.jsx)(Gd,{className:`size-3.5`})}];function JZ(e){let{config:t}=e,n=e.options.provider_types[0]??``,r={...VZ};r.default_provider=t.default?.provider??``,r.default_model=t.default?.model??``;let i=t.default?.compact_threshold;i===!1?r.compact_threshold=`disabled`:typeof i==`number`&&(r.compact_threshold=String(i));let a=t.permission;return typeof a==`string`?r.permission_level=a:a&&(a.level&&(r.permission_level=a.level),a.mode&&(r.permission_mode=a.mode)),r.web_fetch=t.web?.fetch??`local`,r.web_search=t.web?.search??`off`,r.web_tavily=YZ(t.web?.tavily),r.web_exa=YZ(t.web?.exa),r.providers=Object.entries(t.providers??{}).map(([e,t],r)=>({id:`p-${r}-${e}`,name:e,original_name:e,type:t.type??e??n,models:Array.isArray(t.models)?t.models:Object.keys(t.models??{}),model_overrides:t.model_overrides??{},base_url:t.base_url??``,supports_reasoning_effort:!!t.supports_reasoning_effort,api_key_input:typeof t.api_key==`string`?t.api_key:``,api_key_dirty:!1,api_key_saved:!!t.api_key_saved})),r}function YZ(e){return{api_key_input:typeof e?.api_key==`string`?e.api_key:``,api_key_dirty:!1,api_key_saved:!!e?.api_key_saved}}function XZ(e,t){let n={},r={};if(t.trim()&&(r.provider=t.trim()),e.default_provider.trim()===t.trim()&&e.default_model.trim()&&(r.model=e.default_model.trim()),e.compact_threshold===`disabled`)r.compact_threshold=!1;else if(e.compact_threshold.trim()){let t=Number(e.compact_threshold);Number.isFinite(t)&&(r.compact_threshold=t)}Object.keys(r).length&&(n.default=r),n.permission={level:e.permission_level,mode:e.permission_mode};let i={fetch:e.web_fetch,search:e.web_search};for(let t of[`tavily`,`exa`]){let n=t===`tavily`?e.web_tavily:e.web_exa;(n.api_key_saved||n.api_key_input.trim())&&(i[t]={api_key:n.api_key_dirty?n.api_key_input.trim():null})}n.web=i;let a={};for(let t of e.providers){let e=t.name.trim();if(!e)continue;let n={};if(t.type&&(n.type=t.type),t.models.length){let e={};for(let n of t.models){let r=t.model_overrides[n];r&&Object.keys(r).length&&(e[n]=r)}Object.keys(e).length?n.models=Object.fromEntries(t.models.map(t=>[t,e[t]??{}])):n.models=t.models}t.base_url.trim()&&(n.base_url=t.base_url.trim()),t.type===`openai_chat`&&t.supports_reasoning_effort&&(n.supports_reasoning_effort=!0);let r=t.original_name!==``&&t.original_name!==e;n.api_key=t.api_key_dirty||r?t.api_key_input.trim():null,a[e]=n}return Object.keys(a).length&&(n.providers=a),n}var ZZ=[];function QZ(e,t,n){let r=t.api_key_input.trim().match(HZ)?.[1];if(r)return n[r]?(0,L.jsxs)(L.Fragment,{children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:r}),` is set`]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:r}),` is not set`]});if(t.api_key_saved&&!t.api_key_dirty)return`saved key`;if(t.api_key_input.trim())return;let i=e===`tavily`?`TAVILY_API_KEY`:`EXA_API_KEY`;return n[i]?(0,L.jsxs)(L.Fragment,{children:[`using env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i})]}):e===`exa`?(0,L.jsx)(`span`,{className:`text-destructive/80`,children:`key required`}):`optional; requests use Tavily keyless access when unset`}function $Z({open:e,onClose:t,settings:n,loadError:r,remoteConfig:a,onSettingsSaved:o,projectConfigPaths:s}){let c=uf(`(min-width: 768px)`),{theme:l,setTheme:u}=i(),[d,f]=(0,E.useState)(()=>n?JZ(n):VZ),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(null),_=n?.options.provider_types??ZZ,v=n?.env??{},y=n?.provider_type_env_vars??{},b=n?.provider_type_default_models??{},x=(0,E.useMemo)(()=>{let e=new Map;for(let t of d.providers){let n=new Set;for(let e of d.providers)e.id!==t.id&&n.add(e.type);e.set(t.id,n)}return e},[d.providers]),S=(0,E.useMemo)(()=>{let e=new Map;for(let t of d.providers){let n=t.name.trim();n&&e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e)r>1&&t.add(n);return t},[d.providers]),C=Object.keys(a?.providers??{}),w=d.default_provider.trim(),T=a?.default?.provider??``,D=C.includes(w)?w:C.includes(T)?T:C[0]??``,O=S.size>0||d.providers.some(e=>!e.name.trim()||!e.type),k=d.compact_threshold===`disabled`,A=(0,E.useCallback)(e=>{f(t=>({...t,providers:t.providers.map(t=>t.id===e.id?e:t)}))},[]),j=(0,E.useCallback)((e,t)=>{f(n=>e===`tavily`?{...n,web_tavily:{...n.web_tavily,...t}}:{...n,web_exa:{...n.web_exa,...t}})},[]),M=(0,E.useCallback)(e=>{f(t=>({...t,providers:t.providers.filter(t=>t.id!==e)}))},[]),N=(0,E.useCallback)(()=>{f(e=>{let t=_[0]??``,n=e.providers.some(e=>e.type===t),r={id:`p-new-${Math.random().toString(36).slice(2,8)}`,name:n?``:t,original_name:``,type:t,models:[],model_overrides:{},base_url:``,supports_reasoning_effort:!1,api_key_input:``,api_key_dirty:!1,api_key_saved:!1};return{...e,providers:[...e.providers,r]}})},[_]),P=async()=>{if(!(!n||O||p)){m(!0),g(null);try{let e=await fetch(`/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({config:XZ(d,D)})});if(!e.ok){let t=`Save failed (${e.status})`;try{let n=await e.json();n?.detail&&(t=n.detail)}catch{}throw Error(t)}let n=await e.json();f(JZ(n)),o?.(n),t()}catch(e){g(e instanceof Error?e.message:`Failed to save settings`)}finally{m(!1)}}},F=(s??[]).filter(e=>e!==n?.path),I=`Edits ${eQ(n?.path??BZ)}`,ee=(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:li(`flex items-center justify-between shrink-0`,`border-b border-border/30`,`px-4 md:px-6 h-12 md:h-14`,`max-md:pt-[env(safe-area-inset-top)]`,`max-md:h-[calc(3rem+env(safe-area-inset-top))]`),children:[(0,L.jsx)(`h2`,{className:`text-[14px] font-semibold text-foreground`,children:`Settings`}),(0,L.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:li(`inline-flex items-center justify-center rounded-sm -mr-1`,`size-8`,`text-muted-foreground/70 hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),children:(0,L.jsx)(rf,{className:`size-4`})})]}),(0,L.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain scrollbar-subtle`,children:n?(0,L.jsxs)(`div`,{className:`px-4 md:px-6 py-6 flex flex-col gap-7`,children:[F.length>0&&(0,L.jsxs)(`div`,{className:`rounded-md border border-border/40 bg-muted/20 px-3.5 py-2.5 text-[12px] leading-relaxed`,children:[(0,L.jsx)(`div`,{className:`text-foreground/80`,children:`Project-level config in effect:`}),(0,L.jsx)(`ul`,{className:`mt-1.5 ml-4 list-disc text-muted-foreground/80 marker:text-muted-foreground/40 space-y-0.5`,children:F.map(e=>(0,L.jsx)(`li`,{className:`truncate font-mono`,children:eQ(e)},e))}),(0,L.jsx)(`div`,{className:`mt-1.5 text-muted-foreground/70`,children:`These continue to override settings saved here.`})]}),(0,L.jsx)(rZ,{title:`Appearance`,children:(0,L.jsx)(nZ,{label:`Theme`,children:(0,L.jsx)(iZ,{value:l,options:qZ,onChange:u,ariaLabel:`Theme`})})}),(0,L.jsxs)(rZ,{title:`Defaults`,children:[C.length===0?(0,L.jsx)(`div`,{className:`rounded-md border border-dashed border-border/50 px-3.5 py-2.5 text-[12px] text-muted-foreground/70`,children:`No runnable providers are available.`}):(0,L.jsx)(nZ,{label:`Provider`,children:(0,L.jsx)(oZ,{value:D,onChange:e=>f(t=>({...t,default_provider:e.target.value,default_model:``})),children:C.map(e=>(0,L.jsx)(`option`,{value:e,children:e},e))})}),(0,L.jsx)(nZ,{label:`Compact`,hint:k?(0,L.jsxs)(L.Fragment,{children:[`Auto-compaction disabled.`,` `,(0,L.jsx)(`button`,{type:`button`,onClick:()=>f(e=>({...e,compact_threshold:``})),className:`text-accent hover:underline focus-visible:outline-none focus-visible:underline`,children:`Enable`})]}):(0,L.jsxs)(L.Fragment,{children:[`Trigger compaction at this fraction of context window (default 0.8).`,` `,(0,L.jsx)(`button`,{type:`button`,onClick:()=>f(e=>({...e,compact_threshold:`disabled`})),className:`text-accent hover:underline focus-visible:outline-none focus-visible:underline`,children:`Disable`})]}),children:(0,L.jsx)(aZ,{type:`number`,min:0,max:1,step:.05,value:k?``:d.compact_threshold,placeholder:`0.8`,disabled:k,onChange:e=>f(t=>({...t,compact_threshold:e.target.value}))})})]}),(0,L.jsxs)(rZ,{title:`Web access`,children:[(0,L.jsx)(nZ,{label:`Fetch`,children:(0,L.jsxs)(oZ,{"aria-label":`Web fetch provider`,value:d.web_fetch,onChange:e=>f(t=>({...t,web_fetch:e.target.value})),children:[(0,L.jsx)(`option`,{value:`local`,children:`local`}),(0,L.jsx)(`option`,{value:`tavily`,children:`Tavily`}),(0,L.jsx)(`option`,{value:`exa`,children:`Exa`})]})}),(0,L.jsx)(nZ,{label:`Search`,children:(0,L.jsxs)(oZ,{"aria-label":`Web search provider`,value:d.web_search,onChange:e=>f(t=>({...t,web_search:e.target.value})),children:[(0,L.jsx)(`option`,{value:`off`,children:`Off`}),(0,L.jsx)(`option`,{value:`tavily`,children:`Tavily`}),(0,L.jsx)(`option`,{value:`exa`,children:`Exa`})]})}),[`tavily`,`exa`].map(e=>{if(!(d.web_fetch===e||d.web_search===e))return null;let t=e===`tavily`?d.web_tavily:d.web_exa,n=e===`tavily`?`Tavily`:`Exa`;return(0,L.jsx)(nZ,{label:`${n} key`,hint:QZ(e,t,v),children:(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(aZ,{"aria-label":`${n} API key`,value:t.api_key_input,onChange:t=>j(e,{api_key_input:t.target.value,api_key_dirty:!0}),placeholder:t.api_key_saved&&!t.api_key_dirty?`•••••• saved · type to replace`:"paste a key, or use ${ENV_VAR}",spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,autoComplete:`off`}),t.api_key_saved&&!t.api_key_dirty&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>j(e,{api_key_input:``,api_key_dirty:!0}),className:`shrink-0 h-9 px-2 text-[12px] text-muted-foreground/70 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`,"aria-label":`Clear saved ${e} API key`,children:`clear`})]})},e)})]}),(0,L.jsxs)(rZ,{title:`Permissions`,children:[(0,L.jsxs)(nZ,{label:`Level`,children:[(0,L.jsx)(`div`,{className:`md:hidden`,children:(0,L.jsx)(oZ,{value:d.permission_level,onChange:e=>f(t=>({...t,permission_level:e.target.value})),children:UZ.map(e=>(0,L.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,L.jsx)(`div`,{className:`max-md:hidden`,children:(0,L.jsx)(iZ,{value:d.permission_level,onChange:e=>f(t=>({...t,permission_level:e})),options:UZ,ariaLabel:`Permission level`,size:`sm`})})]}),(0,L.jsx)(nZ,{label:`Mode`,children:(0,L.jsx)(iZ,{value:d.permission_mode,onChange:e=>f(t=>({...t,permission_mode:e})),options:WZ,ariaLabel:`Permission mode`,size:`sm`})})]}),(0,L.jsx)(rZ,{title:`Providers`,children:(0,L.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[d.providers.map(e=>(0,L.jsx)(IZ,{draft:e,providerTypes:_,envByName:v,providerTypeEnvVars:y,providerTypeDefaultModels:b,usedTypesByOthers:x.get(e.id)??new Set,duplicateName:S.has(e.name.trim()),onChange:A,onRemove:M},e.id)),(0,L.jsxs)(`button`,{type:`button`,onClick:N,className:li(`inline-flex items-center justify-center gap-1.5 rounded-lg h-9`,`border border-dashed border-border/50 text-muted-foreground/80`,`hover:border-border hover:text-foreground hover:bg-muted/30 active:scale-95 transition-[color,background-color,border-color,scale] duration-150`,`text-[13px]`),children:[(0,L.jsx)(Yd,{className:`size-4`}),`Add provider`]})]})})]}):(0,L.jsx)(`div`,{className:`flex items-center justify-center h-48 px-6 text-center text-[12px] text-muted-foreground/60`,children:r?(0,L.jsx)(`span`,{children:r}):null})}),(0,L.jsxs)(`div`,{className:li(`shrink-0 border-t border-border/30`,`max-md:pb-[env(safe-area-inset-bottom)]`),children:[(0,L.jsxs)(`div`,{className:`md:hidden flex flex-col gap-2 px-4 py-3`,children:[h&&(0,L.jsx)(`div`,{className:`text-[12px] text-destructive/90 leading-relaxed`,children:h}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:t,className:li(GZ,`flex-1 h-9`),children:`Cancel`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void P(),disabled:!n||p||O,className:li(KZ,`flex-2 h-9`),children:[p&&(0,L.jsx)(Ud,{className:`size-3.5 animate-spin`}),`Save`]})]})]}),(0,L.jsxs)(`div`,{className:`max-md:hidden flex items-center justify-between gap-3 px-6 py-3`,children:[(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/70 truncate min-w-0 flex-1`,children:h?(0,L.jsx)(`span`,{className:`text-destructive/90`,children:h}):I}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:t,className:li(GZ,`h-8 px-3.5`),children:`Cancel`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void P(),disabled:!n||p||O,className:li(KZ,`h-8 px-4`),children:[p&&(0,L.jsx)(Ud,{className:`size-3.5 animate-spin`}),`Save`]})]})]})]})]}),te=e=>{e||t()};return c?(0,L.jsx)(ZX,{open:e,onOpenChange:te,children:(0,L.jsxs)(eZ,{showCloseButton:!1,className:`flex flex-col gap-0 p-0 w-160 max-w-[calc(100vw-2rem)] max-h-[82vh] sm:max-w-[calc(100vw-2rem)]`,children:[(0,L.jsx)(tZ,{className:`sr-only`,children:`Settings`}),ee]})}):(0,L.jsx)(af,{open:e,onOpenChange:te,children:(0,L.jsxs)(cf,{side:`bottom`,showCloseButton:!1,className:`flex flex-col gap-0 p-0 h-dvh rounded-none`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Settings`}),ee]})})}function eQ(e){if(!e)return``;let t=e.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(.*)$/);return t?`~${t[2]??``}`:e}function tQ(){return typeof window>`u`?480:Math.min(480,Math.floor(window.innerWidth*.4))}function nQ(e){return Math.max(200,Math.min(tQ(),e))}function rQ(e){return e?!0:typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(hover: hover) and (pointer: fine)`).matches}var iQ=e=>e.replace(/\\/g,`/`),aQ=e=>/^([a-zA-Z]:[\\/]|\/)/.test(e),oQ=(e,t,n=!0)=>{let r=iQ(t);return e.toSorted((e,t)=>t.length-e.length).find(e=>{let t=iQ(e).replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})||(n?e[0]:void 0)},sQ=(e,t)=>{let n=iQ(e).replace(/\/+$/,``),r=iQ(t);return r===n?``:(r.startsWith(n)?r.slice(n.length):r).replace(/^\/+/,``)},cQ=[],lQ=[],uQ=e=>{if(!e||e===`/`||e===`\\`)return`/`;let t=e.replace(/[\\/]+$/,``);if(/\/Users\/[^/]+$/.test(t)||/\/home\/[^/]+$/.test(t))return`~`;let n=t.split(/[/\\]/);return n[n.length-1]||e};async function dQ(e){let t=await fetch(e);if(!t.ok)throw Error(`Failed to load roots`);return(await t.json()).roots??[]}async function fQ(e){let t=await fetch(e);if(!t.ok)throw Error(`Failed to browse directory`);let n=await t.json();if(n.error)throw Error(n.error);return n}var pQ={revalidateOnFocus:!1},mQ={revalidateOnFocus:!1};function hQ(e){if(!e?.root)return null;let t=new URLSearchParams({root:e.root});return e.path&&t.set(`path`,e.path),`/api/workspaces/browse?${t.toString()}`}function gQ(e){return e instanceof Error?e.message:`Unknown error`}function _Q(e,t,n){if(!e||t.length===0)return null;let r=n?oQ(t,n):t[0];return r?{root:r,path:n?sQ(r,n):``}:null}function vQ({open:e,openedWithKeyboard:t,onClose:n,currentCwd:r,cwdHistory:i=cQ,onSelect:a,onMissingHistory:o}){let s=uf(`(min-width: 640px)`),{data:c=[],error:l,isLoading:u}=nt(`/api/workspaces/roots`,dQ,pQ),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(``),[h,g]=(0,E.useState)(``),_=(0,E.useRef)(null),v=(0,E.useMemo)(()=>_Q(e,c,r),[e,c,r]),y=d??v,b=hQ(y),{data:x,error:S}=nt(b,fQ,mQ),C=x?{root:x.root,path:x.path}:y,w=C?.root??``,T=C?.path??``,D=x?.entries??lQ,O=x?.current??``,k=u||!!b&&!x&&!S,A=(0,E.useMemo)(()=>{let e=h.trim().toLowerCase();return e?D.filter(t=>t.name.toLowerCase().includes(e)):D},[h,D]),j=(0,E.useCallback)((e,t)=>{m(``),g(``),f(n=>n?.root===e&&n.path===t?n:{root:e,path:t})},[]),M=(0,E.useCallback)(e=>{let t=e.trim();if(!(!t||c.length===0)){if(aQ(t)){let e=oQ(c,t,!1);if(!e){m(`Path is outside any configured workspace root.`);return}j(e,sQ(e,t))}else if(w){let e=T?`${T}/${t}`:t;j(w,e)}}},[c,w,T,j]),N=(0,E.useCallback)(()=>{if(!w||!T)return;let e=T.split(`/`);j(w,e.slice(0,-1).join(`/`))},[w,T,j]),P=(0,E.useCallback)(()=>{O&&(a(O),n())},[O,a,n]),F=(0,E.useCallback)(async e=>{try{let t=oQ(c,e,!1);if(!t)return!1;let n=hQ({root:t,path:sQ(t,e)});if(!n)return!1;let r=await fetch(n);if(!r.ok)return!1;let i=await r.json();return!!(i.current&&!i.error)}catch{return!1}},[c]),I=(0,E.useCallback)(async e=>{if(!await F(e)){m(`Workspace no longer exists.`),o?.(e);return}a(e),n()},[F,o,a,n]),ee=(0,E.useCallback)(e=>{if(e.key===`Enter`){let e=A.length===1?A[0]:null;e&&w?j(w,e.path):h.trim()&&M(h)}else if(e.key===`Tab`){e.preventDefault();let t=A[0];t&&w&&j(w,t.path)}else e.key===`Escape`&&h?(e.preventDefault(),e.stopPropagation(),g(``)):e.key===`Backspace`&&!h&&N()},[h,A,w,j,M,N]),te=T?T.split(`/`):[],ne=O||r||``,re=i.filter(e=>e!==ne),ie=re.length>0&&!h.trim(),ae=p||(S?`Workspace no longer exists. Choose another workspace.`:``),oe=(l?gQ(l):``)||(!u&&c.length===0?`No workspace roots configured.`:``),se=!!S&&c.length>0&&!h.trim(),ce=(0,L.jsxs)(L.Fragment,{children:[!s&&(0,L.jsx)(`div`,{className:`flex justify-center pt-2.5 pb-1 shrink-0`,"aria-hidden":`true`,children:(0,L.jsx)(`div`,{className:`w-10 h-0.75 rounded-full bg-border/60`})}),(0,L.jsxs)(`div`,{className:`flex items-center min-h-11 px-4 border-b border-border/30 shrink-0 gap-1`,children:[(0,L.jsxs)(`div`,{className:`flex-1 flex items-center overflow-x-auto scrollbar-none min-w-0 gap-0.5`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:()=>w&&j(w,``),className:li(`shrink-0 px-1.5 py-0.5 rounded-sm text-xs font-mono`,`active:scale-95 transition-[color,background-color,scale] duration-150 hover:bg-muted/60 hover:text-foreground`,te.length===0?`text-foreground font-medium`:`text-muted-foreground`),children:uQ(w)||`~`}),te.map((e,t)=>{let n=te.slice(0,t+1).join(`/`);return(0,L.jsxs)(`div`,{className:`flex items-center shrink-0`,children:[(0,L.jsx)(`span`,{className:`text-border select-none mx-0.5 text-xs`,"aria-hidden":`true`,children:`/`}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>j(w,n),className:li(`px-1.5 py-0.5 rounded-sm text-xs font-mono whitespace-nowrap`,`active:scale-95 transition-[color,background-color,scale] duration-150 hover:bg-muted/60 hover:text-foreground`,t===te.length-1?`text-foreground font-medium`:`text-muted-foreground`),children:e})]},n)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:n,className:li(`flex items-center justify-center size-8 rounded-lg shrink-0`,`text-muted-foreground/50 active:scale-95 transition-[color,background-color,scale] duration-150`,`hover:bg-muted/70 hover:text-foreground`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`),"aria-label":`Close`,children:(0,L.jsx)(rf,{className:`size-3.5`})})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2.5 px-4 py-2.5 border-b border-border/20 shrink-0`,children:[(0,L.jsx)(Xd,{className:`size-3.5 shrink-0 text-muted-foreground/30`}),(0,L.jsx)(`input`,{ref:_,name:`workspace-filter`,value:h,onChange:e=>g(e.target.value),onKeyDown:ee,placeholder:`Filter or type a path…`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,className:`w-full bg-transparent text-base sm:text-sm font-mono focus-visible:outline-none text-foreground placeholder:text-muted-foreground/30 caret-accent`,"aria-label":`Filter directories or enter a path`}),h&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>g(``),className:`shrink-0 text-muted-foreground/40 hover:text-muted-foreground active:scale-95 transition-[color,scale] duration-150`,"aria-label":`Clear filter`,children:(0,L.jsx)(rf,{className:`size-3`})})]}),(0,L.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain`,children:[k&&(0,L.jsx)(`div`,{className:`flex items-center justify-center h-36`,children:(0,L.jsx)(`div`,{className:`flex items-end gap-1`,children:[0,1,2].map(e=>(0,L.jsx)(`div`,{className:`w-0.75 rounded-full bg-muted-foreground/30 animate-pulse`,style:{height:`${12+e*4}px`,animationDelay:`${e*120}ms`}},e))})}),!k&&oe&&(0,L.jsx)(`div`,{className:`flex items-center justify-center h-36 px-6 text-center`,children:(0,L.jsx)(`p`,{className:`text-xs text-destructive leading-relaxed`,children:oe})}),!k&&!oe&&(0,L.jsxs)(`div`,{className:`py-1`,children:[ae&&(0,L.jsx)(`div`,{className:`mx-4 my-2 rounded-md border border-border/30 bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-muted-foreground`,children:ae}),ie&&(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`div`,{className:`px-4 pt-3 pb-1.5`,children:(0,L.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/40 select-none`,children:`Recent`})}),re.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void I(e),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(Fd,{className:`size-3.5 shrink-0 text-muted-foreground/35 group-hover:text-accent/60 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-xs font-mono text-muted-foreground group-hover:text-foreground/80 transition-colors`,children:e})]},e)),(A.length>0||se)&&(0,L.jsx)(`div`,{className:`mx-4 mt-1 mb-1 border-b border-border/20`})]}),se&&(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`div`,{className:`px-4 pt-3 pb-1.5`,children:(0,L.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/40 select-none`,children:`Roots`})}),c.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>j(e,``),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(zd,{className:`size-3.5 shrink-0 text-muted-foreground/35 group-hover:text-accent/60 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-xs font-mono text-muted-foreground group-hover:text-foreground/80 transition-colors`,children:e})]},e)),A.length>0&&(0,L.jsx)(`div`,{className:`mx-4 mt-1 mb-1 border-b border-border/20`})]}),A.length===0&&!ie&&!se&&(0,L.jsxs)(`div`,{className:`flex flex-col items-center justify-center gap-3 h-36 text-muted-foreground/30`,children:[(0,L.jsx)(Bd,{className:`size-10`,strokeWidth:1}),(0,L.jsx)(`p`,{className:`text-xs`,children:h.trim()?`No matches`:`This folder is empty`})]}),A.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>j(w,e.path),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(Bd,{className:`size-3.5 shrink-0 text-accent/40 group-hover:text-accent/70 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-sm font-mono text-foreground/70 group-hover:text-foreground transition-colors`,children:e.name})]},e.path))]})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-3 h-12 px-4 border-t border-border/20 shrink-0`,children:[(0,L.jsx)(zd,{className:`size-3.5 shrink-0 text-muted-foreground/30`}),(0,L.jsx)(`span`,{className:`flex-1 min-w-0 truncate text-xs font-mono text-muted-foreground/60`,title:O,children:O||`—`}),(0,L.jsx)(`button`,{type:`button`,onClick:P,disabled:!O,className:li(`shrink-0 px-3.5 h-7 rounded-md text-xs font-semibold`,`active:scale-95 transition-[color,background-color,border-color,scale] duration-150`,`bg-accent/15 text-accent border border-accent/20`,`hover:bg-accent/25 hover:border-accent/40 active:bg-accent/30`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,`disabled:opacity-25 disabled:cursor-not-allowed`),children:`Open`})]})]}),le=e=>{e||n()},ue=rQ(t)?_:void 0;return s?(0,L.jsx)(ZX,{open:e,onOpenChange:le,children:(0,L.jsxs)(eZ,{showCloseButton:!1,initialFocus:ue,className:`flex flex-col gap-0 p-0 w-110 max-w-[calc(100vw-2rem)] max-h-130 sm:max-w-[calc(100vw-2rem)]`,children:[(0,L.jsx)(tZ,{className:`sr-only`,children:`Select workspace`}),ce]})}):(0,L.jsx)(af,{open:e,onOpenChange:le,children:(0,L.jsxs)(cf,{side:`bottom`,showCloseButton:!1,initialFocus:ue,className:`flex flex-col gap-0 p-0 max-h-[82vh] rounded-t-2xl`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Select workspace`}),ce]})})}function yQ(e){if(!e||e===`.`)return`~`;let t=e.replace(/\/+$/,``),n=t.split(/[/\\]/);return n[n.length-1]||t}function bQ(e){if(!e||e===`.`)return``;let t=e.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(.*)$/);return t?`~${t[2]||``}`:e}var xQ={today:`today`,yesterday:`yesterday`,week:`this week`,older:`older`};function SQ(e,t){let n=1440*60*1e3,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),i=r-e.getTime();return i<n&&e.getTime()>=r?`today`:i<2*n?`yesterday`:i<7*n?`week`:`older`}function CQ(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function wQ(e){return e.toLocaleDateString(void 0,{month:`short`,day:`numeric`})}function TQ({width:e,onResize:t,onResizeReset:n}){let[r,i]=(0,E.useState)(!1);return(0,L.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize sidebar`,"aria-valuemin":200,"aria-valuemax":tQ(),"aria-valuenow":e,tabIndex:0,onPointerDown:n=>{if(n.button!==0)return;n.preventDefault();let r=n.clientX,a=e;i(!0),Object.assign(document.body.style,{cursor:`col-resize`,userSelect:`none`});let o=e=>{t(nQ(a+(e.clientX-r)))},s=()=>{i(!1),Object.assign(document.body.style,{cursor:``,userSelect:``}),window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},onDoubleClick:n,onKeyDown:r=>{let i=r.shiftKey?32:8;r.key===`ArrowLeft`?(r.preventDefault(),t(nQ(e-i))):r.key===`ArrowRight`?(r.preventDefault(),t(nQ(e+i))):r.key===`Home`&&(r.preventDefault(),n())},className:li(`group/resizer hidden md:block`,`absolute top-0 bottom-0 -right-0.75 w-1.5 z-20 cursor-col-resize`,`focus-visible:outline-none`),children:(0,L.jsx)(`div`,{className:li(`absolute inset-y-0 right-0.75 w-px transition-colors`,r?`bg-accent`:`bg-transparent group-hover/resizer:bg-accent/60 group-focus-visible/resizer:bg-accent/60`)})})}var EQ=(0,E.memo)(function({className:e,sessions:t,activeSession:n,onSelectSession:r,onCreateSession:i,onDeleteSession:a,config:o,remoteConfig:s,cwdHistory:c,onUpdateConfig:l,onRemoveHistory:u,onOpenSettings:d,workspaceMissing:f=!1,width:p,onResize:m,onResizeReset:h}){let[g,_]=(0,E.useState)(!1),[v,y]=(0,E.useState)(0),b=(0,E.useRef)(!1),x=o.cwd===`.`?s?.cwd||`.`:o.cwd,S=yQ(x),C=bQ(x),w=(0,E.useMemo)(()=>{let e=new Date,n=t.filter(e=>!e.isDraft),r={today:[],yesterday:[],week:[],older:[]};for(let t of n){let n=CQ(t.updated_at)||CQ(t.created_at);r[n?SQ(n,e):`older`].push(t)}let i=[];for(let e of[`today`,`yesterday`,`week`,`older`]){let t=r[e];t.length>0&&i.push({bucket:e,sessions:t})}return i},[t]);return(0,L.jsxs)(`div`,{className:li(`relative flex w-64 md:w-(--sidebar-width) flex-col border-r border-border/50 bg-sidebar-bg`,e),style:{"--sidebar-width":`${p}px`},children:[(0,L.jsxs)(`div`,{className:`shrink-0 flex items-center gap-2.5 px-5 pt-5 pb-5`,children:[(0,L.jsx)(tf,{className:`size-4 text-foreground`,"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:`font-display text-[15px] leading-none tracking-tight text-foreground font-medium`,children:`mycode`})]}),(0,L.jsx)(`div`,{className:`shrink-0 px-5 mb-5`,children:(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,L.jsxs)(`button`,{type:`button`,onPointerDown:()=>{b.current=!1},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(b.current=!0)},onClick:()=>{y(e=>e+1),_(!0)},title:x,"aria-label":`Workspace: ${x}. Click to switch.`,className:li(`group/ws flex flex-col items-start gap-0.5 min-w-0 flex-1 text-left`,`focus-visible:outline-none`),children:[(0,L.jsx)(`span`,{className:`font-mono text-[13px] leading-snug text-foreground/90 group-hover/ws:text-foreground transition-colors truncate max-w-full`,children:S}),C&&(0,L.jsx)(`span`,{className:`font-mono text-[11px] leading-snug text-muted-foreground/60 group-hover/ws:text-muted-foreground/85 transition-colors break-all`,children:C}),f&&(0,L.jsx)(`span`,{className:`font-mono text-[10px] leading-snug text-muted-foreground/55`,children:`missing`})]}),(0,L.jsx)(`button`,{type:`button`,onClick:i,"aria-label":`New chat`,title:`New chat`,className:li(`shrink-0 size-6 mt-0.5 flex items-center justify-center rounded-sm`,`text-muted-foreground hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:bg-muted/60`),children:(0,L.jsx)(Yd,{className:`size-3.5`})})]})}),(0,L.jsx)(vQ,{open:g,openedWithKeyboard:b.current,onClose:()=>_(!1),currentCwd:o.cwd,cwdHistory:c,onSelect:e=>l({...o,cwd:e}),onMissingHistory:u},v),(0,L.jsx)(`div`,{className:`flex-1 overflow-y-auto scrollbar-subtle`,children:w.length===0?(0,L.jsx)(`div`,{className:`px-5 py-12 text-[12px] text-muted-foreground/50`,children:`no history yet`}):w.map(({bucket:e,sessions:t},i)=>(0,L.jsxs)(`div`,{className:li(i>0&&`mt-4`),children:[(0,L.jsx)(`div`,{className:`px-5 pb-1 text-[11px] tracking-wide text-muted-foreground/55 lowercase`,children:xQ[e]}),t.map(t=>{let i=n?.id===t.id,o=t.is_running,s=CQ(t.updated_at)||CQ(t.created_at),c=e===`older`&&s;return(0,L.jsxs)(`div`,{className:`group relative`,children:[(0,L.jsx)(`span`,{className:li(`pointer-events-none absolute inset-y-0 left-0 right-2`,i?`bg-accent/10`:`bg-transparent`),"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:li(`absolute left-0 top-1.5 bottom-1.5 z-10 w-0.5 rounded-r`,i?`bg-accent`:`bg-transparent`),"aria-hidden":`true`}),(0,L.jsxs)(`button`,{type:`button`,"aria-current":i?`true`:void 0,className:li(`relative z-10 flex w-full items-center gap-2 pl-5 pr-9 py-1.5 text-[13px] text-left transition-colors`,i?`text-foreground`:`text-muted-foreground hover:text-foreground`),onClick:()=>r(t.id),children:[(0,L.jsx)(`span`,{className:`truncate flex-1`,children:t.title||`New Chat`}),o&&(0,L.jsx)(`span`,{className:`shrink-0 size-1.5 rounded-full bg-accent animate-breathing`,role:`img`,"aria-label":`Running`}),c&&!o&&(0,L.jsx)(`span`,{className:`shrink-0 text-[10px] font-mono text-muted-foreground/45`,children:wQ(s)})]}),(0,L.jsx)(`button`,{type:`button`,"aria-label":`Delete session`,title:`Delete`,onClick:e=>{e.stopPropagation(),a(t.id)},className:li(`absolute right-3 top-1/2 z-20 -translate-y-1/2 size-5 flex items-center justify-center rounded-sm`,`opacity-0 group-hover:opacity-100 max-md:opacity-100`,`text-muted-foreground/60 hover:text-destructive hover:bg-destructive/10 active:scale-95 transition-[color,background-color,scale] duration-150`),children:(0,L.jsx)(nf,{className:`size-3`})})]},t.id)})]},e))}),(0,L.jsx)(`div`,{className:`shrink-0 p-3 flex items-center`,children:(0,L.jsx)(`button`,{type:`button`,onClick:d,"aria-label":`Open settings`,title:`Settings`,className:li(`size-7 flex items-center justify-center rounded-md active:scale-95 transition-[color,background-color,scale] duration-150`,`text-muted-foreground hover:text-foreground hover:bg-muted/50`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),children:(0,L.jsx)(Zd,{className:`size-3.5`})})}),m&&h&&(0,L.jsx)(TQ,{width:p,onResize:m,onResizeReset:h})]})}),DQ=Object.freeze({});function OQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kQ(e){return Array.isArray(e?.content)?e.content:[]}function AQ(e,t=null){let n={...e};return n.meta&&={...n.meta},t&&(n.renderKey=t),n}function jQ(e,t=[]){return{role:e,content:t}}function MQ(e){return{type:`text`,text:e}}function NQ(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function PQ(e,t){return{type:`text`,text:`<file name="${NQ(t)}">\n${e}\n</file>`,meta:{attachment:!0,path:t}}}function FQ(e){return{type:`thinking`,text:e}}function IQ(e){return{type:`tool_use`,id:e?.id||``,name:e?.name||`tool`,input:OQ(e?.input)?e.input:DQ}}function LQ(e,t,n,r=!1){return{type:`tool_result`,tool_use_id:e,output:t,metadata:n,is_error:r}}function RQ(e,t,n){let r={type:`image`,data:e,mime_type:t};return n&&(r.name=n),r}function zQ(e,t,n){let r={type:`document`,data:e,mime_type:t};return n&&(r.name=n),r}function BQ(e){return e.kind===`image`?RQ(e.data,e.mime_type,e.name):e.kind===`document`?zQ(e.data,e.mime_type,e.name):PQ(e.text,e.name)}function VQ(e){return e.kind===`image`?RQ(``,``,e.name):e.kind===`document`?zQ(``,`application/pdf`,e.name):PQ(``,e.path)}function HQ(e){return jQ(`user`,e?[MQ(e)]:[])}function UQ(e,t,n=[]){let r=[];e&&r.push(MQ(e));for(let e of n)r.push(VQ(e));for(let e of t)r.push(BQ(e));return jQ(`user`,r)}function WQ(e=[]){return jQ(`assistant`,e)}function GQ(e){let t=[...e],n=t.length-1;return n>=0&&t[n]?.role===`assistant`?{messages:t,index:n}:(t.push(WQ([])),{messages:t,index:t.length-1})}function KQ(e,t,n){if(!n)return e;let{messages:r,index:i}=GQ(e),a=r[i]??WQ([]),o=[...kQ(a)],s=o[o.length-1];return s?.type===t?o[o.length-1]={...s,text:`${s.text||``}${n}`}:o.push(t===`thinking`?FQ(n):MQ(n)),r[i]={...a,content:o},r}function qQ(e,t){let{messages:n,index:r}=GQ(e),i=n[r];return i&&(n[r]={...i,content:[...kQ(i),IQ(t)]}),n}function JQ(e){let t=kQ(e);return e?.role===`user`&&t.length>0&&t.every(e=>e?.type===`tool_result`)}function YQ(e,t,n,r,i=!1){let a=LQ(t,n,r,i),o=[...e],s=o.length-1;if(s>=0&&JQ(o[s])){let e=o[s];return e&&(o[s]={...e,content:[...kQ(e),a]}),o}return o.push(jQ(`user`,[a])),o}function XQ(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.role!==`assistant`)continue;let i=kQ(r);for(let a=i.length-1;a>=0;a--){let o=i[a];if(o?.type!==`thinking`)continue;let s=[...e],c=[...i];return c[a]={...o,meta:{...OQ(o.meta)?o.meta:{},duration_ms:t}},s[n]={...r,content:c},s}}return e}function ZQ(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.role!==`assistant`)continue;let i=[...e];return i[n]={...r,meta:{...r.meta??{},...t}},i}return e}function QQ(e,t){let n=typeof e?.output==`string`?e.output:``,r=typeof e?.finalOutput==`string`?e.finalOutput:null,i=typeof t?.output==`string`?t.output:null,a=r??i,o=OQ(e?.metadata)?e.metadata:null,s=OQ(t?.metadata)?t.metadata:null,c=o??s,l=!!(e?.isError||t?.is_error||typeof a==`string`&&a.startsWith(`error:`));return{pending:!!e?.pending,output:n,finalOutput:a,metadata:c,isError:l}}function $Q(e){return{kind:`compact-marker`,sourceIndex:e,renderKey:`compact:${e}`}}var e$=[`total_tokens`,`input_tokens`,`output_tokens`,`cache_read_tokens`,`cache_write_tokens`,`reasoning_tokens`];function t$(e){return OQ(e)&&typeof e.total==`number`?e:void 0}function n$(e,t){if(!t)return e;if(!e)return{...t};let n=e.total+t.total;if(e.input===void 0||e.output===void 0||t.input===void 0||t.output===void 0)return{total:n};let r={input:e.input+t.input,output:e.output+t.output,total:n};return(e.cache_read!==void 0||t.cache_read!==void 0)&&(r.cache_read=(e.cache_read??0)+(t.cache_read??0)),(e.cache_write!==void 0||t.cache_write!==void 0)&&(r.cache_write=(e.cache_write??0)+(t.cache_write??0)),(e.reasoning!==void 0||t.reasoning!==void 0)&&(r.reasoning=(e.reasoning??0)+(t.reasoning??0)),r}function r$(e,t){if(!t)return e;let n=typeof t.context_window==`number`?t.context_window:e?.context_window;if(t.turn_usage!==void 0||t.turn_cost!==void 0){let e={};n!==void 0&&(e.context_window=n),typeof t.context_tokens==`number`&&(e.context_tokens=t.context_tokens);for(let n of e$){let r=t.turn_usage?.[n];r!==void 0&&(e[n]=r)}let r=t$(t.turn_cost);return r&&(e.cost=r),e}let r=OQ(t.usage)?t.usage:null,i=t$(t.cost);if(!r&&!i)return e;let a={...e};if(n!==void 0&&(a.context_window=n),r){let e=r.total_tokens;delete a.context_tokens,typeof e==`number`&&(a.context_tokens=e);for(let e of e$){let t=r[e];typeof t==`number`&&(a[e]=(a[e]??0)+t)}}let o=n$(a.cost,i);return o&&(a.cost=o),a}function i$(e){return{role:`assistant`,content:[],renderKey:`assistant:${e}`,sourceIndex:e}}function a$(e,t={}){if(!Array.isArray(e))return[];let n=[],r={},i=null,a,o=null,s=()=>{if(a&&o!==null){let e=n[o];e&&!Bj(e)&&(n[o]={...e,stats:a})}a=void 0,o=null},c=e=>i||(i=i$(e),n.push(i),i);for(let[l,u]of e.entries()){let e=u?.role,d=kQ(u);if(e===`compact`){let e=a?.context_tokens;a=r$(a,u?.meta),a&&(e===void 0?delete a.context_tokens:a.context_tokens=e),n.push($Q(l)),i=null;continue}if(e===`user`){let e=[],a=[];for(let[t,n]of d.entries())n?.type===`text`&&n.meta?.skill_snapshot||(n?.type===`text`&&n.text||n?.type===`image`||n?.type===`document`?e.push(AQ(n,`user:${l}:${t}`)):n?.type===`tool_result`&&a.push(n));if(e.length>0){s();let t={role:`user`,content:e,renderKey:`user:${l}`,sourceIndex:l};OQ(u?.meta)&&(t.meta={...u.meta}),n.push(t),i=null}if(a.length===0)continue;let o=c(l),f=[...kQ(o)];for(let e of a){let a=e.tool_use_id,s=a?t[a]:void 0,c=a?r[a]:void 0;if(c){let t=n[c.messageIndex];if(t&&!Bj(t)){let r=[...kQ(t)],a=r[c.blockIndex];if(a?.type===`tool_use`){r[c.blockIndex]={...a,runtime:QQ(s,e)};let o={...t,content:r};n[c.messageIndex]=o,c.messageIndex===n.length-1&&(i=o,f=r)}}continue}let u={type:`tool_use`,id:a||``,name:`tool`,input:DQ,runtime:QQ(s,e)},d=f.length;u.renderKey=a||`tool-result:${l}:${d}`,f.push(u),i={...o,content:f},n[n.length-1]=i,a&&(r[a]={messageIndex:n.length-1,blockIndex:d})}continue}if(e!==`assistant`)continue;let f=c(l),p=[...kQ(f)],m=n.length-1;for(let[e,n]of d.entries()){if(n?.type===`thinking`&&n.text){p.push(AQ(n,`assistant:${l}:${e}`));continue}if(n?.type===`text`&&n.text){p.push(AQ(n,`assistant:${l}:${e}`));continue}if(n?.type!==`tool_use`)continue;let i={type:`tool_use`,id:n.id,name:n.name,input:OQ(n.input)?n.input:DQ,runtime:QQ(n.id?t[n.id]:void 0,null)};i.renderKey=n.id||`assistant:${l}:${e}`,OQ(n.meta)&&(i.meta={...n.meta});let a=p.length;p.push(i),n.id&&(r[n.id]={messageIndex:m,blockIndex:a})}let h={...f,content:p},g=u?.meta;g?h.meta={...g}:delete h.meta,a=r$(a,g),a&&(o=m),i=h,n[m]=h}return s(),n.filter((e,t)=>Bj(e)?!0:Array.isArray(e.content)&&e.content.length>0||t===n.length-1&&e.role===`assistant`)}var o$=`mycode_config`,s$=`mycode_cwd_history`,c$=`mycode_active_sessions`,l$=`mycode_sidebar_width`,u$=2,d$={provider:``,model:``,cwd:`.`,reasoningEfforts:{}};function f$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function p$(e,t,n){return typeof e[t]==`string`?e[t]:n}function m$(e){let t=e.reasoningEfforts,n={};if(f$(t))for(let[e,r]of Object.entries(t))bj(r)&&(n[e]=r);return{provider:p$(e,`provider`,d$.provider),model:p$(e,`model`,d$.model),cwd:p$(e,`cwd`,d$.cwd),reasoningEfforts:n}}function h$(){try{let e=localStorage.getItem(o$);if(e){let t=JSON.parse(e);if(!f$(t))return d$;let n=t._v;return n!==1&&n!==u$?d$:m$(t)}}catch(e){console.error(`Failed to load config:`,e)}return d$}function g$(e){try{localStorage.setItem(o$,JSON.stringify({...e,_v:u$}))}catch(e){console.error(`Failed to save config:`,e)}}function _$(){try{let e=localStorage.getItem(s$);if(e){let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}}catch(e){console.error(`Failed to load history:`,e)}return[]}function v$(e){try{localStorage.setItem(s$,JSON.stringify(e.slice(0,6)))}catch(e){console.error(`Failed to save history:`,e)}}function y$(e,t){if(!t)return e;let n=t.trim();return n?[n,...e.filter(e=>e!==n)].slice(0,6):e}function b$(e){return typeof e==`string`&&e.trim()||`.`}function x$(){try{let e=localStorage.getItem(c$);if(!e)return{};let t=JSON.parse(e);return f$(t)?Object.fromEntries(Object.entries(t).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`)):{}}catch(e){return console.error(`Failed to load active sessions:`,e),{}}}function S$(e){try{let t=Object.entries(e).filter(([e,t])=>typeof e==`string`&&e&&typeof t==`string`&&t);if(t.length===0){localStorage.removeItem(c$);return}localStorage.setItem(c$,JSON.stringify(Object.fromEntries(t)))}catch(e){console.error(`Failed to save active sessions:`,e)}}function C$(e){let t=x$()[b$(e)];return typeof t==`string`?t:``}function w$(e,t){if(typeof t!=`string`||!t)return;let n=x$();n[b$(e)]=t,S$(n)}function T$(e){let t=x$();delete t[b$(e)],S$(t)}function E$(){try{let e=localStorage.getItem(l$);if(e){let t=Number(e);if(Number.isFinite(t))return Math.max(200,Math.min(480,t))}}catch(e){console.error(`Failed to load sidebar width:`,e)}return 256}function D$(e){try{localStorage.setItem(l$,String(e))}catch(e){console.error(`Failed to save sidebar width:`,e)}}function O$(e,t){if(!Array.isArray(e)||e.length===0)return null;if(t){let n=e.find(e=>e.id===t);if(n?.id)return n.id}return e[0]?.id||null}function k$({pendingRequestToken:e,requestToken:t,activeCwd:n,requestCwd:r}){return e===t&&n===r}function A$({pendingRequestToken:e,requestToken:t,activeSessionId:n,sessionId:r,activeCwd:i,requestCwd:a}){return k$({pendingRequestToken:e,requestToken:t,activeCwd:i,requestCwd:a})&&n===r}var j$=`New chat`;function M$(e){return e instanceof Error?e.message:`Unknown error`}function N$(e){return`detail`in e?e.detail:void 0}function P$(e){return Array.isArray(e)?null:typeof e==`object`&&e?.run?e.run:null}function F$(e,t){return typeof e==`string`&&e?e:Array.isArray(e)?e.find(e=>e.msg)?.msg||t:e&&typeof e==`object`&&e.message?e.message:t}function I$(){return{id:ff(),title:j$,isDraft:!0}}function L$(e){return e.kind===`text`?{type:`text`,text:e.text,name:e.name,is_attachment:!0}:{type:e.kind===`image`?`image`:`document`,data:e.data,mime_type:e.mime_type,name:e.name}}function R$(e){return e.kind===`text`?{type:`text`,path:e.path,name:e.path,is_attachment:!0}:{type:e.kind,path:e.path,name:e.name,is_attachment:!0}}function z$(e){let t=new Set;return e.filter(e=>{let n=`${e.kind}:${e.path}`;return t.has(n)?!1:(t.add(n),!0)})}function B$(e,t){switch(t.type){case`set_messages`:{if(t.expectedSessionId!=null&&e.messageSessionId!==t.expectedSessionId)return e;let n={messageSessionId:t.sessionId??e.messageSessionId,rawMessages:t.messages,toolRuntimeById:{},sessionCost:t.sessionCost??null,preTurnRawMessages:null};for(let e of t.replayEvents||[])n=B$(n,{type:`apply_event`,event:e});return n}case`start_turn`:{let{content:n,attachments:r,workspaceFiles:i}=t,a=r?.map(e=>e.kind===`document`?{...e,data:``}:e),o=!!(a?.length||i?.length);return{...e,rawMessages:[...e.rawMessages,o?UQ(n,a??[],i):HQ(n),WQ([])],preTurnRawMessages:e.rawMessages}}case`rewind_and_start_turn`:return{...e,rawMessages:[...e.rawMessages.slice(0,t.rewindTo),HQ(t.content),WQ([])],toolRuntimeById:{},preTurnRawMessages:e.rawMessages};case`rollback`:{let t=e.preTurnRawMessages;return t?{rawMessages:t,messageSessionId:e.messageSessionId,toolRuntimeById:{},sessionCost:e.sessionCost,preTurnRawMessages:null}:e}case`apply_event`:{let{event:n}=t,r=e.rawMessages,i={...e.toolRuntimeById};if(n.type===`reasoning`)r=KQ(r,`thinking`,n.delta||``);else if(n.type===`reasoning_done`){let e=n.duration_ms;typeof e==`number`&&(r=XQ(r,e))}else if(n.type===`text`)r=KQ(r,`text`,n.delta||``);else if(n.type===`tool_start`){let e=n.tool_call||{};r=qQ(r,e),e.id&&(i[e.id]={pending:!0,output:``,finalOutput:null,metadata:null,isError:!1})}else if(n.type===`tool_output`){let e=n.tool_use_id||``;if(e){let t=i[e]||{pending:!0,output:``,finalOutput:null,metadata:null,isError:!1},r=n.output||``;i[e]={...t,pending:!0,output:`${t.output}${r}`}}}else if(n.type===`tool_done`){let e=n.tool_use_id||``,t=n.output||``,a=n.metadata??null,o=!!(n.is_error||typeof t==`string`&&t.startsWith(`error:`));e&&(i[e]={...i[e]||{pending:!1,output:``,finalOutput:null,metadata:null,isError:!1},pending:!1,finalOutput:t,metadata:a,isError:o},r=YQ(r,e,t,a,o))}else if(n.type===`error`)r=KQ(r,`text`,`\n\n**Error:** ${n.message||`Unknown`}`);else if(n.type===`usage`){let t={context_tokens:n.context_tokens??null,turn_usage:n.turn_usage??{},turn_cost:n.turn_cost??null};return typeof n.context_window==`number`&&(t.context_window=n.context_window),n.model&&(t.model=n.model),r=ZQ(r,t),{...e,rawMessages:r,toolRuntimeById:i,sessionCost:n.session_cost??null}}else n.type===`compact`&&(r=[...r,{role:`compact`,content:[]}]);return{...e,rawMessages:r,toolRuntimeById:i}}default:return e}}function V$(e,t){let[n,r]=(0,E.useReducer)(B$,{messageSessionId:null,rawMessages:[],toolRuntimeById:{},sessionCost:null,preTurnRawMessages:null}),[i,a]=(0,E.useState)([]),[o,s]=(0,E.useState)(I$),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(null),f=c!==null,[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)([]),_=(0,E.useRef)(!1),v=(0,E.useRef)(e.cwd),y=(0,E.useRef)(o),b=(0,E.useRef)(0),x=(0,E.useRef)(0),S=(0,E.useRef)(0),C=(0,E.useRef)(null),w=(0,E.useRef)(0),T=(0,E.useRef)(null),D=(0,E.useRef)(null),O=(0,E.useCallback)(e=>{y.current=e,s(e)},[]),k=(0,E.useCallback)(async e=>{if(e)try{await fetch(`/api/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`})}catch(e){console.error(`Failed to cancel:`,e)}},[]),A=(0,E.useCallback)(async()=>{let t=e.cwd;if(t!==v.current)return[];try{let e=await fetch(`/api/sessions?cwd=${encodeURIComponent(t)}`);if(!e.ok)throw Error(`Failed to load sessions`);let n=await e.json();if(t!==v.current)return[];let r=n.sessions||[],i=y.current,o=i.isDraft&&!r.some(e=>e.id===i.id)?[i,...r]:r;a(o);let s=o.find(e=>e.id===i.id);return s&&s!==i&&O(s),o}catch(e){return console.error(`Failed to load sessions:`,e),[]}},[e.cwd,O]),j=(0,E.useCallback)(()=>{w.current+=1,x.current=0,C.current?.abort(),C.current=null,T.current=null,l(null),d(null),g([])},[]),M=(0,E.useCallback)(async(e,t,n=0)=>{let i=e?.id;if(!i)return;w.current+=1;let a=w.current;C.current?.abort();let o=new AbortController;C.current=o,T.current=e;let s=e.kind;l(s);let c=async()=>{if(w.current!==a||y.current.id!==t)return!0;let e=D.current;if(!e)return!1;try{return await e(t),!0}catch(e){return console.error(`Failed to recover disconnected stream:`,e),!1}};try{let e=await fetch(`/api/runs/${encodeURIComponent(i)}/stream?after=${n}`,{signal:o.signal});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);if(!e.body)throw Error(`Response body is empty`);let l=e.body.getReader(),u=new TextDecoder,f=``,p=!1;for(;;){let{done:e,value:n}=await l.read();if(e)break;f+=u.decode(n,{stream:!0});let i=f.split(`
|
|
368
|
-
`);f=i.pop()||``;for(let e of i){if(!e.startsWith(`data: `))continue;let n=e.slice(6);if(n===`[DONE]`){p=!0;continue}try{let e=JSON.parse(n);if(w.current!==a||y.current.id!==t)continue;if(e.type===`permission_request`){let t={request_id:e.request_id,tool_use_id:e.tool_use_id,tool_name:e.tool_name,preview:e.preview};g(e=>e.some(e=>e.request_id===t.request_id)?e:[...e,t]);continue}if(e.type===`permission_resolved`){let t=e.request_id;g(e=>e.filter(e=>e.request_id!==t));continue}if(s===`compact`){e.type===`compact`?r({type:`apply_event`,event:e}):e.type===`error`&&(console.error(`Compaction failed:`,e.message),d(e.message||`Compaction failed`));continue}r({type:`apply_event`,event:e})}catch(e){console.error(`Parse error:`,e)}}}if(s===`compact`&&p&&await c(),!p&&await c())return}catch(e){if((!(e instanceof Error)||e.name!==`AbortError`)&&!await c()&&w.current===a&&y.current.id===t){let e=`Stream disconnected. Reload the session to resume.`;s===`compact`?d(e):r({type:`apply_event`,event:{type:`error`,message:e}})}}finally{w.current===a&&(C.current=null,T.current=null,y.current.id===t&&l(null),A())}},[A]),N=(0,E.useCallback)(async(t,n)=>{let i=n?.requestCwd??e.cwd,a=n?.requestToken??S.current,o=()=>k$({pendingRequestToken:S.current,requestToken:a,activeCwd:v.current,requestCwd:i});if(!o())return null;let s=await fetch(`/api/sessions/${encodeURIComponent(t)}`);if(!s.ok)throw Error(`Failed to load session`);let c=await s.json();if(!o()||!c.session)return null;O(c.session),w$(i,c.session.id),g([]);let u=c.active_run||null,f=Array.isArray(c.pending_events)?c.pending_events:[],p=u?.kind===`compact`,m=new Map,h=[];for(let e of f){if(e?.type===`permission_request`){m.set(e.request_id,{request_id:e.request_id,tool_use_id:e.tool_use_id,tool_name:e.tool_name,preview:e.preview});continue}if(e?.type===`permission_resolved`){m.delete(e.request_id);continue}if(p){e?.type===`compact`?h.push(e):e?.type===`error`&&d(e.message||`Compaction failed`);continue}h.push(e)}if((0,E.startTransition)(()=>{r({type:`set_messages`,messages:c.messages||[],sessionId:c.session?.id??t,sessionCost:c.session_cost??null,replayEvents:h,expectedSessionId:c.session?.id??t})}),m.size&&g(Array.from(m.values())),T.current=u,u?.id){let e=f.at(-1)?.seq??0;M(u,c.session.id,e)}else l(null);return c},[e.cwd,O,M]);(0,E.useEffect)(()=>{D.current=N},[N]);let P=(0,E.useCallback)(async(n,i)=>{let a=n.text.trim(),s=z$(n.workspaceFiles);if(!a&&!i?.length&&!s.length||f)return!1;let c=o.id,u=e.cwd,p=b.current+1;b.current=p,x.current=p,r({type:`start_turn`,content:a,...i?.length?{attachments:i}:{},...s.length?{workspaceFiles:s}:{}}),l(`chat`),d(null);let m={session_id:c,provider:e.provider||void 0,model:e.model||void 0,cwd:e.cwd,reasoning_effort:wj(e,t)},h=i?.length||s.length?{...m,input:[...a?[{type:`text`,text:a}]:[],...s.map(R$),...(i??[]).map(L$)]}:{...m,message:a};try{let e=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(h)}),t=await e.json(),n=A$({pendingRequestToken:x.current,requestToken:p,activeSessionId:y.current.id,sessionId:c,activeCwd:v.current,requestCwd:u});if(!e.ok){let i=N$(t),a=P$(i);if(e.status===409&&a?.id)return n&&(x.current=0,r({type:`rollback`}),M(a,c,a.last_seq||0)),!1;throw Error(F$(i,`Failed to start task`))}if(x.current=0,!n)return!1;let i=t;if(i.session){let e=i.session;O(e),w$(u,e.id)}return A(),M(i.run,c,0),!0}catch(e){return x.current===p&&y.current.id===c&&(x.current=0,l(null),r({type:`rollback`}),r({type:`apply_event`,event:{type:`error`,message:M$(e)}})),!1}},[o.id,e,A,f,t,O,M]),F=(0,E.useCallback)(async(n,i)=>{let a=i.trim();if(!a||f)return;let s=o.id,c=e.cwd,u=b.current+1;b.current=u,x.current=u,r({type:`rewind_and_start_turn`,rewindTo:n,content:a}),l(`chat`),d(null);try{let i=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({session_id:s,message:a,rewind_to:n,provider:e.provider||void 0,model:e.model||void 0,cwd:e.cwd,reasoning_effort:wj(e,t)})}),o=await i.json(),d=A$({pendingRequestToken:x.current,requestToken:u,activeSessionId:y.current.id,sessionId:s,activeCwd:v.current,requestCwd:c});if(!i.ok){if(d){x.current=0,r({type:`rollback`});let e=N$(o),t=P$(e);if(i.status===409&&t?.id){M(t,s,t.last_seq||0);return}l(null),r({type:`apply_event`,event:{type:`error`,message:F$(e,`Failed to start task`)}})}return}if(x.current=0,!d)return;let f=o;if(f.session){let e=f.session;O(e),w$(c,e.id)}A(),M(f.run,s,0)}catch(e){x.current===u&&y.current.id===s&&(x.current=0,r({type:`rollback`}),l(null),r({type:`apply_event`,event:{type:`error`,message:M$(e)}}))}},[o.id,e,A,f,t,O,M]),I=(0,E.useCallback)(async()=>{let t=y.current;if(f)return!1;if(t.isDraft)return d(`nothing to compact`),!1;let n=t.id;d(null),l(`compact`);try{let t=await fetch(`/api/sessions/${encodeURIComponent(n)}/compact`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider||void 0,model:e.model||void 0})}),r=await t.json();if(y.current.id!==n)return!1;if(!t.ok){let e=N$(r),i=P$(e);if(t.status===409&&i?.id)return M(i,n,i.last_seq||0),!1;throw Error(F$(e,`Compaction failed`))}return A(),M(r.run,n,0),!0}catch(e){return y.current.id===n&&(console.error(`Failed to start compaction:`,e),l(null),d(M$(e))),!1}},[e.model,e.provider,A,f,M]),ee=(0,E.useCallback)(()=>{let e=T.current?.id,t=y.current.id;if(w.current+=1,x.current=0,C.current?.abort(),C.current=null,T.current=null,g([]),!e){l(null);return}(async()=>{if(await k(e),y.current.id===t)try{await D.current?.(t),A()}catch(e){console.error(`Failed to reload session after cancel:`,e),y.current.id===t&&l(null)}})()},[k,A]),te=(0,E.useCallback)(async e=>{let t=h[0],n=T.current?.id;if(!(!t||!n))try{let r=await fetch(`/api/runs/${encodeURIComponent(n)}/decide`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({request_id:t.request_id,decision:e})});r.ok||console.error(`Decide POST failed: ${r.status}`)}catch(e){console.error(`Failed to send decision:`,e)}},[h]),ne=(0,E.useCallback)(()=>{if(p)return;j(),_.current=!0,S.current+=1;let e=I$();O(e),r({type:`set_messages`,messages:[],sessionId:e.id}),A()},[A,p,O,j]),re=(0,E.useCallback)(async t=>{if(!t||t===o.id)return;j(),_.current=!0;let n=S.current+1;S.current=n,m(!0);let a=i.find(e=>e.id===t);a&&O(a),r({type:`set_messages`,messages:[],sessionId:t}),g([]);let s=()=>k$({pendingRequestToken:S.current,requestToken:n,activeCwd:v.current,requestCwd:e.cwd});try{await N(t,{requestCwd:e.cwd,requestToken:n}),A()}catch(e){console.error(`Failed to load session:`,e)}finally{s()&&m(!1)}},[o.id,e.cwd,A,N,O,i,j]),ie=(0,E.useCallback)(async t=>{if(!t)return;let n=t===o.id,s=i.findIndex(e=>e.id===t),c=i.filter(e=>e.id!==t),u=s>=0&&(c[s]||c[s-1])||null;m(!0);try{if(!(await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:`DELETE`})).ok)throw Error(`Failed to delete session`);if(!n){a(c);return}j(),_.current=!0,S.current+=1;let i=S.current;if(T$(e.cwd),u&&!u.isDraft){a(c),O(u),r({type:`set_messages`,messages:[],sessionId:u.id}),await N(u.id,{requestCwd:e.cwd,requestToken:i});return}let o=I$();O(o),a([o]),r({type:`set_messages`,messages:[],sessionId:o.id}),l(null)}catch(e){console.error(`Failed to delete session:`,e)}finally{m(!1)}},[o.id,e.cwd,N,i,O,j]),ae=(0,E.useCallback)(async()=>{if(f||p)return;let e=y.current;if(!e.isDraft){try{let t=await fetch(`/api/sessions/${encodeURIComponent(e.id)}/clear`,{method:`POST`});if(!t.ok)throw Error(`Clear failed with status ${t.status}`)}catch(e){console.error(`Failed to clear session:`,e);return}y.current.id===e.id&&r({type:`set_messages`,messages:[],sessionId:e.id}),A()}},[f,p,A]);(0,E.useEffect)(()=>{if(v.current!==e.cwd){j(),v.current=e.cwd,_.current=!1,a([]);let t=I$();O(t),r({type:`set_messages`,messages:[],sessionId:t.id})}if(_.current)return;_.current=!0;let t=e.cwd,n=S.current+1;S.current=n,m(!0);let i=()=>k$({pendingRequestToken:S.current,requestToken:n,activeCwd:v.current,requestCwd:t});(async()=>{try{if(!i())return;let e=C$(t),o=await fetch(`/api/sessions?cwd=${encodeURIComponent(t)}`);if(!o.ok)throw Error(`Failed to load sessions`);let s=await o.json();if(!i())return;let c=s.sessions||[];a(c);let u=O$(c,e);if(u){let e=c.find(e=>e.id===u);e&&O(e),r({type:`set_messages`,messages:[],sessionId:u}),await D.current?.(u,{requestCwd:t,requestToken:n})}else{let e=I$();O(e),a([e]),r({type:`set_messages`,messages:[],sessionId:e.id}),l(null)}}catch(e){console.error(`Failed to initialize sessions:`,e)}finally{i()&&m(!1)}})()},[e.cwd,O,j]),(0,E.useEffect)(()=>()=>{j()},[j]);let oe=(0,E.useMemo)(()=>a$(n.rawMessages,n.toolRuntimeById),[n.rawMessages,n.toolRuntimeById]),se=(0,E.useMemo)(()=>{for(let e=oe.length-1;e>=0;e--){let t=oe[e];if(!t||Bj(t))break;let n=t.role===`assistant`?t.stats:void 0;if(n){if(n.context_tokens!==void 0&&n.context_window!==void 0)return{tokens:n.context_tokens,window:n.context_window};break}}return null},[oe]);return{messages:oe,messageSessionId:n.messageSessionId,sessionCost:n.sessionCost,currentContext:se,loading:f,runKind:c,compactError:u,sessions:i,activeSession:o,sessionLoading:p,pendingPermission:h[0]??null,send:P,rewindAndSend:F,compactSession:I,cancel:ee,decidePermission:te,createSession:ne,selectSession:re,deleteSession:ie,clearSession:ae}}async function H$(e){let t=await fetch(e);if(!t.ok){let e=`Request failed with status ${t.status}`;try{let n=await t.json();typeof n?.detail==`string`&&n.detail&&(e=n.detail)}catch{}throw Error(e)}return t.json()}function U$(e,t,n){let r=t||e?.default?.provider||``,i=e?.providers?.[r],a=n||e?.default?.model||``;return{image:!!(i?.supports_image_input&&i.image_input_models?.includes(a)),pdf:!!(i?.supports_pdf_input&&i.pdf_input_models?.includes(a))}}function W$(e,t){return JSON.stringify({open:e,path:t?.path??``,config:t?.config??null,options:t?.options??null})}function G$(e){return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)}function K$(){let[e,t]=(0,E.useState)(h$),[n,r]=(0,E.useState)([]),[i,a]=(0,E.useState)(_$),[o,s]=(0,E.useState)(!1),[c,l]=(0,E.useState)(E$),[u,d]=(0,E.useState)(!1),f=(0,E.useSyncExternalStore)(G$,tQ,()=>480),p=(0,E.useCallback)(()=>{d(!0)},[]),m=(0,E.useCallback)(e=>{l(t=>t===e?t:(D$(e),e))},[]),h=(0,E.useCallback)(()=>{m(256)},[m]),g=uf(`(min-width: 768px)`),_=Math.max(200,Math.min(f,c)),{data:v=null,error:y,mutate:b}=nt(`/api/config?cwd=${encodeURIComponent(e.cwd)}`,H$,{keepPreviousData:!0}),{data:x=null,error:S,mutate:C}=nt(`/api/settings`,H$),w=(0,E.useMemo)(()=>v?Tj(e,v):e,[e,v]),{messages:T,messageSessionId:D,sessionCost:O,currentContext:k,loading:A,runKind:j,compactError:M,sessions:N,activeSession:P,pendingPermission:F,send:I,rewindAndSend:ee,compactSession:te,cancel:ne,decidePermission:re,createSession:ie,selectSession:ae,deleteSession:oe,clearSession:se}=V$(w,v),ce=(0,E.useCallback)(e=>{if(e.cwd!==w.cwd){let t=y$(i,e.cwd);a(t),v$(t)}t(e),g$(e)},[w.cwd,i]),le=(0,E.useCallback)(e=>{a(t=>{if(!t.includes(e))return t;let n=t.filter(t=>t!==e);return v$(n),n})},[]),ue=(0,E.useCallback)(()=>{r(e=>{for(let t of e)t.kind===`image`&&URL.revokeObjectURL(t.preview);return[]})},[]),de=(0,E.useCallback)(async e=>await I(e,n.length?n:void 0)?(ue(),!0):!1,[n,ue,I]),fe=(0,E.useCallback)(e=>{r(t=>[...t,...e])},[]),pe=(0,E.useCallback)(e=>{r(t=>{let n=t.find(t=>t.id===e);return n?(n.kind===`image`&&URL.revokeObjectURL(n.preview),t.filter(t=>t.id!==e)):t})},[]),{image:me,pdf:he}=(0,E.useMemo)(()=>U$(v,w.provider,w.model),[w.model,w.provider,v]),ge=v?.cwd_exists===!1,_e=ge?`Workspace no longer exists. Choose another workspace.`:void 0,ve=!!v?.setup_error||!v&&!!y,ye=ve?v?(0,L.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,L.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add a provider to get started.`}),(0,L.jsx)(di,{variant:`outline`,size:`sm`,onClick:p,children:`Open settings`})]}):(0,L.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Couldn't reach the API.`}):void 0,be=(0,E.useCallback)(e=>{ae(e),s(!1),ue()},[ae,ue]),xe=(0,E.useCallback)(()=>{ie(),s(!1),ue()},[ie,ue]),Se=(0,E.useCallback)(async e=>{let t=P?.id===e;await oe(e),t&&(s(!1),ue())},[P?.id,ue,oe]),Ce=(0,E.useCallback)(e=>{if(e===`/new`){xe();return}if(e===`/compact`){te();return}se()},[xe,se,te]);return(0,L.jsxs)(YX,{children:[(0,L.jsxs)(`div`,{className:`relative flex h-full min-h-0 overflow-hidden`,children:[g?(0,L.jsx)(`div`,{className:`shrink-0`,children:(0,L.jsx)(EQ,{sessions:N,activeSession:P,onSelectSession:be,onCreateSession:xe,onDeleteSession:Se,config:w,remoteConfig:v,cwdHistory:i,onUpdateConfig:ce,onRemoveHistory:le,onOpenSettings:p,workspaceMissing:ge,width:_,onResize:m,onResizeReset:h,className:`h-full`})}):(0,L.jsx)(af,{open:o,onOpenChange:s,children:(0,L.jsxs)(cf,{side:`left`,showCloseButton:!1,className:`p-0 gap-0 w-65 bg-sidebar-bg`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Navigation`}),(0,L.jsx)(EQ,{sessions:N,activeSession:P,onSelectSession:be,onCreateSession:xe,onDeleteSession:Se,config:w,remoteConfig:v,cwdHistory:i,onUpdateConfig:ce,onRemoveHistory:le,onOpenSettings:p,workspaceMissing:ge,width:260,className:`h-full`})]})}),(0,L.jsxs)(`main`,{className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background`,children:[(0,L.jsx)(XX,{title:P?.title,onMenuToggle:()=>s(e=>!e),onCreateSession:xe}),(0,L.jsx)(VX,{sessionId:D??P?.id,messages:ve?[]:T,loading:!ve&&j===`chat`,compacting:!ve&&j===`compact`,compactError:ve?null:M,onRewindAndSend:ge||ve?void 0:ee,emptyStateFooter:ye}),(0,L.jsxs)(`div`,{className:`shrink-0 pb-4 max-md:pb-1`,children:[F&&(0,L.jsx)(JX,{request:F,onDecide:re}),(0,L.jsx)(zj,{loading:A,onSubmit:de,onCancel:ne,supportsImages:me,supportsDocuments:he,files:n,onAttachFiles:fe,onRemoveFile:pe,config:w,remoteConfig:v,onUpdateConfig:ce,onSlashCommand:Ce,disabled:ve,disabledReason:_e,sessionCost:O,currentContext:k},w.cwd)]})]})]}),(0,L.jsx)($Z,{open:u,onClose:()=>d(!1),settings:x,loadError:S?.message,remoteConfig:v,onSettingsSaved:e=>{C(e,{revalidate:!1}),b()},projectConfigPaths:v?.config_paths},W$(u,x))]})}function q$(){return(0,L.jsx)(o,{children:(0,L.jsx)(K$,{})})}var J$=document.getElementById(`root`);if(!J$)throw Error(`Root element not found`);D.createRoot(J$).render((0,L.jsx)(E.StrictMode,{children:(0,L.jsx)(q$,{})}));
|
|
367
|
+
`),textAttachmentBlocks:n,imageBlocks:r,documentBlocks:i}},[t]);(0,E.useEffect)(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]);let b=(0,E.useCallback)(async()=>{if(g)try{await Hj(g),u(!0),h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{u(!1),h.current=null},2e3)}catch{}},[g]),x=c&&!!g&&v.length===0&&y.length===0&&_.length===0&&typeof n==`number`&&!i&&s,S=(0,E.useCallback)(()=>{m(g),f(!0)},[g]),C=(0,E.useCallback)(e=>{e&&(e.focus(),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]),w=(0,E.useCallback)(()=>{let e=p.trim();!e||!s||typeof n!=`number`||(f(!1),s(n,e))},[p,s,n]),T=(0,E.useCallback)(()=>{f(!1)},[]),D=(0,E.useCallback)(e=>{e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),w()):e.key===`Escape`&&T()},[w,T]);return c?d?(0,L.jsx)(`div`,{className:`flex justify-end px-5 max-md:px-4`,children:(0,L.jsxs)(`div`,{className:`max-w-[85%] w-full flex flex-col gap-2`,children:[(0,L.jsx)(`textarea`,{ref:C,name:`edit-message`,"aria-label":`Edit message`,value:p,onChange:e=>{m(e.target.value),e.target.style.height=`auto`,e.target.style.height=`${Math.min(e.target.scrollHeight,300)}px`},onKeyDown:D,className:`w-full resize-none rounded-lg bg-muted px-3.5 py-2 text-base md:text-sm leading-relaxed text-foreground border border-border/60 focus:outline-none focus:border-accent/60 max-h-75`}),(0,L.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:T,className:`px-3 py-1 text-xs rounded-lg text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:`Cancel`}),(0,L.jsx)(`button`,{type:`button`,onClick:w,disabled:!p.trim(),className:li(`px-3 py-1 text-xs rounded-lg transition-[color,background-color,filter,scale] duration-150`,p.trim()?`bg-accent text-accent-foreground hover:brightness-105 hover:saturate-[.9] active:scale-95`:`text-muted-foreground/40`),children:`Send`})]})]})}):(0,L.jsxs)(`div`,{className:`group/user flex justify-end px-5 max-md:px-4`,children:[x&&(0,L.jsx)(`button`,{type:`button`,"aria-label":`Edit message`,onClick:S,className:`self-end mr-2 mb-0.5 opacity-0 group-hover/user:opacity-100 max-md:opacity-60 active:scale-95 transition-[color,opacity,scale] duration-150 size-6 flex items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground`,title:`Edit & resend`,children:(0,L.jsx)(Jd,{className:`size-3`})}),(0,L.jsxs)(`div`,{className:`max-w-[85%] flex flex-col gap-1.5 items-end`,children:[v.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:v.map(e=>e.data?(0,L.jsx)(`img`,{src:`data:${e.mime_type};base64,${e.data}`,alt:e.name??`Image`,className:`max-h-64 max-w-full rounded-lg`},e.renderKey):(0,L.jsx)(PX,{label:`Image`,value:e.name??`image`},e.renderKey))}),y.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:y.map(e=>(0,L.jsx)(PX,{label:`PDF`,value:e.name??`document.pdf`},e.renderKey))}),_.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-2 justify-end`,children:_.map(e=>{let t=EX(e)?.path;return(0,L.jsx)(PX,{label:`Text`,value:typeof t==`string`?t:`attached-file`},e.renderKey)})}),g&&(0,L.jsx)(`div`,{className:`rounded-lg bg-muted px-3.5 py-2 text-sm leading-relaxed text-foreground whitespace-pre-wrap wrap-anywhere`,children:g})]})]}):(0,L.jsxs)(`div`,{className:`group/msg relative px-5 max-md:px-4`,children:[(0,L.jsxs)(`div`,{className:`flex flex-col gap-3 text-foreground/90 leading-relaxed text-sm`,children:[t.map((e,n)=>{if(e.type===`thinking`){let i=e.renderKey||`thinking:${e.text||`block`}`,a=TX(e);return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(oX,{content:e.text,durationMs:a,isStreaming:r&&a==null&&n===t.length-1})},i)}if(e.type===`text`){let t=e.renderKey||`text:${e.text||`block`}`;return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(iX,{content:e.text})},t)}if(e.type===`tool_use`){let t=e.renderKey||e.id||`tool:${e.name||`tool`}`;return(0,L.jsx)(jX,{fallback:MX,children:(0,L.jsx)(wX,{name:e.name,args:e.input,output:e.runtime?.output,finalOutput:e.runtime?.finalOutput,metadata:e.runtime?.metadata,pending:e.runtime?.pending,isError:e.runtime?.isError})},t)}return null}),r&&(0,L.jsx)(`span`,{className:`inline-block w-[1.5px] h-4 bg-foreground/40 ml-0.5 align-middle`})]}),!c&&g&&!r&&(0,L.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 max-md:opacity-60 opacity-0 group-hover/msg:opacity-100 transition-opacity duration-150`,children:[(0,L.jsx)(`button`,{type:`button`,"aria-label":`Copy to clipboard`,onClick:b,className:li(`flex items-center justify-center size-6 rounded-sm active:scale-95 transition-[color,scale] duration-150`,l?`text-accent`:`text-muted-foreground/50 hover:text-foreground`),title:`Copy`,children:l?(0,L.jsx)(Md,{className:`size-3.5`}):(0,L.jsx)(Id,{className:`size-3.5`})}),(a||o)&&(0,L.jsx)(NX,{model:a,stats:o})]})]})},AX),IX=120,LX=`__draft__`,RX=60,zX=30,BX=160,VX=(0,E.memo)(function({sessionId:e,messages:t,loading:n,compacting:r,compactError:i,onRewindAndSend:a,emptyStateFooter:o}){let s=e||LX,c=t.length===0?`empty`:`ready`;return(0,L.jsx)(WX,{messages:t,loading:n,compacting:r,compactError:i,onRewindAndSend:a,emptyStateFooter:o},`${s}:${c}`)});function HX(e){return Math.max(0,e-RX)}function UX(e){let t=e.querySelectorAll(`.chat-message-shell`);for(let e of t)e.style.setProperty(`--chat-message-intrinsic-size`,`${Math.ceil(e.getBoundingClientRect().height)}px`)}function WX({messages:e,loading:t,compacting:n,compactError:r,onRewindAndSend:i,emptyStateFooter:a}){let o=(0,E.useRef)(null),s=(0,E.useRef)(!0),c=(0,E.useRef)(``),l=(0,E.useRef)(null),u=(0,E.useRef)(null),[d,f]=(0,E.useState)(!1),[p,m]=(0,E.useState)(()=>HX(e.length)),h=Math.min(p,HX(e.length)),g=(0,E.useMemo)(()=>e.slice(h),[h,e]),_=e.at(-1),v=n&&(!_||!Bj(_)),y=!_||Bj(_)?0:_.content.length,b=!_||Bj(_)?0:_.content.reduce((e,t)=>t.type!==`text`&&t.type!==`thinking`?e:e+(t.text?.length??0),0),x=`${e.length}:${y}:${b}:${n}:${r??``}`,S=(0,E.useCallback)(e=>e.scrollHeight-e.scrollTop-e.clientHeight<IX,[]),C=(0,E.useCallback)(()=>{let e=o.current;e&&(e.scrollTop=e.scrollHeight)},[]),w=(0,E.useCallback)(()=>{u.current!==null&&window.cancelAnimationFrame(u.current),u.current=window.requestAnimationFrame(()=>{u.current=null;let e=o.current;e&&UX(e),f(!0)})},[]),T=(0,E.useCallback)(()=>{let e=o.current;e&&(s.current=S(e),!(e.scrollTop>BX||h===0)&&(l.current={scrollHeight:e.scrollHeight,scrollTop:e.scrollTop},f(!1),m(Math.max(0,h-zX))))},[h,S]);return(0,E.useLayoutEffect)(()=>{s.current=!0,C(),w()},[w,C]),(0,E.useLayoutEffect)(()=>()=>{u.current!==null&&window.cancelAnimationFrame(u.current)},[]),(0,E.useLayoutEffect)(()=>{let e=l.current;if(e==null)return;let t=o.current;t&&(t.scrollTop=t.scrollHeight-e.scrollHeight+e.scrollTop,l.current=null,s.current=S(t),w())},[S,w]),(0,E.useLayoutEffect)(()=>{!d||!s.current||(l.current??C())},[d,C]),(0,E.useLayoutEffect)(()=>{c.current!==x&&(c.current=x,s.current&&l.current==null&&C())},[x,C]),(0,L.jsx)(`div`,{ref:o,onScroll:T,className:`min-h-0 flex-1 overflow-y-auto pb-4 pt-6 [overflow-anchor:none] [scrollbar-gutter:stable_both-edges]`,children:(0,L.jsxs)(`div`,{className:`mx-auto flex min-h-full max-w-4xl flex-col gap-6 max-md:max-w-none max-md:gap-5`,children:[e.length===0&&(0,L.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center p-8 text-center`,children:[(0,L.jsxs)(`h1`,{className:`font-display text-3xl tracking-[-0.022em] text-foreground/70`,children:[`mycode`,(0,L.jsx)(`span`,{className:`ml-0.5 inline-block h-6 w-0.5 animate-cursor-blink bg-accent/60 align-middle`})]}),a&&(0,L.jsx)(`div`,{className:`mt-8`,children:a})]}),g.map((n,r)=>{let a=h+r,o=n.renderKey||`msg-${a}`,s=t&&a===e.length-1&&!Bj(n)&&n.role===`assistant`;return Bj(n)?(0,L.jsx)(`div`,{className:`chat-message-shell`,"data-layout-optimized":d,children:(0,L.jsx)(Vj,{})},o):(0,L.jsx)(`div`,{className:`chat-message-shell`,"data-layout-optimized":d,children:(0,L.jsx)(FX,{role:n.role,blocks:n.content,sourceIndex:n.sourceIndex,isStreaming:s,isLoading:t,model:n.meta?.model,stats:n.stats,onRewindAndSend:i})},o)}),v&&(0,L.jsx)(`div`,{className:`chat-message-shell`,children:(0,L.jsx)(Vj,{pending:!0})}),!n&&r&&(0,L.jsx)(`div`,{role:`status`,title:r,className:`flex select-none items-center justify-center px-2 py-1`,children:(0,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-[0.18em] text-muted-foreground/50`,children:r===`nothing to compact`?`nothing to compact`:`compaction failed`})}),(e.length>0||v||r)&&(0,L.jsx)(`div`,{className:`h-4`})]})})}var GX={bash:tf,read:Rd,write:qd,edit:Qd,webfetch:Vd,websearch:Xd},KX={bash:`Run this command?`,read:`Read this file?`,write:`Write this file?`,edit:`Edit this file?`,webfetch:`Fetch this page?`,websearch:`Run this search?`};function qX({toolName:e,preview:t}){let n=e===`bash`,r=e===`websearch`;return(0,L.jsxs)(`div`,{className:li(`rounded-md bg-code px-3 py-2 leading-normal text-foreground/80`,r?`text-[13px]`:`font-mono text-[12.5px]`,n&&`max-h-24 overflow-y-auto scrollbar-subtle whitespace-pre-wrap break-words`,!n&&!r&&`break-all`),children:[n&&(0,L.jsx)(`span`,{className:`select-none text-muted-foreground/40`,children:`$ `}),r?`“${t}”`:t]})}var JX=(0,E.memo)(function({request:e,onDecide:t}){let n=(0,E.useCallback)(e=>{e?.focus()},[]),r=e=>{e.key===`Enter`?(e.preventDefault(),t(`allow`)):e.key===`Escape`&&(e.preventDefault(),t(`deny`))},i=GX[e.tool_name]??tf,a=KX[e.tool_name]??`Run this tool?`;return(0,L.jsx)(`div`,{className:`mx-auto max-w-4xl max-md:max-w-none px-5 max-md:px-3 pt-3 max-md:pt-2 pb-1`,children:(0,L.jsxs)(`div`,{ref:n,role:`dialog`,"aria-label":`Tool permission request`,tabIndex:-1,onKeyDown:r,className:`flex flex-col gap-3 rounded-lg bg-card px-3.5 py-3 shadow-card animate-fade-in-up focus:outline-none`,children:[(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`span`,{className:`grid size-6 shrink-0 place-items-center rounded-md bg-accent/10 text-accent`,children:(0,L.jsx)(i,{className:`size-3.5`,"aria-hidden":`true`})}),(0,L.jsx)(`span`,{className:`text-sm text-foreground/90`,children:a})]}),e.preview&&(0,L.jsx)(qX,{toolName:e.tool_name,preview:e.preview}),(0,L.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,L.jsxs)(`button`,{type:`button`,onClick:()=>t(`allow`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-accent px-3 text-[12.5px] font-medium text-accent-foreground transition-[filter,scale] duration-150 hover:brightness-105 hover:saturate-[.9] active:scale-95`,children:[`Allow`,(0,L.jsx)(Ld,{className:`size-3 opacity-70`,"aria-hidden":`true`})]}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>t(`deny`),className:`inline-flex h-7 items-center gap-1.5 rounded-md bg-muted/70 px-3 text-[12.5px] text-muted-foreground transition-[color,background-color,scale] duration-150 hover:bg-muted hover:text-foreground active:scale-95`,children:[`Deny`,(0,L.jsx)(`span`,{className:`text-[10px] uppercase tracking-wider`,"aria-hidden":`true`,children:`esc`})]})]})]},e.request_id)})});function YX({children:e}){return(0,L.jsx)(`div`,{className:li(`flex h-screen min-h-0 w-full flex-col overflow-hidden supports-[height:100dvh]:h-dvh bg-background font-sans text-foreground antialiased`,`transition-colors duration-150`),children:e})}function XX({title:e,onMenuToggle:t,onCreateSession:n}){return(0,L.jsxs)(`header`,{className:`flex md:hidden h-12 shrink-0 items-center justify-between px-4 border-b border-border/40 bg-background`,children:[(0,L.jsx)(`button`,{type:`button`,"aria-label":`Toggle menu`,onClick:t,className:`flex items-center justify-center size-10 -ml-2 text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:(0,L.jsx)(Wd,{className:`size-5`})}),(0,L.jsx)(`span`,{className:`text-xs text-foreground/70 truncate max-w-[60%] text-center`,children:e||`mycode`}),(0,L.jsx)(`button`,{type:`button`,"aria-label":`New chat`,onClick:n,className:`flex items-center justify-center size-10 -mr-2 text-muted-foreground hover:text-foreground active:scale-95 transition-[color,scale] duration-150`,children:(0,L.jsx)(Yd,{className:`size-5`})})]})}function ZX({...e}){return(0,L.jsx)(hd,{"data-slot":`dialog`,...e})}function QX({...e}){return(0,L.jsx)($u,{"data-slot":`dialog-portal`,...e})}function $X({className:e,...t}){return(0,L.jsx)(Ai,{"data-slot":`dialog-overlay`,className:li(`fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}function eZ({className:e,children:t,showCloseButton:n=!0,...r}){return(0,L.jsxs)(QX,{children:[(0,L.jsx)($X,{}),(0,L.jsxs)(Xu,{"data-slot":`dialog-content`,className:li(`fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-md bg-background p-4 text-sm text-foreground shadow-overlay duration-100 ease-out-strong outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r,children:[t,n&&(0,L.jsxs)(Gi,{"data-slot":`dialog-close`,render:(0,L.jsx)(di,{variant:`ghost`,className:`absolute top-2 right-2`,size:`icon-sm`}),children:[(0,L.jsx)(rf,{}),(0,L.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function tZ({className:e,...t}){return(0,L.jsx)(gd,{"data-slot":`dialog-title`,className:li(`text-base leading-none font-medium`,e),...t})}function nZ({label:e,hint:t,children:n}){return(0,L.jsxs)(`div`,{className:li(`flex flex-col gap-1.5`,`md:grid md:grid-cols-[110px_1fr] md:gap-x-3 md:gap-y-0 md:items-start`),children:[(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/80 select-none md:pt-2`,children:e}),(0,L.jsxs)(`div`,{className:`flex flex-col gap-1.5 min-w-0`,children:[n,t&&(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/70 leading-relaxed`,children:t})]})]})}function rZ({title:e,children:t}){return(0,L.jsxs)(`section`,{className:`flex flex-col gap-3.5`,children:[(0,L.jsx)(`h3`,{className:`text-[14px] font-semibold text-foreground select-none`,children:e}),(0,L.jsx)(`div`,{className:`flex flex-col gap-2.5`,children:t})]})}function iZ({value:e,options:t,onChange:n,ariaLabel:r,size:i=`md`}){return(0,L.jsx)(`div`,{role:`radiogroup`,"aria-label":r,className:`inline-flex items-center rounded-md border border-border/50 bg-muted/30 p-0.5`,children:t.map(t=>{let r=t.value===e;return(0,L.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,onClick:()=>n(t.value),className:li(`inline-flex items-center justify-center gap-1.5 rounded-sm font-medium transition-colors`,i===`sm`?`h-7 px-2.5 text-[12px]`:`h-7 px-3 text-[12px]`,r?`bg-background text-foreground`:`text-muted-foreground/80 hover:text-foreground`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent/60`),children:[t.icon,t.label]},t.value)})})}function aZ({className:e,invalid:t,...n}){return(0,L.jsx)(`input`,{...n,className:li(`h-9 w-full bg-transparent px-2`,`text-[13px] font-mono`,`border-b border-border/60`,`transition-colors`,`placeholder:text-muted-foreground/50`,`hover:border-border`,`focus:border-accent focus:outline-none`,`disabled:opacity-50 disabled:hover:border-border/60`,t&&`border-destructive/70 focus:border-destructive`,e)})}function oZ({className:e,children:t,...n}){return(0,L.jsxs)(`div`,{className:`relative inline-flex w-full min-w-0`,children:[(0,L.jsx)(`select`,{...n,className:li(`appearance-none w-full h-9 pl-2 pr-7`,`text-[13px] font-mono bg-transparent`,`border-b border-border/60`,`transition-colors`,`hover:border-border`,`focus:border-accent focus:outline-none`,e),children:t}),(0,L.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground/60`,children:`▾`})]})}function sZ(e){if(!e)return null;for(let t of e.elements){let e=t.tagName;if(e===`BUTTON`||e===`INPUT`){let e=t;if(e.type===`submit`)return e}}return null}var cZ=function(e){return e.checked=`data-checked`,e.unchecked=`data-unchecked`,e.indeterminate=`data-indeterminate`,e.disabled=`data-disabled`,e.readonly=`data-readonly`,e.required=`data-required`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),lZ=function(e){return e.disabled=`data-disabled`,e.valid=`data-valid`,e.invalid=`data-invalid`,e.touched=`data-touched`,e.dirty=`data-dirty`,e.filled=`data-filled`,e.focused=`data-focused`,e}({}),uZ={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},dZ={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},fZ={disabled:!1,...dZ},pZ={valid(e){return e===null?null:e?{[lZ.valid]:``}:{[lZ.invalid]:``}}};function mZ(e){return E.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[cZ.checked]:``}:{[cZ.unchecked]:``}},...pZ}),[e.indeterminate])}var hZ={invalid:void 0,name:void 0,validityData:{state:uZ,errors:[],error:``,value:``,initialValue:null},setValidityData:_n,disabled:void 0,touched:dZ.touched,setTouched:_n,dirty:dZ.dirty,setDirty:_n,filled:dZ.filled,setFilled:_n,focused:dZ.focused,setFocused:_n,validate:()=>null,validationMode:`onSubmit`,validationDebounceTime:0,shouldValidateOnChange:()=>!1,state:fZ,markedDirtyRef:{current:!1},registerFieldControl:_n,validation:{getValidationProps:(e,t=yn)=>t,inputRef:{current:null},registerInput:_n,commit:async()=>{},change:_n}},gZ=E.createContext(hZ);function _Z(e=!0){let t=E.useContext(gZ);if(t.setValidityData===_n&&!e)throw Error(en(28));return t}function vZ(e,t,n,r,i=!0,a){let{registerFieldControl:o}=_Z(),s=E.useRef(null);s.current||=Symbol(),It(()=>{let c=s.current;if(!(!c||!i))return o(c,{controlRef:e,getValue:r,id:t,name:a,value:n}),()=>{o(c,void 0)}},[e,i,r,t,a,o,n])}var yZ=E.createContext({disabled:!1});function bZ(){return E.useContext(yZ)}var xZ=E.createContext({formRef:{current:{fields:new Map}},errors:{},clearErrors:_n,validationMode:`onSubmit`,submitAttemptedRef:{current:!1}});function SZ(){return E.useContext(xZ)}var CZ=E.createContext({controlId:void 0,registerControlId:_n,labelId:void 0,setLabelId:_n,messageIds:[],setMessageIds:_n,getDescriptionProps:e=>e});function wZ(){return E.useContext(CZ)}function TZ(e,t,n,r=!0,i){let[a,o]=E.useState(),s=Xi(i?`${i}-label`:void 0),c=e??t??a;return It(()=>{let i=e||t||!r?void 0:EZ(n.current,s);a!==i&&o(i)}),c}function EZ(e,t){let n=DZ(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function DZ(e){if(!e)return;let t=e.parentElement;if(t&&t.tagName===`LABEL`)return t;let n=e.id;if(n){let t=e.nextElementSibling;if(t&&t.htmlFor===n)return t}let r=e.labels;return r&&r[0]}var OZ=E.createContext(void 0);function kZ(e=!0){let t=E.useContext(OZ);if(t===void 0&&!e)throw Error(en(3));return t}var AZ=E.createContext(void 0);function jZ(){let e=E.useContext(AZ);if(e===void 0)throw Error(en(14));return e}var MZ=`data-parent`,NZ=E.forwardRef(function(e,t){let{checked:n,className:r,defaultChecked:i=!1,"aria-labelledby":a,disabled:o=!1,form:s,id:c,indeterminate:l=!1,inputRef:u,name:d,onCheckedChange:f,parent:p=!1,readOnly:m=!1,render:h,required:g=!1,uncheckedValue:_,value:v,nativeButton:y=!1,style:b,...x}=e,{clearErrors:S}=SZ(),{disabled:C,name:w,setDirty:T,setFilled:D,setFocused:O,setTouched:k,state:A,validationMode:j,validityData:M,validation:N}=_Z(),P=bZ(),{labelId:F,controlId:I,registerControlId:ee,getDescriptionProps:te}=wZ(),ne=kZ(),re=ne?.parent,ie=re&&ne.allValues,ae=C||P.disabled||ne?.disabled||o,oe=w??d,se=v??oe,ce=Xi(),le=Xi(),ue=I;ie?ue=p?le:`${re.id}-${se}`:c&&(ue=c);let de={};ie&&(p?de=ne.parent.getParentProps():se&&(de=ne.parent.getChildProps(se)));let{checked:fe=n,indeterminate:pe=l,onCheckedChange:me,...he}=de,ge=ne?.value,_e=ne?.setValue,ve=ne?.defaultValue,ye=E.useRef(null),be=At(()=>Symbol(`checkbox-control`)),xe=E.useRef(!1),{getButtonProps:Se,buttonRef:Ce}=an({disabled:ae,native:y}),we=ne?.validation??N,[Te,Ee]=Kk({controlled:se&&ge&&!p?ge.includes(se):fe,default:se&&ve&&!p?ve.includes(se):i,name:`Checkbox`,state:`checked`}),De=ie?!!fe:Te,Oe=ie&&pe||l;It(()=>{ee!==_n&&(xe.current=!0,ee(be.current,ue))},[ue,ee,be]),E.useEffect(()=>{let e=be.current;return()=>{!xe.current||ee===_n||(xe.current=!1,ee(e,void 0))}},[ee,be]),vZ(ye,ce,Te,void 0,!ne&&!ae,d);let ke=E.useRef(null),Ae=cn(u,ke,we.inputRef,we.registerInput),je=TZ(a,F,ke,!y,ue??void 0);It(()=>{ke.current&&(ke.current.indeterminate=Oe,Te&&D(!0))},[Te,Oe,D]),vd(Te,()=>{ne||(S(oe),D(Te),T(Te!==M.initialValue),we.change(Te))});let Me=zt({checked:Te,disabled:ae,form:s,name:p?void 0:oe,id:y?void 0:ue??void 0,required:g,ref:Ae,style:oe?to:eo,tabIndex:-1,type:`checkbox`,"aria-hidden":!0,onChange(e){if(e.nativeEvent.defaultPrevented)return;if(m){e.preventDefault();return}let t=e.currentTarget.checked,n=Wi(ji,e.nativeEvent);if(f?.(t,n),!n.isCanceled&&(me?.(t,n),!n.isCanceled&&(Ee(t),se&&ge&&_e&&!p&&!ie))){let e=t?[...ge,se]:ge.filter(e=>e!==se);_e(e,n)}},onFocus(){ye.current?.focus()}},v===void 0?yn:{value:(ne?Te&&v:v)||``},te,e=>we.getValidationProps(ae,e));E.useEffect(()=>{if(!re||!se)return;let e=re.disabledStatesRef.current;return e.set(se,ae),()=>{e.delete(se)}},[re,ae,se]);let Ne=E.useMemo(()=>({...A,checked:De,disabled:ae,readOnly:m,required:g,indeterminate:Oe}),[A,De,ae,m,g,Oe]),Pe=mZ(Ne),Fe=Cn(`span`,e,{state:Ne,ref:[Ce,ye,t,ne?.registerControlRef],props:[{id:y?ue??void 0:ce,role:`checkbox`,"aria-checked":Oe?`mixed`:De,"aria-readonly":m||void 0,"aria-required":g||void 0,"aria-labelledby":je,[MZ]:p?``:void 0,onFocus(){ae||O(!0)},onBlur(){let e=ke.current;e&&(k(!0),O(!1),j===`onBlur`&&we.commit(ne?ge:e.checked))},onKeyDown(e){if(e.key!==`Enter`||(e.preventBaseUIHandler(),e.defaultPrevented))return;let t=ke.current?.form??null,n=e.currentTarget,r=e.nativeEvent,i=e.preventDefault,a=r.preventDefault,o=!1;e.preventDefault=()=>{o=!0,i.call(e)},r.preventDefault=()=>{o=!0,a.call(r)},a.call(r),at(n).queueMicrotask(()=>{e.preventDefault=i,r.preventDefault=a,o||sZ(t)?.click()})},onClick(e){if(m||ae)return;e.preventDefault();let t=ke.current;t&&t.dispatchEvent(new(at(t)).PointerEvent(`click`,{bubbles:!0,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey}))}},x,he,Se,te,e=>we.getValidationProps(ae,e)],stateAttributesMapping:Pe});return(0,L.jsxs)(AZ.Provider,{value:Ne,children:[Fe,!Te&&!ne&&oe&&!p&&_!==void 0&&(0,L.jsx)(`input`,{type:`hidden`,form:s,name:oe,value:_,disabled:ae}),(0,L.jsx)(`input`,{...Me,suppressHydrationWarning:!0})]})}),PZ=E.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=jZ(),c=s.checked||s.indeterminate,{mounted:l,transitionStatus:u,setMounted:d}=Ll(c),f=E.useRef(null),p={...s,transitionStatus:u};zl({open:c,ref:f,onComplete(){c||d(!1)}});let m={...mZ(s),...vi,...pZ},h=a||l,g=Cn(`span`,e,{ref:[t,f],state:p,stateAttributesMapping:m,props:o});return h?g:null}),FZ=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,IZ=(0,E.memo)(function({draft:e,providerTypes:t,envByName:n,providerTypeEnvVars:r,providerTypeDefaultModels:i,usedTypesByOthers:a,duplicateName:o,onChange:s,onRemove:c}){let[l,u]=(0,E.useState)(``),d=(0,E.useId)(),f=t=>s({...e,...t}),p=t=>{if(!(e.name===``||e.name===e.type)){f({type:t});return}let n=a.has(t);f({type:t,name:n?``:t})},m=()=>{let t=l.trim();if(t){if(e.models.includes(t)){u(``);return}f({models:[...e.models,t]}),u(``)}},h=t=>f({models:e.models.filter(e=>e!==t)}),g=t=>{if(t.key===`Enter`||t.key===`,`)t.preventDefault(),m();else if(t.key===`Backspace`&&!l&&e.models.length){t.preventDefault();let n=e.models[e.models.length-1];n&&h(n)}},_=LZ(e,n,r);return(0,L.jsxs)(`div`,{className:li(`relative rounded-lg bg-card shadow-card px-4 py-3.5`,`transition-colors hover:border-border/60`),children:[(0,L.jsx)(`button`,{type:`button`,onClick:()=>c(e.id),"aria-label":`Remove provider ${e.name||`untitled`}`,className:li(`absolute right-2 top-2 inline-flex items-center justify-center rounded-sm size-7`,`text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-destructive/60`),children:(0,L.jsx)(rf,{className:`size-3.5`})}),(0,L.jsxs)(`div`,{className:`flex flex-col gap-2.5 pr-8`,children:[(0,L.jsxs)(nZ,{label:`Name`,hint:RZ(e,a,o),children:[(0,L.jsx)(aZ,{value:e.name,onChange:e=>f({name:e.target.value}),placeholder:`e.g. anthropic`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,invalid:o||!e.name.trim()}),o&&(0,L.jsx)(`span`,{className:`text-[12px] text-destructive/80`,children:`duplicate name`})]}),(0,L.jsx)(nZ,{label:`Type`,children:(0,L.jsx)(oZ,{value:e.type,onChange:e=>p(e.target.value),children:t.map(e=>(0,L.jsx)(`option`,{value:e,children:e},e))})}),(0,L.jsx)(nZ,{label:`Base URL`,children:(0,L.jsx)(aZ,{value:e.base_url,onChange:e=>f({base_url:e.target.value}),placeholder:`(provider default)`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`})}),e.type===`openai_chat`&&(0,L.jsx)(nZ,{label:`Reasoning effort`,hint:`Enable if this endpoint accepts a reasoning effort level.`,children:(0,L.jsxs)(NZ,{checked:e.supports_reasoning_effort,onCheckedChange:e=>f({supports_reasoning_effort:e}),"aria-label":`Reasoning effort supported`,className:li(`group flex h-9 items-center gap-2.5 px-2 cursor-pointer select-none`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent/60`),children:[(0,L.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-border/60 transition-colors group-hover:border-border group-data-[checked]:border-accent group-data-[checked]:bg-accent`,children:(0,L.jsx)(PZ,{children:(0,L.jsx)(Md,{className:`size-3 text-accent-foreground`,strokeWidth:3})})}),(0,L.jsx)(`span`,{className:`text-[13px] text-foreground/90`,children:`Supported`})]})}),(0,L.jsx)(nZ,{label:`API key`,hint:_,children:(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(aZ,{id:d,value:e.api_key_input,onChange:e=>f({api_key_input:e.target.value,api_key_dirty:!0}),placeholder:e.api_key_saved&&!e.api_key_dirty?`•••••• saved · type to replace`:"paste a key, or use ${ENV_VAR}",spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,autoComplete:`off`,type:`text`}),e.api_key_saved&&!e.api_key_dirty&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>f({api_key_input:``,api_key_dirty:!0}),className:li(`shrink-0 text-[12px]`,`text-muted-foreground/70 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`,`h-9 px-2`),"aria-label":`Clear saved API key`,children:`clear`})]})}),(0,L.jsx)(nZ,{label:`Models`,hint:e.models.length===0?zZ(i[e.type]):void 0,children:(0,L.jsxs)(`div`,{className:`flex flex-col gap-2.5`,children:[e.models.length>0&&(0,L.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.models.map(e=>(0,L.jsxs)(`span`,{className:li(`group inline-flex items-center gap-1 rounded-sm h-7 pl-2.5 pr-1`,`bg-muted/60 text-foreground/90 text-[12px] font-mono`),children:[e,(0,L.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:li(`inline-flex items-center justify-center rounded-sm size-5`,`text-muted-foreground/60 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`),"aria-label":`Remove model ${e}`,children:(0,L.jsx)(rf,{className:`size-3`})})]},e))}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:g,"aria-label":`Add model`,placeholder:e.models.length===0?`add a model id…`:`add another…`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,className:li(`flex-1 min-w-0 bg-transparent h-9 px-2`,`text-[13px] font-mono`,`border-b border-border/60`,`transition-colors`,`placeholder:text-muted-foreground/50`,`hover:border-border focus:border-accent focus:outline-none`)}),l&&(0,L.jsx)(`button`,{type:`button`,onClick:m,className:li(`shrink-0 inline-flex items-center justify-center rounded-sm size-9`,`text-muted-foreground/70 hover:text-foreground hover:bg-muted/50 active:scale-95 transition-[color,background-color,scale] duration-150`),"aria-label":`Add model`,children:(0,L.jsx)(Yd,{className:`size-4`})})]})]})})]})]})});function LZ(e,t,n){if(e.original_name!==``&&e.original_name!==e.name.trim()&&e.api_key_saved&&!e.api_key_dirty)return(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`renamed from `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.original_name}),`: saved key won't carry over, paste it again`]});let r=e.api_key_input.trim().match(FZ);if(r){let e=r[1];return t[e]??!1?(0,L.jsxs)(L.Fragment,{children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:e}),` is set`]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:e}),` is not set`]})}if(!e.api_key_input.trim()&&!e.api_key_saved){let r=n[e.type]||[];if(r.length===0)return(0,L.jsx)(`span`,{className:`text-destructive/80`,children:`API key required. Paste a key or use an environment variable`});let i=r[0];return t[i]??!1?(0,L.jsxs)(L.Fragment,{children:[`using env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i})]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i}),` not set. Paste a key or set the env`]})}}function RZ(e,t,n){if(n)return;let r=e.name.trim();if(!r)return t.has(e.type)?(0,L.jsxs)(L.Fragment,{children:[`type `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.type}),` already used. pick an alias name`]}):void 0;if(r===e.type)return(0,L.jsxs)(L.Fragment,{children:[`overrides built-in `,(0,L.jsx)(`code`,{className:`font-mono`,children:e.type})]})}function zZ(e){return!e||e.length===0?`add at least one model id`:(0,L.jsxs)(L.Fragment,{children:[`uses built-in:`,` `,e.map((t,n)=>(0,L.jsxs)(`span`,{children:[(0,L.jsx)(`code`,{className:`font-mono`,children:t}),n<e.length-1?`, `:``]},t))]})}var BZ=`~/.mycode/config.json`,VZ={default_provider:``,default_model:``,compact_threshold:``,permission_level:`safe`,permission_mode:`ask`,web_fetch:`local`,web_search:`off`,web_tavily:{api_key_input:``,api_key_dirty:!1,api_key_saved:!1},web_exa:{api_key_input:``,api_key_dirty:!1,api_key_saved:!1},providers:[]},HZ=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,UZ=[{value:`readonly`,label:`readonly`},{value:`safe`,label:`safe`},{value:`standard`,label:`standard`},{value:`yolo`,label:`yolo`}],WZ=[{value:`ask`,label:`ask`},{value:`deny`,label:`deny`}],GZ=li(`inline-flex items-center justify-center rounded-md text-[13px]`,`text-muted-foreground hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),KZ=li(`inline-flex items-center justify-center gap-1.5 rounded-md text-[13px] font-medium`,`bg-accent text-accent-foreground hover:brightness-105 hover:saturate-[.9] active:scale-95 transition-[color,filter,scale] duration-150`,`disabled:opacity-40 disabled:pointer-events-none`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`),qZ=[{value:`system`,label:`system`,icon:(0,L.jsx)(Hd,{className:`size-3.5`})},{value:`light`,label:`light`,icon:(0,L.jsx)(ef,{className:`size-3.5`})},{value:`dark`,label:`dark`,icon:(0,L.jsx)(Gd,{className:`size-3.5`})}];function JZ(e){let{config:t}=e,n=e.options.provider_types[0]??``,r={...VZ};r.default_provider=t.default?.provider??``,r.default_model=t.default?.model??``;let i=t.default?.compact_threshold;i===!1?r.compact_threshold=`disabled`:typeof i==`number`&&(r.compact_threshold=String(i));let a=t.permission;return typeof a==`string`?r.permission_level=a:a&&(a.level&&(r.permission_level=a.level),a.mode&&(r.permission_mode=a.mode)),r.web_fetch=t.web?.fetch??`local`,r.web_search=t.web?.search??`off`,r.web_tavily=YZ(t.web?.tavily),r.web_exa=YZ(t.web?.exa),r.providers=Object.entries(t.providers??{}).map(([e,t],r)=>({id:`p-${r}-${e}`,name:e,original_name:e,type:t.type??e??n,models:Array.isArray(t.models)?t.models:Object.keys(t.models??{}),model_overrides:t.model_overrides??{},base_url:t.base_url??``,supports_reasoning_effort:!!t.supports_reasoning_effort,api_key_input:typeof t.api_key==`string`?t.api_key:``,api_key_dirty:!1,api_key_saved:!!t.api_key_saved})),r}function YZ(e){return{api_key_input:typeof e?.api_key==`string`?e.api_key:``,api_key_dirty:!1,api_key_saved:!!e?.api_key_saved}}function XZ(e,t){let n={},r={};if(t.trim()&&(r.provider=t.trim()),e.default_provider.trim()===t.trim()&&e.default_model.trim()&&(r.model=e.default_model.trim()),e.compact_threshold===`disabled`)r.compact_threshold=!1;else if(e.compact_threshold.trim()){let t=Number(e.compact_threshold);Number.isFinite(t)&&(r.compact_threshold=t)}Object.keys(r).length&&(n.default=r),n.permission={level:e.permission_level,mode:e.permission_mode};let i={fetch:e.web_fetch,search:e.web_search};for(let t of[`tavily`,`exa`]){let n=t===`tavily`?e.web_tavily:e.web_exa;(n.api_key_saved||n.api_key_input.trim())&&(i[t]={api_key:n.api_key_dirty?n.api_key_input.trim():null})}n.web=i;let a={};for(let t of e.providers){let e=t.name.trim();if(!e)continue;let n={};if(t.type&&(n.type=t.type),t.models.length){let e={};for(let n of t.models){let r=t.model_overrides[n];r&&Object.keys(r).length&&(e[n]=r)}Object.keys(e).length?n.models=Object.fromEntries(t.models.map(t=>[t,e[t]??{}])):n.models=t.models}t.base_url.trim()&&(n.base_url=t.base_url.trim()),t.type===`openai_chat`&&t.supports_reasoning_effort&&(n.supports_reasoning_effort=!0);let r=t.original_name!==``&&t.original_name!==e;n.api_key=t.api_key_dirty||r?t.api_key_input.trim():null,a[e]=n}return Object.keys(a).length&&(n.providers=a),n}var ZZ=[];function QZ(e,t,n){let r=t.api_key_input.trim().match(HZ)?.[1];if(r)return n[r]?(0,L.jsxs)(L.Fragment,{children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:r}),` is set`]}):(0,L.jsxs)(`span`,{className:`text-destructive/80`,children:[`env `,(0,L.jsx)(`code`,{className:`font-mono`,children:r}),` is not set`]});if(t.api_key_saved&&!t.api_key_dirty)return`saved key`;if(t.api_key_input.trim())return;let i=e===`tavily`?`TAVILY_API_KEY`:`EXA_API_KEY`;return n[i]?(0,L.jsxs)(L.Fragment,{children:[`using env `,(0,L.jsx)(`code`,{className:`font-mono`,children:i})]}):e===`exa`?(0,L.jsx)(`span`,{className:`text-destructive/80`,children:`key required`}):`optional; requests use Tavily keyless access when unset`}function $Z({open:e,onClose:t,settings:n,loadError:r,remoteConfig:a,onSettingsSaved:o,projectConfigPaths:s}){let c=uf(`(min-width: 768px)`),{theme:l,setTheme:u}=i(),[d,f]=(0,E.useState)(()=>n?JZ(n):VZ),[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)(null),_=n?.options.provider_types??ZZ,v=n?.env??{},y=n?.provider_type_env_vars??{},b=n?.provider_type_default_models??{},x=(0,E.useMemo)(()=>{let e=new Map;for(let t of d.providers){let n=new Set;for(let e of d.providers)e.id!==t.id&&n.add(e.type);e.set(t.id,n)}return e},[d.providers]),S=(0,E.useMemo)(()=>{let e=new Map;for(let t of d.providers){let n=t.name.trim();n&&e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e)r>1&&t.add(n);return t},[d.providers]),C=Object.keys(a?.providers??{}),w=d.default_provider.trim(),T=a?.default?.provider??``,D=C.includes(w)?w:C.includes(T)?T:C[0]??``,O=S.size>0||d.providers.some(e=>!e.name.trim()||!e.type),k=d.compact_threshold===`disabled`,A=(0,E.useCallback)(e=>{f(t=>({...t,providers:t.providers.map(t=>t.id===e.id?e:t)}))},[]),j=(0,E.useCallback)((e,t)=>{f(n=>e===`tavily`?{...n,web_tavily:{...n.web_tavily,...t}}:{...n,web_exa:{...n.web_exa,...t}})},[]),M=(0,E.useCallback)(e=>{f(t=>({...t,providers:t.providers.filter(t=>t.id!==e)}))},[]),N=(0,E.useCallback)(()=>{f(e=>{let t=_[0]??``,n=e.providers.some(e=>e.type===t),r={id:`p-new-${Math.random().toString(36).slice(2,8)}`,name:n?``:t,original_name:``,type:t,models:[],model_overrides:{},base_url:``,supports_reasoning_effort:!1,api_key_input:``,api_key_dirty:!1,api_key_saved:!1};return{...e,providers:[...e.providers,r]}})},[_]),P=async()=>{if(!(!n||O||p)){m(!0),g(null);try{let e=await fetch(`/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({config:XZ(d,D)})});if(!e.ok){let t=`Save failed (${e.status})`;try{let n=await e.json();n?.detail&&(t=n.detail)}catch{}throw Error(t)}let n=await e.json();f(JZ(n)),o?.(n),t()}catch(e){g(e instanceof Error?e.message:`Failed to save settings`)}finally{m(!1)}}},F=(s??[]).filter(e=>e!==n?.path),I=`Edits ${eQ(n?.path??BZ)}`,ee=(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)(`div`,{className:li(`flex items-center justify-between shrink-0`,`border-b border-border/30`,`px-4 md:px-6 h-12 md:h-14`,`max-md:pt-[env(safe-area-inset-top)]`,`max-md:h-[calc(3rem+env(safe-area-inset-top))]`),children:[(0,L.jsx)(`h2`,{className:`text-[14px] font-semibold text-foreground`,children:`Settings`}),(0,L.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:li(`inline-flex items-center justify-center rounded-sm -mr-1`,`size-8`,`text-muted-foreground/70 hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),children:(0,L.jsx)(rf,{className:`size-4`})})]}),(0,L.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain scrollbar-subtle`,children:n?(0,L.jsxs)(`div`,{className:`px-4 md:px-6 py-6 flex flex-col gap-7`,children:[F.length>0&&(0,L.jsxs)(`div`,{className:`rounded-md border border-border/40 bg-muted/20 px-3.5 py-2.5 text-[12px] leading-relaxed`,children:[(0,L.jsx)(`div`,{className:`text-foreground/80`,children:`Project-level config in effect:`}),(0,L.jsx)(`ul`,{className:`mt-1.5 ml-4 list-disc text-muted-foreground/80 marker:text-muted-foreground/40 space-y-0.5`,children:F.map(e=>(0,L.jsx)(`li`,{className:`truncate font-mono`,children:eQ(e)},e))}),(0,L.jsx)(`div`,{className:`mt-1.5 text-muted-foreground/70`,children:`These continue to override settings saved here.`})]}),(0,L.jsx)(rZ,{title:`Appearance`,children:(0,L.jsx)(nZ,{label:`Theme`,children:(0,L.jsx)(iZ,{value:l,options:qZ,onChange:u,ariaLabel:`Theme`})})}),(0,L.jsxs)(rZ,{title:`Defaults`,children:[C.length===0?(0,L.jsx)(`div`,{className:`rounded-md border border-dashed border-border/50 px-3.5 py-2.5 text-[12px] text-muted-foreground/70`,children:`No runnable providers are available.`}):(0,L.jsx)(nZ,{label:`Provider`,children:(0,L.jsx)(oZ,{value:D,onChange:e=>f(t=>({...t,default_provider:e.target.value,default_model:``})),children:C.map(e=>(0,L.jsx)(`option`,{value:e,children:e},e))})}),(0,L.jsx)(nZ,{label:`Compact`,hint:k?(0,L.jsxs)(L.Fragment,{children:[`Auto-compaction disabled.`,` `,(0,L.jsx)(`button`,{type:`button`,onClick:()=>f(e=>({...e,compact_threshold:``})),className:`text-accent hover:underline focus-visible:outline-none focus-visible:underline`,children:`Enable`})]}):(0,L.jsxs)(L.Fragment,{children:[`Trigger compaction at this fraction of context window (default 0.8).`,` `,(0,L.jsx)(`button`,{type:`button`,onClick:()=>f(e=>({...e,compact_threshold:`disabled`})),className:`text-accent hover:underline focus-visible:outline-none focus-visible:underline`,children:`Disable`})]}),children:(0,L.jsx)(aZ,{type:`number`,min:0,max:1,step:.05,value:k?``:d.compact_threshold,placeholder:`0.8`,disabled:k,onChange:e=>f(t=>({...t,compact_threshold:e.target.value}))})})]}),(0,L.jsxs)(rZ,{title:`Web access`,children:[(0,L.jsx)(nZ,{label:`Fetch`,children:(0,L.jsxs)(oZ,{"aria-label":`Web fetch provider`,value:d.web_fetch,onChange:e=>f(t=>({...t,web_fetch:e.target.value})),children:[(0,L.jsx)(`option`,{value:`local`,children:`local`}),(0,L.jsx)(`option`,{value:`tavily`,children:`Tavily`}),(0,L.jsx)(`option`,{value:`exa`,children:`Exa`})]})}),(0,L.jsx)(nZ,{label:`Search`,children:(0,L.jsxs)(oZ,{"aria-label":`Web search provider`,value:d.web_search,onChange:e=>f(t=>({...t,web_search:e.target.value})),children:[(0,L.jsx)(`option`,{value:`off`,children:`Off`}),(0,L.jsx)(`option`,{value:`tavily`,children:`Tavily`}),(0,L.jsx)(`option`,{value:`exa`,children:`Exa`})]})}),[`tavily`,`exa`].map(e=>{if(!(d.web_fetch===e||d.web_search===e))return null;let t=e===`tavily`?d.web_tavily:d.web_exa,n=e===`tavily`?`Tavily`:`Exa`;return(0,L.jsx)(nZ,{label:`${n} key`,hint:QZ(e,t,v),children:(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(aZ,{"aria-label":`${n} API key`,value:t.api_key_input,onChange:t=>j(e,{api_key_input:t.target.value,api_key_dirty:!0}),placeholder:t.api_key_saved&&!t.api_key_dirty?`•••••• saved · type to replace`:"paste a key, or use ${ENV_VAR}",spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,autoComplete:`off`}),t.api_key_saved&&!t.api_key_dirty&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>j(e,{api_key_input:``,api_key_dirty:!0}),className:`shrink-0 h-9 px-2 text-[12px] text-muted-foreground/70 hover:text-destructive active:scale-95 transition-[color,scale] duration-150`,"aria-label":`Clear saved ${e} API key`,children:`clear`})]})},e)})]}),(0,L.jsxs)(rZ,{title:`Permissions`,children:[(0,L.jsxs)(nZ,{label:`Level`,children:[(0,L.jsx)(`div`,{className:`md:hidden`,children:(0,L.jsx)(oZ,{value:d.permission_level,onChange:e=>f(t=>({...t,permission_level:e.target.value})),children:UZ.map(e=>(0,L.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,L.jsx)(`div`,{className:`max-md:hidden`,children:(0,L.jsx)(iZ,{value:d.permission_level,onChange:e=>f(t=>({...t,permission_level:e})),options:UZ,ariaLabel:`Permission level`,size:`sm`})})]}),(0,L.jsx)(nZ,{label:`Mode`,children:(0,L.jsx)(iZ,{value:d.permission_mode,onChange:e=>f(t=>({...t,permission_mode:e})),options:WZ,ariaLabel:`Permission mode`,size:`sm`})})]}),(0,L.jsx)(rZ,{title:`Providers`,children:(0,L.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[d.providers.map(e=>(0,L.jsx)(IZ,{draft:e,providerTypes:_,envByName:v,providerTypeEnvVars:y,providerTypeDefaultModels:b,usedTypesByOthers:x.get(e.id)??new Set,duplicateName:S.has(e.name.trim()),onChange:A,onRemove:M},e.id)),(0,L.jsxs)(`button`,{type:`button`,onClick:N,className:li(`inline-flex items-center justify-center gap-1.5 rounded-lg h-9`,`border border-dashed border-border/50 text-muted-foreground/80`,`hover:border-border hover:text-foreground hover:bg-muted/30 active:scale-95 transition-[color,background-color,border-color,scale] duration-150`,`text-[13px]`),children:[(0,L.jsx)(Yd,{className:`size-4`}),`Add provider`]})]})})]}):(0,L.jsx)(`div`,{className:`flex items-center justify-center h-48 px-6 text-center text-[12px] text-muted-foreground/60`,children:r?(0,L.jsx)(`span`,{children:r}):null})}),(0,L.jsxs)(`div`,{className:li(`shrink-0 border-t border-border/30`,`max-md:pb-[env(safe-area-inset-bottom)]`),children:[(0,L.jsxs)(`div`,{className:`md:hidden flex flex-col gap-2 px-4 py-3`,children:[h&&(0,L.jsx)(`div`,{className:`text-[12px] text-destructive/90 leading-relaxed`,children:h}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:t,className:li(GZ,`flex-1 h-9`),children:`Cancel`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void P(),disabled:!n||p||O,className:li(KZ,`flex-2 h-9`),children:[p&&(0,L.jsx)(Ud,{className:`size-3.5 animate-spin`}),`Save`]})]})]}),(0,L.jsxs)(`div`,{className:`max-md:hidden flex items-center justify-between gap-3 px-6 py-3`,children:[(0,L.jsx)(`div`,{className:`text-[12px] text-muted-foreground/70 truncate min-w-0 flex-1`,children:h?(0,L.jsx)(`span`,{className:`text-destructive/90`,children:h}):I}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:t,className:li(GZ,`h-8 px-3.5`),children:`Cancel`}),(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void P(),disabled:!n||p||O,className:li(KZ,`h-8 px-4`),children:[p&&(0,L.jsx)(Ud,{className:`size-3.5 animate-spin`}),`Save`]})]})]})]})]}),te=e=>{e||t()};return c?(0,L.jsx)(ZX,{open:e,onOpenChange:te,children:(0,L.jsxs)(eZ,{showCloseButton:!1,className:`flex flex-col gap-0 p-0 w-160 max-w-[calc(100vw-2rem)] max-h-[82vh] sm:max-w-[calc(100vw-2rem)]`,children:[(0,L.jsx)(tZ,{className:`sr-only`,children:`Settings`}),ee]})}):(0,L.jsx)(af,{open:e,onOpenChange:te,children:(0,L.jsxs)(cf,{side:`bottom`,showCloseButton:!1,className:`flex flex-col gap-0 p-0 h-dvh rounded-none`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Settings`}),ee]})})}function eQ(e){if(!e)return``;let t=e.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(.*)$/);return t?`~${t[2]??``}`:e}function tQ(){return typeof window>`u`?480:Math.min(480,Math.floor(window.innerWidth*.4))}function nQ(e){return Math.max(200,Math.min(tQ(),e))}function rQ(e){return e?!0:typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(hover: hover) and (pointer: fine)`).matches}var iQ=e=>e.replace(/\\/g,`/`),aQ=e=>/^([a-zA-Z]:[\\/]|\/)/.test(e),oQ=(e,t,n=!0)=>{let r=iQ(t);return e.toSorted((e,t)=>t.length-e.length).find(e=>{let t=iQ(e).replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})||(n?e[0]:void 0)},sQ=(e,t)=>{let n=iQ(e).replace(/\/+$/,``),r=iQ(t);return r===n?``:(r.startsWith(n)?r.slice(n.length):r).replace(/^\/+/,``)},cQ=[],lQ=[],uQ=e=>{if(!e||e===`/`||e===`\\`)return`/`;let t=e.replace(/[\\/]+$/,``);if(/\/Users\/[^/]+$/.test(t)||/\/home\/[^/]+$/.test(t))return`~`;let n=t.split(/[/\\]/);return n[n.length-1]||e};async function dQ(e){let t=await fetch(e);if(!t.ok)throw Error(`Failed to load roots`);return(await t.json()).roots??[]}async function fQ(e){let t=await fetch(e);if(!t.ok)throw Error(`Failed to browse directory`);let n=await t.json();if(n.error)throw Error(n.error);return n}var pQ={revalidateOnFocus:!1},mQ={revalidateOnFocus:!1};function hQ(e){if(!e?.root)return null;let t=new URLSearchParams({root:e.root});return e.path&&t.set(`path`,e.path),`/api/workspaces/browse?${t.toString()}`}function gQ(e){return e instanceof Error?e.message:`Unknown error`}function _Q(e,t,n){if(!e||t.length===0)return null;let r=n?oQ(t,n):t[0];return r?{root:r,path:n?sQ(r,n):``}:null}function vQ({open:e,openedWithKeyboard:t,onClose:n,currentCwd:r,cwdHistory:i=cQ,onSelect:a,onMissingHistory:o}){let s=uf(`(min-width: 640px)`),{data:c=[],error:l,isLoading:u}=nt(`/api/workspaces/roots`,dQ,pQ),[d,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(``),[h,g]=(0,E.useState)(``),_=(0,E.useRef)(null),v=(0,E.useMemo)(()=>_Q(e,c,r),[e,c,r]),y=d??v,b=hQ(y),{data:x,error:S}=nt(b,fQ,mQ),C=x?{root:x.root,path:x.path}:y,w=C?.root??``,T=C?.path??``,D=x?.entries??lQ,O=x?.current??``,k=u||!!b&&!x&&!S,A=(0,E.useMemo)(()=>{let e=h.trim().toLowerCase();return e?D.filter(t=>t.name.toLowerCase().includes(e)):D},[h,D]),j=(0,E.useCallback)((e,t)=>{m(``),g(``),f(n=>n?.root===e&&n.path===t?n:{root:e,path:t})},[]),M=(0,E.useCallback)(e=>{let t=e.trim();if(!(!t||c.length===0)){if(aQ(t)){let e=oQ(c,t,!1);if(!e){m(`Path is outside any configured workspace root.`);return}j(e,sQ(e,t))}else if(w){let e=T?`${T}/${t}`:t;j(w,e)}}},[c,w,T,j]),N=(0,E.useCallback)(()=>{if(!w||!T)return;let e=T.split(`/`);j(w,e.slice(0,-1).join(`/`))},[w,T,j]),P=(0,E.useCallback)(()=>{O&&(a(O),n())},[O,a,n]),F=(0,E.useCallback)(async e=>{try{let t=oQ(c,e,!1);if(!t)return!1;let n=hQ({root:t,path:sQ(t,e)});if(!n)return!1;let r=await fetch(n);if(!r.ok)return!1;let i=await r.json();return!!(i.current&&!i.error)}catch{return!1}},[c]),I=(0,E.useCallback)(async e=>{if(!await F(e)){m(`Workspace no longer exists.`),o?.(e);return}a(e),n()},[F,o,a,n]),ee=(0,E.useCallback)(e=>{if(e.key===`Enter`){let e=A.length===1?A[0]:null;e&&w?j(w,e.path):h.trim()&&M(h)}else if(e.key===`Tab`){e.preventDefault();let t=A[0];t&&w&&j(w,t.path)}else e.key===`Escape`&&h?(e.preventDefault(),e.stopPropagation(),g(``)):e.key===`Backspace`&&!h&&N()},[h,A,w,j,M,N]),te=T?T.split(`/`):[],ne=O||r||``,re=i.filter(e=>e!==ne),ie=re.length>0&&!h.trim(),ae=p||(S?`Workspace no longer exists. Choose another workspace.`:``),oe=(l?gQ(l):``)||(!u&&c.length===0?`No workspace roots configured.`:``),se=!!S&&c.length>0&&!h.trim(),ce=(0,L.jsxs)(L.Fragment,{children:[!s&&(0,L.jsx)(`div`,{className:`flex justify-center pt-2.5 pb-1 shrink-0`,"aria-hidden":`true`,children:(0,L.jsx)(`div`,{className:`w-10 h-0.75 rounded-full bg-border/60`})}),(0,L.jsxs)(`div`,{className:`flex items-center min-h-11 px-4 border-b border-border/30 shrink-0 gap-1`,children:[(0,L.jsxs)(`div`,{className:`flex-1 flex items-center overflow-x-auto scrollbar-none min-w-0 gap-0.5`,children:[(0,L.jsx)(`button`,{type:`button`,onClick:()=>w&&j(w,``),className:li(`shrink-0 px-1.5 py-0.5 rounded-sm text-xs font-mono`,`active:scale-95 transition-[color,background-color,scale] duration-150 hover:bg-muted/60 hover:text-foreground`,te.length===0?`text-foreground font-medium`:`text-muted-foreground`),children:uQ(w)||`~`}),te.map((e,t)=>{let n=te.slice(0,t+1).join(`/`);return(0,L.jsxs)(`div`,{className:`flex items-center shrink-0`,children:[(0,L.jsx)(`span`,{className:`text-border select-none mx-0.5 text-xs`,"aria-hidden":`true`,children:`/`}),(0,L.jsx)(`button`,{type:`button`,onClick:()=>j(w,n),className:li(`px-1.5 py-0.5 rounded-sm text-xs font-mono whitespace-nowrap`,`active:scale-95 transition-[color,background-color,scale] duration-150 hover:bg-muted/60 hover:text-foreground`,t===te.length-1?`text-foreground font-medium`:`text-muted-foreground`),children:e})]},n)})]}),(0,L.jsx)(`button`,{type:`button`,onClick:n,className:li(`flex items-center justify-center size-8 rounded-lg shrink-0`,`text-muted-foreground/50 active:scale-95 transition-[color,background-color,scale] duration-150`,`hover:bg-muted/70 hover:text-foreground`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`),"aria-label":`Close`,children:(0,L.jsx)(rf,{className:`size-3.5`})})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-2.5 px-4 py-2.5 border-b border-border/20 shrink-0`,children:[(0,L.jsx)(Xd,{className:`size-3.5 shrink-0 text-muted-foreground/30`}),(0,L.jsx)(`input`,{ref:_,name:`workspace-filter`,value:h,onChange:e=>g(e.target.value),onKeyDown:ee,placeholder:`Filter or type a path…`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,className:`w-full bg-transparent text-base sm:text-sm font-mono focus-visible:outline-none text-foreground placeholder:text-muted-foreground/30 caret-accent`,"aria-label":`Filter directories or enter a path`}),h&&(0,L.jsx)(`button`,{type:`button`,onClick:()=>g(``),className:`shrink-0 text-muted-foreground/40 hover:text-muted-foreground active:scale-95 transition-[color,scale] duration-150`,"aria-label":`Clear filter`,children:(0,L.jsx)(rf,{className:`size-3`})})]}),(0,L.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto overscroll-contain`,children:[k&&(0,L.jsx)(`div`,{className:`flex items-center justify-center h-36`,children:(0,L.jsx)(`div`,{className:`flex items-end gap-1`,children:[0,1,2].map(e=>(0,L.jsx)(`div`,{className:`w-0.75 rounded-full bg-muted-foreground/30 animate-pulse`,style:{height:`${12+e*4}px`,animationDelay:`${e*120}ms`}},e))})}),!k&&oe&&(0,L.jsx)(`div`,{className:`flex items-center justify-center h-36 px-6 text-center`,children:(0,L.jsx)(`p`,{className:`text-xs text-destructive leading-relaxed`,children:oe})}),!k&&!oe&&(0,L.jsxs)(`div`,{className:`py-1`,children:[ae&&(0,L.jsx)(`div`,{className:`mx-4 my-2 rounded-md border border-border/30 bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-muted-foreground`,children:ae}),ie&&(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`div`,{className:`px-4 pt-3 pb-1.5`,children:(0,L.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/40 select-none`,children:`Recent`})}),re.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>void I(e),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(Fd,{className:`size-3.5 shrink-0 text-muted-foreground/35 group-hover:text-accent/60 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-xs font-mono text-muted-foreground group-hover:text-foreground/80 transition-colors`,children:e})]},e)),(A.length>0||se)&&(0,L.jsx)(`div`,{className:`mx-4 mt-1 mb-1 border-b border-border/20`})]}),se&&(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(`div`,{className:`px-4 pt-3 pb-1.5`,children:(0,L.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/40 select-none`,children:`Roots`})}),c.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>j(e,``),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(zd,{className:`size-3.5 shrink-0 text-muted-foreground/35 group-hover:text-accent/60 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-xs font-mono text-muted-foreground group-hover:text-foreground/80 transition-colors`,children:e})]},e)),A.length>0&&(0,L.jsx)(`div`,{className:`mx-4 mt-1 mb-1 border-b border-border/20`})]}),A.length===0&&!ie&&!se&&(0,L.jsxs)(`div`,{className:`flex flex-col items-center justify-center gap-3 h-36 text-muted-foreground/30`,children:[(0,L.jsx)(Bd,{className:`size-10`,strokeWidth:1}),(0,L.jsx)(`p`,{className:`text-xs`,children:h.trim()?`No matches`:`This folder is empty`})]}),A.map(e=>(0,L.jsxs)(`button`,{type:`button`,onClick:()=>j(w,e.path),className:`group flex items-center gap-3 w-full min-h-11 px-4 py-2 text-left transition-colors hover:bg-muted/50 active:bg-muted/70 focus-visible:outline-none focus-visible:bg-muted/50`,children:[(0,L.jsx)(Bd,{className:`size-3.5 shrink-0 text-accent/40 group-hover:text-accent/70 transition-colors`}),(0,L.jsx)(`span`,{className:`truncate text-sm font-mono text-foreground/70 group-hover:text-foreground transition-colors`,children:e.name})]},e.path))]})]}),(0,L.jsxs)(`div`,{className:`flex items-center gap-3 h-12 px-4 border-t border-border/20 shrink-0`,children:[(0,L.jsx)(zd,{className:`size-3.5 shrink-0 text-muted-foreground/30`}),(0,L.jsx)(`span`,{className:`flex-1 min-w-0 truncate text-xs font-mono text-muted-foreground/60`,title:O,children:O||`—`}),(0,L.jsx)(`button`,{type:`button`,onClick:P,disabled:!O,className:li(`shrink-0 px-3.5 h-7 rounded-md text-xs font-semibold`,`active:scale-95 transition-[color,background-color,border-color,scale] duration-150`,`bg-accent/15 text-accent border border-accent/20`,`hover:bg-accent/25 hover:border-accent/40 active:bg-accent/30`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,`disabled:opacity-25 disabled:cursor-not-allowed`),children:`Open`})]})]}),le=e=>{e||n()},ue=rQ(t)?_:void 0;return s?(0,L.jsx)(ZX,{open:e,onOpenChange:le,children:(0,L.jsxs)(eZ,{showCloseButton:!1,initialFocus:ue,className:`flex flex-col gap-0 p-0 w-110 max-w-[calc(100vw-2rem)] max-h-130 sm:max-w-[calc(100vw-2rem)]`,children:[(0,L.jsx)(tZ,{className:`sr-only`,children:`Select workspace`}),ce]})}):(0,L.jsx)(af,{open:e,onOpenChange:le,children:(0,L.jsxs)(cf,{side:`bottom`,showCloseButton:!1,initialFocus:ue,className:`flex flex-col gap-0 p-0 max-h-[82vh] rounded-t-2xl`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Select workspace`}),ce]})})}function yQ(e){if(!e||e===`.`)return`~`;let t=e.replace(/\/+$/,``),n=t.split(/[/\\]/);return n[n.length-1]||t}function bQ(e){if(!e||e===`.`)return``;let t=e.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(.*)$/);return t?`~${t[2]||``}`:e}var xQ={today:`today`,yesterday:`yesterday`,week:`this week`,older:`older`};function SQ(e,t){let n=1440*60*1e3,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),i=r-e.getTime();return i<n&&e.getTime()>=r?`today`:i<2*n?`yesterday`:i<7*n?`week`:`older`}function CQ(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function wQ(e){return e.toLocaleDateString(void 0,{month:`short`,day:`numeric`})}function TQ({width:e,onResize:t,onResizeReset:n}){let[r,i]=(0,E.useState)(!1);return(0,L.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize sidebar`,"aria-valuemin":200,"aria-valuemax":tQ(),"aria-valuenow":e,tabIndex:0,onPointerDown:n=>{if(n.button!==0)return;n.preventDefault();let r=n.clientX,a=e;i(!0),Object.assign(document.body.style,{cursor:`col-resize`,userSelect:`none`});let o=e=>{t(nQ(a+(e.clientX-r)))},s=()=>{i(!1),Object.assign(document.body.style,{cursor:``,userSelect:``}),window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},onDoubleClick:n,onKeyDown:r=>{let i=r.shiftKey?32:8;r.key===`ArrowLeft`?(r.preventDefault(),t(nQ(e-i))):r.key===`ArrowRight`?(r.preventDefault(),t(nQ(e+i))):r.key===`Home`&&(r.preventDefault(),n())},className:li(`group/resizer hidden md:block`,`absolute top-0 bottom-0 -right-0.75 w-1.5 z-20 cursor-col-resize`,`focus-visible:outline-none`),children:(0,L.jsx)(`div`,{className:li(`absolute inset-y-0 right-0.75 w-px transition-colors`,r?`bg-accent`:`bg-transparent group-hover/resizer:bg-accent/60 group-focus-visible/resizer:bg-accent/60`)})})}var EQ=(0,E.memo)(function({className:e,sessions:t,activeSession:n,onSelectSession:r,onCreateSession:i,onDeleteSession:a,config:o,remoteConfig:s,cwdHistory:c,onUpdateConfig:l,onRemoveHistory:u,onOpenSettings:d,workspaceMissing:f=!1,width:p,onResize:m,onResizeReset:h}){let[g,_]=(0,E.useState)(!1),[v,y]=(0,E.useState)(0),b=(0,E.useRef)(!1),x=o.cwd===`.`?s?.cwd||`.`:o.cwd,S=yQ(x),C=bQ(x),w=(0,E.useMemo)(()=>{let e=new Date,n=t.filter(e=>!e.isDraft),r={today:[],yesterday:[],week:[],older:[]};for(let t of n){let n=CQ(t.updated_at)||CQ(t.created_at);r[n?SQ(n,e):`older`].push(t)}let i=[];for(let e of[`today`,`yesterday`,`week`,`older`]){let t=r[e];t.length>0&&i.push({bucket:e,sessions:t})}return i},[t]);return(0,L.jsxs)(`div`,{className:li(`relative flex w-64 md:w-(--sidebar-width) flex-col border-r border-border/50 bg-sidebar-bg`,e),style:{"--sidebar-width":`${p}px`},children:[(0,L.jsxs)(`div`,{className:`shrink-0 flex items-center gap-2.5 px-5 pt-5 pb-5`,children:[(0,L.jsx)(tf,{className:`size-4 text-foreground`,"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:`font-display text-[15px] leading-none tracking-tight text-foreground font-medium`,children:`mycode`})]}),(0,L.jsx)(`div`,{className:`shrink-0 px-5 mb-5`,children:(0,L.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,L.jsxs)(`button`,{type:`button`,onPointerDown:()=>{b.current=!1},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(b.current=!0)},onClick:()=>{y(e=>e+1),_(!0)},title:x,"aria-label":`Workspace: ${x}. Click to switch.`,className:li(`group/ws flex flex-col items-start gap-0.5 min-w-0 flex-1 text-left`,`focus-visible:outline-none`),children:[(0,L.jsx)(`span`,{className:`font-mono text-[13px] leading-snug text-foreground/90 group-hover/ws:text-foreground transition-colors truncate max-w-full`,children:S}),C&&(0,L.jsx)(`span`,{className:`font-mono text-[11px] leading-snug text-muted-foreground/60 group-hover/ws:text-muted-foreground/85 transition-colors break-all`,children:C}),f&&(0,L.jsx)(`span`,{className:`font-mono text-[10px] leading-snug text-muted-foreground/55`,children:`missing`})]}),(0,L.jsx)(`button`,{type:`button`,onClick:i,"aria-label":`New chat`,title:`New chat`,className:li(`shrink-0 size-6 mt-0.5 flex items-center justify-center rounded-sm`,`text-muted-foreground hover:text-foreground hover:bg-muted/60 active:scale-95 transition-[color,background-color,scale] duration-150`,`focus-visible:outline-none focus-visible:bg-muted/60`),children:(0,L.jsx)(Yd,{className:`size-3.5`})})]})}),(0,L.jsx)(vQ,{open:g,openedWithKeyboard:b.current,onClose:()=>_(!1),currentCwd:o.cwd,cwdHistory:c,onSelect:e=>l({...o,cwd:e}),onMissingHistory:u},v),(0,L.jsx)(`div`,{className:`flex-1 overflow-y-auto scrollbar-subtle`,children:w.length===0?(0,L.jsx)(`div`,{className:`px-5 py-12 text-[12px] text-muted-foreground/50`,children:`no history yet`}):w.map(({bucket:e,sessions:t},i)=>(0,L.jsxs)(`div`,{className:li(i>0&&`mt-4`),children:[(0,L.jsx)(`div`,{className:`px-5 pb-1 text-[11px] tracking-wide text-muted-foreground/55 lowercase`,children:xQ[e]}),t.map(t=>{let i=n?.id===t.id,o=t.is_running,s=CQ(t.updated_at)||CQ(t.created_at),c=e===`older`&&s;return(0,L.jsxs)(`div`,{className:`group relative`,children:[(0,L.jsx)(`span`,{className:li(`pointer-events-none absolute inset-y-0 left-0 right-2`,i?`bg-accent/10`:`bg-transparent`),"aria-hidden":`true`}),(0,L.jsx)(`span`,{className:li(`absolute left-0 top-1.5 bottom-1.5 z-10 w-0.5 rounded-r`,i?`bg-accent`:`bg-transparent`),"aria-hidden":`true`}),(0,L.jsxs)(`button`,{type:`button`,"aria-current":i?`true`:void 0,className:li(`relative z-10 flex w-full items-center gap-2 pl-5 pr-9 py-1.5 text-[13px] text-left transition-colors`,i?`text-foreground`:`text-muted-foreground hover:text-foreground`),onClick:()=>r(t.id),children:[(0,L.jsx)(`span`,{className:`truncate flex-1`,children:t.title||`New Chat`}),o&&(0,L.jsx)(`span`,{className:`shrink-0 size-1.5 rounded-full bg-accent animate-breathing`,role:`img`,"aria-label":`Running`}),c&&!o&&(0,L.jsx)(`span`,{className:`shrink-0 text-[10px] font-mono text-muted-foreground/45`,children:wQ(s)})]}),(0,L.jsx)(`button`,{type:`button`,"aria-label":`Delete session`,title:`Delete`,onClick:e=>{e.stopPropagation(),a(t.id)},className:li(`absolute right-3 top-1/2 z-20 -translate-y-1/2 size-5 flex items-center justify-center rounded-sm`,`opacity-0 group-hover:opacity-100 max-md:opacity-100`,`text-muted-foreground/60 hover:text-destructive hover:bg-destructive/10 active:scale-95 transition-[color,background-color,scale] duration-150`),children:(0,L.jsx)(nf,{className:`size-3`})})]},t.id)})]},e))}),(0,L.jsx)(`div`,{className:`shrink-0 p-3 flex items-center`,children:(0,L.jsx)(`button`,{type:`button`,onClick:d,"aria-label":`Open settings`,title:`Settings`,className:li(`size-7 flex items-center justify-center rounded-md active:scale-95 transition-[color,background-color,scale] duration-150`,`text-muted-foreground hover:text-foreground hover:bg-muted/50`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`),children:(0,L.jsx)(Zd,{className:`size-3.5`})})}),m&&h&&(0,L.jsx)(TQ,{width:p,onResize:m,onResizeReset:h})]})}),DQ=Object.freeze({});function OQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kQ(e){return Array.isArray(e?.content)?e.content:[]}function AQ(e,t=null){let n={...e};return n.meta&&={...n.meta},t&&(n.renderKey=t),n}function jQ(e,t=[]){return{role:e,content:t}}function MQ(e){return{type:`text`,text:e}}function NQ(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function PQ(e,t){return{type:`text`,text:`<file name="${NQ(t)}">\n${e}\n</file>`,meta:{attachment:!0,path:t}}}function FQ(e){return{type:`thinking`,text:e}}function IQ(e){return{type:`tool_use`,id:e?.id||``,name:e?.name||`tool`,input:OQ(e?.input)?e.input:DQ}}function LQ(e,t,n,r=!1){return{type:`tool_result`,tool_use_id:e,output:t,metadata:n,is_error:r}}function RQ(e,t,n){let r={type:`image`,data:e,mime_type:t};return n&&(r.name=n),r}function zQ(e,t,n){let r={type:`document`,data:e,mime_type:t};return n&&(r.name=n),r}function BQ(e){return e.kind===`image`?RQ(e.data,e.mime_type,e.name):e.kind===`document`?zQ(e.data,e.mime_type,e.name):PQ(e.text,e.name)}function VQ(e){return e.kind===`image`?RQ(``,``,e.name):e.kind===`document`?zQ(``,`application/pdf`,e.name):PQ(``,e.path)}function HQ(e){return jQ(`user`,e?[MQ(e)]:[])}function UQ(e,t,n=[]){let r=[];e&&r.push(MQ(e));for(let e of n)r.push(VQ(e));for(let e of t)r.push(BQ(e));return jQ(`user`,r)}function WQ(e=[]){return jQ(`assistant`,e)}function GQ(e){let t=[...e],n=t.length-1;return n>=0&&t[n]?.role===`assistant`?{messages:t,index:n}:(t.push(WQ([])),{messages:t,index:t.length-1})}function KQ(e,t,n){if(!n)return e;let{messages:r,index:i}=GQ(e),a=r[i]??WQ([]),o=[...kQ(a)],s=o[o.length-1];return s?.type===t?o[o.length-1]={...s,text:`${s.text||``}${n}`}:o.push(t===`thinking`?FQ(n):MQ(n)),r[i]={...a,content:o},r}function qQ(e,t){let{messages:n,index:r}=GQ(e),i=n[r];return i&&(n[r]={...i,content:[...kQ(i),IQ(t)]}),n}function JQ(e){let t=kQ(e);return e?.role===`user`&&t.length>0&&t.every(e=>e?.type===`tool_result`)}function YQ(e,t,n,r,i=!1){let a=LQ(t,n,r,i),o=[...e],s=o.length-1;if(s>=0&&JQ(o[s])){let e=o[s];return e&&(o[s]={...e,content:[...kQ(e),a]}),o}return o.push(jQ(`user`,[a])),o}function XQ(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.role!==`assistant`)continue;let i=kQ(r);for(let a=i.length-1;a>=0;a--){let o=i[a];if(o?.type!==`thinking`)continue;let s=[...e],c=[...i];return c[a]={...o,meta:{...OQ(o.meta)?o.meta:{},duration_ms:t}},s[n]={...r,content:c},s}}return e}function ZQ(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.role!==`assistant`)continue;let i=[...e];return i[n]={...r,meta:{...r.meta??{},...t}},i}return e}function QQ(e,t){let n=typeof e?.output==`string`?e.output:``,r=typeof e?.finalOutput==`string`?e.finalOutput:null,i=typeof t?.output==`string`?t.output:null,a=r??i,o=OQ(e?.metadata)?e.metadata:null,s=OQ(t?.metadata)?t.metadata:null,c=o??s,l=!!(e?.isError||t?.is_error||typeof a==`string`&&a.startsWith(`error:`));return{pending:!!e?.pending,output:n,finalOutput:a,metadata:c,isError:l}}function $Q(e){return{kind:`compact-marker`,sourceIndex:e,renderKey:`compact:${e}`}}var e$=[`total_tokens`,`input_tokens`,`output_tokens`,`cache_read_tokens`,`cache_write_tokens`,`reasoning_tokens`];function t$(e){return OQ(e)&&typeof e.total==`number`?e:void 0}function n$(e,t){if(!t)return e;if(!e)return{...t};let n=e.total+t.total;if(e.input===void 0||e.output===void 0||t.input===void 0||t.output===void 0)return{total:n};let r={input:e.input+t.input,output:e.output+t.output,total:n};return(e.cache_read!==void 0||t.cache_read!==void 0)&&(r.cache_read=(e.cache_read??0)+(t.cache_read??0)),(e.cache_write!==void 0||t.cache_write!==void 0)&&(r.cache_write=(e.cache_write??0)+(t.cache_write??0)),(e.reasoning!==void 0||t.reasoning!==void 0)&&(r.reasoning=(e.reasoning??0)+(t.reasoning??0)),r}function r$(e,t){if(!t)return e;let n=typeof t.context_window==`number`?t.context_window:e?.context_window;if(t.turn_usage!==void 0||t.turn_cost!==void 0){let e={};n!==void 0&&(e.context_window=n),typeof t.context_tokens==`number`&&(e.context_tokens=t.context_tokens);for(let n of e$){let r=t.turn_usage?.[n];r!==void 0&&(e[n]=r)}let r=t$(t.turn_cost);return r&&(e.cost=r),e}let r=OQ(t.usage)?t.usage:null,i=t$(t.cost);if(!r&&!i)return e;let a={...e};if(n!==void 0&&(a.context_window=n),r){let e=r.total_tokens;delete a.context_tokens,typeof e==`number`&&(a.context_tokens=e);for(let e of e$){let t=r[e];typeof t==`number`&&(a[e]=(a[e]??0)+t)}}let o=n$(a.cost,i);return o&&(a.cost=o),a}function i$(e){return{role:`assistant`,content:[],renderKey:`assistant:${e}`,sourceIndex:e}}function a$(e,t={}){if(!Array.isArray(e))return[];let n=[],r={},i=null,a,o=null,s=()=>{if(a&&o!==null){let e=n[o];e&&!Bj(e)&&(n[o]={...e,stats:a})}a=void 0,o=null},c=e=>i||(i=i$(e),n.push(i),i);for(let[l,u]of e.entries()){let e=u?.role,d=kQ(u);if(e===`compact`){let e=a?.context_tokens;a=r$(a,u?.meta),a&&(e===void 0?delete a.context_tokens:a.context_tokens=e),n.push($Q(l)),i=null;continue}if(e===`user`){let e=[],a=[];for(let[t,n]of d.entries())n?.type===`text`&&n.meta?.skill_snapshot||(n?.type===`text`&&n.text||n?.type===`image`||n?.type===`document`?e.push(AQ(n,`user:${l}:${t}`)):n?.type===`tool_result`&&a.push(n));if(e.length>0){s();let t={role:`user`,content:e,renderKey:`user:${l}`,sourceIndex:l};OQ(u?.meta)&&(t.meta={...u.meta}),n.push(t),i=null}if(a.length===0)continue;let o=c(l),f=[...kQ(o)];for(let e of a){let a=e.tool_use_id,s=a?t[a]:void 0,c=a?r[a]:void 0;if(c){let t=n[c.messageIndex];if(t&&!Bj(t)){let r=[...kQ(t)],a=r[c.blockIndex];if(a?.type===`tool_use`){r[c.blockIndex]={...a,runtime:QQ(s,e)};let o={...t,content:r};n[c.messageIndex]=o,c.messageIndex===n.length-1&&(i=o,f=r)}}continue}let u={type:`tool_use`,id:a||``,name:`tool`,input:DQ,runtime:QQ(s,e)},d=f.length;u.renderKey=a||`tool-result:${l}:${d}`,f.push(u),i={...o,content:f},n[n.length-1]=i,a&&(r[a]={messageIndex:n.length-1,blockIndex:d})}continue}if(e!==`assistant`)continue;let f=c(l),p=[...kQ(f)],m=n.length-1;for(let[e,n]of d.entries()){if(n?.type===`thinking`&&n.text){p.push(AQ(n,`assistant:${l}:${e}`));continue}if(n?.type===`text`&&n.text){p.push(AQ(n,`assistant:${l}:${e}`));continue}if(n?.type!==`tool_use`)continue;let i={type:`tool_use`,id:n.id,name:n.name,input:OQ(n.input)?n.input:DQ,runtime:QQ(n.id?t[n.id]:void 0,null)};i.renderKey=n.id||`assistant:${l}:${e}`,OQ(n.meta)&&(i.meta={...n.meta});let a=p.length;p.push(i),n.id&&(r[n.id]={messageIndex:m,blockIndex:a})}let h={...f,content:p},g=u?.meta;g?h.meta={...g}:delete h.meta,a=r$(a,g),a&&(o=m),i=h,n[m]=h}return s(),n.filter((e,t)=>Bj(e)?!0:Array.isArray(e.content)&&e.content.length>0||t===n.length-1&&e.role===`assistant`)}var o$=`mycode_config`,s$=`mycode_cwd_history`,c$=`mycode_active_sessions`,l$=`mycode_sidebar_width`,u$=2,d$={provider:``,model:``,cwd:`.`,reasoningEfforts:{}};function f$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function p$(e,t,n){return typeof e[t]==`string`?e[t]:n}function m$(e){let t=e.reasoningEfforts,n={};if(f$(t))for(let[e,r]of Object.entries(t))bj(r)&&(n[e]=r);return{provider:p$(e,`provider`,d$.provider),model:p$(e,`model`,d$.model),cwd:p$(e,`cwd`,d$.cwd),reasoningEfforts:n}}function h$(){try{let e=localStorage.getItem(o$);if(e){let t=JSON.parse(e);if(!f$(t))return d$;let n=t._v;return n!==1&&n!==u$?d$:m$(t)}}catch(e){console.error(`Failed to load config:`,e)}return d$}function g$(e){try{localStorage.setItem(o$,JSON.stringify({...e,_v:u$}))}catch(e){console.error(`Failed to save config:`,e)}}function _$(){try{let e=localStorage.getItem(s$);if(e){let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}}catch(e){console.error(`Failed to load history:`,e)}return[]}function v$(e){try{localStorage.setItem(s$,JSON.stringify(e.slice(0,6)))}catch(e){console.error(`Failed to save history:`,e)}}function y$(e,t){if(!t)return e;let n=t.trim();return n?[n,...e.filter(e=>e!==n)].slice(0,6):e}function b$(e){return typeof e==`string`&&e.trim()||`.`}function x$(){try{let e=localStorage.getItem(c$);if(!e)return{};let t=JSON.parse(e);return f$(t)?Object.fromEntries(Object.entries(t).filter(e=>typeof e[0]==`string`&&typeof e[1]==`string`)):{}}catch(e){return console.error(`Failed to load active sessions:`,e),{}}}function S$(e){try{let t=Object.entries(e).filter(([e,t])=>typeof e==`string`&&e&&typeof t==`string`&&t);if(t.length===0){localStorage.removeItem(c$);return}localStorage.setItem(c$,JSON.stringify(Object.fromEntries(t)))}catch(e){console.error(`Failed to save active sessions:`,e)}}function C$(e){let t=x$()[b$(e)];return typeof t==`string`?t:``}function w$(e,t){if(typeof t!=`string`||!t)return;let n=x$();n[b$(e)]=t,S$(n)}function T$(e){let t=x$();delete t[b$(e)],S$(t)}function E$(){try{let e=localStorage.getItem(l$);if(e){let t=Number(e);if(Number.isFinite(t))return Math.max(200,Math.min(480,t))}}catch(e){console.error(`Failed to load sidebar width:`,e)}return 256}function D$(e){try{localStorage.setItem(l$,String(e))}catch(e){console.error(`Failed to save sidebar width:`,e)}}function O$(e,t){if(!Array.isArray(e)||e.length===0)return null;if(t){let n=e.find(e=>e.id===t);if(n?.id)return n.id}return e[0]?.id||null}function k$({pendingRequestToken:e,requestToken:t,activeCwd:n,requestCwd:r}){return e===t&&n===r}function A$({pendingRequestToken:e,requestToken:t,activeSessionId:n,sessionId:r,activeCwd:i,requestCwd:a}){return k$({pendingRequestToken:e,requestToken:t,activeCwd:i,requestCwd:a})&&n===r}var j$=`New chat`;function M$(e){return e instanceof Error?e.message:`Unknown error`}function N$(e){return`detail`in e?e.detail:void 0}function P$(e){return Array.isArray(e)?null:typeof e==`object`&&e?.run?e.run:null}function F$(e,t){return typeof e==`string`&&e?e:Array.isArray(e)?e.find(e=>e.msg)?.msg||t:e&&typeof e==`object`&&e.message?e.message:t}function I$(){return{id:ff(),title:j$,isDraft:!0}}function L$(e){return e.kind===`text`?{type:`text`,text:e.text,name:e.name,is_attachment:!0}:{type:e.kind===`image`?`image`:`document`,data:e.data,mime_type:e.mime_type,name:e.name}}function R$(e){return e.kind===`text`?{type:`text`,path:e.path,name:e.path,is_attachment:!0}:{type:e.kind,path:e.path,name:e.name,is_attachment:!0}}function z$(e){let t=new Set;return e.filter(e=>{let n=`${e.kind}:${e.path}`;return t.has(n)?!1:(t.add(n),!0)})}function B$(e,t){switch(t.type){case`set_messages`:{if(t.expectedSessionId!=null&&e.messageSessionId!==t.expectedSessionId)return e;let n={messageSessionId:t.sessionId??e.messageSessionId,rawMessages:t.messages,toolRuntimeById:{},sessionCost:t.sessionCost??null,preTurnRawMessages:null};for(let e of t.replayEvents||[])n=B$(n,{type:`apply_event`,event:e});return n}case`start_turn`:{let{content:n,attachments:r,workspaceFiles:i}=t,a=r?.map(e=>e.kind===`document`?{...e,data:``}:e),o=!!(a?.length||i?.length);return{...e,rawMessages:[...e.rawMessages,o?UQ(n,a??[],i):HQ(n),WQ([])],preTurnRawMessages:e.rawMessages}}case`rewind_and_start_turn`:return{...e,rawMessages:[...e.rawMessages.slice(0,t.rewindTo),HQ(t.content),WQ([])],toolRuntimeById:{},preTurnRawMessages:e.rawMessages};case`rollback`:{let t=e.preTurnRawMessages;return t?{rawMessages:t,messageSessionId:e.messageSessionId,toolRuntimeById:{},sessionCost:e.sessionCost,preTurnRawMessages:null}:e}case`apply_event`:{let{event:n}=t,r=e.rawMessages,i={...e.toolRuntimeById};if(n.type===`reasoning`)r=KQ(r,`thinking`,n.delta||``);else if(n.type===`reasoning_done`){let e=n.duration_ms;typeof e==`number`&&(r=XQ(r,e))}else if(n.type===`text`)r=KQ(r,`text`,n.delta||``);else if(n.type===`tool_start`){let e=n.tool_call||{};r=qQ(r,e),e.id&&(i[e.id]={pending:!0,output:``,finalOutput:null,metadata:null,isError:!1})}else if(n.type===`tool_output`){let e=n.tool_use_id||``;if(e){let t=i[e]||{pending:!0,output:``,finalOutput:null,metadata:null,isError:!1},r=n.output||``;i[e]={...t,pending:!0,output:`${t.output}${r}`}}}else if(n.type===`tool_done`){let e=n.tool_use_id||``,t=n.output||``,a=n.metadata??null,o=!!(n.is_error||typeof t==`string`&&t.startsWith(`error:`));e&&(i[e]={...i[e]||{pending:!1,output:``,finalOutput:null,metadata:null,isError:!1},pending:!1,finalOutput:t,metadata:a,isError:o},r=YQ(r,e,t,a,o))}else if(n.type===`error`)r=KQ(r,`text`,`\n\n**Error:** ${n.message||`Unknown`}`);else if(n.type===`cancelled`)for(let[e,t]of Object.entries(i))t.pending&&(i[e]={...t,pending:!1,isError:!0});else if(n.type===`usage`){let t={context_tokens:n.context_tokens??null,turn_usage:n.turn_usage??{},turn_cost:n.turn_cost??null};return typeof n.context_window==`number`&&(t.context_window=n.context_window),n.model&&(t.model=n.model),r=ZQ(r,t),{...e,rawMessages:r,toolRuntimeById:i,sessionCost:n.session_cost??null}}else n.type===`compact`&&(r=[...r,{role:`compact`,content:[]}]);return{...e,rawMessages:r,toolRuntimeById:i}}default:return e}}function V$(e,t){let[n,r]=(0,E.useReducer)(B$,{messageSessionId:null,rawMessages:[],toolRuntimeById:{},sessionCost:null,preTurnRawMessages:null}),[i,a]=(0,E.useState)([]),[o,s]=(0,E.useState)(I$),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(null),f=c!==null,[p,m]=(0,E.useState)(!1),[h,g]=(0,E.useState)([]),_=(0,E.useRef)(!1),v=(0,E.useRef)(e.cwd),y=(0,E.useRef)(o),b=(0,E.useRef)(0),x=(0,E.useRef)(0),S=(0,E.useRef)(0),C=(0,E.useRef)(null),w=(0,E.useRef)(0),T=(0,E.useRef)(null),D=(0,E.useRef)(null),O=(0,E.useCallback)(e=>{y.current=e,s(e)},[]),k=(0,E.useCallback)(async e=>{if(e)try{await fetch(`/api/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`})}catch(e){console.error(`Failed to cancel:`,e)}},[]),A=(0,E.useCallback)(async()=>{let t=e.cwd;if(t!==v.current)return[];try{let e=await fetch(`/api/sessions?cwd=${encodeURIComponent(t)}`);if(!e.ok)throw Error(`Failed to load sessions`);let n=await e.json();if(t!==v.current)return[];let r=n.sessions||[],i=y.current,o=i.isDraft&&!r.some(e=>e.id===i.id)?[i,...r]:r;a(o);let s=o.find(e=>e.id===i.id);return s&&s!==i&&O(s),o}catch(e){return console.error(`Failed to load sessions:`,e),[]}},[e.cwd,O]),j=(0,E.useCallback)(()=>{w.current+=1,x.current=0,C.current?.abort(),C.current=null,T.current=null,l(null),d(null),g([])},[]),M=(0,E.useCallback)(async(e,t,n=0)=>{let i=e?.id;if(!i)return;w.current+=1;let a=w.current;C.current?.abort();let o=new AbortController;C.current=o,T.current=e;let s=e.kind;l(s);let c=async()=>{if(w.current!==a||y.current.id!==t)return!0;let e=D.current;if(!e)return!1;try{return await e(t),!0}catch(e){return console.error(`Failed to recover disconnected stream:`,e),!1}};try{let e=await fetch(`/api/runs/${encodeURIComponent(i)}/stream?after=${n}`,{signal:o.signal});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);if(!e.body)throw Error(`Response body is empty`);let l=e.body.getReader(),u=new TextDecoder,f=``,p=!1;for(;;){let{done:e,value:n}=await l.read();if(e)break;f+=u.decode(n,{stream:!0});let i=f.split(`
|
|
368
|
+
`);f=i.pop()||``;for(let e of i){if(!e.startsWith(`data: `))continue;let n=e.slice(6);if(n===`[DONE]`){p=!0;continue}try{let e=JSON.parse(n);if(w.current!==a||y.current.id!==t)continue;if(e.type===`permission_request`){let t={request_id:e.request_id,tool_use_id:e.tool_use_id,tool_name:e.tool_name,preview:e.preview};g(e=>e.some(e=>e.request_id===t.request_id)?e:[...e,t]);continue}if(e.type===`permission_resolved`){let t=e.request_id;g(e=>e.filter(e=>e.request_id!==t));continue}if(e.type===`cancelled`&&g([]),s===`compact`){e.type===`compact`?r({type:`apply_event`,event:e}):e.type===`error`&&(console.error(`Compaction failed:`,e.message),d(e.message||`Compaction failed`));continue}r({type:`apply_event`,event:e})}catch(e){console.error(`Parse error:`,e)}}}if(s===`compact`&&p&&await c(),!p&&await c())return}catch(e){if((!(e instanceof Error)||e.name!==`AbortError`)&&!await c()&&w.current===a&&y.current.id===t){let e=`Stream disconnected. Reload the session to resume.`;s===`compact`?d(e):r({type:`apply_event`,event:{type:`error`,message:e}})}}finally{w.current===a&&(C.current=null,T.current=null,y.current.id===t&&l(null),A())}},[A]),N=(0,E.useCallback)(async(t,n)=>{let i=n?.requestCwd??e.cwd,a=n?.requestToken??S.current,o=()=>k$({pendingRequestToken:S.current,requestToken:a,activeCwd:v.current,requestCwd:i});if(!o())return null;let s=await fetch(`/api/sessions/${encodeURIComponent(t)}`);if(!s.ok)throw Error(`Failed to load session`);let c=await s.json();if(!o()||!c.session)return null;O(c.session),w$(i,c.session.id),g([]);let u=c.active_run||null,f=Array.isArray(c.pending_events)?c.pending_events:[],p=u?.kind===`compact`,m=new Map,h=[];for(let e of f){if(e?.type===`permission_request`){m.set(e.request_id,{request_id:e.request_id,tool_use_id:e.tool_use_id,tool_name:e.tool_name,preview:e.preview});continue}if(e?.type===`permission_resolved`){m.delete(e.request_id);continue}if(e?.type===`cancelled`&&m.clear(),p){e?.type===`compact`?h.push(e):e?.type===`error`&&d(e.message||`Compaction failed`);continue}h.push(e)}if((0,E.startTransition)(()=>{r({type:`set_messages`,messages:c.messages||[],sessionId:c.session?.id??t,sessionCost:c.session_cost??null,replayEvents:h,expectedSessionId:c.session?.id??t})}),m.size&&g(Array.from(m.values())),T.current=u,u?.id){let e=f.at(-1)?.seq??0;M(u,c.session.id,e)}else l(null);return c},[e.cwd,O,M]);(0,E.useEffect)(()=>{D.current=N},[N]);let P=(0,E.useCallback)(async(n,i)=>{let a=n.text.trim(),s=z$(n.workspaceFiles);if(!a&&!i?.length&&!s.length||f)return!1;let c=o.id,u=e.cwd,p=b.current+1;b.current=p,x.current=p,r({type:`start_turn`,content:a,...i?.length?{attachments:i}:{},...s.length?{workspaceFiles:s}:{}}),l(`chat`),d(null);let m={session_id:c,provider:e.provider||void 0,model:e.model||void 0,cwd:e.cwd,reasoning_effort:wj(e,t)},h=i?.length||s.length?{...m,input:[...a?[{type:`text`,text:a}]:[],...s.map(R$),...(i??[]).map(L$)]}:{...m,message:a};try{let e=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(h)}),t=await e.json(),n=A$({pendingRequestToken:x.current,requestToken:p,activeSessionId:y.current.id,sessionId:c,activeCwd:v.current,requestCwd:u});if(!e.ok){let i=N$(t),a=P$(i);if(e.status===409&&a?.id)return n&&(x.current=0,r({type:`rollback`}),M(a,c,a.last_seq||0)),!1;throw Error(F$(i,`Failed to start task`))}if(x.current=0,!n)return!1;let i=t;if(i.session){let e=i.session;O(e),w$(u,e.id)}return A(),M(i.run,c,0),!0}catch(e){return x.current===p&&y.current.id===c&&(x.current=0,l(null),r({type:`rollback`}),r({type:`apply_event`,event:{type:`error`,message:M$(e)}})),!1}},[o.id,e,A,f,t,O,M]),F=(0,E.useCallback)(async(n,i)=>{let a=i.trim();if(!a||f)return;let s=o.id,c=e.cwd,u=b.current+1;b.current=u,x.current=u,r({type:`rewind_and_start_turn`,rewindTo:n,content:a}),l(`chat`),d(null);try{let i=await fetch(`/api/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({session_id:s,message:a,rewind_to:n,provider:e.provider||void 0,model:e.model||void 0,cwd:e.cwd,reasoning_effort:wj(e,t)})}),o=await i.json(),d=A$({pendingRequestToken:x.current,requestToken:u,activeSessionId:y.current.id,sessionId:s,activeCwd:v.current,requestCwd:c});if(!i.ok){if(d){x.current=0,r({type:`rollback`});let e=N$(o),t=P$(e);if(i.status===409&&t?.id){M(t,s,t.last_seq||0);return}l(null),r({type:`apply_event`,event:{type:`error`,message:F$(e,`Failed to start task`)}})}return}if(x.current=0,!d)return;let f=o;if(f.session){let e=f.session;O(e),w$(c,e.id)}A(),M(f.run,s,0)}catch(e){x.current===u&&y.current.id===s&&(x.current=0,r({type:`rollback`}),l(null),r({type:`apply_event`,event:{type:`error`,message:M$(e)}}))}},[o.id,e,A,f,t,O,M]),I=(0,E.useCallback)(async()=>{let t=y.current;if(f)return!1;if(t.isDraft)return d(`nothing to compact`),!1;let n=t.id;d(null),l(`compact`);try{let t=await fetch(`/api/sessions/${encodeURIComponent(n)}/compact`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider||void 0,model:e.model||void 0})}),r=await t.json();if(y.current.id!==n)return!1;if(!t.ok){let e=N$(r),i=P$(e);if(t.status===409&&i?.id)return M(i,n,i.last_seq||0),!1;throw Error(F$(e,`Compaction failed`))}return A(),M(r.run,n,0),!0}catch(e){return y.current.id===n&&(console.error(`Failed to start compaction:`,e),l(null),d(M$(e))),!1}},[e.model,e.provider,A,f,M]),ee=(0,E.useCallback)(()=>{let e=T.current?.id,t=y.current.id;if(w.current+=1,x.current=0,C.current?.abort(),C.current=null,T.current=null,g([]),!e){l(null);return}(async()=>{if(await k(e),y.current.id===t)try{await D.current?.(t),A()}catch(e){console.error(`Failed to reload session after cancel:`,e),y.current.id===t&&l(null)}})()},[k,A]),te=(0,E.useCallback)(async e=>{let t=h[0],n=T.current?.id;if(!(!t||!n))try{let r=await fetch(`/api/runs/${encodeURIComponent(n)}/decide`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({request_id:t.request_id,decision:e})});r.ok||console.error(`Decide POST failed: ${r.status}`)}catch(e){console.error(`Failed to send decision:`,e)}},[h]),ne=(0,E.useCallback)(()=>{if(p)return;j(),_.current=!0,S.current+=1;let e=I$();O(e),r({type:`set_messages`,messages:[],sessionId:e.id}),A()},[A,p,O,j]),re=(0,E.useCallback)(async t=>{if(!t||t===o.id)return;j(),_.current=!0;let n=S.current+1;S.current=n,m(!0);let a=i.find(e=>e.id===t);a&&O(a),r({type:`set_messages`,messages:[],sessionId:t}),g([]);let s=()=>k$({pendingRequestToken:S.current,requestToken:n,activeCwd:v.current,requestCwd:e.cwd});try{await N(t,{requestCwd:e.cwd,requestToken:n}),A()}catch(e){console.error(`Failed to load session:`,e)}finally{s()&&m(!1)}},[o.id,e.cwd,A,N,O,i,j]),ie=(0,E.useCallback)(async t=>{if(!t)return;let n=t===o.id,s=i.findIndex(e=>e.id===t),c=i.filter(e=>e.id!==t),u=s>=0&&(c[s]||c[s-1])||null;m(!0);try{if(!(await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:`DELETE`})).ok)throw Error(`Failed to delete session`);if(!n){a(c);return}j(),_.current=!0,S.current+=1;let i=S.current;if(T$(e.cwd),u&&!u.isDraft){a(c),O(u),r({type:`set_messages`,messages:[],sessionId:u.id}),await N(u.id,{requestCwd:e.cwd,requestToken:i});return}let o=I$();O(o),a([o]),r({type:`set_messages`,messages:[],sessionId:o.id}),l(null)}catch(e){console.error(`Failed to delete session:`,e)}finally{m(!1)}},[o.id,e.cwd,N,i,O,j]),ae=(0,E.useCallback)(async()=>{if(f||p)return;let e=y.current;if(!e.isDraft){try{let t=await fetch(`/api/sessions/${encodeURIComponent(e.id)}/clear`,{method:`POST`});if(!t.ok)throw Error(`Clear failed with status ${t.status}`)}catch(e){console.error(`Failed to clear session:`,e);return}y.current.id===e.id&&r({type:`set_messages`,messages:[],sessionId:e.id}),A()}},[f,p,A]);(0,E.useEffect)(()=>{if(v.current!==e.cwd){j(),v.current=e.cwd,_.current=!1,a([]);let t=I$();O(t),r({type:`set_messages`,messages:[],sessionId:t.id})}if(_.current)return;_.current=!0;let t=e.cwd,n=S.current+1;S.current=n,m(!0);let i=()=>k$({pendingRequestToken:S.current,requestToken:n,activeCwd:v.current,requestCwd:t});(async()=>{try{if(!i())return;let e=C$(t),o=await fetch(`/api/sessions?cwd=${encodeURIComponent(t)}`);if(!o.ok)throw Error(`Failed to load sessions`);let s=await o.json();if(!i())return;let c=s.sessions||[];a(c);let u=O$(c,e);if(u){let e=c.find(e=>e.id===u);e&&O(e),r({type:`set_messages`,messages:[],sessionId:u}),await D.current?.(u,{requestCwd:t,requestToken:n})}else{let e=I$();O(e),a([e]),r({type:`set_messages`,messages:[],sessionId:e.id}),l(null)}}catch(e){console.error(`Failed to initialize sessions:`,e)}finally{i()&&m(!1)}})()},[e.cwd,O,j]),(0,E.useEffect)(()=>()=>{j()},[j]);let oe=(0,E.useMemo)(()=>a$(n.rawMessages,n.toolRuntimeById),[n.rawMessages,n.toolRuntimeById]),se=(0,E.useMemo)(()=>{for(let e=oe.length-1;e>=0;e--){let t=oe[e];if(!t||Bj(t))break;let n=t.role===`assistant`?t.stats:void 0;if(n){if(n.context_tokens!==void 0&&n.context_window!==void 0)return{tokens:n.context_tokens,window:n.context_window};break}}return null},[oe]);return{messages:oe,messageSessionId:n.messageSessionId,sessionCost:n.sessionCost,currentContext:se,loading:f,runKind:c,compactError:u,sessions:i,activeSession:o,sessionLoading:p,pendingPermission:h[0]??null,send:P,rewindAndSend:F,compactSession:I,cancel:ee,decidePermission:te,createSession:ne,selectSession:re,deleteSession:ie,clearSession:ae}}async function H$(e){let t=await fetch(e);if(!t.ok){let e=`Request failed with status ${t.status}`;try{let n=await t.json();typeof n?.detail==`string`&&n.detail&&(e=n.detail)}catch{}throw Error(e)}return t.json()}function U$(e,t,n){let r=t||e?.default?.provider||``,i=e?.providers?.[r],a=n||e?.default?.model||``;return{image:!!(i?.supports_image_input&&i.image_input_models?.includes(a)),pdf:!!(i?.supports_pdf_input&&i.pdf_input_models?.includes(a))}}function W$(e,t){return JSON.stringify({open:e,path:t?.path??``,config:t?.config??null,options:t?.options??null})}function G$(e){return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)}function K$(){let[e,t]=(0,E.useState)(h$),[n,r]=(0,E.useState)([]),[i,a]=(0,E.useState)(_$),[o,s]=(0,E.useState)(!1),[c,l]=(0,E.useState)(E$),[u,d]=(0,E.useState)(!1),f=(0,E.useSyncExternalStore)(G$,tQ,()=>480),p=(0,E.useCallback)(()=>{d(!0)},[]),m=(0,E.useCallback)(e=>{l(t=>t===e?t:(D$(e),e))},[]),h=(0,E.useCallback)(()=>{m(256)},[m]),g=uf(`(min-width: 768px)`),_=Math.max(200,Math.min(f,c)),{data:v=null,error:y,mutate:b}=nt(`/api/config?cwd=${encodeURIComponent(e.cwd)}`,H$,{keepPreviousData:!0}),{data:x=null,error:S,mutate:C}=nt(`/api/settings`,H$),w=(0,E.useMemo)(()=>v?Tj(e,v):e,[e,v]),{messages:T,messageSessionId:D,sessionCost:O,currentContext:k,loading:A,runKind:j,compactError:M,sessions:N,activeSession:P,pendingPermission:F,send:I,rewindAndSend:ee,compactSession:te,cancel:ne,decidePermission:re,createSession:ie,selectSession:ae,deleteSession:oe,clearSession:se}=V$(w,v),ce=(0,E.useCallback)(e=>{if(e.cwd!==w.cwd){let t=y$(i,e.cwd);a(t),v$(t)}t(e),g$(e)},[w.cwd,i]),le=(0,E.useCallback)(e=>{a(t=>{if(!t.includes(e))return t;let n=t.filter(t=>t!==e);return v$(n),n})},[]),ue=(0,E.useCallback)(()=>{r(e=>{for(let t of e)t.kind===`image`&&URL.revokeObjectURL(t.preview);return[]})},[]),de=(0,E.useCallback)(async e=>await I(e,n.length?n:void 0)?(ue(),!0):!1,[n,ue,I]),fe=(0,E.useCallback)(e=>{r(t=>[...t,...e])},[]),pe=(0,E.useCallback)(e=>{r(t=>{let n=t.find(t=>t.id===e);return n?(n.kind===`image`&&URL.revokeObjectURL(n.preview),t.filter(t=>t.id!==e)):t})},[]),{image:me,pdf:he}=(0,E.useMemo)(()=>U$(v,w.provider,w.model),[w.model,w.provider,v]),ge=v?.cwd_exists===!1,_e=ge?`Workspace no longer exists. Choose another workspace.`:void 0,ve=!!v?.setup_error||!v&&!!y,ye=ve?v?(0,L.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,L.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add a provider to get started.`}),(0,L.jsx)(di,{variant:`outline`,size:`sm`,onClick:p,children:`Open settings`})]}):(0,L.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Couldn't reach the API.`}):void 0,be=(0,E.useCallback)(e=>{ae(e),s(!1),ue()},[ae,ue]),xe=(0,E.useCallback)(()=>{ie(),s(!1),ue()},[ie,ue]),Se=(0,E.useCallback)(async e=>{let t=P?.id===e;await oe(e),t&&(s(!1),ue())},[P?.id,ue,oe]),Ce=(0,E.useCallback)(e=>{if(e===`/new`){xe();return}if(e===`/compact`){te();return}se()},[xe,se,te]);return(0,L.jsxs)(YX,{children:[(0,L.jsxs)(`div`,{className:`relative flex h-full min-h-0 overflow-hidden`,children:[g?(0,L.jsx)(`div`,{className:`shrink-0`,children:(0,L.jsx)(EQ,{sessions:N,activeSession:P,onSelectSession:be,onCreateSession:xe,onDeleteSession:Se,config:w,remoteConfig:v,cwdHistory:i,onUpdateConfig:ce,onRemoveHistory:le,onOpenSettings:p,workspaceMissing:ge,width:_,onResize:m,onResizeReset:h,className:`h-full`})}):(0,L.jsx)(af,{open:o,onOpenChange:s,children:(0,L.jsxs)(cf,{side:`left`,showCloseButton:!1,className:`p-0 gap-0 w-65 bg-sidebar-bg`,children:[(0,L.jsx)(lf,{className:`sr-only`,children:`Navigation`}),(0,L.jsx)(EQ,{sessions:N,activeSession:P,onSelectSession:be,onCreateSession:xe,onDeleteSession:Se,config:w,remoteConfig:v,cwdHistory:i,onUpdateConfig:ce,onRemoveHistory:le,onOpenSettings:p,workspaceMissing:ge,width:260,className:`h-full`})]})}),(0,L.jsxs)(`main`,{className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background`,children:[(0,L.jsx)(XX,{title:P?.title,onMenuToggle:()=>s(e=>!e),onCreateSession:xe}),(0,L.jsx)(VX,{sessionId:D??P?.id,messages:ve?[]:T,loading:!ve&&j===`chat`,compacting:!ve&&j===`compact`,compactError:ve?null:M,onRewindAndSend:ge||ve?void 0:ee,emptyStateFooter:ye}),(0,L.jsxs)(`div`,{className:`shrink-0 pb-4 max-md:pb-1`,children:[F&&(0,L.jsx)(JX,{request:F,onDecide:re}),(0,L.jsx)(zj,{loading:A,onSubmit:de,onCancel:ne,supportsImages:me,supportsDocuments:he,files:n,onAttachFiles:fe,onRemoveFile:pe,config:w,remoteConfig:v,onUpdateConfig:ce,onSlashCommand:Ce,disabled:ve,disabledReason:_e,sessionCost:O,currentContext:k},w.cwd)]})]})]}),(0,L.jsx)($Z,{open:u,onClose:()=>d(!1),settings:x,loadError:S?.message,remoteConfig:v,onSettingsSaved:e=>{C(e,{revalidate:!1}),b()},projectConfigPaths:v?.config_paths},W$(u,x))]})}function q$(){return(0,L.jsx)(o,{children:(0,L.jsx)(K$,{})})}var J$=document.getElementById(`root`);if(!J$)throw Error(`Root element not found`);D.createRoot(J$).render((0,L.jsx)(E.StrictMode,{children:(0,L.jsx)(q$,{})}));
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
</script>
|
|
20
20
|
<link rel="icon" type="image/svg+xml" href="/favicon_slashes.svg" />
|
|
21
21
|
<title>mycode</title>
|
|
22
|
-
<script type="module" crossorigin src="/assets/index-
|
|
22
|
+
<script type="module" crossorigin src="/assets/index-CT9f_Z06.js"></script>
|
|
23
23
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-QTnfLwEv.js">
|
|
24
24
|
<link rel="modulepreload" crossorigin href="/assets/ThemeProvider-zTKbpxjH.js">
|
|
25
25
|
<link rel="modulepreload" crossorigin href="/assets/preload-helper-FMEmyu_K.js">
|
mycode_cli/tui/chat.py
CHANGED
|
@@ -350,7 +350,6 @@ def clone_agent(agent: Agent, *, store: SessionStore, session_id: str, cwd: str)
|
|
|
350
350
|
compact_threshold=agent.compact_threshold,
|
|
351
351
|
reasoning_effort=agent.reasoning_effort,
|
|
352
352
|
supports_reasoning_effort=agent.supports_reasoning_effort,
|
|
353
|
-
supports_reasoning=agent.supports_reasoning,
|
|
354
353
|
supports_image_input=agent.supports_image_input,
|
|
355
354
|
supports_pdf_input=agent.supports_pdf_input,
|
|
356
355
|
system=agent.system,
|
mycode_cli/tui/render.py
CHANGED
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import time
|
|
6
6
|
from collections import deque
|
|
7
|
+
from contextlib import aclosing
|
|
7
8
|
from datetime import datetime
|
|
8
9
|
from typing import Any, ClassVar, override
|
|
9
10
|
|
|
@@ -389,38 +390,42 @@ class ReplyRenderer:
|
|
|
389
390
|
|
|
390
391
|
self._ensure_live()
|
|
391
392
|
|
|
392
|
-
async
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
393
|
+
async with aclosing(agent.achat(message, on_persist=on_persist)) as stream:
|
|
394
|
+
async for event in stream:
|
|
395
|
+
match event.type:
|
|
396
|
+
case "reasoning":
|
|
397
|
+
self.reasoning(event.data.get("delta", ""))
|
|
398
|
+
case "reasoning_done":
|
|
399
|
+
duration_ms = event.data.get("duration_ms")
|
|
400
|
+
if isinstance(duration_ms, int):
|
|
401
|
+
self._thinking_duration_ms = duration_ms
|
|
402
|
+
case "text":
|
|
403
|
+
self.text(event.data.get("delta", ""))
|
|
404
|
+
case "tool_start":
|
|
405
|
+
tool_call = event.data.get("tool_call") or {}
|
|
406
|
+
self.tool_start(tool_call.get("name", ""), tool_call.get("input") or {})
|
|
407
|
+
case "tool_output":
|
|
408
|
+
self.tool_output(event.data.get("output", ""))
|
|
409
|
+
case "tool_done":
|
|
410
|
+
output = str(event.data.get("output") or "")
|
|
411
|
+
is_error = bool(event.data.get("is_error"))
|
|
412
|
+
raw_meta = event.data.get("metadata")
|
|
413
|
+
metadata = raw_meta if isinstance(raw_meta, dict) else None
|
|
414
|
+
self.tool_done(output, is_error=is_error, metadata=metadata)
|
|
415
|
+
if is_error:
|
|
416
|
+
exit_code = 1
|
|
417
|
+
case "usage":
|
|
418
|
+
self._stats = dict(event.data)
|
|
419
|
+
case "compact":
|
|
420
|
+
self.compact()
|
|
421
|
+
case "cancelled":
|
|
422
|
+
self.cancel()
|
|
423
|
+
return 0
|
|
424
|
+
case "error":
|
|
414
425
|
exit_code = 1
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
self.compact()
|
|
419
|
-
case "error":
|
|
420
|
-
exit_code = 1
|
|
421
|
-
self.error(event.data.get("message", ""))
|
|
422
|
-
case _:
|
|
423
|
-
pass
|
|
426
|
+
self.error(event.data.get("message", ""))
|
|
427
|
+
case _:
|
|
428
|
+
pass
|
|
424
429
|
|
|
425
430
|
self.finish()
|
|
426
431
|
return exit_code
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mycode-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.16.0
|
|
4
4
|
Summary: Minimal coding agent CLI and web UI built on mycode-sdk.
|
|
5
5
|
Project-URL: Homepage, https://github.com/legibet/mycode
|
|
6
6
|
Project-URL: Repository, https://github.com/legibet/mycode
|
|
@@ -25,7 +25,7 @@ Requires-Dist: beautifulsoup4>=4.15.0
|
|
|
25
25
|
Requires-Dist: fastapi>=0.139.0
|
|
26
26
|
Requires-Dist: httpx2>=2.10.0
|
|
27
27
|
Requires-Dist: markdownify>=1.2.3
|
|
28
|
-
Requires-Dist: mycode-sdk==0.
|
|
28
|
+
Requires-Dist: mycode-sdk==0.16.0
|
|
29
29
|
Requires-Dist: prompt-toolkit>=3.0.52
|
|
30
30
|
Requires-Dist: pydantic>=2.13.4
|
|
31
31
|
Requires-Dist: pyyaml>=6.0.3
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
mycode_cli/__init__.py,sha256=K9OoBd9T-1JdpfLnjTgRoVyv8gSnA4telBRzYSl23OE,231
|
|
2
|
-
mycode_cli/config.py,sha256=
|
|
3
|
-
mycode_cli/main.py,sha256=
|
|
2
|
+
mycode_cli/config.py,sha256=XwkbECjpqIl6YSYlSwQhRSR6KaHKxbYgJzIg-RuCzXI,31195
|
|
3
|
+
mycode_cli/main.py,sha256=IKQ5EXudhqEfOr5JVMugc4XQKzHkyvQdRgYehm8BLBs,12053
|
|
4
4
|
mycode_cli/permissions.py,sha256=GESSo6YxMLudE_WI_XtAHHih4sgREsIlNnXirkoR1G4,7765
|
|
5
|
-
mycode_cli/runtime.py,sha256=
|
|
5
|
+
mycode_cli/runtime.py,sha256=CfSNoNDeHUnENvxWk1DAhcTcMNMgiRBYEP5WFZZIUrw,2765
|
|
6
6
|
mycode_cli/sessions.py,sha256=g97vpaTIZw5xhh1hKV0pz91496H5hBS3rMKhZ0_v5gw,8434
|
|
7
7
|
mycode_cli/system_prompt.py,sha256=S9ehciURi4kZgeKBOfXpUeuI1NRMKomekHdWMQDhIL8,12793
|
|
8
8
|
mycode_cli/tools.py,sha256=jwvQiu8U95qMj6KPI5qMJyBr73M6lX7qMOJhZWuL_hc,26476
|
|
@@ -11,7 +11,7 @@ mycode_cli/workspace.py,sha256=n139AXmrJyfuErpfDViSzGeZE_VQz2Q3ixibmqO2NqI,961
|
|
|
11
11
|
mycode_cli/server/__init__.py,sha256=Bt8J0HJdkPdE2VQl7zjnEjofriUHksen5tHQ8agw7RM,32
|
|
12
12
|
mycode_cli/server/app.py,sha256=v1jdOv8qJ8FyQwd8dd8UMSvbUOIJ5i4ejjgT9M0ZC_Q,2687
|
|
13
13
|
mycode_cli/server/deps.py,sha256=MKwd89W0Vv954xThrbcOPyqEySCO5YJtP_WS91nUqpk,1050
|
|
14
|
-
mycode_cli/server/run_manager.py,sha256=
|
|
14
|
+
mycode_cli/server/run_manager.py,sha256=iWt_-bLt2dgbUu9Nmb8CUhbHAHuxLvq5Kw_XsVzpvJo,17137
|
|
15
15
|
mycode_cli/server/schemas.py,sha256=ZXN2L1pBqDiGDDZmHgsLoPNUFWS_SNEOz_imkX-eUFU,4999
|
|
16
16
|
mycode_cli/server/routers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
17
|
mycode_cli/server/routers/chat.py,sha256=6qj96sWjAgcNHqFa90JYsDy_Qrcw_xPCW6wiAhS0oaU,18406
|
|
@@ -19,7 +19,7 @@ mycode_cli/server/routers/sessions.py,sha256=hod6havxtTE81kv88cOi7PKlPHIkG1GnApQ
|
|
|
19
19
|
mycode_cli/server/routers/settings.py,sha256=9fqltbqpezH5LgZKw_7tjU2nRnwfHuU3gLFi4Poe2fU,7017
|
|
20
20
|
mycode_cli/server/routers/workspaces.py,sha256=lPm48yLWszazi0sOODj5alqcwrollKxOFf3NCA89hwc,5468
|
|
21
21
|
mycode_cli/server/static/favicon_slashes.svg,sha256=bxMiM7G7NR1zLWyUWnFBCa1FSu0AzFiDW2YY6DtcOWQ,504
|
|
22
|
-
mycode_cli/server/static/index.html,sha256=
|
|
22
|
+
mycode_cli/server/static/index.html,sha256=LkSM2-xqa0dufrDPoQ7S4C4spp8sWgXJ9U0kDkPqE-s,1265
|
|
23
23
|
mycode_cli/server/static/assets/EditDiff-DOjxGJl-.js,sha256=6y0JCwtOGrYKdmM0j0OT2VaE57J38IbLSiUIjc01XLU,251313
|
|
24
24
|
mycode_cli/server/static/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2,sha256=DN04fJWQoan5eUVgAi27WWVKfYbxh6oMgUla1C06cwg,28076
|
|
25
25
|
mycode_cli/server/static/assets/KaTeX_AMS-Regular-DMm9YOAa.woff,sha256=MNqR6EyJP4deJSaJ-uvcWQsocRReitx_mp1NvYzgslE,33516
|
|
@@ -207,7 +207,7 @@ mycode_cli/server/static/assets/hurl-CWPsiEpf.js,sha256=xxII-ILG8BJ5XoxR3pHm76FZ
|
|
|
207
207
|
mycode_cli/server/static/assets/hxml-B0Qn7Nwc.js,sha256=y-9WYsgm3XxPY3fredLKacW_IWt75ccNBeqSogYciZg,1740
|
|
208
208
|
mycode_cli/server/static/assets/hy-CZbG8q4J.js,sha256=8uFqToldKwdl_D56AakMEylI1RjrJff9glTR4qnKPoQ,2641
|
|
209
209
|
mycode_cli/server/static/assets/imba-DsUTQ-LC.js,sha256=wv-qk2du1uD2yS9TIEgAjmIHEYbQCS68-YOSLBGXPE0,49923
|
|
210
|
-
mycode_cli/server/static/assets/index-
|
|
210
|
+
mycode_cli/server/static/assets/index-CT9f_Z06.js,sha256=oedZ56PRleAsd1O97vfBmQs_Zm9-GjOy4LQYIQFq4aA,1185684
|
|
211
211
|
mycode_cli/server/static/assets/index-g5_LkRCI.css,sha256=FQzZy0XHTcSC70zRzz8ByDTXn3WKFdKgdrFWmPeif-M,116610
|
|
212
212
|
mycode_cli/server/static/assets/ini-B5eOa1yu.js,sha256=4ZLTowwXiG4TZpJmBjFLN1aHaP9sd5DXG1jIzSrmj00,1518
|
|
213
213
|
mycode_cli/server/static/assets/java-CGc3VwQr.js,sha256=-mBHySdIcHF5kFpymkcs0tJ4hKKZhuI4zZfCYd2vzHE,27285
|
|
@@ -398,12 +398,12 @@ mycode_cli/server/static/fonts/OFL.txt,sha256=5ntCh7US9uFmOUyAp0oMbVNwk26XBuNd-d
|
|
|
398
398
|
mycode_cli/server/static/fonts/SourceCodePro-Variable.woff2,sha256=i3dKqlE3o470D0rJ0225pe7hUrL2ZYnf3IL_AH_IcTU,22044
|
|
399
399
|
mycode_cli/server/static/fonts/SourceSans3-Variable.woff2,sha256=ehmnAn4SUlfTEMbb14rjowteoeN5TWCxK7KCJ6ADv9o,28740
|
|
400
400
|
mycode_cli/tui/__init__.py,sha256=5sPlJS3c8HdNEBwcF0bUuj8f8brAD-_6MNmF4Q_1Edg,69
|
|
401
|
-
mycode_cli/tui/chat.py,sha256
|
|
402
|
-
mycode_cli/tui/render.py,sha256=
|
|
401
|
+
mycode_cli/tui/chat.py,sha256=-zvVwVWbNaVvJHukOAbYQMU7052prjlVX-WCL13SNr0,35229
|
|
402
|
+
mycode_cli/tui/render.py,sha256=HBiUINT7h7xsTycdW54rNKxdthpFtym3sKL8IfYNMBs,26542
|
|
403
403
|
mycode_cli/tui/state.py,sha256=vtG1NJQl6e7hI6ovlbyIsgckQiKbApnYPbRT0N0ybS0,1175
|
|
404
404
|
mycode_cli/tui/theme.py,sha256=HS3C1kSoIONrSaiSx22AWRLk1n6-T-Tn5iohCMewAg4,3455
|
|
405
|
-
mycode_cli-0.
|
|
406
|
-
mycode_cli-0.
|
|
407
|
-
mycode_cli-0.
|
|
408
|
-
mycode_cli-0.
|
|
409
|
-
mycode_cli-0.
|
|
405
|
+
mycode_cli-0.16.0.dist-info/METADATA,sha256=C0tllW3k6WeR4rIGen3uIrF5DnYyID-RwkniCciNo5o,4907
|
|
406
|
+
mycode_cli-0.16.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
407
|
+
mycode_cli-0.16.0.dist-info/entry_points.txt,sha256=1R7YN8dxJUy5AMC4q2J5Ly9xuEom3ZbTaa8xXwxuZyk,48
|
|
408
|
+
mycode_cli-0.16.0.dist-info/licenses/LICENSE,sha256=DSE6T-B9WhrWypr6H7y2kTZzoF1tef5xf7veUyImQsM,1064
|
|
409
|
+
mycode_cli-0.16.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|