cli-jaw 2.17.61 → 2.17.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.ja.md +376 -339
  2. package/README.ko.md +338 -393
  3. package/README.md +163 -508
  4. package/README.zh-CN.md +365 -376
  5. package/dist/server.js +3 -0
  6. package/dist/server.js.map +1 -1
  7. package/dist/src/agent/pi-runtime.js +37 -18
  8. package/dist/src/agent/pi-runtime.js.map +1 -1
  9. package/dist/src/agent/runtime/acp/permissions.js +2 -3
  10. package/dist/src/agent/runtime/acp/permissions.js.map +1 -1
  11. package/dist/src/agent/runtime/pi-turn.js +7 -0
  12. package/dist/src/agent/runtime/pi-turn.js.map +1 -1
  13. package/dist/src/agent/spawn/line-buffer.js +84 -13
  14. package/dist/src/agent/spawn/line-buffer.js.map +1 -1
  15. package/dist/src/agent/spawn.js +26 -15
  16. package/dist/src/agent/spawn.js.map +1 -1
  17. package/dist/src/code-mode/host.js +34 -5
  18. package/dist/src/code-mode/host.js.map +1 -1
  19. package/dist/src/code-mode/manager.js +24 -7
  20. package/dist/src/code-mode/manager.js.map +1 -1
  21. package/dist/src/code-mode/providers/provider-live-models.js +3 -1
  22. package/dist/src/code-mode/providers/provider-live-models.js.map +1 -1
  23. package/dist/src/code-mode/store.js +31 -6
  24. package/dist/src/code-mode/store.js.map +1 -1
  25. package/dist/src/core/config.js +119 -17
  26. package/dist/src/core/config.js.map +1 -1
  27. package/dist/src/core/runtime-settings.js +7 -1
  28. package/dist/src/core/runtime-settings.js.map +1 -1
  29. package/dist/src/core/settings-merge.js +9 -0
  30. package/dist/src/core/settings-merge.js.map +1 -1
  31. package/dist/src/core/settings-watch.js +19 -1
  32. package/dist/src/core/settings-watch.js.map +1 -1
  33. package/dist/src/discord/bot.js +6 -4
  34. package/dist/src/discord/bot.js.map +1 -1
  35. package/dist/src/discord/send-only-client.js +37 -3
  36. package/dist/src/discord/send-only-client.js.map +1 -1
  37. package/dist/src/manager/memory/embedding/sync.js +6 -0
  38. package/dist/src/manager/memory/embedding/sync.js.map +1 -1
  39. package/dist/src/manager/routes/dashboard-memory.js +20 -7
  40. package/dist/src/manager/routes/dashboard-memory.js.map +1 -1
  41. package/dist/src/manager/server.js +8 -0
  42. package/dist/src/manager/server.js.map +1 -1
  43. package/dist/src/manager/shutdown.js +29 -3
  44. package/dist/src/manager/shutdown.js.map +1 -1
  45. package/dist/src/manager/worker-events.js +70 -8
  46. package/dist/src/manager/worker-events.js.map +1 -1
  47. package/dist/src/routes/code-native.js +23 -3
  48. package/dist/src/routes/code-native.js.map +1 -1
  49. package/dist/src/routes/events.js +4 -0
  50. package/dist/src/routes/events.js.map +1 -1
  51. package/dist/src/routes/settings.js +45 -1
  52. package/dist/src/routes/settings.js.map +1 -1
  53. package/dist/src/routes/sse-connections.js +31 -0
  54. package/dist/src/routes/sse-connections.js.map +1 -0
  55. package/dist/src/shared/permissions.js +47 -0
  56. package/dist/src/shared/permissions.js.map +1 -0
  57. package/package.json +1 -1
  58. package/public/dist/.vite/manifest.json +31 -31
  59. package/public/dist/assets/AdvancedExport-B7h_ZvBu.js +1 -0
  60. package/public/dist/assets/Agent-DnbZJP7b.js +1 -0
  61. package/public/dist/assets/{ChannelEnablementControl-B2tq8Ji4.js → ChannelEnablementControl-Dl0uYx38.js} +5 -5
  62. package/public/dist/assets/ChannelSetupEntry-DxtOrN01.js +1 -0
  63. package/public/dist/assets/ChannelsDiscord-BEGGwd_3.js +1 -0
  64. package/public/dist/assets/{ChannelsSlack-B9FV0ftr.js → ChannelsSlack-BryC2Ahr.js} +1 -1
  65. package/public/dist/assets/ChannelsTelegram-CGSpaImJ.js +1 -0
  66. package/public/dist/assets/CodeCanvas-DpkFi5Au.js +2 -0
  67. package/public/dist/assets/Permissions-BwiMEoTV.js +1 -0
  68. package/public/dist/assets/Permissions-CodIW-Yd.js +1 -0
  69. package/public/dist/assets/{manager-C5cU1joU.js → manager-Bi_xw7TW.js} +2 -2
  70. package/public/dist/assets/{settings-CA2LQDGh.js → settings-W4KG9ivu.js} +1 -1
  71. package/public/dist/assets/{settings-embedding-oGvFayh-.js → settings-embedding-BfWzWKMM.js} +1 -1
  72. package/public/dist/manager/index.html +1 -1
  73. package/public/dist/settings/index.html +1 -1
  74. package/public/js/features/settings-discord.ts +39 -5
  75. package/public/js/features/settings-telegram.ts +38 -4
  76. package/public/js/features/settings-types.ts +2 -0
  77. package/public/locales/en.json +2 -0
  78. package/public/locales/ja.json +2 -0
  79. package/public/locales/ko.json +2 -0
  80. package/public/locales/zh.json +2 -0
  81. package/public/manager/src/App.tsx +4 -1
  82. package/public/manager/src/code/code-controller-runtime.ts +13 -6
  83. package/public/manager/src/code/code-session-client.ts +1 -1
  84. package/public/manager/src/code/session-order.ts +6 -7
  85. package/public/manager/src/dashboard-url-state.ts +8 -0
  86. package/public/manager/src/settings/pages/AdvancedExport.tsx +2 -0
  87. package/public/manager/src/settings/pages/Agent.tsx +13 -5
  88. package/public/manager/src/settings/pages/ChannelsDiscord.tsx +27 -4
  89. package/public/manager/src/settings/pages/ChannelsTelegram.tsx +26 -4
  90. package/public/manager/src/settings/pages/Permissions.tsx +50 -27
  91. package/public/manager/src/settings/pages/components/ChannelSetupEntry.tsx +4 -3
  92. package/public/manager/src/settings/pages/components/agent/PermissionQuickSection.tsx +10 -2
  93. package/public/dist/assets/AdvancedExport-BNMjYkw6.js +0 -1
  94. package/public/dist/assets/Agent-D4g8TPjm.js +0 -1
  95. package/public/dist/assets/ChannelSetupEntry-zKYImWXx.js +0 -1
  96. package/public/dist/assets/ChannelsDiscord-CWRKV-Zl.js +0 -1
  97. package/public/dist/assets/ChannelsTelegram-BdK-fTPI.js +0 -1
  98. package/public/dist/assets/CodeCanvas-D5jp8-t5.js +0 -2
  99. package/public/dist/assets/Permissions-Bh947tUG.js +0 -1
  100. package/public/dist/assets/Permissions-DzNJCt8K.js +0 -1
@@ -15,9 +15,16 @@ import {
15
15
  usePageSnapshot,
16
16
  } from './page-shell';
17
17
  import { InlineWarn } from './components/InlineWarn';
18
+ import { isPermissionToken as isStorePermissionToken, isPermissionsPolicy } from '../../../../../src/shared/permissions';
18
19
 
19
20
  export type PermissionMode = 'auto' | 'safe' | 'custom';
20
21
 
22
+ /** Editing state for the stored value. 'invalid' is the recoverable case: the
23
+ * stored value matched no public shape, so no policy option is pre-selected
24
+ * and the saved readout keeps reporting 'Unrecognized' until the user picks
25
+ * one — never rendered as Auto (#788). */
26
+ export type PermissionEditMode = PermissionMode | 'invalid';
27
+
21
28
  type PermissionsSnapshot = {
22
29
  permissions?: 'auto' | string[] | unknown;
23
30
  [key: string]: unknown;
@@ -26,8 +33,7 @@ type PermissionsSnapshot = {
26
33
  // Permission tokens accepted by the runtime. We don't enforce a closed set —
27
34
  // MCP namespaces (`mcp.*`) and tool-specific tokens grow over time — but we
28
35
  // do validate the *shape* so a stray space, control char, or empty chip can't
29
- // slip through.
30
- const TOKEN_RE = /^[a-zA-Z0-9._:*-]+$/;
36
+ // slip through. The literal contract lives in src/shared/permissions.
31
37
 
32
38
  const DEFAULT_AUTO_TOKENS: ReadonlyArray<string> = [
33
39
  'bash',
@@ -43,7 +49,10 @@ export function configuredPolicyLabel(value: unknown): string {
43
49
  if (value === 'auto') return 'Auto (YOLO)';
44
50
  if (value === 'safe') return 'Safe';
45
51
  if (value === null || value === undefined) return 'Not provided';
46
- if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) {
52
+ // Count only what the shared validator would store: a token list containing
53
+ // an unwritable entry is not a policy, and labeling it 'Custom' is how an
54
+ // unrecognized value hid inside the readout while the editors disagreed (#788).
55
+ if (Array.isArray(value) && isPermissionsPolicy(value)) {
47
56
  return `Custom (${value.length} ${value.length === 1 ? 'entry' : 'entries'})`;
48
57
  }
49
58
  return 'Unrecognized';
@@ -76,11 +85,19 @@ export function parsePermissionsValue(
76
85
  }
77
86
 
78
87
  export function isPermissionToken(token: string): boolean {
79
- if (typeof token !== 'string') return false;
80
- if (token.length === 0 || token.length > 64) return false;
81
88
  // Strict shape on the literal — no trim. A token containing whitespace,
82
89
  // newline, quote, or control char must fail outright.
83
- return TOKEN_RE.test(token);
90
+ return isStorePermissionToken(token);
91
+ }
92
+
93
+ /** The editing mode a stored value opens in. Anything the shared validator
94
+ * would not store lands in 'invalid', so the editors show a recoverable state
95
+ * instead of silently selecting Auto (#788). */
96
+ export function permissionsEditMode(value: unknown): PermissionEditMode {
97
+ if (!isPermissionsPolicy(value)) return 'invalid';
98
+ if (value === 'auto') return 'auto';
99
+ if (value === 'safe') return 'safe';
100
+ return 'custom';
84
101
  }
85
102
 
86
103
  /**
@@ -115,7 +132,7 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
115
132
  client,
116
133
  '/api/settings',
117
134
  );
118
- const [mode, setMode] = useState<PermissionMode>('auto');
135
+ const [mode, setMode] = useState<PermissionEditMode>('auto');
119
136
  const [tokens, setTokens] = useState<string[]>([]);
120
137
 
121
138
  const original = useMemo(
@@ -125,17 +142,15 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
125
142
 
126
143
  useEffect(() => {
127
144
  if (state.kind !== 'ready') return;
145
+ // A Safe instance must read as Safe. Showing it as Auto (YOLO) hides the policy the
146
+ // user is about to change and reports 'auto' as the original, so a round trip
147
+ // through Custom and back writes a widened policy the user never chose. Anything
148
+ // the shared stored-shape validator would not have written opens as 'invalid' —
149
+ // recoverable, not Auto (#788).
150
+ const editMode = permissionsEditMode(state.data.permissions);
128
151
  const parsed = parsePermissionsValue(state.data.permissions);
129
- if (parsed.mode === 'custom') {
130
- setMode('custom');
131
- setTokens(parsed.tokens);
132
- } else {
133
- // A Safe instance must read as Safe. Showing it as Auto (YOLO) hides the policy the
134
- // user is about to change and reports 'auto' as the original, so a round trip
135
- // through Custom and back writes a widened policy the user never chose.
136
- setMode(parsed.mode === 'safe' ? 'safe' : 'auto');
137
- setTokens([]);
138
- }
152
+ setMode(editMode);
153
+ setTokens(editMode === 'custom' && parsed.mode === 'custom' ? parsed.tokens : []);
139
154
  }, [state]);
140
155
 
141
156
  useEffect(() => {
@@ -149,12 +164,17 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
149
164
  [dirty],
150
165
  );
151
166
 
152
- const originalSerialized = useMemo<'auto' | 'safe' | string[]>(() => {
167
+ const storedPermissions = state.kind === 'ready' ? state.data.permissions : undefined;
168
+
169
+ const originalSerialized = useMemo<unknown>(() => {
153
170
  if (!original) return 'auto';
154
171
  if (original.mode === 'custom') return original.tokens;
155
172
  if (original.mode === 'safe') return 'safe';
173
+ // Keep the actual stored value as the dirty-entry original: reporting 'auto'
174
+ // here is what let an Unrecognized policy read as Auto (#788).
175
+ if (original.mode === 'unknown') return storedPermissions;
156
176
  return 'auto';
157
- }, [original]);
177
+ }, [original, storedPermissions]);
158
178
 
159
179
  const handleModeChange = useCallback(
160
180
  (next: string) => {
@@ -218,14 +238,10 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
218
238
  ? (updated as { data: PermissionsSnapshot }).data
219
239
  : updated) as PermissionsSnapshot;
220
240
  dirty.clear();
241
+ const editMode = permissionsEditMode(fresh.permissions);
221
242
  const parsed = parsePermissionsValue(fresh.permissions);
222
- if (parsed.mode === 'custom') {
223
- setMode('custom');
224
- setTokens(parsed.tokens);
225
- } else {
226
- setMode(parsed.mode === 'safe' ? 'safe' : 'auto');
227
- setTokens([]);
228
- }
243
+ setMode(editMode);
244
+ setTokens(editMode === 'custom' && parsed.mode === 'custom' ? parsed.tokens : []);
229
245
  setData(fresh);
230
246
  await refresh();
231
247
  }, [client, dirty, refresh, setData]);
@@ -258,7 +274,14 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
258
274
  value={mode}
259
275
  options={MODE_OPTIONS}
260
276
  onChange={handleModeChange}
277
+ missingValueLabel={mode === 'invalid' ? 'Unrecognized saved policy' : undefined}
261
278
  />
279
+ {mode === 'invalid' && (
280
+ <InlineWarn role="alert">
281
+ The saved permissions value is not a recognized policy.
282
+ Pick a policy above to replace it.
283
+ </InlineWarn>
284
+ )}
262
285
  {mode === 'custom' && (
263
286
  <>
264
287
  <ChipListField
@@ -298,7 +321,7 @@ export default function Permissions({ port, client, dirty, registerSave }: Setti
298
321
  <span>{activeSummary}</span>
299
322
  </p>
300
323
  {original?.mode === 'unknown' ? (
301
- <p className="settings-section-hint">Use Agent to change this configured policy.</p>
324
+ <p className="settings-section-hint">Unrecognized value: choose a policy above (or in Agent) to replace it.</p>
302
325
  ) : null}
303
326
  </SettingsSection>
304
327
  </form>
@@ -9,10 +9,11 @@ type Props = {
9
9
  open: boolean;
10
10
  onOpenChange: (open: boolean) => void;
11
11
  onSaved: () => Promise<void>;
12
+ disabled?: boolean;
12
13
  };
13
14
 
14
15
  /** The page retains its save owner; setup starts only after any page draft is saved. */
15
- export function ChannelSetupEntry({ channel, client, dirty, open, onOpenChange, onSaved }: Props) {
16
+ export function ChannelSetupEntry({ channel, client, dirty, open, onOpenChange, onSaved, disabled = false }: Props) {
16
17
  const trigger = useRef<HTMLButtonElement>(null);
17
18
  const active = useRef(false);
18
19
  const key = `${channel}.setup`;
@@ -24,8 +25,8 @@ export function ChannelSetupEntry({ channel, client, dirty, open, onOpenChange,
24
25
  const pendingDraft = !open && dirty.isDirty();
25
26
  return <>
26
27
  <button ref={trigger} type="button" data-onboard-channel={channel}
27
- disabled={open || pendingDraft} onClick={() => {
28
- if (dirty.isDirty()) return;
28
+ disabled={disabled || open || pendingDraft} onClick={() => {
29
+ if (disabled || dirty.isDirty()) return;
29
30
  dirty.set(key, { value: true, original: false, valid: false });
30
31
  onOpenChange(true);
31
32
  }}>{t('onboarding.open')}</button>
@@ -4,6 +4,7 @@ import {
4
4
  configuredPolicyLabel,
5
5
  isAllowlistValid,
6
6
  parsePermissionsValue,
7
+ permissionsEditMode,
7
8
  seedAutoAllowlist,
8
9
  } from '../../Permissions';
9
10
 
@@ -22,8 +23,9 @@ const MODE_OPTIONS = [
22
23
  export function PermissionQuickSection({ value, configuredValue, onChange }: PermissionQuickSectionProps) {
23
24
  const parsed = parsePermissionsValue(value);
24
25
  // Never fall through to 'auto': a Safe instance shown as Auto (YOLO) means the user cannot
25
- // see the permission they are about to lose when they touch this control.
26
- const mode = parsed.mode === 'custom' ? 'custom' : parsed.mode === 'safe' ? 'safe' : 'auto';
26
+ // see the permission they are about to lose when they touch this control. An unrecognized
27
+ // stored value lands in 'invalid' — no option is pre-selected, and picking one repairs it.
28
+ const mode = permissionsEditMode(value);
27
29
  const tokens = parsed.mode === 'custom' ? parsed.tokens : [];
28
30
  const summary = parsed.mode === 'custom'
29
31
  ? `Editor draft: ${tokens.length} explicit token${tokens.length === 1 ? '' : 's'}`
@@ -39,12 +41,18 @@ export function PermissionQuickSection({ value, configuredValue, onChange }: Per
39
41
  label="Change policy to"
40
42
  value={mode}
41
43
  options={MODE_OPTIONS}
44
+ missingValueLabel={mode === 'invalid' ? 'Unrecognized saved policy' : undefined}
42
45
  onChange={(next) => {
43
46
  if (next === 'auto') onChange('auto');
44
47
  else if (next === 'safe') onChange('safe');
45
48
  else onChange(tokens.length > 0 && isAllowlistValid(tokens) ? tokens : seedAutoAllowlist(null));
46
49
  }}
47
50
  />
51
+ {mode === 'invalid' ? (
52
+ <p className="settings-agent-note" role="alert">
53
+ The saved permissions value is not a recognized policy. Choose a policy to replace it.
54
+ </p>
55
+ ) : null}
48
56
  {summary ? <p className="settings-agent-note">{summary}</p> : null}
49
57
  <p className="settings-agent-note" id="agent-configured-policy">Configured policy: {configuredPolicyLabel(configuredValue)}</p>
50
58
  </SettingsSection>
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-C_pPTFsM.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./error-normalize-CL69Bl7z.js";import{a as i,i as a,n as o,r as s,t as c}from"./page-shell-BeGD0rRQ.js";var l=e(t(),1),u=n();function d(e,t){let n=new Blob([t],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),URL.revokeObjectURL(r)}function f(e){let t;try{t=JSON.parse(e)}catch(e){return{ok:!1,error:`Invalid JSON: ${e.message}`}}return!t||typeof t!=`object`||Array.isArray(t)?{ok:!1,error:`Import payload must be a JSON object.`}:{ok:!0,value:p(t)}}function p(e){let{settingsSchemaVersion:t,runtimeDefaultMigration:n,multiSessionDefaultMigration:r,nativeTransportMigration:i,maxConcurrentDefaultMigration:a,slackEnvironmentVariables:o,...s}=e;return s}function m({port:e,client:t,triggerDownload:n}){let{state:m}=i(t,`/api/settings`),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(``),[y,b]=(0,l.useState)(null),[x,S]=(0,l.useState)(!1),[C,w]=(0,l.useState)(null),T=n||d;(0,l.useEffect)(()=>{v(``),b(null),w(null)},[e]);let E=(0,l.useCallback)(()=>{if(m.kind!==`ready`)return;let t=`cli-jaw-settings-${e}.json`;T(t,JSON.stringify(p(m.data),null,2))},[m,e,T]),D=(0,l.useCallback)(async()=>{let e=f(_);if(!e.ok){b(e.error),w(null);return}b(null),w(null),S(!0);try{await t.put(`/api/settings`,e.value),w(`Imported. Reload the page to refresh other tabs.`)}catch(e){b(r(e))}finally{S(!1)}},[t,_]);return m.kind===`loading`?(0,u.jsx)(o,{}):m.kind===`offline`?(0,u.jsx)(s,{port:e}):m.kind===`error`?(0,u.jsx)(c,{message:m.message}):(0,u.jsxs)(`div`,{className:`settings-page-form`,children:[(0,u.jsx)(a,{title:`Export`,hint:`Download the resolved /i/${e}/api/settings document as JSON.`,children:(0,u.jsx)(`button`,{type:`button`,className:`settings-action settings-action-secondary`,onClick:E,children:`Download settings JSON`})}),(0,u.jsxs)(a,{title:`Import (advanced)`,hint:`Replaces matching keys via PUT. Only enable when you understand the impact.`,children:[(0,u.jsxs)(`label`,{className:`settings-field`,htmlFor:`advanced-toggle`,children:[(0,u.jsx)(`span`,{className:`settings-field-label`,children:`Show import controls`}),(0,u.jsx)(`input`,{id:`advanced-toggle`,type:`checkbox`,checked:h,onChange:e=>g(e.target.checked)})]}),h?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`label`,{className:`settings-field`,htmlFor:`advanced-import`,children:[(0,u.jsx)(`span`,{className:`settings-field-label`,children:`Settings JSON`}),(0,u.jsx)(`textarea`,{id:`advanced-import`,rows:8,value:_,placeholder:`{"cli":"codex","tui":{"themeSeed":"jaw-dark"}}`,onChange:e=>v(e.target.value),"aria-invalid":!!y}),y?(0,u.jsx)(`span`,{className:`settings-field-error`,role:`alert`,children:y}):null,C?(0,u.jsx)(`span`,{className:`settings-field-description`,role:`status`,children:C}):null]}),(0,u.jsx)(`button`,{type:`button`,className:`settings-action settings-action-save`,onClick:()=>void D(),disabled:x||_.trim()===``,children:x?`Importing…`:`Apply import`})]}):null]})]})}export{m as default,p as stripServerOwnedSettingsFields,f as validateImportPayload};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{r as t,t as n}from"./cli-engine-NdU0lzs_.js";import{n as r}from"./settings-types-D3cd6SWy.js";import{t as i}from"./react-C_pPTFsM.js";import{t as a}from"./jsx-runtime-NZYk81nU.js";import{t as o}from"./settings-client-CmwRsVd1.js";import{t as s}from"./error-normalize-CL69Bl7z.js";import{a as c,i as l,n as u,r as d,t as f}from"./page-shell-BeGD0rRQ.js";import{i as p,s as m}from"./fields-mlGpofqQ.js";import{n as h,o as ee,r as g,s as _}from"./Permissions-DzNJCt8K.js";import{a as v,c as te,d as y,i as ne,l as b,n as re,o as x,r as ie,s as ae,t as oe,u as S}from"./agent-meta-94LMwZZK.js";import{t as se}from"./path-utils-B6vBr0DD.js";var C=e(i(),1),w=1e3,T=8e3,ce=9e4;function le(e,t){if(!e||!t)return!1;let n=e[t]?.probeState;return n?n===`checking`||n===`failing`:!1}function E(e){let t=w*2**Math.min(Number.isFinite(e)&&e>0?Math.floor(e):0,8);return Math.min(Math.max(t,w),T)}function ue(e){let{snapshot:t,cli:n,attempts:r,now:i,deadline:a}=e;if(!le(t,n))return{kind:`stop`};if(i>=a||r>=24)return{kind:`exhausted`};let o=t?.[n]?.nextRetryAt,s=typeof o==`number`&&o>i?o:i+E(r);return{kind:`wait`,delayMs:Math.max(Math.min(s,a)-i,0)}}var D=a();function de({cli:e,cliOptions:r,provider:i=``,providerOptions:a=[],model:o,modelOptions:s,effort:c,effortOptions:u,workingDir:d,workingDirError:f,cliMeta:h,onCliChange:ee,onProviderChange:g,onModelChange:_,onEffortChange:y,onWorkingDirChange:ne}){let b=te(r),x=n(e),ie=b.filter(e=>re.includes(e)).length;return(0,D.jsx)(l,{title:`Agent runtime`,hint:`Active CLI, model, effort, and workspace used by this instance.`,children:(0,D.jsxs)(`div`,{className:`settings-agent-runtime-grid`,children:[(0,D.jsx)(p,{id:`agent-cli`,label:`Active CLI`,value:e,missingValueLabel:n(e)?t(e):void 0,error:x?`This runtime is retired. Select an available runtime to continue.`:null,options:b.map(e=>({value:e,label:v(e,h).label||e})),collapsedAfter:ie,onChange:ee}),a.length>0?(0,D.jsx)(p,{id:`agent-${e}-provider`,label:`Provider`,value:i,options:a.map(e=>({value:e,label:e})),onChange:e=>g?.(e)}):null,(0,D.jsx)(p,{id:`agent-model`,label:`Active model`,value:o,disabled:x,options:s.length>0?s:[{value:``,label:`(default)`}],onChange:_}),(0,D.jsx)(p,{id:`agent-effort`,label:`Effort`,value:c,options:[{value:``,label:`(default)`},...u.map(e=>({value:e,label:e}))],disabled:x||u.length===0,onChange:y}),(0,D.jsx)(m,{id:`agent-workingDir`,label:`Working directory`,value:d,error:f,placeholder:`/path/to/project`,onChange:ne})]})})}var fe=[{value:`auto`,label:`Auto (YOLO)`},{value:`safe`,label:`Safe`},{value:`custom`,label:`Custom allowlist`}];function pe({value:e,configuredValue:t,onChange:n}){let r=ee(e),i=r.mode===`custom`?`custom`:r.mode===`safe`?`safe`:`auto`,a=r.mode===`custom`?r.tokens:[],o=r.mode===`custom`?`Editor draft: ${a.length} explicit token${a.length===1?``:`s`}`:null;return(0,D.jsxs)(l,{title:`Permissions`,hint:`Selecting a value changes the draft. Save applies it. Auto (YOLO) requests automatic approval or permission bypass. Behavior varies by runtime.`,children:[(0,D.jsx)(p,{id:`agent-permissions-mode`,label:`Change policy to`,value:i,options:fe,onChange:e=>{n(e===`auto`?`auto`:e===`safe`?`safe`:a.length>0&&g(a)?a:_(null))}}),o?(0,D.jsx)(`p`,{className:`settings-agent-note`,children:o}):null,(0,D.jsxs)(`p`,{className:`settings-agent-note`,id:`agent-configured-policy`,children:[`Configured policy: `,h(t)]})]})}function me({activeCli:e,flushCli:r,flushModel:i,cliOptions:a,modelOptions:o,cliMeta:s,loading:c,error:u,onFlushCliChange:d,onFlushModelChange:f}){let m=r||e,h=m?v(m,s).label||m:`active`;return(0,D.jsx)(l,{title:`Flush Agent`,hint:`Separate summary agent used for context flush and compact work.`,children:(0,D.jsxs)(`details`,{className:`settings-agent-flush`,children:[(0,D.jsxs)(`summary`,{children:[(0,D.jsx)(`span`,{children:`Flush runtime`}),(0,D.jsxs)(`code`,{children:[h,i&&i!=="default"?` / ${i}`:``]})]}),c?(0,D.jsx)(`p`,{className:`settings-agent-note`,children:`Loading flush settings...`}):null,u?(0,D.jsx)(`p`,{className:`settings-field-error`,role:`alert`,children:u}):null,(0,D.jsxs)(`div`,{className:`settings-agent-runtime-grid`,children:[(0,D.jsx)(p,{id:`agent-flush-cli`,label:`Flush CLI`,value:r,missingValueLabel:n(r)?t(r):void 0,error:n(m)?`The saved flush runtime is retired. Choose an available runtime.`:null,options:[{value:``,label:`(active CLI)`},...y(a).map(e=>({value:e,label:v(e,s).label||e}))],onChange:d}),(0,D.jsx)(p,{id:`agent-flush-model`,label:`Flush model`,value:i,disabled:n(m),options:[{value:``,label:`(default)`},...o],onChange:f})]})]})})}function O(e){return e.source===`static`||e.id.startsWith(`static:`)}function k(){return`new:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`}function he(e,t){let n=y(e)[0]||`claude`,r=t?.[n]?.models?.[0]||`default`;return{id:k(),name:`New Agent`,cli:n,model:r,role:``,status:`idle`,source:`db`}}function ge(e){return Array.isArray(e)?e.map(A).filter(Boolean):e.data.map(A).filter(Boolean)}function A(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.id==`string`?t.id:``,r=typeof t.name==`string`?t.name:``;if(!n||!r)return null;let i=t.source===`static`||n.startsWith(`static:`)?`static`:`db`,a={id:n,name:r,cli:typeof t.cli==`string`&&t.cli?t.cli:`claude`,model:typeof t.model==`string`&&t.model?t.model:`default`,role:typeof t.role==`string`?t.role:``,source:i};return typeof t.status==`string`&&(a.status=t.status),a}function j(e){return e.name.trim()?e.cli.trim()?e.model.trim()?null:`Model is required`:`CLI is required`:`Name is required`}function M(e){return e.some(e=>j(e)!==null)}function _e(e,t){return JSON.stringify(e.map(I))===JSON.stringify(t.map(I))}function N(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Set(t.map(e=>e.id)),i=[],a=[],o=[];for(let e of t){let t=n.get(e.id);if(!t||e.id.startsWith(`new:`)){i.push(e);continue}let r=ye(t,e);Object.keys(r).length>0&&a.push({before:t,after:e,patch:r})}for(let t of e)!r.has(t.id)&&!O(t)&&o.push(t);return{added:i,updated:a,removed:o}}function ve(e,t){let n=N(e,t);return{added:n.added.length,updated:n.updated.length,removed:n.removed.length}}async function P(e,t,n){let r=N(t,n);for(let t of r.removed)await e.delete(`/api/employees/${encodeURIComponent(t.id)}`);for(let t of r.added)await e.post(`/api/employees`,F(t));for(let t of r.updated)await e.put(`/api/employees/${encodeURIComponent(t.after.id)}`,t.patch)}function ye(e,t){if(O(t))return e.model===t.model?{}:{model:t.model};let n={};for(let r of[`name`,`cli`,`model`,`role`,`status`])(e[r]||``)!==(t[r]||``)&&(n[r]=t[r]||``);return n}function F(e){return{name:e.name.trim()||`New Agent`,cli:e.cli.trim()||`claude`,model:e.model.trim()||`default`,role:e.role.trim()}}function I(e){let t={id:e.id,name:e.name,cli:e.cli,model:e.model,role:e.role,source:e.source};return e.status!==void 0&&(t.status=e.status),t}function be({employee:e,index:r,cliOptions:i,cliMeta:a,onChange:o,onRemove:s}){let c=O(e),l=v(e.cli,a),u=ae(l.models,e.model),d=j(e),f=n(e.cli),h=y(Array.from(new Set([...i,e.cli,`claude`])).filter(Boolean));return(0,D.jsxs)(`fieldset`,{className:`settings-runtime-employee-row`,children:[(0,D.jsxs)(`legend`,{children:[e.name||`Employee ${r+1}`,c?(0,D.jsx)(`span`,{children:`static`}):null]}),(0,D.jsxs)(`div`,{className:`settings-runtime-employee-grid`,children:[(0,D.jsx)(m,{id:`runtime-employee-${e.id}-name`,label:`Name`,value:e.name,disabled:c,error:d===`Name is required`?d:null,onChange:e=>o({name:e})}),(0,D.jsx)(p,{id:`runtime-employee-${e.id}-cli`,label:`CLI`,value:e.cli,missingValueLabel:n(e.cli)?t(e.cli):void 0,error:f?`This saved runtime cannot execute. Choose an available runtime.`:null,disabled:c,options:h.map(e=>({value:e,label:v(e,a).label||e})),onChange:e=>{o({cli:e,model:v(e,a).models[0]||`default`})}}),(0,D.jsx)(p,{id:`runtime-employee-${e.id}-model`,label:`Model`,value:e.model,disabled:f,options:u.length>0?u:[{value:`default`,label:`default`}],onChange:e=>o({model:e})}),(0,D.jsx)(m,{id:`runtime-employee-${e.id}-role`,label:`Role`,value:e.role,disabled:c,onChange:e=>o({role:e})})]}),(0,D.jsxs)(`div`,{className:`settings-runtime-employee-footer`,children:[(0,D.jsxs)(`span`,{children:[e.source,e.status?` / ${e.status}`:``]}),(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-discard`,disabled:c,onClick:s,"aria-label":`Remove employee ${e.name||r+1}`,children:`Remove`})]})]})}function xe({roster:e,original:t,cliOptions:n,cliMeta:r,loading:i,error:a,onRosterChange:o}){let s=ve(t,e),c=M(e);function u(t,n){o(e.map((e,r)=>r===t?{...e,...n}:e))}function d(t){o(e.filter((e,n)=>n!==t))}return(0,D.jsxs)(l,{title:`Employees`,hint:`Runtime dispatch roster. Static employees keep their locked identity; database employees can be edited.`,children:[(0,D.jsxs)(`div`,{className:`settings-runtime-employee-summary`,children:[(0,D.jsxs)(`span`,{children:[`+`,s.added]}),(0,D.jsxs)(`span`,{children:[`~`,s.updated]}),(0,D.jsxs)(`span`,{children:[`-`,s.removed]}),c?(0,D.jsx)(`strong`,{children:`Fix invalid rows before saving.`}):null]}),i?(0,D.jsx)(`p`,{className:`settings-agent-note`,children:`Loading employees...`}):null,a?(0,D.jsx)(`p`,{className:`settings-field-error`,role:`alert`,children:a}):null,e.length===0?(0,D.jsx)(`p`,{className:`settings-empty`,children:`No runtime employees configured.`}):(0,D.jsx)(`div`,{className:`settings-runtime-employee-list`,children:e.map((e,t)=>(0,D.jsx)(be,{employee:e,index:t,cliOptions:n,cliMeta:r??null,onChange:e=>u(t,e),onRemove:()=>d(t)},e.id))}),(0,D.jsx)(`div`,{className:`settings-employee-footer-bar`,children:(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-discard`,onClick:()=>o([...e,he(n,r)]),children:`+ Add employee`})})]})}var Se=new Set([`runtimeEmployees`,`flushCli`,`flushModel`]);function L(e){let t={},n=null,r=null;for(let[i,a]of Object.entries(e))i===`runtimeEmployees`?r=a:i===`flushCli`||i===`flushModel`?(n??={},n[i===`flushCli`?`cli`:`model`]=String(a??``)):Se.has(i)||(t[i]=a);return{settingsBundle:t,flushPatch:n,runtimeEmployeesNext:r}}async function Ce(e){let{client:t,bundle:n,employeeDraft:r,employeeOriginal:i}=e;if(M(r))throw Error(`runtime employees: fix invalid rows before saving`);let{settingsBundle:a,flushPatch:o,runtimeEmployeesNext:s}=L(n),c=null;try{if(Object.keys(a).length>0){let e=await t.put(`/api/settings`,se(a));c=e&&typeof e==`object`&&`data`in e?e.data:e}}catch(e){throw Error(`settings save failed: ${e instanceof Error?e.message:String(e)}`)}try{o&&await t.put(`/api/memory-files/settings`,o)}catch(e){throw Error(`flush settings save failed: ${e instanceof Error?e.message:String(e)}`)}try{if(s){let e=i;try{let n=ge(await t.get(`/api/employees`)),r=new Set(i.map(e=>e.id)),a=new Set(s.map(e=>e.id));e=n.filter(e=>r.has(e.id)||a.has(e.id))}catch{}await P(t,e,s)}}catch(e){throw Error(`runtime employees save failed: ${e instanceof Error?e.message:String(e)}`)}return c}function we({status:e,exhausted:t=!1}){if(t)return(0,D.jsx)(`div`,{className:`settings-inline-notice`,role:`alert`,children:`상태 확인이 끝나지 않았습니다. 새로고침하거나 잠시 후 다시 확인하세요.`});if(!e)return null;let n=r(e);return n.kind===`checking`?(0,D.jsx)(`div`,{className:`settings-inline-notice`,role:`status`,"aria-live":`polite`,children:`상태 확인 중`}):n.kind===`unknown`?(0,D.jsx)(`div`,{className:`settings-inline-notice`,role:`alert`,children:n.message}):n.kind===`failing`?(0,D.jsxs)(`div`,{className:`settings-inline-notice`,role:`alert`,children:[`상태 확인 실패 (재시도 중)`,e.probeError?`: ${e.probeError}`:``]}):null}function R(e){if(!(e instanceof o)||e.status!==409)return null;try{return JSON.parse(e.detail).settings??null}catch{return null}}function z({port:e,client:t,dirty:n,registerSave:r}){let{state:i,refresh:a,setData:o}=c(t,`/api/settings`),[l,p]=(0,C.useState)({cli:``,provider:``,model:``,effort:``,workingDir:``,permissions:`auto`}),[m,h]=(0,C.useState)({}),[g,_]=(0,C.useState)({}),[te,re]=(0,C.useState)(!0),[se,w]=(0,C.useState)(null),[T,le]=(0,C.useState)([]),[E,fe]=(0,C.useState)([]),[O,k]=(0,C.useState)(!0),[he,A]=(0,C.useState)(null),[j,N]=(0,C.useState)(null),[ve,P]=(0,C.useState)({}),[ye,F]=(0,C.useState)(!1),[I,be]=(0,C.useState)(null),[Se,L]=(0,C.useState)(!1),[z,Te]=(0,C.useState)(null),B=(0,C.useCallback)(async()=>{try{let e=await t.get(`/api/cli-registry`),n=e&&typeof e==`object`&&`data`in e?e.data:e;N(x(n))}catch{N(null)}},[t]),V=(0,C.useRef)(0),H=(0,C.useRef)({}),[Ee,De]=(0,C.useState)(!1),U=(0,C.useCallback)(async e=>{try{let n=await t.get(`/api/cli-status`);if(e!==void 0&&e!==V.current)return;H.current=n,P(n)}catch{if(e!==void 0&&e!==V.current)return;H.current={},P({})}},[t]),W=(0,C.useCallback)(async()=>{re(!0),w(null);try{let e=await t.get(`/api/memory-files`),n={cli:e.cli||``,model:e.model||``};h(n),_(n)}catch(e){w(e instanceof Error?e.message:String(e))}finally{re(!1)}},[t]),G=(0,C.useCallback)(async()=>{k(!0),A(null);try{let e=ge(await t.get(`/api/employees`));le(e),fe(e)}catch(e){A(e instanceof Error?e.message:String(e))}finally{k(!1)}},[t]);(0,C.useEffect)(()=>{B(),U(),W(),G()},[B,U,G,W]),(0,C.useEffect)(()=>{if(!l.cli)return;let e=V.current+1;V.current=e,De(!1);let t=Date.now()+ce,n=0,r,i=()=>{if(e!==V.current)return;let a=ue({snapshot:H.current,cli:l.cli,attempts:n,now:Date.now(),deadline:t});if(a.kind!==`stop`){if(a.kind===`exhausted`){De(!0);return}r=setTimeout(()=>{e===V.current&&(n+=1,U(e).then(()=>{e===V.current&&i()}))},a.delayMs)}};return i(),()=>{V.current=e+1,r!==void 0&&clearTimeout(r)}},[l.cli,U]),(0,C.useEffect)(()=>{if(i.kind!==`ready`)return;let e=Object.keys(i.data.perCli||{}),t=i.data.cli||e[0]||``,n=ee(i.data.permissions),r=v(t,j);p({cli:t,provider:i.data.perCli?.[t]?.provider||r.defaultProvider||``,model:S(t,i.data.perCli,i.data.activeOverrides),effort:b(t,i.data.perCli,i.data.activeOverrides),workingDir:i.data.workingDir||``,permissions:n.mode===`custom`?n.tokens:n.mode===`safe`?`safe`:`auto`})},[j,i]),(0,C.useEffect)(()=>()=>{for(let e of Array.from(n.pending.keys()))(e===`cli`||e===`workingDir`||e===`permissions`||e===`runtimeEmployees`||e===`flushCli`||e===`flushModel`||e.startsWith(`activeOverrides.`))&&n.remove(e)},[n]);let K=(0,C.useCallback)((e,t)=>n.set(e,t),[n]),Oe=(0,C.useCallback)(async()=>{let e=n.saveBundle();if(Object.keys(e).length===0)return;let r=await Ce({client:t,bundle:e,employeeDraft:E,employeeOriginal:T});n.clear(),r&&o(r),await a(),await B(),await W(),await G()},[t,n,E,T,B,G,W,a,o]);(0,C.useEffect)(()=>{if(r)return r(Oe),()=>r(null)},[r,Oe]);let q=i.kind===`ready`?i.data:{},J=q.perCli||{},Y=q.activeOverrides||{},ke=(0,C.useMemo)(()=>{let e=y(Object.keys(J));return e.length?e:y(Object.keys(j||oe))},[J,j]),X=v(l.cli,j),Z=l.provider||X.defaultProvider||X.providers?.[0]||``,Ae=l.cli===`pi`,Q=!Ae&&(X.providers?.length??0)>0,je=ae(Q&&X.modelsByProvider?.[Z]||X.models,l.model),Me=Q?ne(X,l.model,X.effortsByProvider?.[Z]||X.efforts,Z):ne(X,l.model),Ne=l.workingDir.trim()?null:`Required`,Pe=(0,C.useCallback)(async e=>{F(!0),be(null);try{let n=await t.post(`/api/settings/runtime-default-migration`,{action:e}),r;r=`settings`in n&&n.settings?n.settings:`data`in n&&n.data?n.data:n,o(r)}catch(e){let t=R(e);if(t){o(t);return}be(s(e))}finally{F(!1)}},[t,o]),Fe=(0,C.useCallback)(async e=>{L(!0),Te(null);try{let n=await t.post(`/api/settings/multi-session-default-migration`,{action:e}),r;r=`settings`in n&&n.settings?n.settings:`data`in n&&n.data?n.data:n,o(r)}catch(e){let t=R(e);if(t){o(t);return}Te(s(e))}finally{L(!1)}},[t,o]);if(i.kind===`loading`)return(0,D.jsx)(u,{});if(i.kind===`offline`)return(0,D.jsx)(d,{port:e});if(i.kind===`error`)return(0,D.jsx)(f,{message:i.message});function Ie(){for(let e of Array.from(n.pending.keys()))e.startsWith(`activeOverrides.`)&&n.remove(e)}function $(e){p(e)}return(0,D.jsxs)(`form`,{className:`settings-page-form`,onSubmit:e=>{e.preventDefault(),Oe()},children:[q.runtimeDefaultMigration?.state===`pending`?(0,D.jsxs)(`div`,{className:`settings-inline-notice`,role:`status`,children:[(0,D.jsx)(`strong`,{children:`기본 런타임 변경 안내`}),(0,D.jsx)(`p`,{children:`기존 선택은 유지됩니다. Codex App으로 전환하거나 현재 런타임을 계속 사용할 수 있습니다.`}),(0,D.jsxs)(`div`,{className:`settings-inline-actions`,children:[(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-save`,disabled:ye,onClick:()=>void Pe(`accept`),children:`Codex App 사용`}),(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-secondary`,disabled:ye,onClick:()=>void Pe(`keep`),children:`현재 런타임 유지`})]}),I?(0,D.jsx)(`span`,{className:`settings-field-error`,role:`alert`,children:I}):null]}):null,q.multiSessionDefaultMigration?.state===`pending`?(0,D.jsxs)(`div`,{className:`settings-inline-notice`,role:`status`,children:[(0,D.jsx)(`strong`,{children:`다중 세션 안내`}),(0,D.jsx)(`p`,{children:`대화 세션을 여러 개 열 수 있습니다. 켜면 동시 실행도 20으로 올라가서, 두 번째 세션이 첫 번째가 끝나기를 기다리지 않습니다. 지금 설정은 그대로 유지됩니다.`}),(0,D.jsxs)(`div`,{className:`settings-inline-actions`,children:[(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-save`,disabled:Se,onClick:()=>void Fe(`accept`),children:`다중 세션 켜기`}),(0,D.jsx)(`button`,{type:`button`,className:`settings-action settings-action-secondary`,disabled:Se,onClick:()=>void Fe(`keep`),children:`지금 설정 유지`})]}),z?(0,D.jsx)(`span`,{className:`settings-field-error`,role:`alert`,children:z}):null]}):null,(0,D.jsxs)(`label`,{className:`settings-field settings-field-select`,htmlFor:`midrun-policy-select`,children:[(0,D.jsx)(`span`,{className:`settings-field-label`,children:`실행 중 메시지 처리 (mid-run policy)`}),(0,D.jsxs)(`select`,{id:`midrun-policy-select`,value:String(q.multiSession?.midRunPolicy||`steer`),onChange:e=>{let t=e.target.value;K(`multiSession.midRunPolicy`,{value:t,original:String(q.multiSession?.midRunPolicy||`steer`),valid:!0})},children:[(0,D.jsx)(`option`,{value:`steer`,children:`steer (기본) — 실행 중 지시 변경`}),(0,D.jsx)(`option`,{value:`followup`,children:`followup — 끝나면 순서대로 실행`}),(0,D.jsx)(`option`,{value:`collect`,children:`collect — 모아서 한 번에 실행`}),(0,D.jsx)(`option`,{value:`interrupt`,children:`interrupt — 현재 실행을 중단하고 즉시 실행`})]}),(0,D.jsx)(`span`,{className:`settings-field-hint`,children:`다중 세션이 켜져 있을 때 적용됩니다. codex-app은 같은 턴에 입력을 전달합니다. Cursor·Grok의 native 모드는 현재 요청의 취소와 정리가 끝난 뒤 같은 세션에 다시 요청합니다(cancel-reprompt). 그 외 런타임은 중단 후 새 실행으로 이어갑니다(kill-steer). 보존되는 맥락은 런타임에 따라 다릅니다. 끝난 뒤 실행하려면 followup을 선택하세요.`})]}),(0,D.jsx)(we,{status:ve[l.cli],exhausted:Ee}),(0,D.jsx)(de,{cli:l.cli,cliOptions:ke,provider:Z,providerOptions:Ae?[]:X.providers||[],model:l.model,modelOptions:je,effort:l.effort,effortOptions:Me,workingDir:l.workingDir,workingDirError:Ne,cliMeta:j,onCliChange:e=>{let t=v(e,j),n={...l,cli:e,provider:J[e]?.provider||t.defaultProvider||``,model:S(e,J,Y),effort:b(e,J,Y)};Ie(),$(n),K(`cli`,{value:e,original:q.cli||``,valid:!0})},onProviderChange:e=>{let t=X.modelsByProvider?.[e]||[],n=X.effortsByProvider?.[e]||[],r=t.includes(l.model)?l.model:t[0]||``,i=ie(X,r,l.effort,n,e);$({...l,provider:e,model:r,effort:i}),K(`perCli.${l.cli}.provider`,{value:e,original:J[l.cli]?.provider||X.defaultProvider||``,valid:!0}),K(`activeOverrides.${l.cli}.model`,{value:r,original:S(l.cli,J,Y),valid:r.trim().length>0}),K(`activeOverrides.${l.cli}.effort`,{value:i,original:b(l.cli,J,Y),valid:!0})},onModelChange:e=>{let t=ie(X,e,l.effort,Q?X.effortsByProvider?.[Z]||X.efforts:void 0,Q?Z:void 0);$({...l,model:e,effort:t}),K(`activeOverrides.${l.cli}.model`,{value:e,original:S(l.cli,J,Y),valid:e.trim().length>0}),t!==l.effort&&K(`activeOverrides.${l.cli}.effort`,{value:t,original:b(l.cli,J,Y),valid:!0})},onEffortChange:e=>{$({...l,effort:e}),K(`activeOverrides.${l.cli}.effort`,{value:e,original:b(l.cli,J,Y),valid:!0})},onWorkingDirChange:e=>{$({...l,workingDir:e}),K(`workingDir`,{value:e,original:q.workingDir||``,valid:e.trim().length>0})}}),(0,D.jsx)(pe,{value:l.permissions,configuredValue:q.permissions,onChange:e=>{$({...l,permissions:e}),K(`permissions`,{value:e,original:q.permissions??`auto`,valid:e===`auto`||e.length>0})}}),(0,D.jsx)(me,{activeCli:l.cli,flushCli:g.cli||``,flushModel:g.model||``,cliOptions:ke,cliMeta:j,modelOptions:ae(v(g.cli||l.cli,j).models,g.model||``),loading:te,error:se,onFlushCliChange:e=>{let t=e&&v(e,j).models[0]||``;_({cli:e,model:t}),K(`flushCli`,{value:e,original:m.cli||``,valid:!0}),K(`flushModel`,{value:t,original:m.model||``,valid:!0})},onFlushModelChange:e=>{_({...g,model:e}),K(`flushModel`,{value:e,original:m.model||``,valid:!0})}}),(0,D.jsx)(xe,{roster:E,original:T,cliOptions:ke,cliMeta:j,loading:O,error:he,onRosterChange:e=>{if(fe(e),_e(e,T)){n.remove(`runtimeEmployees`);return}n.set(`runtimeEmployees`,{value:e,original:T,valid:!M(e)})}})]})}export{we as CliProbeNotice,R as conflictSettingsFromError,z as default,L as splitAgentSaveBundle};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-C_pPTFsM.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{t as r}from"./settings-client-CmwRsVd1.js";import{i,n as a}from"./ChannelEnablementControl-B2tq8Ji4.js";var o=e(t(),1),s=n();function c({client:e,label:t,endpoint:n,method:i=`GET`,interpret:a,auto:c=!1}){let[d,f]=(0,o.useState)({kind:`idle`}),p=(0,o.useRef)(null),m=(0,o.useRef)(!0),h=(0,o.useCallback)(async()=>{p.current?.abort();let t=new AbortController;p.current=t,f({kind:`checking`});try{let r=i===`POST`?await e.post(n,{},{signal:t.signal}):await e.get(n,{signal:t.signal});if(!m.current||t.signal.aborted)return;f(a(r))}catch(e){if(!m.current||t.signal.aborted)return;if(e instanceof r&&e.status===404){f({kind:`unknown`,reason:`Probe endpoint not implemented on this instance.`});return}let n=e instanceof Error?e.message:String(e);f({kind:`error`,reason:n})}},[e,n,a,i]);return(0,o.useEffect)(()=>(m.current=!0,c&&h(),()=>{m.current=!1,p.current?.abort()}),[c,h]),(0,s.jsxs)(`div`,{className:`settings-health-badge`,role:`status`,"aria-live":`polite`,children:[(0,s.jsx)(`button`,{type:`button`,className:`settings-action settings-action-discard`,onClick:()=>void h(),disabled:d.kind===`checking`,children:d.kind===`checking`?`Checking…`:`Check ${t}`}),(0,s.jsx)(`span`,{className:`settings-health-pill is-${d.kind}`,children:l(d)}),u(d)?(0,s.jsx)(`span`,{className:`settings-health-detail`,children:u(d)}):null]})}function l(e){switch(e.kind){case`idle`:return`Not checked`;case`checking`:return`Checking`;case`ok`:return`Healthy`;case`degraded`:return`Degraded`;case`unknown`:return`Unknown`;case`error`:return`Error`}}function u(e){return e.kind===`ok`&&e.detail||e.kind===`degraded`?e.detail:e.kind===`unknown`||e.kind===`error`?e.reason:null}function d(e){if(!e||typeof e!=`object`)return{kind:`unknown`,reason:`Empty probe response.`};let t=e;if(t.ok===!0){let e=typeof t.username==`string`?t.username:void 0;return e?{kind:`ok`,detail:`@${e}`}:{kind:`ok`}}return{kind:`error`,reason:typeof t.error==`string`?t.error:`Probe failed.`}}function f(e){if(!e||typeof e!=`object`)return{kind:`unknown`,reason:`Empty health response.`};let t=e,n=t.discord&&typeof t.discord==`object`?t.discord:null;return n?n.ready===!0&&n.degraded!==!0?{kind:`ok`}:n.degraded===!0?{kind:`degraded`,detail:typeof n.degradedReason==`string`?n.degradedReason:`MESSAGE_CONTENT intent missing — slash commands only.`}:n.ready===!1?{kind:`error`,reason:typeof n.error==`string`?n.error:`Bot not connected.`}:{kind:`unknown`,reason:`Discord status indeterminate.`}:{kind:`unknown`,reason:`No discord block in /api/health.`}}function p({channel:e,client:t,dirty:n,open:r,onOpenChange:c,onSaved:l}){let u=(0,o.useRef)(null),d=(0,o.useRef)(!1),f=`${e}.setup`,p=(0,o.useMemo)(()=>i(document.documentElement.lang),[]);(0,o.useEffect)(()=>(d.current=!0,()=>{d.current=!1,n.remove(f)}),[t,n,f]);let m=!r&&n.isDirty();return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(`button`,{ref:u,type:`button`,"data-onboard-channel":e,disabled:r||m,onClick:()=>{n.isDirty()||(n.set(f,{value:!0,original:!1,valid:!1}),c(!0))},children:p(`onboarding.open`)}),m&&(0,s.jsx)(`p`,{className:`settings-field-hint`,children:`Save or discard your changes before opening setup.`}),r&&(0,s.jsx)(a,{channel:e,client:t,t:p,initialDraft:{},returnFocus:u.current,onBeforeSave:()=>async()=>{d.current&&(await l(),d.current&&n.remove(f))},onClose:()=>{n.remove(f),c(!1)}},e)]})}export{d as i,c as n,f as r,p as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-C_pPTFsM.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{a as r,i,n as a,r as o,t as s}from"./page-shell-BeGD0rRQ.js";import{a as c,n as l,o as u,s as d}from"./fields-mlGpofqQ.js";import{t as f}from"./path-utils-B6vBr0DD.js";import{n as p,r as m,t as h}from"./ChannelSetupEntry-zKYImWXx.js";import{a as g,t as _}from"./ChannelEnablementControl-B2tq8Ji4.js";var v=e(t(),1),y=n(),b=[`messaging.enabledChannels`,`messaging.homeChannel`,`discord.enabled`,`discord.token`,`discord.guildId`,`discord.channelIds`,`discord.forwardAll`,`discord.allowBots`,`discord.mentionOnly`];function x(e){return e?/^\d{5,32}$/.test(e.trim()):!1}function S({port:e,client:t,dirty:n,registerSave:S}){let{state:w,refresh:T,setData:E}=r(t,`/api/settings`),[D,O]=(0,v.useState)(!1),[k,A]=(0,v.useState)([]),[j,M]=(0,v.useState)(`telegram`),[N,P]=(0,v.useState)(!1),[F,I]=(0,v.useState)(``),[L,R]=(0,v.useState)(``),[z,B]=(0,v.useState)([]),[V,H]=(0,v.useState)(!0),[U,W]=(0,v.useState)(!1),[G,K]=(0,v.useState)(!1);(0,v.useEffect)(()=>{if(w.kind!==`ready`)return;let e=w.data.messaging||{},t=Array.isArray(e.enabledChannels)?e.enabledChannels:[];A(t.filter(C)),M(C(e.homeChannel)?e.homeChannel:`telegram`);let n=w.data.discord||{};P(!!n.enabled),I(``),R(n.guildId??``),B(Array.isArray(n.channelIds)?[...n.channelIds]:[]),H(n.forwardAll!==!1),W(!!n.allowBots),K(!!n.mentionOnly)},[w]),(0,v.useEffect)(()=>()=>{for(let e of b)n.remove(e)},[n]);let q=(0,v.useCallback)((e,t)=>n.set(e,t),[n]),J=(0,v.useMemo)(()=>w.kind===`ready`&&w.data.discord||{},[w]),Y=(0,v.useCallback)(async()=>{if(D)throw Error(`Finish channel setup before saving settings.`);let e=n.saveBundle();if(Object.keys(e).length===0)return;let r=f(e),i=await t.put(`/api/settings`,r),a=i&&typeof i==`object`&&`data`in i?i.data:i;n.clear(),E(a);let o=a.messaging||{};A(Array.isArray(o.enabledChannels)?o.enabledChannels.filter(C):[]),M(C(o.homeChannel)?o.homeChannel:`telegram`);let s=a.discord||{};P(!!s.enabled),I(``),R(s.guildId??``),B(Array.isArray(s.channelIds)?[...s.channelIds]:[]),H(s.forwardAll!==!1),W(!!s.allowBots),K(!!s.mentionOnly),await T()},[t,n,T,E,D]);if((0,v.useEffect)(()=>{if(S)return S(Y),()=>S(null)},[S,Y]),w.kind===`loading`)return(0,y.jsx)(a,{});if(w.kind===`offline`)return(0,y.jsx)(o,{port:e});if(w.kind===`error`)return(0,y.jsx)(s,{message:w.message});let X=J.token?J.token.slice(-4):``,Z=J.token?`••••••••${X}`:`(empty)`,Q=L&&!x(L)?`Guild ID must be a numeric snowflake.`:null,$=z.filter(e=>!x(e)),ee=$.length>0?`Snowflake IDs only — invalid: ${$.join(`, `)}`:null;return(0,y.jsxs)(`form`,{className:`settings-page-form`,onSubmit:e=>{e.preventDefault(),Y()},children:[(0,y.jsxs)(`fieldset`,{disabled:D,className:`settings-slack-fields`,children:[(0,y.jsxs)(i,{title:`Channels`,hint:`Choose which channels receive inbound chat. Outbound send can still work on any configured channel.`,children:[(0,y.jsx)(_,{pageChannel:`discord`,snapshot:w.kind===`ready`?w.data:{},enabledChannels:k,homeChannel:j,setEnabledChannels:A,setHomeChannel:M,dirty:n,idPrefix:`di-channel`}),(0,y.jsx)(g,{client:t,channel:`discord`})]}),(0,y.jsxs)(i,{title:`Discord`,hint:`Bot token, guild + channels, forwarding rules.`,children:[(0,y.jsx)(c,{id:`dc-enabled`,label:`Discord enabled`,value:N,onChange:e=>{P(e),q(`discord.enabled`,{value:e,original:!!J.enabled,valid:!0})}}),(0,y.jsx)(u,{id:`dc-token`,label:`Bot token`,value:F,placeholder:Z,onChange:e=>{if(I(e),e.length===0){n.remove(`discord.token`);return}q(`discord.token`,{value:e,original:J.token??``,valid:!0})}}),(0,y.jsx)(d,{id:`dc-guildId`,label:`Guild ID`,value:L,placeholder:`123456789012345678`,error:Q,onChange:e=>{R(e);let t=e.length===0||x(e);q(`discord.guildId`,{value:e,original:J.guildId??``,valid:t})}}),(0,y.jsx)(l,{id:`dc-channelIds`,label:`Channel IDs`,value:z,placeholder:`987654321098765432`,error:ee,onChange:e=>{B(e);let t=e.every(x);q(`discord.channelIds`,{value:e,original:J.channelIds??[],valid:t})}}),(0,y.jsx)(c,{id:`dc-forwardAll`,label:`Forward all`,value:V,onChange:e=>{H(e),q(`discord.forwardAll`,{value:e,original:J.forwardAll!==!1,valid:!0})}}),(0,y.jsx)(c,{id:`dc-allowBots`,label:`Allow other bots`,value:U,onChange:e=>{W(e),q(`discord.allowBots`,{value:e,original:!!J.allowBots,valid:!0})}}),(0,y.jsx)(c,{id:`dc-mentionOnly`,label:`Mention only`,value:G,onChange:e=>{K(e),q(`discord.mentionOnly`,{value:e,original:!!J.mentionOnly,valid:!0})}})]}),(0,y.jsx)(i,{title:`Health`,hint:`Probes /api/health for Discord readiness. Degraded mode means the bot is missing the MESSAGE_CONTENT intent (slash commands only).`,children:(0,y.jsx)(p,{client:t,label:`Discord`,endpoint:`/api/health`,method:`GET`,interpret:m})})]}),(0,y.jsx)(h,{channel:`discord`,client:t,dirty:n,open:D,onOpenChange:O,onSaved:async()=>E(await t.get(`/api/settings`))})]})}function C(e){return e===`telegram`||e===`discord`||e===`slack`}export{S as default,x as isValidSnowflake};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-C_pPTFsM.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{a as r,i,n as a,r as o,t as s}from"./page-shell-BeGD0rRQ.js";import{a as c,n as l,o as u}from"./fields-mlGpofqQ.js";import{t as d}from"./path-utils-B6vBr0DD.js";import{i as f,n as p,t as m}from"./ChannelSetupEntry-zKYImWXx.js";import{a as h,t as g}from"./ChannelEnablementControl-B2tq8Ji4.js";var _=e(t(),1),v=n(),y=[`messaging.enabledChannels`,`messaging.homeChannel`,`telegram.enabled`,`telegram.token`,`telegram.allowedChatIds`,`telegram.forwardAll`,`telegram.mentionOnly`];function b(e){return e?/^-?\d+$/.test(e.trim()):!1}function x(e){let t=[],n=[];for(let r of e)b(r)?t.push(r.trim()):n.push(r);return{valid:t,invalid:n}}function S(e){return e?e.filter(e=>Number.isFinite(e)).map(e=>String(e)):[]}function C(e){let t=[];for(let n of e){if(!b(n))continue;let e=Number(n);Number.isFinite(e)&&t.push(e)}return t}function w({port:e,client:t,dirty:n,registerSave:w}){let{state:E,refresh:D,setData:O}=r(t,`/api/settings`),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)([]),[N,P]=(0,_.useState)(`telegram`),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(``),[z,B]=(0,_.useState)([]),[V,H]=(0,_.useState)(!0),[U,W]=(0,_.useState)(!0);(0,_.useEffect)(()=>{if(E.kind!==`ready`)return;let e=E.data.messaging||{},t=Array.isArray(e.enabledChannels)?e.enabledChannels:[];M(t.filter(T)),P(T(e.homeChannel)?e.homeChannel:`telegram`);let n=E.data.telegram||{};I(!!n.enabled),R(``),B(S(n.allowedChatIds)),H(n.forwardAll!==!1),W(n.mentionOnly!==!1)},[E]),(0,_.useEffect)(()=>()=>{for(let e of y)n.remove(e)},[n]);let G=(0,_.useCallback)((e,t)=>n.set(e,t),[n]),K=(0,_.useMemo)(()=>E.kind===`ready`&&E.data.telegram||{},[E]),q=(0,_.useCallback)(async()=>{if(k)throw Error(`Finish channel setup before saving settings.`);let e=n.saveBundle();if(Object.keys(e).length===0)return;let r=d(e),i=await t.put(`/api/settings`,r),a=i&&typeof i==`object`&&`data`in i?i.data:i;n.clear(),O(a);let o=a.messaging||{};M(Array.isArray(o.enabledChannels)?o.enabledChannels.filter(T):[]),P(T(o.homeChannel)?o.homeChannel:`telegram`);let s=a.telegram||{};I(!!s.enabled),R(``),B(S(s.allowedChatIds)),H(s.forwardAll!==!1),W(s.mentionOnly!==!1),await D()},[t,n,D,O,k]);if((0,_.useEffect)(()=>{if(w)return w(q),()=>w(null)},[w,q]),E.kind===`loading`)return(0,v.jsx)(a,{});if(E.kind===`offline`)return(0,v.jsx)(o,{port:e});if(E.kind===`error`)return(0,v.jsx)(s,{message:E.message});let J=K.token?K.token.slice(-4):``,Y=K.token?`••••••••${J}`:`(empty)`,{invalid:X}=x(z),Z=X.length>0?`Numeric chat IDs only — invalid: ${X.join(`, `)}`:null;return(0,v.jsxs)(`form`,{className:`settings-page-form`,onSubmit:e=>{e.preventDefault(),q()},children:[(0,v.jsxs)(`fieldset`,{disabled:k,className:`settings-slack-fields`,children:[(0,v.jsxs)(i,{title:`Channels`,hint:`Choose which channels receive inbound chat. Outbound send can still work on any configured channel.`,children:[(0,v.jsx)(g,{pageChannel:`telegram`,snapshot:E.kind===`ready`?E.data:{},enabledChannels:j,homeChannel:N,setEnabledChannels:M,setHomeChannel:P,dirty:n,idPrefix:`tg-channel`}),(0,v.jsx)(h,{client:t,channel:`telegram`})]}),(0,v.jsxs)(i,{title:`Telegram`,hint:`Bot token, allow-list, and forwarding rules.`,children:[(0,v.jsx)(c,{id:`tg-enabled`,label:`Telegram enabled`,value:F,onChange:e=>{I(e),G(`telegram.enabled`,{value:e,original:!!K.enabled,valid:!0})}}),(0,v.jsx)(u,{id:`tg-token`,label:`Bot token`,value:L,placeholder:Y,onChange:e=>{if(R(e),e.length===0){n.remove(`telegram.token`);return}G(`telegram.token`,{value:e,original:K.token??``,valid:!0})}}),(0,v.jsx)(l,{id:`tg-allowedChatIds`,label:`Allowed chat IDs`,value:z,placeholder:`123456789`,error:Z,onChange:e=>{B(e);let t=e.every(b);G(`telegram.allowedChatIds`,{value:C(e),original:K.allowedChatIds??[],valid:t})}}),(0,v.jsx)(c,{id:`tg-forwardAll`,label:`Forward all responses`,value:V,onChange:e=>{H(e),G(`telegram.forwardAll`,{value:e,original:K.forwardAll!==!1,valid:!0})}}),(0,v.jsx)(c,{id:`tg-mentionOnly`,label:`Mention only`,value:U,onChange:e=>{W(e),G(`telegram.mentionOnly`,{value:e,original:K.mentionOnly!==!1,valid:!0})}})]}),(0,v.jsx)(i,{title:`Health`,hint:`Probe the bot to confirm token + connectivity. 404 means the instance hasn't shipped the probe endpoint yet.`,children:(0,v.jsx)(p,{client:t,label:`Telegram`,endpoint:`/api/telegram/probe`,method:`POST`,interpret:f})})]}),(0,v.jsx)(m,{channel:`telegram`,client:t,dirty:n,open:k,onOpenChange:A,onSaved:async()=>O(await t.get(`/api/settings`))})]})}function T(e){return e===`telegram`||e===`discord`||e===`slack`}export{S as chatIdsToChips,C as chipsToChatIds,w as default,b as isValidChatId,x as partitionChatIds};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-render-DSSkXCir.css"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./preload-helper-CfbQpVni.js";import{a as n,i as r,n as i,r as a,t as o}from"./esm-Q6VOkDbn.js";import{t as s}from"./react-C_pPTFsM.js";import{t as c}from"./react-dom-DyUOYpVL.js";import{t as l}from"./jsx-runtime-NZYk81nU.js";var u=e(s(),1),d=c(),f={session_busy:`This session is busy. Wait for it to finish or stop the current turn.`,request_not_current:`This approval is no longer current. Refreshing its status.`,invalid_option:`This approval option is no longer available. Refreshing its status.`,revision_conflict:`Session settings changed elsewhere. Review the updated values and try again.`,invalid_sequence:`Conversation history needs to be refreshed.`,snapshot_limit:`This conversation exceeds the snapshot limit. Stop and recovery controls remain available.`,transcript_limit:`The conversation has reached its storage limit.`,event_too_large:`A conversation update exceeds the supported size.`,provider_unavailable:`This runtime is unavailable. Check its installation and authentication.`,unsupported_model:`This model is not available for the selected runtime.`,unsupported_effort:`This effort is not supported by the selected runtime.`,unsupported_policy:`This permission mode is not supported by the selected runtime.`,unsupported_capability:`This runtime does not support this action.`,session_not_found:`This session is no longer available. Its local draft is retained.`,unauthorized:`Authentication is required to access this instance.`},p=class extends Error{code;status;session;constructor(e,t,n){super(f[e]??`The request could not be completed. Refresh the session and try again.`),this.code=e,this.status=t,this.session=n,this.name=`CodeClientError`}};function m(e){return typeof window<`u`&&window.location.port===String(e)?window.location.origin:`http://127.0.0.1:${e}`}function h(e){let t=m(e);async function n(e,n,r,i){let a=await fetch(`${t}/api/code${n}`,{method:e,...i===void 0?{}:{signal:i},...r===void 0?{}:{headers:{"Content-Type":`application/json`},body:JSON.stringify(r)}}),o=await a.json();if(!a.ok||o.ok!==!0)throw new p(typeof o.error==`string`?o.error:`code_request_failed`,a.status,o.session);return o}let r=e=>`/sessions/${encodeURIComponent(e)}`,i=async(e,t,r)=>(await n(e,t,r)).session;return{listSessions(e={},t){let r=new URLSearchParams;for(let[t,n]of Object.entries(e))n!==void 0&&r.set(t,String(n));return n(`GET`,`/sessions?${r}`,void 0,t)},listModelOptions:e=>n(`GET`,`/models`,void 0,e),snapshot:(e,t)=>n(`GET`,r(e),void 0,t),events:(e,t,i)=>n(`GET`,`${r(e)}/events?afterSequence=${t}&limit=500`,void 0,i),history:(e,t,i)=>n(`GET`,`${r(e)}/items?beforeSequence=${t}&limit=200`,void 0,i),createSession:e=>i(`POST`,`/sessions`,e),patchSession:(e,t)=>i(`PATCH`,r(e),t),sendPrompt:(e,t)=>n(`POST`,`${r(e)}/prompt`,t),cancelPrompt:(e,t)=>i(`POST`,`${r(e)}/cancel`,t),attachSession:e=>i(`POST`,`${r(e)}/attach`,{}),async answerPermission(e,t){await n(`POST`,`/permissions/${encodeURIComponent(e)}`,t)},getGitInfo:(e,t)=>n(`GET`,`/git-info?cwd=${encodeURIComponent(e)}`,void 0,t),pickWorkspace:()=>n(`POST`,`/workspace/pick`)}}var g=512,_=2097152,v=2e3,y=16777216;function b(e){return{sessionId:e,session:null,items:[],permissions:[],cursor:0,hydrated:!1,hydrating:!1,synced:!1,needsSnapshot:!1,buffered:[],hasOlder:!1,beforeSequence:null,error:null}}function x(e){return!!e&&[`starting`,`streaming`,`stopping`].includes(e.status)}var S=e=>e.sort((e,t)=>(e.firstSequence??0)-(t.firstSequence??0)),C=e=>e.reduce((e,t)=>e+JSON.stringify(t).length,0);function w(e){let t=e.items,n=C(t);if(t.length<=v&&n<=y)return e;for(t=[...t];t.length>v||n>y;){let r=t.findIndex(t=>!e.session?.turnId||t.turnId!==e.session.turnId);if(r<0)return{...e,items:[],synced:!1,needsSnapshot:!0,error:`Conversation exceeds the display capacity.`};n-=JSON.stringify(t[r]).length,t.splice(r,1)}return{...e,items:t,hasOlder:!0,beforeSequence:t[0]?.firstSequence??null}}function T(e,t){let{items:n,session:r,permissions:i}=e;if(t.event===`code_session`){if(!t.session||t.session.sessionId!==e.sessionId)return{...e,needsSnapshot:!0,synced:!1};r=t.session.contextUsage===void 0&&r?.contextUsage!==void 0?{...t.session,contextUsage:r.contextUsage}:t.session,i=i.filter(e=>e.epoch===r.epoch&&e.turnId===r.turnId)}else{let a=t.item?.itemId??t.update?.itemId,o=n.find(e=>e.itemId===a),s;if(t.event===`code_item`&&t.item)s={...t.item,firstSequence:o?.firstSequence??t.item.firstSequence??t.sequence};else if(t.event===`code_item_update`&&t.update&&o&&o.turnId===t.update.turnId){let n=t.update;if(n.appendToolOutput!==void 0&&!o.tool)return{...e,needsSnapshot:!0,synced:!1};s={...o,updatedAt:n.updatedAt,...n.appendText===void 0?{}:{text:(o.text??``)+n.appendText},...n.appendToolOutput===void 0?{}:{tool:{...o.tool,output:(o.tool.output??``)+n.appendToolOutput}},...n.status===void 0?{}:{status:n.status},...n.phase===void 0?{}:{phase:n.phase}}}else return{...e,needsSnapshot:!0,synced:!1};n=S([...n.filter(e=>e.itemId!==s.itemId),s]),s.permission&&(i=i.filter(e=>e.permissionId!==s.permission.permissionId),s.status===`pending`&&s.permission.epoch===r?.epoch&&s.permission.turnId===r?.turnId&&(i=[...i,s.permission]))}return w({...e,items:n,session:r,permissions:i,cursor:t.sequence})}function E(e){let t=e;if(!t.hydrated||t.hydrating||t.needsSnapshot)return t;let n=t.buffered.filter(e=>e.sequence>t.cursor);for(;n[0]?.sequence===t.cursor+1;){let e=n[0];if(t=T(t,e),t.needsSnapshot)break;n.shift()}return{...t,buffered:n,synced:t.synced&&!n.length&&!t.needsSnapshot}}function D(e,t){if(t.sessionId!==e.sessionId||t.sequence<=e.cursor||e.buffered.some(e=>e.sequence===t.sequence))return e;let n=[...e.buffered,t].sort((e,t)=>e.sequence-t.sequence);return n.length>g||JSON.stringify(n).length>_?{...e,buffered:[],synced:!1,needsSnapshot:!0,error:`Live updates exceeded the buffer. Refreshing history.`}:E({...e,buffered:n})}function O(e,t){switch(t.type){case`stale`:return{...e,synced:!1};case`error`:return{...e,hydrating:!1,synced:!1,error:t.error};case`snapshot-start`:return{...e,hydrating:!0,synced:!1,error:null};case`event`:return D(e,t.event);case`snapshot`:{let n=t.snapshot;if(n.session.sessionId!==e.sessionId||n.sequence<e.cursor)return{...e,hydrating:!1,synced:!1,needsSnapshot:!0};let r=S([...n.items]);return E(w({...e,session:n.session,items:r,permissions:n.pendingPermissions,cursor:n.sequence,hydrated:!0,hydrating:!1,synced:!0,needsSnapshot:!1,hasOlder:n.truncated,beforeSequence:r[0]?.firstSequence??null,error:null}))}case`page`:{let n=e;for(let e of t.page.events)n=D(n,e);let r=n.cursor>=t.page.throughSequence&&!n.buffered.length&&!n.needsSnapshot;return{...n,synced:r,error:r?null:n.error}}case`history`:{let n=new Set(e.items.map(e=>e.itemId)),r=S([...e.items,...t.page.items.filter(e=>!n.has(e.itemId))]);return r.length>v||C(r)>y?{...e,error:`Older history exceeds the display capacity. Reload to return to recent items.`}:{...e,items:r,hasOlder:t.page.hasMore,beforeSequence:t.page.beforeSequence}}}}var k=`cli-jaw:code-drafts:v1`,A=`cli-jaw:code-draft-warnings:v1`,j=1,M=4,ee=32,te=262144,N=1048576,ne=2097152,P=`Draft recovery is unavailable in this tab. Your current text remains in memory.`,re=`Draft recovery is incomplete: some recent text or request state was not saved for reload. Check your draft before sending.`,F=`Draft recovery is incomplete: some text was not saved for reload because this tab reached its recovery limit.`,I=e=>!!e&&typeof e==`object`&&!Array.isArray(e),L=(e,t)=>typeof e==`string`&&e.length<=t,R=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0;function z(e){if(!I(e)||!L(e.input,te)||!R(e.edit)||!R(e.selectionEdit)||typeof e.creating!=`boolean`)return null;let t=e.selection;if(!I(t)||![`codex-app`,`claude`,`cursor`,`grok`].includes(String(t.provider))||!L(t.cwd,4096)||!L(t.model,1024)||!(t.effort===null||L(t.effort,80))||![`ask`,`auto`,`read-only`].includes(String(t.permissionMode)))return null;let n=e.retry,r=e.stop;return n!==null&&(!I(n)||!L(n.text,te)||!L(n.key,240)||!n.key||!R(n.edit)||n.edit>e.edit)||r!==null&&(!I(r)||!L(r.turnId,240)||!r.turnId||!R(r.epoch))?null:{input:e.input,edit:e.edit,selectionEdit:e.selectionEdit,creating:e.creating,selection:{provider:t.provider,cwd:t.cwd,model:t.model,effort:t.effort,permissionMode:t.permissionMode},retry:n===null?null:{text:n.text,key:n.key,edit:n.edit,...n.resend===!0?{resend:!0}:{}},stop:r===null?null:{turnId:r.turnId,epoch:r.epoch}}}function ie(e){if(e===null)return{version:j,endpoints:[]};if(e.length>ne)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!I(t)||t.version!==j||!Array.isArray(t.endpoints)||t.endpoints.length>M)return null;let n=[];for(let e of t.endpoints){if(!I(e)||!L(e.endpoint,2048)||!(e.selectedId===null||L(e.selectedId,240))||!Array.isArray(e.sessions)||e.sessions.length>ee)return null;let t=z(e.fresh);if(!t||t.retry||t.stop)return null;let r=[];for(let t of e.sessions){if(!I(t)||!L(t.id,240)||!t.id)return null;let e=z(t.draft);if(!e||e.creating||r.some(e=>e.id===t.id))return null;r.push({id:t.id,draft:e})}if(e.selectedId!==null&&!r.some(t=>t.id===e.selectedId)||n.some(t=>t.endpoint===e.endpoint)||JSON.stringify(e).length>N)return null;n.push({endpoint:e.endpoint,selectedId:e.selectedId,fresh:t,sessions:r})}return{version:j,endpoints:n}}function ae(e){let t=e.getItem(A);if(!t||t.length>16384)return[];try{let e=JSON.parse(t);return Array.isArray(e)&&e.length<=M&&e.every(e=>L(e,2048))?e:[]}catch{return[]}}function B(e,t,n){try{let r=ae(e).filter(e=>e!==t);n&&r.push(t),r.length?e.setItem(A,JSON.stringify(r.slice(-4))):e.removeItem(A)}catch{}}function oe(){if(typeof window>`u`)return{storage:null,warning:null};try{return{storage:window.sessionStorage,warning:null}}catch{return{storage:null,warning:P}}}function se(e,t){try{let n=ie(e.getItem(k));if(!n)return{data:null,warning:`Saved Code drafts could not be read. No saved requests were sent.`};let r=n.endpoints.find(e=>e.endpoint===t)??null,i=ae(e);return{data:r,warning:i.includes(t)||!r&&i.length>0?re:null}}catch{return{data:null,warning:P}}}function ce(e){let{provider:t,cwd:n,model:r,effort:i,permissionMode:a}=e.selection;return z({input:e.input,edit:e.edit,selection:{provider:t,cwd:n,model:r,effort:i,permissionMode:a},selectionEdit:e.selectionEdit,creating:e.createUnknown||e.operation.kind===`creating`,retry:e.retry?{text:e.retry.text,key:e.retry.key,edit:e.retry.edit,...e.retry.resend?{resend:!0}:{}}:null,stop:e.stopTarget?{turnId:e.stopTarget.turnId,epoch:e.stopTarget.epoch}:null})}function le(e,t,n){try{let r=ce(n.fresh);if(!r)return B(e,t,!0),F;let i={endpoint:t,selectedId:null,fresh:r,sessions:[]},a=!1,o=[...n.sessions].sort(([e],[t])=>Number(t===n.selectedId)-Number(e===n.selectedId));for(let[r,s]of o){if(r!==n.selectedId&&!s.input&&!s.retry&&!s.stopTarget)continue;let o=ce(s);if(!o)return B(e,t,!0),F;if(i.sessions.length>=ee){a=!0;continue}let c={...i,selectedId:r===n.selectedId?r:i.selectedId,sessions:[...i.sessions,{id:r,draft:o}]};if(JSON.stringify(c).length>N){a=!0;continue}i.sessions=c.sessions,i.selectedId=c.selectedId}if(n.selectedId!==null&&i.selectedId===null||JSON.stringify(i).length>N)return B(e,t,!0),F;let s=e.getItem(k),c=[...(ie(s)??{version:j,endpoints:[]}).endpoints.filter(e=>e.endpoint!==t),i],l=JSON.stringify({version:j,endpoints:c});for(;c.length>M||l.length>ne;){let t=c.shift();t&&B(e,t.endpoint,!0),l=JSON.stringify({version:j,endpoints:c})}return l!==s&&e.setItem(k,l),B(e,t,a||n.recoveryWarning!==null),a?F:null}catch{return B(e,t,!0),P}}var ue=new Map,de=new WeakMap;function V(e){return{input:``,edit:0,selection:{...e},selectionEdit:0,operation:{kind:`idle`,error:null},retry:null,createUnknown:!1,requiredSequence:0,stopTarget:null,permissionOperations:{}}}function fe(e){let t=V(e.selection);return t.input=e.input,t.edit=e.edit,t.selectionEdit=e.selectionEdit,t.createUnknown=e.creating,t.retry=e.retry,e.creating&&(t.operation={kind:`creating`,error:`Creation was interrupted by reload. The original session may exist; no request has been retried.`}),e.retry&&(t.operation={kind:`unknown-send`,error:e.retry.resend?`The original attempt ended on the server without running. The message was not resent; Retry will submit it as a new message.`:`The original message has not been reconciled after reload. It will not be sent automatically.`}),e.stop&&(t.stopTarget={...e.stop,outcome:`unknown`},t.operation={kind:`stopping`,error:`Checking the captured Stop after reload. No cancellation has been resent.`}),t}function pe(e,t){let n=oe(),r=n.storage?de.get(n.storage):ue;r||(r=new Map,de.set(n.storage,r));let i=r.get(e);if(!i){let a=n.storage?se(n.storage,e):{data:null,warning:n.warning};i={endpoint:e,storage:n.storage,storageWarning:n.warning,recoveryWarning:a.warning,selectedId:a.data?.selectedId??null,navigation:0,fresh:a.data?fe(a.data.fresh):V({provider:`codex-app`,cwd:t,model:``,effort:null,permissionMode:`ask`}),sessions:new Map(a.data?.sessions.map(e=>[e.id,fe(e.draft)])??[]),listeners:new Set},r.set(e,i)}return i}function me(e){e.storage&&(e.storageWarning=le(e.storage,e.endpoint,e))}function he(e){return{provider:e.provider,cwd:e.cwd,model:e.model,effort:e.effort,permissionMode:e.permissionMode}}function ge(e,t,n=!1){let r=e.providers.find(e=>e.id===t.provider);if(!r)return t;let i=r.capabilities;return{...t,model:!n&&r.models.includes(t.model)?t.model:r.defaultModel,effort:!n&&t.effort!==null&&i.efforts.includes(t.effort)?t.effort:null,permissionMode:i.permissions?!n&&i.permissionModes.includes(t.permissionMode)?t.permissionMode:i.permissions&&i.permissionModes.includes(`ask`)?`ask`:i.permissionModes.includes(`auto`)?`auto`:`read-only`:`auto`}}function H(e,t){e.retry?.key===t&&(e.edit===e.retry.edit&&(e.input=``,e.edit++),e.retry=null,(e.operation.kind===`sending`||e.operation.kind===`unknown-send`)&&(e.operation={kind:`idle`,error:null}))}var _e=`pending:user`;function ve(e,t,n=Date.now()){let r=e.retry;if(!r||r.resend||t.some(e=>e.kind===`user_message`&&e.clientTurnKey===r.key))return null;let i=e.operation.kind===`unknown-send`;return{itemId:_e,turnId:null,kind:`user_message`,status:`pending`,text:r.text,clientTurnKey:r.key,firstSequence:2**53-1,createdAt:n,updatedAt:n,...i?{phase:`unknown`}:{}}}function ye(e,t,n=Date.now()){let r=ve(e,t,n);return r?[...t,r]:t}var be=6,U=1e3,xe=100,Se=32,Ce=150,W=e=>e instanceof p?e.message:`Connection lost. Refresh to check the current state.`,G=e=>e instanceof p&&e.status>=400&&e.status<500,K=(e,t)=>!t||e.epoch>t.epoch||e.epoch===t.epoch&&(e.sequence>t.sequence||e.sequence===t.sequence&&e.revision>=t.revision),we=e=>e===`failed`||e===`cancelled`;function Te(e,t){let n=e?.items.find(e=>e.kind===`user_message`&&e.clientTurnKey===t);return n?e.items.some(e=>e.turnId===n.turnId&&(e.kind===`turn_failed`||e.kind===`turn_cancelled`)):!1}var Ee=class{client;book;details=new Map;summaries=new Map;attention=new Map;rows=[];catalog=null;catalogError=null;transport=`disconnected`;filter={scope:`all`,archived:!1};workingDir;gitInfo=null;gitError=null;gitGeneration=0;pickerGeneration=0;indexGeneration=0;catalogGeneration=0;lifetime=0;active=!1;abort=new AbortController;syncing=new Map;detailReads=new Map;historyLoading=new Set;indexLoading=!1;moreSessions=!1;offset=0;indexError=null;timer;listeners=new Set;model;draftSyncQueued=!1;constructor(e){this.client=h(e.port),this.workingDir=e.workingDir,this.book=pe(m(e.port),e.workingDir),this.model=this.makeModel()}getModel=()=>this.model;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));changed=()=>{this.model=this.makeModel();for(let e of this.listeners)e();let e=this.book.selectedId,t=e?this.details.get(e):void 0;this.active&&e&&!t?.error&&(!t||this.draft(e).requiredSequence>t.cursor)&&!this.draftSyncQueued&&(this.draftSyncQueued=!0,queueMicrotask(()=>{this.draftSyncQueued=!1,this.active&&this.book.selectedId===e&&!this.syncing.has(e)&&this.sync(e)}))};notify(){me(this.book),this.changed();for(let e of this.book.listeners)e!==this.changed&&e()}mount=()=>(this.active=!0,this.lifetime++,this.abort=new AbortController,this.book.listeners.add(this.changed),this.refresh(),()=>{me(this.book),this.active=!1,this.lifetime++,this.abort.abort(),this.syncing.clear();for(let e of this.detailReads.values())e.abort();this.detailReads.clear(),this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,this.book.listeners.delete(this.changed),this.details.clear(),this.summaries.clear(),this.attention.clear(),this.rows=[],this.gitGeneration++,this.pickerGeneration++});setWorkingDir(e){if(e===this.workingDir)return;this.workingDir=e;let t=this.book.fresh;!t.selectionEdit&&!t.input&&t.operation.kind===`idle`&&!t.createUnknown&&(t.selection={...t.selection,cwd:e}),this.filter.scope===`cwd`&&this.readIndex(),this.readGit(),this.notify()}draft(e=this.book.selectedId){if(e===null)return this.book.fresh;let t=this.book.sessions.get(e);if(!t){let n=this.info(e);t=V(n?he(n):this.book.fresh.selection),this.book.sessions.set(e,t)}return t}info(e){if(!e)return null;let t=this.details.get(e)?.session,n=this.summaries.get(e);return n&&K(n,t)?n:t??n??null}observe(e){let t=this.attention.get(e.sessionId);(!t||K(e,{...e,epoch:t.epoch,sequence:t.sequence,revision:t.revision}))&&this.attention.set(e.sessionId,{epoch:e.epoch,sequence:e.sequence,revision:e.revision,...e.pendingPermissionCount===void 0?{}:{pendingPermissionCount:e.pendingPermissionCount},...e.contextUsage===void 0?{}:{contextUsage:e.contextUsage}})}resolve(e,t){let n=this.attention.get(e),{contextUsage:r,pendingPermissionCount:i,...a}=t;return{...a,...n?.pendingPermissionCount===void 0?{}:{pendingPermissionCount:n.pendingPermissionCount},...n?.contextUsage===void 0?{}:{contextUsage:n.contextUsage}}}accept(e){if(!this.active||!K(e,this.info(e.sessionId)))return;let{contextUsage:t,pendingPermissionCount:n,...r}=e;if(this.summaries.set(r.sessionId,r),this.summaries.size>1006){let e=[...this.summaries.keys()].find(e=>e!==this.book.selectedId&&!this.details.has(e)&&!this.rows.includes(e));e&&(this.summaries.delete(e),this.attention.delete(e))}let i=this.book.sessions.get(r.sessionId);i?.stopTarget&&(r.turnId!==i.stopTarget.turnId||r.epoch!==i.stopTarget.epoch||!x(r))&&(i.stopTarget=null,i.operation.kind===`stopping`&&(i.operation=i.retry?{kind:`unknown-send`,error:`The original message still needs reconciliation.`}:{kind:`idle`,error:null}))}state(e){let t=this.details.get(e);return t||(t=b(e),this.details.set(e,t),this.trimDetails()),t}trimDetails(){for(let e of this.details.keys()){if(this.details.size<=be)break;e!==this.book.selectedId&&(this.details.delete(e),this.detailReads.get(e)?.abort(),this.detailReads.delete(e),this.syncing.delete(e))}}update(e,t){this.details.set(e,t),t.session&&this.accept(t.session);let n=this.book.sessions.get(e);if(n?.retry&&t.items.some(e=>e.kind===`user_message`&&e.clientTurnKey===n.retry.key)&&(Te(t,n.retry.key)?this.requireNewKey(n):H(n,n.retry.key)),n&&t.synced){let e=new Set(t.permissions.map(e=>e.permissionId));for(let t of Object.keys(n.permissionOperations))!e.has(t)&&!n.permissionOperations[t].pending&&delete n.permissionOperations[t]}this.notify()}requireNewKey(e){e.retry&&(e.retry={...e.retry,key:crypto.randomUUID(),resend:!0},e.operation={kind:`unknown-send`,error:`The original attempt ended on the server without running. The message was not resent; Retry will submit it as a new message.`})}makeModel(){let e=this.book.selectedId,t=this.info(e),n=this.draft(e),r=e?this.details.get(e):void 0,i=(e,t)=>{let n=this.resolve(e.sessionId,e);return t?.synced?{...n,pendingPermissionCount:t.permissions.length}:n},a=t&&i(t,r),o=n.operation,s=this.book.storageWarning??this.book.recoveryWarning,c=[`creating`,`sending`,`stopping`,`resuming`,`patching`].includes(o.kind)&&!o.error,l=e===null?!!this.catalog:!!r?.synced&&(!a||a.sequence<=r.cursor)&&n.requiredSequence<=(r?.cursor??0);return{catalog:this.catalog,sessions:this.rows.map(e=>{let t=this.info(e),n=this.details.get(e);return t&&i(t,n)}).filter(e=>!!e),selectedId:e,session:a,items:ye(n,r?.items??[]),permissions:r?.permissions??[],input:n.input,selection:a?he(a):n.selection,gitInfo:this.gitInfo,loading:this.indexLoading||!!r?.hydrating||!!e&&!r?.hydrated&&!r?.error,pending:c,busy:x(a),synced:l,transport:this.transport,error:[o.error??r?.error??this.indexError??this.catalogError??this.gitError??a?.error?.message,s].filter(Boolean).join(` `)||null,operation:{...o,error:o.error&&s?`${o.error} ${s}`:o.error},retryText:n.retry?.text??null,canRetrySameSend:!!e&&o.kind===`unknown-send`&&!!n.retry&&l&&a?.archivedAt===null,resendRequired:!!n.retry?.resend,permissionOperations:{...n.permissionOperations},hasMoreSessions:this.moreSessions,hasOlderHistory:r?.hasOlder??!1,filter:this.filter,creationUnknown:e===null&&n.createUnknown,startAnotherSession:this.startAnotherSession,newSession:this.newSession,selectSession:this.selectSession,setInput:this.setInput,setSelection:this.setSelection,pickWorkspace:this.pickWorkspace,send:this.send,retrySameSend:this.retrySameSend,stop:this.stop,resume:this.resume,rename:this.rename,archive:this.archive,answer:this.answer,refresh:this.refresh,loadMoreSessions:this.loadMoreSessions,loadOlderHistory:this.loadOlderHistory,setFilter:this.setFilter,clearError:this.clearError}}async readCatalog(){let e=++this.catalogGeneration,t=this.lifetime;try{let n=await this.client.listModelOptions(this.abort.signal);if(!this.active||t!==this.lifetime||e!==this.catalogGeneration)return;this.catalog=n,this.catalogError=null;let r=this.book.fresh;!r.selection.model&&!r.selectionEdit&&r.operation.kind===`idle`&&(r.selection=ge(n,{...r.selection,provider:n.defaultProvider})),this.notify()}catch(n){this.active&&t===this.lifetime&&e===this.catalogGeneration&&(this.catalogError=W(n),this.notify())}}async readIndex(e=!1){let t=++this.indexGeneration,n=this.lifetime,r=e?this.offset:0,i=e?xe:Math.min(U,Math.max(xe,this.offset));this.indexLoading=!0,this.notify();try{let a=await this.client.listSessions({...this.filter,limit:i,offset:r,...this.filter.scope===`cwd`?{cwd:this.workingDir}:{}},this.abort.signal);if(!this.active||n!==this.lifetime||t!==this.indexGeneration)return;for(let e of a.sessions){this.observe(e),this.accept(e);let t=this.details.get(e.sessionId);t?.hydrated&&!t.hydrating&&e.sequence>t.cursor&&(this.details.set(e.sessionId,O(t,{type:`stale`})),this.sync(e.sessionId))}this.rows=[...new Set([...e?this.rows:[],...a.sessions.map(e=>e.sessionId)])].slice(0,U),this.offset=a.offset+a.sessions.length,this.moreSessions=a.hasMore&&this.rows.length<U,this.indexError=null;let o=new Set([...this.rows,...this.details.keys(),...this.book.selectedId?[this.book.selectedId]:[]]);for(let e of this.summaries.keys())o.has(e)||(this.summaries.delete(e),this.attention.delete(e))}catch(e){this.active&&n===this.lifetime&&t===this.indexGeneration&&(this.indexError=W(e))}finally{this.active&&n===this.lifetime&&t===this.indexGeneration&&(this.indexLoading=!1,this.notify())}}scheduleIndex(){this.active&&this.timer===void 0&&(this.timer=setTimeout(()=>{this.timer=void 0,this.readIndex()},Ce))}sync(e,t=!1){let n=this.syncing.get(e);if(n)return n;let r=this.lifetime,i=new AbortController;this.detailReads.set(e,i),this.state(e);let a=()=>this.active&&r===this.lifetime&&this.detailReads.get(e)===i&&this.details.has(e),o=(async()=>{let n=0,r=null;try{for(let o=0;o<Se&&a();o++){let o=this.state(e);if(t||!o.hydrated||o.needsSnapshot){if(++n>2)throw Error(`snapshot did not cover live updates`);t=!1,this.update(e,O(o,{type:`snapshot-start`}));let s=this.book.sessions.get(e)?.stopTarget,c=s?.outcome===`unknown`?s:null,l=await this.client.snapshot(e,i.signal);if(!a())return;r=c,this.observe(l.session),this.update(e,O(this.state(e),{type:`snapshot`,snapshot:l}))}if(o=this.state(e),o.needsSnapshot)continue;let s=o.cursor,c=await this.client.events(e,s,i.signal);if(!a())return;let l=O(this.state(e),{type:`page`,page:c});if(this.update(e,l),!l.needsSnapshot){if(l.synced&&l.cursor>=(this.book.sessions.get(e)?.requiredSequence??0)){this.reconcileStop(e,r);return}if(l.cursor<=s){t=!0;continue}}}a()&&this.update(e,O(this.state(e),{type:`error`,error:`History is still catching up. Refresh to continue.`}))}catch(t){if(!a())return;if(t instanceof p&&t.code===`invalid_sequence`&&n<2){let t=await this.client.snapshot(e,i.signal).catch(()=>null);if(!a())return;if(t){this.update(e,O(this.state(e),{type:`snapshot`,snapshot:t}));return}}this.update(e,O(this.state(e),{type:`error`,error:W(t)})),t instanceof p&&t.code===`session_not_found`&&this.scheduleIndex()}})().finally(()=>{this.syncing.get(e)===o&&this.syncing.delete(e),this.detailReads.get(e)===i&&this.detailReads.delete(e),this.trimDetails()});return this.syncing.set(e,o),o}onEvent=e=>{if(!this.active)return;e.session?.sessionId===e.sessionId&&this.accept(e.session),(e.event===`code_session`||e.item?.kind===`permission_request`||e.update?.status)&&this.scheduleIndex();let t=this.book.sessions.get(e.sessionId);e.item?.kind===`user_message`&&e.item.clientTurnKey&&t?.retry?.key===e.item.clientTurnKey&&(t.requiredSequence=Math.max(t.requiredSequence,e.sequence),Te(this.details.get(e.sessionId),e.item.clientTurnKey)?this.requireNewKey(t):H(t,e.item.clientTurnKey));let n=this.details.get(e.sessionId);if(!n){this.notify();return}let r=O(n,{type:`event`,event:e});this.update(e.sessionId,r),!r.synced&&!r.hydrating&&this.sync(e.sessionId)};onTransport=e=>{this.transport=e;for(let[e,t]of this.details)this.details.set(e,O(t,{type:`stale`}));if(this.notify(),e===`connected`&&this.active){this.readIndex();for(let e of this.details.keys())this.sync(e,!0)}};refresh=async()=>{let e=this.book.selectedId;await Promise.all([this.readCatalog(),this.readIndex(),e?this.sync(e,!0):Promise.resolve(),this.readGit()])};loadMoreSessions=async()=>{this.moreSessions&&!this.indexLoading&&await this.readIndex(!0)};setFilter=e=>{this.filter={...e},this.offset=0,this.rows=[],this.moreSessions=!1,this.notify(),this.readIndex()};startAnotherSession=()=>{let e=this.book.fresh;if(this.book.selectedId!==null||!e.createUnknown)return;let t=V(e.selection);t.input=e.input,t.edit=e.edit,t.selectionEdit=e.selectionEdit,t.operation.error=`The original session may still exist. Your text is preserved; Send will create another session.`,this.book.fresh=t,this.book.navigation++,this.pickerGeneration++,this.notify()};newSession=()=>{this.book.selectedId=null,this.book.navigation++,this.gitInfo=null,this.notify(),this.readGit()};selectSession=async e=>{this.book.selectedId=e,this.book.navigation++,this.draft(e),this.state(e),this.gitInfo=null,this.notify(),await this.sync(e,!0),this.book.selectedId===e&&await this.readGit()};setInput=e=>{let t=this.draft();t.input=e,t.edit++,this.notify()};clearError=()=>{let e=this.draft();e.operation.kind===`idle`&&(e.operation={kind:`idle`,error:null}),this.indexError=null,this.book.recoveryWarning=null,this.notify()};async readGit(){let e=++this.gitGeneration,t=this.lifetime,n=this.book.selectedId,r=this.info(n)?.cwd??(n===null?this.book.fresh.selection.cwd:``);if(this.gitInfo=null,this.gitError=null,r&&this.active)try{let i=await this.client.getGitInfo(r,this.abort.signal);this.active&&t===this.lifetime&&e===this.gitGeneration&&n===this.book.selectedId&&(this.gitInfo=i,this.notify())}catch(r){this.active&&t===this.lifetime&&e===this.gitGeneration&&n===this.book.selectedId&&(this.gitError=W(r),this.notify())}}pickWorkspace=async()=>{let e=this.book.fresh;if(this.book.selectedId!==null||e.operation.kind!==`idle`||e.createUnknown)return;let t=this.book.navigation,n=e.selectionEdit,r=++this.pickerGeneration;try{let i=await this.client.pickWorkspace();if(!this.active||r!==this.pickerGeneration||t!==this.book.navigation||n!==e.selectionEdit||e!==this.book.fresh||e.operation.kind!==`idle`)return;!i.cancelled&&i.path&&(e.selection={...e.selection,cwd:i.path},e.selectionEdit++,this.notify(),await this.readGit())}catch(i){this.active&&r===this.pickerGeneration&&t===this.book.navigation&&n===e.selectionEdit&&e===this.book.fresh&&e.operation.kind===`idle`&&(e.operation.error=W(i),this.notify())}};setSelection=async e=>{let t=this.book.selectedId,n=this.info(t);if(n&&e.provider&&e.provider!==n.provider){this.newSession(),await this.setSelection({...e,cwd:n.cwd});return}let r=this.draft();if(r.operation.kind!==`idle`||r.createUnknown)return;if(n&&t){if(e.cwd!==void 0&&e.cwd!==n.cwd||e.provider&&e.provider!==n.provider){r.operation.error=`Runtime and workspace are fixed for this session. Create a new session to change them.`,this.notify();return}if(n.status!==`idle`||!this.model.synced||n.archivedAt!==null){r.operation.error=`Wait for this session to be idle and synchronized before changing settings.`,this.notify();return}await this.patch(t,{model:e.model??n.model,effort:e.effort===void 0?n.effort:e.effort,permissionMode:e.permissionMode??n.permissionMode});return}if(t)return;let i=e.provider!==void 0&&e.provider!==r.selection.provider,a={...r.selection,...e};this.catalog&&i&&(a=ge(this.catalog,a,!0));let o=this.catalog?.providers.find(e=>e.id===a.provider);a.effort!==null&&o&&!o.capabilities.efforts.includes(a.effort)&&(a.effort=null),r.selection=a,r.selectionEdit++,this.notify(),e.cwd!==void 0&&await this.readGit()};async patch(e,t,n=!1){let r=this.draft(e),i=this.info(e);if(!i||r.operation.kind!==`idle`||x(i)){let e=Error(i?`Wait for the current session action to finish before changing it.`:`Refresh this session before changing it.`);if(r.operation.error=e.message,this.notify(),n)throw e;return}let a=null;r.operation={kind:`patching`,error:null},this.notify();try{this.accept(await this.client.patchSession(e,{...t,expectedRevision:i.revision})),r.operation={kind:`idle`,error:null}}catch(t){t instanceof p&&t.session?.sessionId===e&&(this.observe(t.session),this.accept(t.session)),a=t instanceof p?t:Error(W(t)),r.operation={kind:`idle`,error:a.message}}if(this.notify(),this.scheduleIndex(),this.active&&await this.sync(e,!0),n&&a)throw a}rename=async(e,t)=>{await this.patch(e,{title:t},!0)};archive=async(e,t)=>{await this.patch(e,{archived:t},!0)};send=async()=>{let e=this.book.selectedId,t=this.draft(e);if(t.operation.kind!==`idle`||t.createUnknown||!t.input.trim())return;let n=this.info(e);if(e&&(!n||n.status!==`idle`||n.archivedAt!==null||!this.model.synced)){t.operation.error=`Wait for the session to be idle and synchronized before sending.`,this.notify();return}let r={text:t.input,edit:t.edit,key:crypto.randomUUID()},i=this.book.navigation;if(!e){let n={...t.selection},r=this.catalog?.providers.find(e=>e.id===n.provider);if(!r?.available||!n.cwd.trim()||!r.models.includes(n.model)||!r.capabilities.permissionModes.includes(n.permissionMode)||n.effort!==null&&!r.capabilities.efforts.includes(n.effort)){t.operation.error=`Choose an available runtime, workspace, model and supported settings before sending.`,this.notify();return}t.operation={kind:`creating`,error:null},this.notify();try{let r=await this.client.createSession(n);e=r.sessionId,this.book.sessions.set(e,t),this.book.fresh===t&&(this.book.fresh=V(n)),this.book.navigation===i&&this.book.selectedId===null&&(this.book.selectedId=e,this.book.navigation++),this.accept(r),this.active&&this.state(e),this.scheduleIndex()}catch(e){t.createUnknown=!G(e),t.operation={kind:t.createUnknown?`creating`:`idle`,error:t.createUnknown?`Session creation could not be confirmed. The original session may exist. Refresh the list, or choose Start another session to keep this text in a new draft.`:W(e)},this.notify(),this.scheduleIndex();return}}t=this.draft(e),t.retry=r,await this.submit(e,t)};async submit(e,t){let n=t.retry;if(n){t.operation={kind:`sending`,error:null},this.notify();try{let r=await this.client.sendPrompt(e,{text:n.text,clientTurnKey:n.key});if(r.clientTurnKey!==n.key)throw Error(`Mismatched prompt receipt`);t.requiredSequence=Math.max(t.requiredSequence,r.sequence);let i=this.details.get(e);i&&this.details.set(e,O(i,{type:`stale`})),we(r.status)?this.requireNewKey(t):H(t,n.key)}catch(e){t.retry?.key===n.key&&(t.operation={kind:G(e)?`idle`:`unknown-send`,error:G(e)?W(e):`Message acceptance is unknown. Refresh, or explicitly retry the original message with the same key.`},G(e)&&(t.retry=null))}this.notify(),this.scheduleIndex(),this.active&&await this.sync(e,!0)}}retrySameSend=async()=>{let e=this.book.selectedId,t=this.draft(e);e&&this.model.canRetrySameSend&&t.operation.kind===`unknown-send`&&await this.submit(e,t)};reconcileStop(e,t){let n=this.book.sessions.get(e),r=this.details.get(e),i=this.info(e);!t||t.outcome!==`unknown`||n?.stopTarget!==t||!r?.synced||!i||i.sequence>r.cursor||i.turnId!==t.turnId||i.epoch!==t.epoch||(i.status===`starting`||i.status===`streaming`?(t.outcome=`retryable`,n.operation={kind:n.retry?`unknown-send`:`idle`,error:`Stop could not be confirmed. The same turn is still running. Press Stop to retry for this turn.`}):i.status===`stopping`&&(t.outcome=`accepted`,n.operation={kind:`stopping`,error:null}),this.notify())}stop=async()=>{let e=this.book.selectedId,t=this.info(e);if(!e||!t?.turnId||!x(t)||!t.capabilities.interrupt||t.status===`stopping`)return;let n=this.draft(e),r=n.stopTarget;if(r&&(r.outcome!==`retryable`||!this.model.synced||r.turnId!==t.turnId||r.epoch!==t.epoch))return;let i=r??{turnId:t.turnId,epoch:t.epoch,outcome:`pending`};i.outcome=`pending`,n.stopTarget=i,n.operation={kind:`stopping`,error:null},this.notify();try{let t=await this.client.cancelPrompt(e,{turnId:i.turnId,epoch:i.epoch});n.stopTarget===i&&(i.outcome=`accepted`),this.accept(t)}catch(e){n.stopTarget===i&&(i.outcome=`unknown`,n.operation={kind:`stopping`,error:W(e)},G(e)&&(n.stopTarget=null,n.operation.kind=`idle`))}this.notify(),this.scheduleIndex(),this.active&&(i.outcome===`unknown`&&await this.syncing.get(e),this.active&&await this.sync(e,!0))};resume=async()=>{let e=this.book.selectedId,t=this.info(e),n=this.draft(e);if(e&&t&&this.model.synced&&n.operation.kind===`idle`&&t.archivedAt===null&&[`suspended`,`failed`].includes(t.status)&&t.capabilities.resume&&t.resume.available&&(t.status!==`failed`||t.error?.recoverable)){n.operation={kind:`resuming`,error:null},this.notify();try{this.accept(await this.client.attachSession(e)),n.operation={kind:`idle`,error:null}}catch(e){n.operation={kind:`idle`,error:W(e)}}this.notify(),this.scheduleIndex(),this.active&&await this.sync(e,!0)}};answer=async(e,t)=>{let n=e.sessionId,r=this.details.get(n),i=this.info(n),a=this.draft(n);if(a.permissionOperations[e.permissionId]?.pending)return;let o=r?.permissions.find(t=>t.permissionId===e.permissionId);if(!r?.synced||!i||i.sequence>r.cursor||!o||o.turnId!==e.turnId||o.epoch!==e.epoch||i.turnId!==e.turnId||i.epoch!==e.epoch||!o.options.some(e=>e.optionId===t)){a.permissionOperations[e.permissionId]={pending:!1,error:`This approval is no longer current. Refresh its status.`},this.notify(),this.active&&await this.sync(n,!0);return}a.permissionOperations[e.permissionId]={pending:!0,error:null},this.notify();try{await this.client.answerPermission(e.permissionId,{sessionId:n,turnId:e.turnId,epoch:e.epoch,optionId:t}),a.permissionOperations[e.permissionId]={pending:!0,error:null}}catch(t){a.permissionOperations[e.permissionId]={pending:!0,error:W(t)}}this.notify(),this.scheduleIndex(),this.active&&await this.sync(n,!0);let s=this.details.get(n),c=!s?.synced||s.permissions.some(t=>t.permissionId===e.permissionId),l=a.permissionOperations[e.permissionId];c&&l?a.permissionOperations[e.permissionId]={pending:!1,error:l.error}:delete a.permissionOperations[e.permissionId],this.notify()};loadOlderHistory=async()=>{let e=this.book.selectedId;if(!e||this.historyLoading.has(e))return;let t=this.details.get(e);if(!t?.hydrated||!t.hasOlder||t.beforeSequence===null)return;let n=this.lifetime;this.historyLoading.add(e);try{let r=await this.client.history(e,t.beforeSequence,this.abort.signal);this.active&&n===this.lifetime&&this.details.get(e)?.beforeSequence===t.beforeSequence&&this.update(e,O(this.state(e),{type:`history`,page:r}))}catch(t){this.active&&n===this.lifetime&&(this.draft(e).operation.error=W(t),this.notify())}finally{this.historyLoading.delete(e)}}};function De({port:e,onEvent:t,onTransport:n}){let r=(0,u.useRef)({onEvent:t,onTransport:n});r.current={onEvent:t,onTransport:n},(0,u.useEffect)(()=>{if(!e)return;let t=!0,n=new EventSource(`${m(e)}/api/events`);return n.onopen=()=>{t&&r.current.onTransport?.(`connected`)},n.onmessage=e=>{if(!t)return;let n;try{n=JSON.parse(e.data)}catch{return}n?.topic!==`code`||typeof n.sessionId!=`string`||!Number.isSafeInteger(n.sequence)||n.sequence<1||!Number.isSafeInteger(n.epoch)||(n.event===`code_item`||n.event===`code_item_update`||n.event===`code_session`)&&r.current.onEvent(n)},n.onerror=()=>{t&&r.current.onTransport?.(n.readyState===EventSource.CLOSED?`disconnected`:`reconnecting`)},()=>{t=!1,n.close()}},[e])}function Oe({port:e,workingDir:t}){let n=m(e),r=(0,u.useMemo)(()=>new Ee({port:e,workingDir:t}),[n,e]);return(0,u.useEffect)(()=>r.mount(),[r]),(0,u.useEffect)(()=>r.setWorkingDir(t),[r,t]),De({port:e,onEvent:r.onEvent,onTransport:r.onTransport}),(0,u.useSyncExternalStore)(r.subscribe,r.getModel,r.getModel)}var q={"codex-app":`Codex`,claude:`Claude`,cursor:`Cursor`,grok:`Grok`},ke={ask:`Ask first`,auto:`Auto (YOLO)`,"read-only":`Read only`},Ae={ask:`Review native permission requests before allowing actions.`,auto:`The native runtime may execute actions without asking for approval.`,"read-only":`The native runtime restricts actions to read-only access.`},je={idle:`Ready`,starting:`Starting`,streaming:`Running`,stopping:`Stopping`,suspended:`Suspended`,failed:`Runtime failed`};function Me(e){return e.status===`starting`||e.status===`streaming`||e.status===`stopping`}function Ne(e){return e.archivedAt===null&&e.capabilities.resume&&e.resume.available&&(e.status===`suspended`||e.status===`failed`&&e.error?.recoverable===!0)}function Pe(e){return e.kind===`turn_cancelled`||e.status===`cancelled`?`Stopped`:e.kind===`turn_failed`||e.status===`error`?`Failed`:e.kind===`turn_completed`?`Completed`:{pending:`Pending`,running:`Running`,done:`Done`,error:`Failed`,cancelled:`Stopped`}[e.status]}function Fe(e){return e.archivedAt===null?`active`:`archived`}function Ie(e,t){return t.createdAt-e.createdAt||e.sessionId.localeCompare(t.sessionId)}function Le(e){let t=e.filter(e=>Fe(e)===`active`).sort(Ie),n=e.filter(e=>Fe(e)===`archived`).sort((e,t)=>(t.archivedAt??t.createdAt)-(e.archivedAt??e.createdAt)||e.sessionId.localeCompare(t.sessionId)),r=[];return t.length&&r.push({section:`active`,sessions:t}),n.length&&r.push({section:`archived`,sessions:n}),r}function Re(e){return e===void 0?{kind:`unknown`}:e>0?{kind:`approvals`,count:e}:{kind:`none`}}function ze(e){return e.kind===`unknown`?`Approval status unknown`:e.kind===`none`?`No pending approvals`:`${e.count} pending approval${e.count===1?``:`s`}`}var J=l();function Be({session:e,controller:t}){let[n,r]=(0,u.useState)(!1),[i,a]=(0,u.useState)(e.title??``),[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(null),d=(0,u.useRef)(!1),f=(0,u.useRef)(null),p=(0,u.useId)(),m=t.selectedId===e.sessionId,h=Me(e),g=Re(m&&t.synced?t.permissions.length:e.pendingPermissionCount);async function _(e,t){if(!d.current){d.current=!0,s(!0),l(null);try{await e(),t?.()}catch(e){l(e instanceof Error?e.message:String(e))}finally{d.current=!1,s(!1)}}}function v(){r(!1),f.current?.focus()}return(0,J.jsxs)(`li`,{className:`code-session-row`,children:[(0,J.jsxs)(`button`,{ref:f,type:`button`,className:`code-session-item${m?` active`:``}`,"aria-current":m?`true`:void 0,onClick:()=>void _(()=>t.selectSession(e.sessionId)),children:[(0,J.jsx)(`span`,{className:`code-session-cwd`,children:e.title||`Untitled session`}),(0,J.jsxs)(`span`,{className:`code-session-meta`,title:e.cwd,children:[q[e.provider],` · `,e.cwd]}),(0,J.jsx)(`span`,{className:`code-session-status code-session-status-${e.status}`,"data-quiet":e.status===`idle`?`true`:void 0,children:je[e.status]}),(0,J.jsx)(`span`,{className:`code-session-attention code-session-attention-${g.kind}`,"data-quiet":g.kind===`none`?`true`:void 0,children:ze(g)})]}),n?(0,J.jsxs)(`form`,{className:`code-session-rename`,onSubmit:n=>{n.preventDefault(),i.trim()&&_(()=>t.rename(e.sessionId,i.trim()),v)},children:[(0,J.jsx)(`input`,{autoFocus:!0,"aria-label":`Session title`,"aria-describedby":c?p:void 0,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:t=>{t.key===`Escape`&&!o&&(t.preventDefault(),a(e.title??``),v())}}),(0,J.jsx)(`button`,{type:`submit`,disabled:o||!i.trim(),children:`Save`}),(0,J.jsx)(`button`,{type:`button`,disabled:o,onClick:v,children:`Cancel`})]}):(0,J.jsxs)(`details`,{className:`code-session-actions`,children:[(0,J.jsx)(`summary`,{"aria-label":`Actions for ${e.title||`Untitled session`}`,children:`Actions`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`button`,{type:`button`,disabled:o||h,onClick:()=>{a(e.title??``),r(!0)},children:`Rename`}),(0,J.jsx)(`button`,{type:`button`,disabled:o||h,title:h?`Stop before archiving`:void 0,onClick:()=>void _(()=>t.archive(e.sessionId,e.archivedAt===null)),children:e.archivedAt===null?`Archive`:`Restore`}),Ne(e)&&(0,J.jsx)(`button`,{type:`button`,disabled:o||!m||!t.synced||t.pending,title:m?`Resume without resending a prompt`:`Select this session to resume it`,onClick:()=>void _(t.resume),children:`Resume`}),h&&(0,J.jsx)(`small`,{children:`Stop before changing session metadata.`})]})]},`${t.selectedId}:${e.sessionId}`),o&&(0,J.jsx)(`span`,{className:`code-session-view-hint`,role:`status`,children:`Updating session…`}),c&&(0,J.jsx)(`div`,{id:p,className:`code-session-list-error`,role:`alert`,children:c})]})}function Ve({controller:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(null),[s,c]=(0,u.useState)(!1),l=(0,u.useRef)(!1),d=e.sessions.filter(e=>`${e.title??``} ${e.cwd} ${q[e.provider]}`.toLowerCase().includes(t.toLowerCase())),f=r?[...d.reduce((e,t)=>{let n=e.get(t.cwd)??[];return n.push(t),e.set(t.cwd,n),e},new Map)].map(([e,t])=>({title:e,key:e,sessions:t})):Le(d).map(e=>({key:e.section,title:e.section===`archived`?`Archived`:``,sessions:e.sessions}));async function p(){if(!l.current){l.current=!0,c(!0),o(null);try{await e.loadMoreSessions()}catch(e){o(e instanceof Error?e.message:String(e))}finally{l.current=!1,c(!1)}}}return(0,J.jsxs)(`nav`,{className:`code-session-list`,"aria-label":`Code sessions`,children:[(0,J.jsxs)(`div`,{className:`code-session-list-header`,children:[(0,J.jsx)(`span`,{className:`code-session-list-title`,children:`Sessions`}),(0,J.jsx)(`button`,{type:`button`,className:`code-session-new-btn`,onClick:e.newSession,"aria-label":`New Code session`,children:`+`})]}),(0,J.jsxs)(`div`,{className:`code-session-view-toggle`,"aria-label":`Session view`,children:[(0,J.jsx)(`button`,{type:`button`,"aria-pressed":e.filter.scope===`all`,className:`code-session-view-btn${e.filter.scope===`all`?` active`:``}`,onClick:()=>e.setFilter({...e.filter,scope:`all`}),children:`All`}),(0,J.jsx)(`button`,{type:`button`,"aria-pressed":e.filter.scope===`cwd`,className:`code-session-view-btn${e.filter.scope===`cwd`?` active`:``}`,onClick:()=>e.setFilter({...e.filter,scope:`cwd`}),children:`This cwd`}),(0,J.jsx)(`button`,{type:`button`,"aria-pressed":r,className:`code-session-view-btn${r?` active`:``}`,onClick:()=>i(!r),children:`Group`})]}),(0,J.jsxs)(`label`,{className:`code-session-archive-filter`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:e.filter.archived,onChange:t=>e.setFilter({...e.filter,archived:t.target.checked})}),`Archived`]}),(0,J.jsx)(`input`,{className:`code-session-search`,type:`search`,"aria-label":`Search loaded sessions`,placeholder:`Search loaded sessions…`,value:t,onChange:e=>n(e.target.value)}),(0,J.jsxs)(`button`,{type:`button`,className:`code-session-item${e.selectedId===null?` active`:``}`,"aria-current":e.selectedId===null?`true`:void 0,onClick:e.newSession,children:[(0,J.jsx)(`span`,{className:`code-session-cwd`,children:`New session draft`}),(0,J.jsx)(`span`,{className:`code-session-meta`,children:`Preserved unsent draft`})]}),e.loading&&(0,J.jsx)(`div`,{className:`code-session-list-loading`,role:`status`,children:`Loading sessions…`}),f.map(t=>(0,J.jsxs)(`section`,{className:`code-session-group`,children:[t.title&&(0,J.jsx)(`h3`,{className:`code-session-group-title`,title:t.title,children:t.title}),(0,J.jsx)(`ul`,{className:`code-session-list-items`,children:t.sessions.map(t=>(0,J.jsx)(Be,{session:t,controller:e},t.sessionId))})]},t.key)),!e.loading&&!d.length&&(0,J.jsx)(`p`,{className:`code-session-list-empty`,children:t?`No loaded sessions match. Clear search or load more.`:`No sessions here. Start with the new session draft.`}),e.hasMoreSessions&&(0,J.jsx)(`button`,{type:`button`,className:`code-inline-action`,disabled:s,onClick:()=>void p(),children:s?`Loading…`:`Load more sessions`}),(0,J.jsx)(`button`,{type:`button`,className:`code-inline-action`,onClick:()=>{o(null),e.refresh().catch(e=>o(e instanceof Error?e.message:String(e)))},children:`Refresh sessions`}),a&&(0,J.jsx)(`div`,{className:`code-session-list-error`,role:`alert`,children:a})]})}var He={"codex-app":{viewBox:`0 0 24 24`,rule:`evenodd`,d:`M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z`},claude:{viewBox:`0 0 24 24`,rule:`evenodd`,d:`M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z`},cursor:{viewBox:`675 357 250 286`,d:`M920.015 424.958L805.919 359.086C802.256 356.97 797.735 356.97 794.071 359.086L679.981 424.958C676.901 426.736 675 430.025 675 433.587V566.419C675 569.981 676.901 573.269 679.981 575.048L794.077 640.92C797.74 643.036 802.261 643.036 805.925 640.92L920.02 575.048C923.1 573.269 925.001 569.981 925.001 566.419V433.587C925.001 430.025 923.1 426.736 920.02 424.958H920.015ZM912.848 438.911L802.706 629.682C801.961 630.968 799.995 630.443 799.995 628.954V504.039C799.995 501.543 798.662 499.234 796.498 497.981L688.321 435.526C687.036 434.781 687.561 432.816 689.05 432.816H909.334C912.462 432.816 914.417 436.206 912.853 438.917H912.848V438.911Z`},grok:{viewBox:`0 0 24 24`,rule:`evenodd`,d:`M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815`}};function Ue({provider:e}){let t=He[e];return(0,J.jsx)(`svg`,{className:`code-provider-glyph`,viewBox:t.viewBox,width:`16`,height:`16`,"aria-hidden":`true`,focusable:`false`,fill:`currentColor`,...t.rule?{fillRule:`evenodd`,clipRule:`evenodd`}:{},children:(0,J.jsx)(`path`,{d:t.d})})}function We(){return(0,J.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,"aria-hidden":`true`,focusable:`false`,children:(0,J.jsx)(`path`,{d:`M10 16V4.6M5.2 9.4 10 4.4l4.8 5`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function Ge(){return(0,J.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,"aria-hidden":`true`,focusable:`false`,children:(0,J.jsx)(`rect`,{x:`6`,y:`6`,width:`8`,height:`8`,rx:`1.6`,fill:`currentColor`})})}function Ke({muted:e}){return(0,J.jsxs)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,"aria-hidden":`true`,focusable:`false`,children:[(0,J.jsx)(`path`,{d:`M10 3.6a2 2 0 0 1 2 2v4.2a2 2 0 0 1-4 0V5.6a2 2 0 0 1 2-2ZM5.4 9.6a4.6 4.6 0 0 0 9.2 0M10 14.4V16.4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`,strokeLinejoin:`round`}),e&&(0,J.jsx)(`path`,{d:`M4.6 4.6 15.4 15.4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})]})}function qe(){return(0,J.jsx)(`svg`,{className:`code-footer-check`,viewBox:`0 0 20 20`,width:`16`,height:`16`,"aria-hidden":`true`,focusable:`false`,children:(0,J.jsx)(`path`,{d:`m4.8 10.4 3.3 3.3 7.1-7.4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function Je(){if(typeof MediaRecorder>`u`)return``;for(let e of[`audio/webm;codecs=opus`,`audio/mp4`,`audio/ogg;codecs=opus`])if(MediaRecorder.isTypeSupported(e))return e;return``}function Ye(e){return e.includes(`mp4`)?`.mp4`:e.includes(`ogg`)?`.ogg`:`.webm`}function Y(e){let t=e?.name;return t===`NotAllowedError`?`Microphone access was denied.`:t===`NotFoundError`?`No microphone was found.`:t===`NotReadableError`||t===`AbortError`?`The microphone is in use by another application.`:e instanceof Error?e.message:`Dictation failed.`}function Xe(e,t){let[n,r]=(0,u.useState)(`unsupported`),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(null),s=(0,u.useRef)(null),c=(0,u.useRef)([]),l=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=typeof MediaRecorder<`u`&&typeof navigator<`u`&&!!navigator.mediaDevices?.getUserMedia;return r(e?`idle`:`unsupported`),()=>{l.current=!1,o.current?.state===`recording`&&o.current.stop(),s.current?.getTracks().forEach(e=>e.stop())}},[]);let d=(0,u.useCallback)(async(t,n)=>{r(`transcribing`);try{let r=await fetch(`/api/voice`,{method:`POST`,headers:{"Content-Type":n||`audio/webm`,"X-Voice-Ext":Ye(n),"X-Stt-Only":`true`},body:t}),i=await r.json().catch(()=>null);if(!r.ok)throw Error(i?.error||`Transcription failed (${r.status}).`);let o=i?.text?.trim();if(!l.current)return;o?e(o):a(`Nothing was transcribed.`)}catch(e){l.current&&a(Y(e))}finally{l.current&&r(`idle`)}},[e]),f=(0,u.useCallback)(()=>{if(!(n===`unsupported`||n===`transcribing`||t)){if(n===`recording`){o.current?.stop();return}a(null),(async()=>{let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){a(Y(e));return}if(!l.current){e.getTracks().forEach(e=>e.stop());return}s.current=e;let t=Je(),n;try{n=new MediaRecorder(e,t?{mimeType:t}:{})}catch(t){e.getTracks().forEach(e=>e.stop()),a(Y(t));return}o.current=n,c.current=[],n.ondataavailable=e=>{e.data.size>0&&c.current.push(e.data)},n.onerror=()=>{a(`Recording failed.`)},n.onstop=()=>{e.getTracks().forEach(e=>e.stop()),s.current=null,o.current=null;let n=new Blob(c.current,{type:t||`audio/webm`});if(c.current=[],l.current){if(n.size===0){r(`idle`),a(`Nothing was recorded.`);return}d(n,t)}},n.start(),r(`recording`)})()}},[t,n,d]);return{status:n,reason:n===`unsupported`?`Dictation needs microphone access, which this browser context does not provide.`:n===`recording`?`Stop dictation`:n===`transcribing`?`Transcribing…`:`Dictation`,error:i,toggle:f}}function Ze(e){let t=(0,u.useRef)(!1),n=(0,u.useRef)(!1),r=(0,u.useRef)(!1),[i,a]=(0,u.useState)(null),o=Xe((0,u.useCallback)(t=>{let n=e.inputText;e.onInputChange(n?`${n.replace(/\s+$/,``)} ${t}`:t)},[e.inputText,e.onInputChange]),e.readOnly);async function s(){if(e.canSend&&e.inputText.trim()&&!n.current){n.current=!0,a(null);try{await e.onSubmit()}catch(e){a(e instanceof Error?e.message:String(e))}finally{n.current=!1}}}async function c(){if(e.canStop&&!r.current){r.current=!0,a(null);try{await e.onStop()}catch(e){a(e instanceof Error?e.message:String(e))}finally{r.current=!1}}}function l(e){e.nativeEvent.isComposing||t.current||e.nativeEvent.keyCode===229||e.key===`Enter`&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.preventDefault(),s())}return(0,J.jsxs)(`div`,{className:`code-composer`,children:[(0,J.jsxs)(`div`,{className:`code-composer-input-shell`,children:[(0,J.jsx)(`textarea`,{className:`code-composer-input`,"aria-label":`Code prompt`,value:e.inputText,onChange:t=>e.onInputChange(t.target.value),onKeyDown:l,onCompositionStart:()=>{t.current=!0},onCompositionEnd:()=>{t.current=!1},placeholder:e.busy?`Draft a follow-up while this turn runs…`:`Describe a task or ask a question…`,rows:2,readOnly:e.readOnly}),(0,J.jsx)(`span`,{className:`code-composer-hint`,children:`Enter to send · Shift+Enter for a new line`})]}),(0,J.jsxs)(`div`,{className:`code-composer-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`code-composer-icon-button${o.status===`recording`?` is-recording`:``}`,"aria-label":o.status===`recording`?`Stop dictation`:`Dictation`,"aria-pressed":o.status===`recording`,disabled:o.status===`unsupported`||o.status===`transcribing`||e.readOnly,title:o.reason,onClick:o.toggle,children:(0,J.jsx)(Ke,{muted:o.status===`unsupported`})}),e.busy?(0,J.jsx)(`button`,{type:`button`,className:`code-composer-send code-composer-stop`,"aria-label":`Stop current turn`,title:e.stopping?`Stopping`:`Stop current turn`,disabled:!e.canStop||e.stopping,onClick:()=>void c(),children:(0,J.jsx)(Ge,{})}):(0,J.jsx)(`button`,{type:`button`,className:`code-composer-send`,"aria-label":`Send prompt`,title:e.pending?`Sending`:`Send prompt`,disabled:!e.canSend||!e.inputText.trim(),onClick:()=>void s(),children:(0,J.jsx)(We,{})})]}),(e.stopping||e.pending||o.status===`recording`||o.status===`transcribing`)&&(0,J.jsx)(`span`,{className:`code-composer-status`,role:`status`,children:e.stopping?`Stopping…`:e.pending?`Sending…`:o.status===`recording`?`Recording…`:`Transcribing…`}),(i||o.error)&&(0,J.jsx)(`div`,{className:`code-action-error`,role:`alert`,children:i??o.error})]})}function Qe(e){if(!e||!Number.isFinite(e.totalTokens)||e.totalTokens<0)return{state:`hidden`};let t=e.modelContextWindow;if(t===null||!Number.isFinite(t)||t<=0)return{state:`counted`,usedTokens:e.totalTokens};let n=Math.round(e.totalTokens/t*100);return{state:`measured`,usedTokens:e.totalTokens,maxTokens:t,percent:Math.min(100,n),over:n>100}}function $e(e,t){let n=e/t;return n<10?n.toFixed(1):String(Math.round(n))}function X(e){if(!Number.isFinite(e)||e<0)return`—`;let t=Math.round(e);if(t<1e3)return String(t);let n=$e(t,1e3);return Number(n)<1e3?`${n}k`:`${$e(t,1e6)}M`}function et(e){return e===null||!Number.isFinite(e)||e<0?`—`:e.toLocaleString(`en-US`)}function Z(e){return e===null?`—`:X(e)}function tt(e){return e>=90?`critical`:e>=75?`high`:`normal`}function nt(e){return e.state===`hidden`?``:e.state===`counted`?`Context: ${X(e.usedTokens)} tokens used, window unknown`:e.over?`Context: over the window, ${X(e.usedTokens)} of ${X(e.maxTokens)} tokens`:`Context: ${e.percent}% used, ${X(e.usedTokens)} of ${X(e.maxTokens)} tokens`}function rt({usage:e}){let t=Qe(e),[n,r]=(0,u.useState)(!1),[i,a]=(0,u.useState)(!1),o=n||i,s=(0,u.useId)();if(t.state===`hidden`)return null;let c=nt(t),l=t.state===`measured`?t.over?`critical`:tt(t.percent):`normal`,d=2*Math.PI*7,f=t.state===`measured`?t.percent/100*d:0;return(0,J.jsxs)(`div`,{className:`code-context-usage`,onPointerEnter:()=>r(!0),onPointerLeave:()=>r(!1),children:[(0,J.jsxs)(`button`,{type:`button`,className:`code-context-trigger is-${l}`,"aria-label":c,"aria-describedby":o?s:void 0,onFocus:()=>a(!0),onBlur:()=>a(!1),children:[t.state===`measured`?(0,J.jsxs)(`svg`,{className:`code-context-ring`,viewBox:`0 0 18 18`,"aria-hidden":`true`,children:[(0,J.jsx)(`circle`,{className:`code-context-ring-track`,cx:`9`,cy:`9`,r:`7`}),(0,J.jsx)(`circle`,{className:`code-context-ring-fill`,cx:`9`,cy:`9`,r:`7`,strokeDasharray:`${f} ${d}`})]}):null,(0,J.jsx)(`span`,{className:`code-context-value`,children:t.state===`measured`?t.over?`over`:`${t.percent}%`:X(t.usedTokens)})]}),o&&(0,J.jsxs)(`div`,{id:s,className:`code-context-detail`,role:`note`,children:[(0,J.jsx)(`p`,{className:`code-context-detail-total`,children:t.state===`measured`?`${X(t.usedTokens)} of ${X(t.maxTokens)} tokens`:`${X(t.usedTokens)} tokens used`}),t.state===`measured`&&t.over&&(0,J.jsx)(`p`,{className:`code-context-detail-note`,children:`Past the window the runtime last reported.`}),t.state===`counted`&&(0,J.jsx)(`p`,{className:`code-context-detail-note`,children:`This runtime did not report a context window.`}),(0,J.jsxs)(`dl`,{className:`code-context-breakdown`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:`Used`}),(0,J.jsx)(`dd`,{children:et(e?.totalTokens??null)})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:`Input`}),(0,J.jsx)(`dd`,{children:Z(e?.inputTokens??null)})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:`Cached`}),(0,J.jsx)(`dd`,{children:Z(e?.cachedInputTokens??null)})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:`Output`}),(0,J.jsx)(`dd`,{children:Z(e?.outputTokens??null)})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:`Reasoning`}),(0,J.jsx)(`dd`,{children:Z(e?.reasoningOutputTokens??null)})]})]}),e?.processedTokens!=null&&(0,J.jsxs)(`p`,{className:`code-context-detail-note`,children:[`Processed across the conversation: `,X(e.processedTokens)]})]})]})}function Q({label:e,value:t,options:n,disabled:r,onChange:i,displayValue:a,triggerContent:o,filterable:s,filterPlaceholder:c,className:l,title:f}){let p=(0,u.useId)(),m=(0,u.useRef)(null),h=(0,u.useRef)(null),g=(0,u.useRef)(null),[_,v]=(0,u.useState)(null),[y,b]=(0,u.useState)(``),x=n.find(e=>e.value===t),S=(0,u.useMemo)(()=>{let e=y.trim().toLowerCase();return!s||!e?n:n.filter(t=>t.value.toLowerCase().includes(e)||t.label.toLowerCase().includes(e))},[s,n,y]);function C(e=!0){v(null),b(``),e&&m.current?.focus()}function w(){let e=m.current?.getBoundingClientRect();if(!e||r)return;let t=Math.max(192,Math.min(s?340:260,window.innerWidth-28)),n=Math.max(0,e.top-16),i=Math.max(0,window.innerHeight-e.bottom-16),a={left:Math.max(14,Math.min(e.left,window.innerWidth-t-14)),width:t};v(n>=i?{...a,bottom:window.innerHeight-e.top+8,maxHeight:Math.min(288,n)}:{...a,bottom:`auto`,top:e.bottom+8,maxHeight:Math.min(288,i)})}(0,u.useEffect)(()=>{if(!_)return;if(s)g.current?.focus();else{let e=h.current?.querySelectorAll(`button:not(:disabled)`);([...e??[]].find(e=>e.getAttribute(`aria-selected`)===`true`)??e?.[0])?.focus()}let e=e=>{!h.current?.contains(e.target)&&!m.current?.contains(e.target)&&C(!1)},t=()=>C(!1);return document.addEventListener(`pointerdown`,e),window.addEventListener(`resize`,t),()=>{document.removeEventListener(`pointerdown`,e),window.removeEventListener(`resize`,t)}},[_,s]),(0,u.useEffect)(()=>{r&&(v(null),b(``))},[r]);function T(e){if(e.key===`Escape`){e.preventDefault(),C();return}if(e.key===`Tab`){C(!1);return}let t=[...h.current?.querySelectorAll(`button:not(:disabled)`)??[]];if(t.length===0)return;let n=t.findIndex(e=>e===document.activeElement),r;if(e.key===`ArrowDown`)r=(n+1)%t.length;else if(e.key===`ArrowUp`)r=(n-1+t.length)%t.length;else if(e.key===`Home`)r=0;else if(e.key===`End`)r=t.length-1;else return;e.preventDefault(),t[r]?.focus()}let E=`${e}: ${x?.label??a??(t||`not selected`)}`;return(0,J.jsxs)(`div`,{className:`code-footer-menu${l?` ${l}`:``}`,children:[(0,J.jsx)(`button`,{ref:m,type:`button`,className:`code-footer-menu-trigger${o?` is-icon`:``}`,"aria-label":E,"aria-haspopup":`listbox`,"aria-expanded":!!_,"aria-controls":_?p:void 0,disabled:r,title:f??x?.detail??E,onClick:()=>_?C():w(),onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),w())},children:o??(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`code-footer-label`,children:e}),(0,J.jsx)(`strong`,{children:x?.label??a??(t||`Not selected`)})]})}),_&&(0,d.createPortal)((0,J.jsxs)(`div`,{ref:h,id:p,role:`listbox`,"aria-label":e,className:`code-footer-dropup code-footer-floating`,style:_,onKeyDown:T,children:[s&&(0,J.jsx)(`input`,{ref:g,type:`text`,className:`code-footer-filter`,value:y,"aria-label":`Filter ${e.toLowerCase()}`,placeholder:c??`Filter…`,onChange:e=>b(e.target.value)}),(0,J.jsxs)(`div`,{className:`code-footer-dropup-list`,children:[S.map(e=>(0,J.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":e.value===t,disabled:e.disabled,className:`code-footer-dropup-option`,title:e.detail??e.label,onClick:()=>{i(e.value),C()},children:[e.icon&&(0,J.jsx)(`span`,{className:`code-footer-option-icon`,children:e.icon}),(0,J.jsxs)(`span`,{className:`code-footer-option-text`,children:[(0,J.jsx)(`strong`,{children:e.label}),e.detail&&(0,J.jsx)(`small`,{children:e.detail})]}),e.value===t&&(0,J.jsx)(qe,{})]},e.value)),S.length===0&&(0,J.jsxs)(`p`,{className:`code-footer-dropup-empty`,role:`note`,children:[`No match for “`,y.trim(),`”.`]})]})]}),document.body)]})}function it({controller:e,onNotice:t}){let n=e.selection,r=e.catalog?.providers.find(e=>e.id===n.provider),i=e.session?.capabilities??r?.capabilities,a=e.selectedId!==null,o=e.pending||e.busy||e.creationUnknown||e.operation.kind!==`idle`||a&&(!e.synced||e.session?.status!==`idle`||e.session?.archivedAt!==null),[s,c]=(0,u.useState)(!1),[l,d]=(0,u.useState)(null),f=(0,u.useRef)(!1),p=(0,u.useRef)(t);p.current=t,(0,u.useEffect)(()=>{if(n.permissionMode!==`auto`){p.current?.({id:`code:permission-mode`,clear:!0});return}p.current?.({id:`code:permission-mode`,variant:`warning`,message:`Auto (YOLO): actions may run without approval.`,durationMs:1/0})},[n.permissionMode]);async function m(t){if(!(o||f.current)){f.current=!0,c(!0),d(null);try{await e.setSelection(t)}catch(e){d(e instanceof Error?e.message:String(e))}finally{f.current=!1,c(!1)}}}let h=o||s,g=r?.effortsByModel?.[n.model]??i?.efforts??[],_=e.session?.capabilities.efforts,v=_?g.filter(e=>_.includes(e)):g,y=r?.models??[];return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`code-composer-footer`,children:[(0,J.jsx)(Q,{label:`Runtime`,value:n.provider,className:`code-footer-runtime`,disabled:a?!e.catalog:h||!e.catalog,triggerContent:(0,J.jsx)(Ue,{provider:n.provider}),title:q[n.provider],options:Object.keys(q).map(t=>{let r=e.catalog?.providers.find(e=>e.id===t);return{value:t,label:a&&t!==n.provider?`New ${q[t]} session`:q[t],disabled:!r?.available||a&&t===n.provider,icon:(0,J.jsx)(Ue,{provider:t}),detail:r?.reason??(r?.available?void 0:`Availability unknown`)}}),onChange:t=>{a?e.setSelection({provider:t}).catch(e=>d(e instanceof Error?e.message:String(e))):m({provider:t})}}),(0,J.jsx)(Q,{label:`Permission`,value:n.permissionMode,displayValue:ke[n.permissionMode],disabled:h||!i?.permissions,options:(i?.permissionModes??[]).map(e=>({value:e,label:ke[e],detail:Ae[e]})),onChange:e=>void m({permissionMode:e})}),(0,J.jsx)(`span`,{className:`code-composer-footer-spacer`,"aria-hidden":`true`}),(0,J.jsx)(rt,{usage:e.session?.contextUsage}),(0,J.jsx)(Q,{label:`Model`,value:n.model,className:`code-footer-model`,disabled:h||y.length===0,filterable:!0,filterPlaceholder:`Filter models…`,displayValue:n.model||`Select model`,options:y.map(e=>({value:e,label:e})),onChange:e=>void m({model:e})}),v.length>0&&(0,J.jsx)(Q,{label:`Effort`,value:n.effort??``,className:`code-footer-effort`,displayValue:n.effort??`Default`,options:[{value:``,label:`Native default`},...v.map(e=>({value:e,label:e}))],disabled:h,onChange:e=>void m({effort:e||null})}),a&&(0,J.jsx)(`button`,{type:`button`,className:`code-inline-action`,onClick:e.newSession,children:`New session`})]}),y.length===0&&r?.available&&(0,J.jsxs)(`div`,{className:`code-selection-notice`,children:[`This runtime published no models.`,(0,J.jsx)(`button`,{type:`button`,className:`code-inline-action`,onClick:()=>{e.refresh().catch(e=>d(e instanceof Error?e.message:String(e)))},children:`Refresh catalog`})]}),!r?.available&&(0,J.jsxs)(`div`,{className:`code-selection-notice`,children:[r?.reason??`Runtime availability has not been confirmed.`,(0,J.jsx)(`button`,{type:`button`,className:`code-inline-action`,onClick:()=>{e.refresh().catch(e=>d(e instanceof Error?e.message:String(e)))},children:`Refresh availability`})]}),(s||e.operation.kind===`patching`)&&(0,J.jsx)(`span`,{role:`status`,children:`Saving settings…`}),l&&(0,J.jsx)(`div`,{className:`code-action-error`,role:`alert`,children:l})]})}function at({permission:e,operation:t,eligible:n,onAnswer:r}){let i=(0,u.useRef)(!1),[a,o]=(0,u.useState)(!1),[s,c]=(0,u.useState)(null);async function l(a){if(!(!n||i.current||t?.pending)){i.current=!0,o(!0),c(null);try{await r(e,a)}catch(e){c(e instanceof Error?e.message:String(e))}finally{i.current=!1,o(!1)}}}return(0,J.jsxs)(`section`,{className:`code-permission-card`,"aria-label":e.title,children:[(0,J.jsxs)(`div`,{className:`code-permission-title`,children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsx)(`p`,{children:e.detail}),!n&&(0,J.jsx)(`small`,{children:`Updating permission availability…`}),(a||t?.pending)&&(0,J.jsx)(`small`,{role:`status`,children:`Checking decision…`}),(t?.error||s)&&(0,J.jsx)(`div`,{className:`code-action-error`,role:`alert`,children:t?.error||s})]}),(0,J.jsxs)(`div`,{className:`code-permission-actions`,children:[e.options.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`code-permission-btn`,disabled:!n||a||t?.pending,onClick:()=>void l(e.optionId),children:e.label},e.optionId)),e.options.length===0&&(0,J.jsx)(`span`,{children:`No native actions available. Refresh this session.`})]})]})}function ot({permissions:e,operations:t,session:n,synced:r,onAnswer:i}){return e.length?(0,J.jsxs)(`aside`,{className:`code-permissions`,"aria-label":`Pending permissions`,tabIndex:-1,id:`code-pending-permissions`,children:[(0,J.jsxs)(`div`,{className:`code-permissions-heading`,role:`status`,children:[e.length,` pending · `,n?q[n.provider]:`Session updating`]}),e.map(e=>(0,J.jsx)(at,{permission:e,operation:t[e.permissionId],eligible:r&&n!==null&&n.archivedAt===null&&n.sessionId===e.sessionId&&n.turnId===e.turnId&&n.epoch===e.epoch&&(n.status===`starting`||n.status===`streaming`),onAnswer:i},`${e.sessionId}:${e.permissionId}`))]}):null}var st=92,ct=6;function lt(e){let[{virtualItems:t,totalSize:s},c]=(0,u.useState)({virtualItems:[],totalSize:0}),l=(0,u.useRef)(null);l.current||=new o({count:e.count,getScrollElement:()=>e.scrollElementRef.current,estimateSize:e.estimateSize||(()=>st),overscan:ct,getItemKey:e.getItemKey,indexAttribute:`data-code-transcript-idx`,useAnimationFrameWithResizeObserver:!0,observeElementRect:n,observeElementOffset:r,scrollToFn:i,measureElement:a,onChange:e=>{c({virtualItems:e.getVirtualItems(),totalSize:e.getTotalSize()})}});let d=l.current;return(0,u.useEffect)(()=>d._didMount(),[d]),(0,u.useEffect)(()=>{d.measure()},[d,e.resetKey]),(0,u.useEffect)(()=>()=>{l.current=null},[]),(0,u.useLayoutEffect)(()=>{d.setOptions({...d.options,count:e.count,getItemKey:e.getItemKey,estimateSize:e.estimateSize||(()=>st)}),d._willUpdate(),c({virtualItems:d.getVirtualItems(),totalSize:d.getTotalSize()})},[e.count,e.estimateSize,e.getItemKey,d]),{restoreAnchor:(e,t)=>{let n=d.getOffsetForIndex(e,`start`);n&&d.scrollToOffset(n[0]+t,{behavior:`auto`})},measureElement:e=>{e&&d.measureElement(e)},virtualItems:t,totalSize:s}}var ut=64,dt=64;function ft({items:e,sessionKey:t,transcriptRef:n,virtual:r}){let i=(0,u.useRef)(new Map),a=(0,u.useRef)(!0),[o,s]=(0,u.useState)(!1),c=(0,u.useRef)({sessionKey:``,firstId:``}),l=(0,u.useRef)({items:e,virtual:r,sessionKey:t});l.current={items:e,virtual:r,sessionKey:t};let d=(0,u.useCallback)(()=>{a.current=!0,s(!1);let e=n.current;e&&(e.scrollTop=e.scrollHeight)},[n]);return(0,u.useLayoutEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{let t=l.current,n=t.virtual.virtualItems.find(t=>t.end>e.scrollTop),r={itemId:n?t.items[n.index]?.itemId??null:null,offset:n?e.scrollTop-n.start:0,following:a.current};if(i.current.delete(t.sessionKey),i.current.set(t.sessionKey,r),i.current.size>ut){let e=i.current.keys().next().value;e!==void 0&&i.current.delete(e)}},r=()=>{l.current.items.length&&(a.current=e.scrollHeight-e.scrollTop-e.clientHeight<=dt,s(!a.current),t())};return e.addEventListener(`scroll`,r,{passive:!0}),()=>e.removeEventListener(`scroll`,r)},[n]),(0,u.useLayoutEffect)(()=>{let o=n.current;if(!o)return;let l=e[0]?.itemId??``,u=c.current.sessionKey!==t,d=!u&&c.current.firstId!==l;c.current={sessionKey:t,firstId:l};let f=i.current.get(t);if(u&&(a.current=f?.following??!0,s(!a.current)),a.current){o.scrollTop=o.scrollHeight;return}if((u||d)&&f?.itemId){let t=e.findIndex(e=>e.itemId===f.itemId);t>=0&&r.restoreAnchor(t,f.offset)}},[e,t,n,r.totalSize]),{showJump:o,jumpToLatest:d}}var pt=2e3,mt=80,ht=400;function gt(e){return e<=pt?mt:Math.min(ht,Math.round(mt*e/pt))}function _t(e,t=!1,n=``){let[r,i]=(0,u.useState)({text:e,identity:n}),a=(0,u.useRef)(0),o=t||r.identity!==n||!e.startsWith(r.text);return(0,u.useEffect)(()=>{if(r.text===e&&r.identity===n)return;let t=()=>{a.current=Date.now(),i({text:e,identity:n})},s=gt(e.length)-(Date.now()-a.current);if(o||s<=0){t();return}let c=window.setTimeout(t,s);return()=>window.clearTimeout(c)},[e,n,o,r]),o?e:r.text}var vt=[[/^(read|read_file|get_file|open_file|view|cat)$/i,`Read`,`Reading`],[/^(write|write_file|create_file|edit|edit_file|apply_patch|str_replace\w*|update_file)$/i,`Edit`,`Editing`],[/^(bash|shell|exec|exec_command|run|run_command|terminal)$/i,`Bash`,`Running`],[/^(search|grep|rg|ripgrep|glob|find|codebase_search)$/i,`Search`,`Searching`],[/^(fetch|browser\w*|web_\w*|open_url|http)$/i,`Open`,`Opening`],[/^(list|ls|list_dir|list_files)$/i,`List`,`Listing`]];function yt(e){return e===`running`||e===`pending`}function bt(e,t){let n=e.trim();if(t&&n.startsWith(t)){let e=n.slice(t.length).replace(/^[\\/]+/,``);if(e)return e}if(n.length<=64)return n;let r=n.split(/[\\/]/).filter(Boolean);return r.length>2?`…/${r.slice(-2).join(`/`)}`:`…${n.slice(-60)}`}function xt(e){let t=(e.split(/\r?\n/).find(e=>e.trim())??``).replace(/\s+/g,` `).trim();return t.length>96?`${t.slice(0,95)}…`:t}function St(e,t){if(!e)return``;let n=e.trim();if(!n)return``;if(n.startsWith(`{`))try{let e=JSON.parse(n);for(let n of[`command`,`cmd`,`path`,`file_path`,`file`,`url`,`query`,`pattern`]){let r=e[n];if(typeof r==`string`&&r.trim())return n===`path`||n===`file`||n===`file_path`?bt(r,t):xt(r)}return``}catch{}return n.includes(`/`)&&!n.includes(` `)?bt(n,t):xt(n)}function Ct(e,t){let n=yt(e.status);if(e.kind===`file_change`){let r=St(e.tool?.input,t)||e.tool?.detail||``;return r?`${n?`Editing`:`Edit`} ${r}`:`File change`}let r=e.tool?.name?.trim()||`Tool`,i=vt.find(([e])=>e.test(r)),a=i?n?i[2]:i[1]:void 0,o=St(e.tool?.input,t);return a?o?`${a} ${o}`:a:o?`${r} ${o}`:r}function wt(e){return e.kind===`turn_cancelled`||e.status===`cancelled`?`Stopped`:e.kind===`turn_failed`||e.status===`error`?`Failed`:e.status===`running`?`Running`:e.status===`pending`?`Pending`:null}var Tt=(0,u.lazy)(()=>t(()=>import(`./MarkdownRenderer-DyVx6DxM.js`).then(e=>({default:e.MarkdownRenderer})),__vite__mapDeps([0]))),Et=new Set([`turn_started`,`turn_completed`]),Dt=44,Ot=320,kt=64;function $(e,t,n){let r=e.get(`${t}:${n.itemId}`);return r===void 0?n.status===`error`&&n.kind!==`reasoning`:r}function At({item:e,identity:t,onOpenLocalFile:n}){let r=_t(e.text??``,e.status!==`running`&&e.status!==`pending`,t);return r.trim()?(0,J.jsx)(u.Suspense,{fallback:(0,J.jsx)(`span`,{className:`code-plain-text`,children:r}),children:(0,J.jsx)(Tt,{markdown:r,tableMode:`linear`,onLocalFileOpen:n})}):(0,J.jsx)(`span`,{className:`code-plain-text`,children:r})}function jt({item:e,provider:t,sessionKey:n,workingDir:r=``,onOpenLocalFile:i,expanded:a,onExpandedChange:o}){let s=e.kind===`tool_call`||e.kind===`file_change`,c=e.kind===`reasoning`,l=e.kind===`assistant_message`,u=e.kind===`user_message`,d=Pe(e),f=wt(e),p=e.itemId===_e,m=a??(e.status===`error`&&e.kind!==`reasoning`),h=e.status===`running`||e.status===`pending`,g=h?null:f,_=u?`You`:l?q[t]:c?`Reasoning`:e.kind===`turn_started`?`Turn started`:e.kind===`session_runtime`?`Runtime`:e.kind===`permission_request`?`Permission record`:e.kind===`notice`?`Notice`:d;return(0,J.jsxs)(`article`,{className:`code-message code-message-${s?`tool`:l?`assistant`:u?`user`:`system`} is-${e.status}${p?` is-unsent`:``}`,"data-code-item-id":e.itemId,"aria-label":`${_} · ${d}`,children:[s?(0,J.jsxs)(`details`,{className:`code-tool-card code-tool-${e.status}`,open:m,onToggle:t=>o?.(e.itemId,t.currentTarget.open),children:[(0,J.jsxs)(`summary`,{className:`code-tool-summary`,children:[(0,J.jsx)(`span`,{className:`code-tool-chevron`,"aria-hidden":`true`,children:`›`}),(0,J.jsx)(`span`,{className:`code-tool-name${h?` code-tool-name-running`:``}`,children:Ct(e,r)}),g&&(0,J.jsx)(`span`,{className:`code-tool-status`,children:g})]}),m&&(0,J.jsxs)(J.Fragment,{children:[e.tool?.detail!==void 0&&(0,J.jsx)(`p`,{className:`code-tool-text`,children:e.tool.detail}),e.tool?.input!==void 0&&(0,J.jsxs)(`section`,{className:`code-tool-section`,children:[(0,J.jsx)(`span`,{className:`code-tool-section-label`,children:`Input`}),(0,J.jsx)(`pre`,{className:`code-tool-args`,children:e.tool.input})]}),e.tool?.output!==void 0&&(0,J.jsxs)(`section`,{className:`code-tool-section`,children:[(0,J.jsx)(`span`,{className:`code-tool-section-label`,children:`Output`}),(0,J.jsx)(`pre`,{className:`code-tool-output`,children:e.tool.output})]}),e.text!==void 0&&(0,J.jsx)(`pre`,{className:`code-tool-text`,children:e.text})]})]}):c?(0,J.jsxs)(`details`,{className:`code-thinking`,open:m,onToggle:t=>o?.(e.itemId,t.currentTarget.open),children:[(0,J.jsx)(`summary`,{className:`code-thinking-summary${e.status===`running`?` code-tool-name-running`:``}`,children:e.status===`running`?`Thinking…`:`Reasoning`}),m&&(0,J.jsx)(`div`,{className:`code-thinking-text`,children:e.text})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`span`,{className:`code-message-role`,children:[_,l&&e.phase===`commentary`?` · Commentary`:``,f&&` · ${p?`Sending`:f}`]}),(0,J.jsx)(`div`,{className:`code-message-text`,children:l?(0,J.jsx)(At,{item:e,identity:`${n}:${e.itemId}`,onOpenLocalFile:i}):(0,J.jsx)(`span`,{className:`code-plain-text`,children:e.text??e.permission?.title??``})}),e.permission?.detail&&(0,J.jsx)(`p`,{className:`code-plain-text`,children:e.permission.detail})]}),(l||c)&&(e.status===`cancelled`||e.status===`error`)&&(0,J.jsxs)(`span`,{className:`code-partial-label`,children:[`Partial output · `,d]}),e.truncation&&(0,J.jsxs)(`p`,{className:`code-truncation`,role:`note`,children:[`Output truncated: `,e.truncation.storedChars.toLocaleString(),` of `,e.truncation.sourceChars.toLocaleString(),` characters retained.`]})]})}function Mt({items:e,provider:t,sessionKey:n,workingDir:r,loading:i,hasOlderHistory:a,loadOlderHistory:o,permissionCount:s,onOpenLocalFile:c}){let l=(0,u.useRef)(null),d=(0,u.useMemo)(()=>e.filter(e=>!Et.has(e.kind)),[e]),f=(0,u.useRef)(d);f.current=d;let[p,m]=(0,u.useState)(()=>new Map),h=(0,u.useRef)(p);h.current=p;let[g,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),b=(0,u.useRef)(!1),x=d[0]?.itemId,S=(0,u.useCallback)(e=>{let t=f.current[e];return t?`${n}:${t.itemId}${$(h.current,n,t)?`:open`:``}`:`${n}:${e}`},[n,x,p]),C=(0,u.useCallback)(e=>{let t=f.current[e];return t?.kind!==`tool_call`&&t?.kind!==`file_change`&&t?.kind!==`reasoning`?64+Math.min(420,(t?.text?.length??0)/6):t&&$(p,n,t)?Ot:Dt},[p,n]),w=lt({count:d.length,resetKey:n,scrollElementRef:l,getItemKey:S,estimateSize:C}),{showJump:T,jumpToLatest:E}=ft({items:d,sessionKey:n,transcriptRef:l,virtual:w}),D=(0,u.useCallback)((e,t)=>{let r=`${n}:${e}`;m(e=>{if(e.get(r)===t)return e;let n=new Map(e);if(n.delete(r),n.set(r,t),n.size>kt){let e=n.keys().next().value;e!==void 0&&n.delete(e)}return n})},[n]);async function O(){if(!b.current){b.current=!0,_(!0),y(null);try{await o()}catch(e){y({sessionKey:n,message:e instanceof Error?e.message:String(e)})}finally{b.current=!1,_(!1)}}}function k(e){if(e.target!==e.currentTarget||e.altKey||e.ctrlKey||e.metaKey)return;let t=l.current;if(!t)return;let n=Math.max(160,t.clientHeight*.78);[`j`,`d`,`PageDown`].includes(e.key)?(e.preventDefault(),t.scrollBy({top:n,behavior:`auto`})):[`k`,`u`,`PageUp`].includes(e.key)?(e.preventDefault(),t.scrollBy({top:-n,behavior:`auto`})):e.key===`End`?(e.preventDefault(),E()):e.key===`Home`&&(e.preventDefault(),t.scrollTo({top:0,behavior:`auto`}))}return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`code-transcript-controls`,children:[a&&(0,J.jsx)(`button`,{type:`button`,disabled:g||i,onClick:()=>void O(),children:g?`Loading history…`:`Load older history`}),T&&(0,J.jsx)(`button`,{type:`button`,onClick:E,children:`Jump to latest`}),s>0&&(0,J.jsxs)(`button`,{type:`button`,onClick:()=>document.getElementById(`code-pending-permissions`)?.focus(),children:[`Jump to permissions (`,s,`)`]}),v?.sessionKey===n&&(0,J.jsx)(`span`,{className:`code-action-error`,role:`alert`,children:v.message})]}),(0,J.jsx)(`div`,{ref:l,className:`code-transcript`,role:`log`,"aria-label":`Code transcript`,"aria-live":`off`,tabIndex:0,onKeyDown:k,children:d.length?(0,J.jsx)(`div`,{className:`code-transcript-virtual-spacer`,style:{height:w.totalSize},children:w.virtualItems.map(e=>{let i=d[e.index];return i?(0,J.jsx)(`div`,{ref:w.measureElement,className:`code-transcript-virtual-row`,"data-code-transcript-idx":e.index,style:{transform:`translateY(${e.start}px)`},children:(0,J.jsx)(jt,{item:i,provider:t,sessionKey:n,workingDir:r,onOpenLocalFile:c,expanded:$(p,n,i),onExpandedChange:D})},e.key):null})}):(0,J.jsxs)(`div`,{className:`code-transcript-empty`,children:[(0,J.jsx)(`p`,{children:i?`Loading conversation…`:`Type a prompt below to start this conversation.`}),(0,J.jsxs)(`p`,{className:`code-transcript-cwd`,children:[`Workspace: `,r||`not set`]})]})})]})}function Nt(e){return Number.isFinite(e.durationMs)&&e.durationMs>0}function Pt(e,t){let n=e.find(e=>e.id===t.id),r=e.filter(e=>e.id!==t.id);return r.push({...t,revision:(n?.revision??0)+1}),r.slice(Math.max(0,r.length-3))}function Ft(e,t){let n=e.filter(e=>e.id!==t);return n.length===e.length?e:n}function It(e,t){return`clear`in t?Ft(e,t.id):Pt(e,{id:t.id,message:t.message,variant:t.variant,durationMs:t.durationMs??4e3})}function Lt({toast:e,onDismiss:t}){let[n,r]=(0,u.useState)(!1),i=(0,u.useRef)(null);return(0,u.useEffect)(()=>{if(n||!Nt(e))return;let r=setTimeout(()=>t(e.id),e.durationMs);return()=>clearTimeout(r)},[e.id,e.revision,e.durationMs,t,n]),(0,J.jsxs)(`div`,{ref:i,className:`code-toast code-toast-${e.variant}`,onPointerEnter:()=>r(!0),onPointerLeave:()=>r(!1),onFocusCapture:()=>r(!0),onBlurCapture:e=>{i.current?.contains(e.relatedTarget)||r(!1)},children:[(0,J.jsx)(`span`,{className:`code-toast-message`,children:e.message}),(0,J.jsx)(`button`,{type:`button`,className:`code-toast-dismiss`,"aria-label":`Dismiss notice`,onClick:()=>t(e.id),children:`×`})]})}function Rt({toasts:e,onDismiss:t}){return(0,J.jsx)(`div`,{className:`code-toast-host`,children:(0,J.jsx)(`div`,{className:`code-toast-region`,role:`status`,children:e.map(e=>(0,J.jsx)(Lt,{toast:e,onDismiss:t},e.id))})})}function zt({controller:e}){let[t,n]=(0,u.useState)(!1),[r,i]=(0,u.useState)(null),a=e.session?.cwd??e.selection.cwd,o=e.selectedId!==null||e.pending||e.creationUnknown||e.operation.kind!==`idle`;async function s(){if(!(o||t)){n(!0),i(null);try{await e.pickWorkspace()}catch(e){i(e instanceof Error?e.message:String(e))}finally{n(!1)}}}return(0,J.jsxs)(`header`,{className:`code-workspace-header`,children:[(0,J.jsxs)(`div`,{className:`code-session-header`,children:[(0,J.jsx)(`span`,{className:`code-session-title`,children:e.session?.title||(e.selectedId?`Untitled session`:`New session draft`)}),(0,J.jsx)(`span`,{children:q[e.session?.provider??e.selection.provider]}),(0,J.jsxs)(`span`,{role:`status`,children:[e.session?je[e.session.status]:e.creationUnknown?`Creation unconfirmed`:e.operation.kind===`creating`?`Creating session`:`Draft`,e.session?.archivedAt!==null&&e.session?` · Archived`:``]})]}),(0,J.jsxs)(`div`,{className:`code-workspace-primary`,children:[o?(0,J.jsx)(`span`,{className:`code-workspace-chip`,title:a,children:a||`Workspace not set`}):(0,J.jsx)(`button`,{type:`button`,className:`code-workspace-picker`,"aria-label":`Choose Code workspace`,disabled:t,title:a||`Choose a folder`,onClick:()=>void s(),children:(0,J.jsx)(`span`,{className:`code-workspace-picker-label`,children:t?`Choosing folder…`:a||`Choose workspace`})}),e.gitInfo?.isRepo&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`span`,{className:`code-workspace-pill`,children:[e.gitInfo.branch??`detached`,e.gitInfo.head?` · ${e.gitInfo.head}`:``]}),e.gitInfo.status&&(0,J.jsx)(`span`,{className:`code-workspace-pill${e.gitInfo.status.dirty?` is-dirty`:``}`,children:e.gitInfo.status.dirty?`${e.gitInfo.status.changed} changed · ${e.gitInfo.status.untracked} untracked`:`clean`})]}),r&&(0,J.jsx)(`span`,{className:`code-action-error`,role:`alert`,children:r})]})]})}function Bt({controller:e,endpointKey:t,onOpenLocalFile:n}){let r=`${t}:${e.selectedId??`new`}`,[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(null),c=(0,u.useRef)(new Set),[l,d]=(0,u.useState)([]),f=(0,u.useCallback)(e=>{d(t=>It(t,e))},[]),p=(0,u.useCallback)(e=>d(t=>Ft(t,e)),[]),m=e.session?.archivedAt!=null,h=e.session?.status===`stopping`||e.operation.kind===`stopping`,g=e.busy||h||e.session?.status===`starting`||e.session?.status===`streaming`,_=e.catalog?.providers.find(t=>t.id===e.selection.provider),v=e.operation.kind===`unknown-send`,y=!g&&!e.pending&&!e.creationUnknown&&!m&&e.operation.kind===`idle`&&!!_?.available&&!!e.selection.cwd.trim()&&!!e.selection.model.trim()&&(e.selectedId===null||e.synced&&e.session?.status===`idle`),b=!!e.session?.turnId&&e.session.capabilities.interrupt&&g&&!h,x=!!e.session&&Ne(e.session)&&e.synced&&!e.pending&&!v,S=e.operation.error||e.error||(i?.key===r?i.message:null),C=[...e.items].reverse().find(e=>e.kind===`turn_cancelled`||e.kind===`turn_failed`||e.kind===`turn_completed`),w=C&&C.kind!==`turn_completed`?e.items.find(e=>e.kind===`user_message`&&e.turnId===C.turnId)?.text:void 0;function T(e){a(null),e().catch(e=>a({key:r,message:e instanceof Error?e.message:String(e)}))}async function E(){if(e.canRetrySameSend&&!c.current.has(r)){c.current.add(r),s(r),a(null);try{await e.retrySameSend()}catch(e){a({key:r,message:e instanceof Error?e.message:String(e)})}finally{c.current.delete(r),s(e=>e===r?null:e)}}}return(0,J.jsxs)(`div`,{className:`code-canvas-main`,children:[(0,J.jsx)(zt,{controller:e},r),(e.transport!==`connected`||e.selectedId!==null&&!e.synced)&&(0,J.jsxs)(`section`,{className:`code-transport-status is-${e.transport}`,role:`status`,children:[e.transport===`reconnecting`?`Live updates reconnecting. History may be out of date.`:e.transport===`disconnected`?`Live updates disconnected. History may be out of date.`:`Updating conversation…`,(0,J.jsx)(`button`,{type:`button`,onClick:()=>T(e.refresh),children:`Refresh`})]}),S&&(0,J.jsxs)(`section`,{className:`code-recovery-strip`,role:`alert`,children:[(0,J.jsx)(`p`,{children:S}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>T(e.refresh),children:`Refresh session`}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>{e.clearError(),a(null)},children:`Dismiss`})]}),e.creationUnknown&&(0,J.jsxs)(`section`,{className:`code-recovery-strip`,"aria-label":`Unconfirmed session creation`,children:[(0,J.jsx)(`strong`,{children:`Session creation not confirmed`}),(0,J.jsx)(`p`,{children:`The original session may still exist.`}),(0,J.jsx)(`p`,{children:`Your draft and choices are kept. Press Send when you are ready to create another session.`}),(0,J.jsx)(`button`,{type:`button`,onClick:e.startAnotherSession,children:`Start another session`})]}),v&&(0,J.jsxs)(`section`,{className:`code-recovery-strip`,"aria-label":e.resendRequired?`Send not started`:`Unconfirmed send`,children:[(0,J.jsx)(`strong`,{children:e.resendRequired?`Send did not start`:`Send outcome not confirmed`}),(0,J.jsx)(`p`,{children:e.resendRequired?`The original attempt ended on the server without running. Retry sends this as a new message.`:`Retry uses the original request. It may submit it if the server has not already accepted it.`}),(0,J.jsx)(`pre`,{className:`code-retry-preview`,"aria-label":`Original prompt`,children:e.retryText}),(0,J.jsx)(`button`,{type:`button`,disabled:!e.canRetrySameSend||o===r,onClick:()=>void E(),children:o===r?e.resendRequired?`Sending as a new message…`:`Retrying original send…`:e.resendRequired?`Send as a new message`:`Retry same send`})]}),m?(0,J.jsxs)(`section`,{className:`code-recovery-strip`,children:[(0,J.jsx)(`span`,{children:`Archived · Read-only history`}),(0,J.jsx)(`button`,{type:`button`,disabled:!e.synced||e.pending,onClick:()=>{let t=e.selectedId;t&&T(()=>e.archive(t,!1))},children:`Restore session`})]}):e.session&&(e.session.status===`failed`||e.session.status===`suspended`)&&(0,J.jsxs)(`section`,{className:`code-recovery-strip`,role:`status`,children:[(0,J.jsx)(`p`,{children:e.session.error?.message??`Native session suspended.`}),x?(0,J.jsx)(`button`,{type:`button`,onClick:()=>T(e.resume),children:`Resume session`}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{children:e.session.resume.reason??`Resume is not currently available.`}),(0,J.jsx)(`button`,{type:`button`,onClick:e.newSession,children:`New session`})]})]}),(0,J.jsx)(Rt,{toasts:l,onDismiss:p}),(0,J.jsx)(Mt,{items:e.items,provider:e.session?.provider??e.selection.provider,sessionKey:r,workingDir:e.session?.cwd??e.selection.cwd,loading:e.loading,hasOlderHistory:e.hasOlderHistory,loadOlderHistory:e.loadOlderHistory,permissionCount:e.permissions.length,onOpenLocalFile:n}),(0,J.jsx)(ot,{permissions:e.permissions,operations:e.permissionOperations,session:e.session,synced:e.synced,onAnswer:e.answer}),(0,J.jsxs)(`div`,{className:`code-composer-dock`,children:[w!==void 0&&!g&&!m&&(0,J.jsxs)(`div`,{className:`code-input-recovery`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:!!e.input||v,title:e.input?`Keep or clear your current draft before restoring the submitted prompt`:void 0,onClick:()=>e.setInput(w),children:`Restore submitted prompt`}),(0,J.jsx)(`span`,{children:`Restores text for editing without sending.`})]}),(0,J.jsxs)(`div`,{className:`code-composer-surface`,"aria-label":`Code composer controls`,children:[(0,J.jsx)(Ze,{inputText:e.input,canSend:y,busy:g,canStop:b,stopping:h,pending:e.pending,readOnly:m,onInputChange:e.setInput,onSubmit:e.send,onStop:e.stop},`composer:${r}`),(0,J.jsx)(it,{controller:e,onNotice:f},`footer:${r}`)]})]})]})}function Vt({port:e,workingDir:t,onWorkingDirChange:n,onOpenLocalFile:r}){let i=Oe({port:e,workingDir:t}),[a,o]=(0,u.useState)(null),s=(0,u.useRef)({port:e,id:i.selectedId,cwd:i.selection.cwd});(0,u.useEffect)(()=>{o(document.getElementById(`code-session-sidebar-host`))},[]),(0,u.useEffect)(()=>{let t=s.current,r={port:e,id:i.selectedId,cwd:i.selection.cwd};s.current=r,t.port===e&&t.id===null&&r.id===null&&t.cwd!==r.cwd&&n?.(r.cwd||null)},[e,i.selectedId,i.selection.cwd,n]);let c=(0,J.jsx)(Ve,{controller:i},e),l=(0,J.jsx)(Bt,{controller:i,endpointKey:String(e),onOpenLocalFile:r},e);return a?(0,J.jsxs)(J.Fragment,{children:[(0,d.createPortal)((0,J.jsx)(`div`,{className:`code-manager-session-navigator-content`,children:c}),a),(0,J.jsx)(`div`,{className:`code-canvas code-canvas-workbench`,children:l})]}):(0,J.jsxs)(`div`,{className:`code-canvas`,children:[(0,J.jsx)(`div`,{className:`code-canvas-sidebar`,children:c}),l]})}export{Vt as CodeCanvas};
@@ -1 +0,0 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./Permissions-DzNJCt8K.js";export{n as configuredPolicyLabel,o as default,i as isAllowlistValid,t as isPermissionToken,e as isPermissionsAuto,r as parsePermissionsValue,a as seedAutoAllowlist};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{t}from"./react-C_pPTFsM.js";import{t as n}from"./jsx-runtime-NZYk81nU.js";import{a as r,i,n as a,r as o,t as s}from"./page-shell-BeGD0rRQ.js";import{i as c,n as l}from"./fields-mlGpofqQ.js";import{t as u}from"./InlineWarn-DIMbcbzk.js";var d=e(t(),1),f=n(),p=/^[a-zA-Z0-9._:*-]+$/,m=[`bash`,`read`,`write`,`edit`,`mcp.*`];function h(e){return e===`auto`?`Auto (YOLO)`:e===`safe`?`Safe`:e==null?`Not provided`:Array.isArray(e)&&e.every(e=>typeof e==`string`)?`Custom (${e.length} ${e.length===1?`entry`:`entries`})`:`Unrecognized`}function g(e){return e===`auto`}function _(e){return g(e)?{mode:`auto`}:e===`safe`?{mode:`safe`}:Array.isArray(e)?{mode:`custom`,tokens:e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>e.length>0)}:{mode:`unknown`}}function v(e){return typeof e!=`string`||e.length===0||e.length>64?!1:p.test(e)}function y(e){return Array.isArray(e)&&e.length>0?Array.from(new Set(e.filter(v))):[...m]}function b(e){return e.length!==0&&e.every(v)}var x=[{value:`auto`,label:`Auto (YOLO)`},{value:`safe`,label:`Safe`},{value:`custom`,label:`Custom — explicit allowlist below`}];function S({port:e,client:t,dirty:n,registerSave:p}){let{state:m,refresh:g,setData:S}=r(t,`/api/settings`),[C,w]=(0,d.useState)(`auto`),[T,E]=(0,d.useState)([]),D=(0,d.useMemo)(()=>m.kind===`ready`?_(m.data.permissions):null,[m]);(0,d.useEffect)(()=>{if(m.kind!==`ready`)return;let e=_(m.data.permissions);e.mode===`custom`?(w(`custom`),E(e.tokens)):(w(e.mode===`safe`?`safe`:`auto`),E([]))},[m]),(0,d.useEffect)(()=>()=>{n.remove(`permissions`)},[n]);let O=(0,d.useCallback)(e=>n.set(`permissions`,e),[n]),k=(0,d.useMemo)(()=>D?D.mode===`custom`?D.tokens:D.mode===`safe`?`safe`:`auto`:`auto`,[D]),A=(0,d.useCallback)(e=>{if(e===`auto`){w(`auto`),E([]),O({value:`auto`,original:k,valid:!0});return}if(e===`safe`){w(`safe`),E([]),O({value:`safe`,original:k,valid:!0});return}if(e===`custom`){w(`custom`);let e=D&&D.mode===`custom`&&D.tokens.length>0?[...D.tokens]:y(null);E(e),O({value:e,original:k,valid:b(e)})}},[D,k,O]),j=(0,d.useCallback)(e=>{let t=e.map(e=>e.trim()).filter(e=>e.length>0);E(t),O({value:t,original:k,valid:b(t)})},[k,O]),M=(0,d.useCallback)(async()=>{let e=n.saveBundle();if(Object.keys(e).length===0)return;let r=await t.put(`/api/settings`,e),i=r&&typeof r==`object`&&`data`in r?r.data:r;n.clear();let a=_(i.permissions);a.mode===`custom`?(w(`custom`),E(a.tokens)):(w(a.mode===`safe`?`safe`:`auto`),E([])),S(i),await g()},[t,n,g,S]);if((0,d.useEffect)(()=>{if(p)return p(M),()=>p(null)},[p,M]),m.kind===`loading`)return(0,f.jsx)(a,{});if(m.kind===`offline`)return(0,f.jsx)(o,{port:e});if(m.kind===`error`)return(0,f.jsx)(s,{message:m.message});let N=T.filter(e=>!v(e)),P=N.length>0,F=C===`custom`&&T.length===0,I=h(m.data.permissions);return(0,f.jsxs)(`form`,{className:`settings-page-form`,onSubmit:e=>e.preventDefault(),children:[(0,f.jsxs)(i,{title:`Permissions`,hint:`Selecting a value changes the draft. Save applies it. Auto (YOLO) requests automatic approval or permission bypass. Behavior varies by runtime.`,children:[(0,f.jsx)(c,{id:`permissions-mode`,label:`Change policy to`,value:C,options:x,onChange:A}),C===`custom`&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(l,{id:`permissions-allowlist`,label:`Allowlist`,value:T,onChange:j,placeholder:`bash, read, mcp.*`,error:P?`Invalid token${N.length===1?``:`s`}: ${N.join(`, `)}`:F?`Allowlist cannot be empty in Custom mode.`:null}),(0,f.jsxs)(`p`,{className:`settings-section-hint`,children:[`Each chip is a permission token. Examples: `,(0,f.jsx)(`code`,{children:`bash`}),`,`,(0,f.jsx)(`code`,{children:` read`}),`, `,(0,f.jsx)(`code`,{children:` write`}),`, `,(0,f.jsx)(`code`,{children:` mcp.*`}),`.`]}),F&&(0,f.jsx)(u,{role:`alert`,children:`An empty Custom allowlist cannot be saved. Add at least one token or switch back to Auto (YOLO).`})]})]}),(0,f.jsxs)(i,{title:`Saved policy`,hint:`Shows the saved permission policy.`,children:[(0,f.jsxs)(`p`,{className:`settings-readonly-line`,children:[(0,f.jsx)(`span`,{className:`settings-field-label`,children:`Configured policy:`}),` `,(0,f.jsx)(`span`,{children:I})]}),D?.mode===`unknown`?(0,f.jsx)(`p`,{className:`settings-section-hint`,children:`Use Agent to change this configured policy.`}):null]})]})}export{g as a,v as i,h as n,_ as o,b as r,y as s,S as t};