specrails-hub 1.45.0 → 1.47.0

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 (29) hide show
  1. package/.claude/commands/specrails/explore-spec.md +173 -0
  2. package/client/dist/assets/ActivityFeedPage-BAfa_GyX.js +1 -0
  3. package/client/dist/assets/{AgentsPage-BD9IQo7V.js → AgentsPage-BqOKVmnl.js} +2 -2
  4. package/client/dist/assets/AnalyticsPage-DtIuG3n_.js +4 -0
  5. package/client/dist/assets/{dracula-colors-BgsgBGTu.js → BarChart-BE3HyxWy.js} +3 -3
  6. package/client/dist/assets/{DocsDialog-BDVH7ShW.js → DocsDialog-DGFJFTcb.js} +5 -5
  7. package/client/dist/assets/{DocsPage-Bo1wC8CP.js → DocsPage-DVAx5c74.js} +5 -5
  8. package/client/dist/assets/{ExportDropdown-CI7A-4cJ.js → ExportDropdown-CGL1PqHH.js} +1 -1
  9. package/client/dist/assets/HubAnalyticsPage-CY6Frck1.js +1 -0
  10. package/client/dist/assets/JobDetailPage-4HTOCzUr.js +16 -0
  11. package/client/dist/assets/JobsPage-DdRGolPq.js +1 -0
  12. package/client/dist/assets/{dist-js-DsbP3mpV.js → dist-js-BXjx_Zkw.js} +1 -1
  13. package/client/dist/assets/{dist-js-BfIyF60r.js → dist-js-DyTCNFi6.js} +1 -1
  14. package/client/dist/assets/index-BJdyP2-d.css +2 -0
  15. package/client/dist/assets/{index-DxrdFIhh.js → index-DXv4GvQj.js} +43 -43
  16. package/client/dist/assets/{lib-DuYH34Ny.js → lib-BronG8Mz.js} +2 -2
  17. package/client/dist/index.html +56 -13
  18. package/package.json +1 -1
  19. package/server/dist/chat-manager.js +165 -13
  20. package/server/dist/hub-db.js +6 -0
  21. package/server/dist/hub-router.js +23 -0
  22. package/server/dist/project-router.js +106 -3
  23. package/server/dist/spec-draft-parser.js +133 -0
  24. package/client/dist/assets/ActivityFeedPage-YruEq_WF.js +0 -1
  25. package/client/dist/assets/AnalyticsPage-CY1qModL.js +0 -4
  26. package/client/dist/assets/HubAnalyticsPage-hMyOCcVi.js +0 -1
  27. package/client/dist/assets/JobDetailPage-Bz8Z9h0R.js +0 -16
  28. package/client/dist/assets/JobsPage-DRS94nur.js +0 -1
  29. package/client/dist/assets/index-CKUFLw5U.css +0 -2
@@ -0,0 +1,173 @@
1
+ ---
2
+ description: Interactive thinking partner that helps the user shape a spec through conversation. Maintains a structured live draft via fenced spec-draft JSON blocks. The hub commits the ticket — never call ticket-creation commands yourself.
3
+ ---
4
+
5
+ You are a senior product engineer helping the user shape a single spec through conversation. The user has opened the **Explore Spec** experience inside specrails-hub. You are their thinking partner — same stance as `/opsx:explore`, but the artefact you produce is a single backlog ticket (committed by the hub), not OpenSpec change files.
6
+
7
+ # Your role
8
+
9
+ - **Investigate first**, then ask. Do the homework on the codebase and existing specs before bombarding the user with questions. A grounded clarification beats five guess-questions.
10
+ - **Listen** to the user's idea.
11
+ - **Ask** only the questions you genuinely need to clarify scope, intent, constraints. Avoid filler questions. Two well-aimed questions beat eight generic ones.
12
+ - **Surface** trade-offs, alternatives, and risks the user may not have considered.
13
+ - **Propose** concrete shape: title, priority, labels, what's in/out, acceptance criteria.
14
+ - **Stop asking** once you have enough information for a small, clear, testable spec.
15
+
16
+ # Recommended first-turn investigation
17
+
18
+ On the **first turn only**, take a moment to ground yourself in the project before responding. Read what is cheap to read and likely to inform the spec. Do not dump the findings into the chat — keep them in your context to inform questions and the draft.
19
+
20
+ Useful sources, in order of priority:
21
+
22
+ 1. **Existing tickets** — `.specrails/local-tickets.json` if it exists. Tells you the labels in use, the tone of prior specs, and whether a similar item already exists.
23
+ 2. **OpenSpec specs (if the project uses OpenSpec)** — `openspec/specs/<capability>/spec.md` for capabilities related to the user's idea. Skim `openspec/specs/` to discover capability names. Check `openspec list --json` if it is available.
24
+ 3. **OpenSpec active changes** — `openspec/changes/` if it exists. A spec already in flight may overlap.
25
+ 4. **Project README / CLAUDE.md** — high-signal architectural notes. Often answers "where does X live" without grepping.
26
+ 5. **Targeted code reads** — only when the user's idea names a concrete component / module / feature. Use Glob + Grep to locate, then Read 1-3 focused files. Do **not** open dozens of files looking for inspiration.
27
+
28
+ Stop reading as soon as you have enough to ask a meaningful question. If the idea is generic ("dark mode", "notifications"), you may not need to read any code at all — go straight to clarifying scope.
29
+
30
+ # When to read more code mid-conversation
31
+
32
+ If a later user reply names something specific you haven't seen yet, fetch it then. Examples:
33
+
34
+ - "It should integrate with the SettingsPage" → open `SettingsPage` to confirm structure.
35
+ - "Use the same labels as the auth specs" → grep `local-tickets.json` for auth tickets.
36
+ - "Like the existing dark mode toggle in X" → read X.
37
+
38
+ Avoid reading large or generic code areas. Read with intent.
39
+
40
+ # Critical rule: do NOT modify the project
41
+
42
+ You **MUST NOT**:
43
+ - Create files of any kind.
44
+ - Write to `.specrails/local-tickets.json`, `openspec/**`, or any project file.
45
+ - Call `/specrails:propose-spec`, `/specrails:implement`, or other slash commands that produce side effects.
46
+ - Run shell commands beyond read-only inspection (`ls`, `cat`-equivalents via Read).
47
+
48
+ You may **read** anywhere in the project. The hub commits the final ticket via `POST /tickets/from-draft` when the user clicks **Create Spec**.
49
+
50
+ # The structured draft protocol
51
+
52
+ After every assistant turn that has new draft information, end your message with a fenced code block tagged `spec-draft` containing JSON. The hub parses this block and updates the live draft pane the user sees on the right side of the overlay.
53
+
54
+ ```spec-draft
55
+ {
56
+ "title": "Concise, action-oriented title",
57
+ "description": "## Problem Statement\n2-3 sentences.\n\n## Proposed Solution\n3-5 sentences.\n\n## Out of Scope\n- bullet\n- bullet\n\n## Technical Considerations\n- bullet\n- bullet\n\n## Estimated Complexity\nMedium — one sentence justification.",
58
+ "labels": ["short-label", "another"],
59
+ "priority": "low | medium | high | critical",
60
+ "acceptanceCriteria": ["Bullet 1", "Bullet 2"],
61
+ "chips": ["Up to 3 short user-reply suggestions"],
62
+ "ready": false
63
+ }
64
+ ```
65
+
66
+ Field semantics:
67
+
68
+ - All fields are **optional**. Only include fields you actually want to update; omitted fields keep their previous value.
69
+ - **Empty strings** mean "leave the prior value alone" (no-op). Do not use `""` to clear a field.
70
+ - **Arrays replace** the previous value entirely (they are not appended). To clear, send `[]`.
71
+ - **`priority`** must be one of `low`, `medium`, `high`, `critical`. Other values are dropped.
72
+ - **`description`** must follow this exact section template in markdown:
73
+ - `## Problem Statement` (2-3 sentences)
74
+ - `## Proposed Solution` (3-5 sentences)
75
+ - `## Out of Scope` (bullet list)
76
+ - `## Technical Considerations` (bullet list)
77
+ - `## Estimated Complexity` (`Low`/`Medium`/`High`/`Very High` plus one sentence)
78
+ - **Never include a `## Spec Title` heading inside `description`** — the title lives in its own field. Repeating it inside the body produces redundant tickets.
79
+ - **Never duplicate the acceptance criteria inside `description`** — they live in their own `acceptanceCriteria` array. The hub appends them to the ticket body under a `## Acceptance Criteria` section automatically.
80
+ - **`acceptanceCriteria`** is a separate array of short, testable bullet strings. The hub appends them to the ticket body under a `## Acceptance Criteria` section automatically — do NOT duplicate them inside `description`.
81
+ - **`chips`** are 0-3 short replies the user can click to send as their next message. Use them sparingly; capping the user's options is bad in early turns where the conversation is still wide.
82
+ - **`ready: true`** signals "I think the draft is in good enough shape to commit." Set this when you have a meaningful title, a populated description matching the template, and at least one acceptance criterion. Setting `ready: true` does NOT create the ticket — it only highlights the Create Spec button for the user. The user is always the commit.
83
+ - The block is **not shown to the user**. The hub strips it before rendering your message. So put your visible reasoning above the block, in plain prose.
84
+
85
+ # Language
86
+
87
+ - **Spec content MUST be in English.** All draft fields — `title`, `description`, `labels`, `acceptanceCriteria` — are always written in English regardless of the language the user is speaking. This matches how `/specrails:propose-spec` produces specs and keeps `local-tickets.json` consistent across the project.
88
+ - **Conversation in the user's language.** Your visible prose (questions, summaries, chip suggestions) follows whichever language the user is using. Spanish in, Spanish out — Spanish in, English spec.
89
+ - **Chips** can be in the user's language (they are conversational replies, not part of the spec).
90
+
91
+ # Example interaction
92
+
93
+ **User:** dark mode toggle
94
+
95
+ **Assistant:**
96
+ Good — quick clarifications to scope this tight:
97
+
98
+ - Where lives the toggle: Settings page, in the header, or both?
99
+ - Persistence: localStorage, server-side per user, or just session?
100
+
101
+ ```spec-draft
102
+ {
103
+ "title": "Add dark mode toggle",
104
+ "labels": ["ui", "theme"],
105
+ "priority": "medium",
106
+ "chips": ["Settings page", "Both header and settings", "Just session, no persist"],
107
+ "ready": false
108
+ }
109
+ ```
110
+
111
+ **User:** settings, persist to localStorage, respect system preference as default
112
+
113
+ **Assistant:**
114
+ Got it. That keeps it focused. Anything you want explicitly out of scope (e.g. inline preview, smooth transition animation)?
115
+
116
+ ```spec-draft
117
+ {
118
+ "description": "## Problem Statement\nThe app currently follows the OS theme passively, leaving users no way to override it per session.\n\n## Proposed Solution\nAdd a toggle on the Settings page that switches between light and dark. The first visit honors the OS preference (`prefers-color-scheme`); once the user picks a theme, the choice persists in `localStorage` and overrides the OS on later visits.\n\n## Out of Scope\n- Smooth fade transitions between themes\n- Per-page or per-component theme overrides\n- Multi-account theme sync\n\n## Technical Considerations\n- Read `localStorage['theme']` on bootstrap; fall back to `matchMedia('(prefers-color-scheme: dark)')`\n- Apply the resolved theme via a `data-theme` attribute on `<html>`\n- Toggle component lives in `SettingsPage`\n\n## Estimated Complexity\nLow — small, well-bounded change with no backend touchpoints.",
119
+ "acceptanceCriteria": [
120
+ "Toggle visible in Settings page",
121
+ "Manual choice persists across reloads",
122
+ "First visit honors prefers-color-scheme",
123
+ "Toggle reflects the active theme"
124
+ ],
125
+ "chips": ["No animation needed", "Looks good — create"],
126
+ "ready": true
127
+ }
128
+ ```
129
+
130
+ **User (Spanish):** modo oscuro, toggle en settings, recuerda en localStorage
131
+
132
+ **Assistant (Spanish prose, English spec):**
133
+ Hecho. ¿Algo que quieras dejar fuera explícitamente (p.ej. animaciones de transición)?
134
+
135
+ ```spec-draft
136
+ {
137
+ "title": "Add dark mode toggle",
138
+ "description": "## Problem Statement\nUsers cannot override the OS theme on a per-session basis.\n\n## Proposed Solution\nAdd a Settings page toggle that switches the app between light and dark. The first visit honors the OS preference; once a manual choice is made, it persists in `localStorage` and overrides the OS on later visits.\n\n## Out of Scope\n- Smooth transitions between themes\n- Per-component theme overrides\n\n## Technical Considerations\n- Read `localStorage['theme']` on bootstrap with `prefers-color-scheme` fallback\n- Apply via `data-theme` on `<html>`\n\n## Estimated Complexity\nLow — small, well-scoped change.",
139
+ "acceptanceCriteria": [
140
+ "Toggle visible in Settings page",
141
+ "Manual choice persists across reloads",
142
+ "First visit honors prefers-color-scheme"
143
+ ],
144
+ "labels": ["ui", "theme"],
145
+ "priority": "medium",
146
+ "chips": ["Sin animaciones", "Listo, crear"],
147
+ "ready": true
148
+ }
149
+ ```
150
+
151
+ # Style and tone
152
+
153
+ - Be brief. Two short sentences and a question beats a paragraph.
154
+ - Don't pad with "great question". Get to the substance.
155
+ - Match the user's language (English, Spanish, etc.) on each turn.
156
+ - Don't quote your own draft block back at the user — the user sees the structured panel; you don't need to repeat its content in prose.
157
+ - Treat the user as expert in their domain. Ask, don't lecture.
158
+
159
+ # When to set ready: true
160
+
161
+ Set ready when **all** of these are true:
162
+ - The draft has a title.
163
+ - The draft has a description.
164
+ - The draft has at least one acceptance criterion.
165
+ - You don't have an outstanding clarifying question for the user.
166
+
167
+ Until then, leave `ready: false` (or omit `ready`).
168
+
169
+ The user's idea follows below. Begin the conversation.
170
+
171
+ ---
172
+
173
+ $ARGUMENTS
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-CilyBKbf.js";import{At as t,F as n,ct as r,dt as i,et as a,ft as o,lt as s,q as c,st as l,tt as u,ut as d}from"./index-DXv4GvQj.js";var f=r(`ban`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}]]),p=e(t(),1);function m(e){let t=new Set;return e.filter(e=>{let n=`${e.type}:${e.jobId}`;return t.has(n)?!1:(t.add(n),!0)})}function h({activeProjectId:e,limit:t=50}){let[n,r]=(0,p.useState)([]),[i,a]=(0,p.useState)(!1),[s,c]=(0,p.useState)(!0),l=(0,p.useRef)(e);(0,p.useEffect)(()=>{l.current=e},[e]);let{registerHandler:u,unregisterHandler:f}=d();(0,p.useEffect)(()=>{if(!e){r([]),c(!0);return}let n=!1;a(!0),r([]),c(!0);async function i(){let e=o();try{let i=await fetch(`${e}/activity?limit=${t}`);if(!i.ok||n)return;let a=await i.json();if(n)return;r(a),c(a.length===t)}catch{}finally{n||a(!1)}}return i(),()=>{n=!0}},[e,t]);let h=(0,p.useCallback)(async()=>{if(i||!s)return;a(!0);let e=o();try{r(n=>{let i=n[n.length-1];if(!i)return n;let o=encodeURIComponent(i.timestamp);return fetch(`${e}/activity?limit=${t}&before=${o}`).then(e=>e.json()).then(e=>{r(t=>m([...t,...e])),c(e.length===t),a(!1)}).catch(()=>a(!1)),n})}catch{a(!1)}},[i,s,t]),g=(0,p.useCallback)(e=>{let t=e,n=l.current;if(!(!t||typeof t.type!=`string`)&&!(t.projectId&&t.projectId!==n)){if(t.type===`queue`&&Array.isArray(t.jobs)){let e=[];for(let n of t.jobs){let t=n.status===`completed`?`job_completed`:n.status===`failed`?`job_failed`:n.status===`canceled`?`job_canceled`:`job_started`;e.push({id:`${t}:${n.id}`,type:t,jobId:n.id,jobCommand:n.command??``,timestamp:n.startedAt??new Date().toISOString(),summary:`${t.replace(`_`,` `)}: ${n.command??``}`,costUsd:null})}e.length>0&&r(t=>m([...e,...t]))}if(t.type===`phase`&&t.phase&&t.state&&t.timestamp){let e={id:`phase:${t.phase}:${t.state}:${t.timestamp}`,type:`job_started`,jobId:`phase-${t.phase}`,jobCommand:`Phase: ${t.phase} → ${t.state}`,timestamp:t.timestamp,summary:`Phase ${t.phase} is ${t.state}`,costUsd:null};r(t=>m([e,...t]))}}},[]);return(0,p.useLayoutEffect)(()=>(u(`activity`,g),()=>f(`activity`)),[g,u,f]),{items:n,loading:i,hasMore:s,loadMore:h}}var g=i();function _(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function v({type:e}){switch(e){case`job_completed`:return(0,g.jsx)(u,{className:`w-4 h-4 text-green-500 flex-shrink-0`});case`job_failed`:return(0,g.jsx)(a,{className:`w-4 h-4 text-red-500 flex-shrink-0`});case`job_canceled`:return(0,g.jsx)(f,{className:`w-4 h-4 text-muted-foreground flex-shrink-0`});default:return(0,g.jsx)(n,{className:`w-4 h-4 text-blue-500 flex-shrink-0`})}}function y(e){switch(e){case`job_completed`:return`Completed`;case`job_failed`:return`Failed`;case`job_canceled`:return`Canceled`;default:return`Started`}}function b(e){switch(e){case`job_completed`:return`text-green-500`;case`job_failed`:return`text-red-500`;case`job_canceled`:return`text-muted-foreground`;default:return`text-blue-500`}}function x(){let{activeProjectId:e}=s(),{items:t,loading:n,hasMore:r,loadMore:i}=h({activeProjectId:e}),a=(0,p.useRef)(null);return(0,p.useEffect)(()=>{let e=a.current;if(!e)return;let t=new IntersectionObserver(e=>{e[0].isIntersecting&&r&&!n&&i()},{threshold:.1});return t.observe(e),()=>t.disconnect()},[r,n,i]),(0,g.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden`,children:[(0,g.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-3 border-b border-border bg-background/50`,children:[(0,g.jsx)(l,{className:`w-4 h-4 text-muted-foreground`}),(0,g.jsx)(`h1`,{className:`text-sm font-medium`,children:`Activity`})]}),(0,g.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[n&&t.length===0?(0,g.jsx)(`div`,{className:`flex items-center justify-center h-32`,children:(0,g.jsx)(c,{className:`w-4 h-4 animate-spin text-muted-foreground`})}):t.length===0?(0,g.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground`,children:[(0,g.jsx)(l,{className:`w-8 h-8 opacity-40`}),(0,g.jsx)(`p`,{className:`text-sm`,children:`No activity yet`}),(0,g.jsx)(`p`,{className:`text-xs opacity-70`,children:`Job events will appear here when jobs run`})]}):(0,g.jsx)(`ul`,{className:`divide-y divide-border/50`,children:t.map(e=>(0,g.jsxs)(`li`,{className:`flex items-center gap-3 px-4 py-2.5 hover:bg-accent/30 transition-colors`,children:[(0,g.jsx)(v,{type:e.type}),(0,g.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,g.jsx)(`p`,{className:`text-xs text-foreground truncate`,title:e.jobCommand,children:e.jobCommand}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5`,children:[(0,g.jsx)(`span`,{className:`text-xs font-medium ${b(e.type)}`,children:y(e.type)}),e.costUsd!=null&&(0,g.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`$`,e.costUsd.toFixed(4)]})]})]}),(0,g.jsx)(`span`,{className:`text-xs text-muted-foreground flex-shrink-0 tabular-nums`,children:_(e.timestamp)})]},`${e.type}:${e.jobId}`))}),(0,g.jsx)(`div`,{ref:a,className:`h-1`}),n&&t.length>0&&(0,g.jsx)(`div`,{className:`flex justify-center py-3`,children:(0,g.jsx)(c,{className:`w-4 h-4 animate-spin text-muted-foreground`})}),!r&&t.length>0&&(0,g.jsx)(`p`,{className:`text-center text-xs text-muted-foreground py-3`,children:`All activity loaded`})]})]})}export{x as default};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./chunk-CilyBKbf.js";import{A as t,B as n,Ct as r,D as i,E as a,F as o,I as s,J as c,K as l,L as u,N as d,O as f,R as p,St as m,U as h,W as g,Y as _,Z as v,_t as ee,at as y,bt as b,c as x,ct as S,d as C,dt as w,ft as T,gt as E,ht as D,j as O,k,kt as A,l as j,lt as M,mt as N,pt as P,q as F,s as I,st as L,u as R,ut as z,vt as B,wt as V,xt as H,yt as te,z as U}from"./index-DxrdFIhh.js";var W=L(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),G=L(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),ne=L(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),K=L(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),q=L(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),J=L(`pin`,[[`path`,{d:`M12 17v5`,key:`bb1du9`}],[`path`,{d:`M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z`,key:`1nkz8b`}]]),re=L(`tag`,[[`path`,{d:`M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z`,key:`vktsd0`}],[`circle`,{cx:`7.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`kqv944`}]]),ie=L(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),Y=e(A(),1),X=z(),ae=/^[a-z0-9][a-z0-9-]*$/;function oe({open:e,mode:n=`add`,initial:r,chainAgents:o,onConfirm:s,onCancel:c}){let[l,u]=(0,Y.useState)(``),[p,m]=(0,Y.useState)(o[0]??``);(0,Y.useEffect)(()=>{e&&(n===`edit`&&r?(u(r.tags.join(`, `)),m(o.includes(r.agent)?r.agent:o[0]??``)):(u(``),m(o[0]??``)))},[e,n,r,o]);let h=l.split(`,`).map(e=>e.trim()).filter(Boolean),g=h.filter(e=>!ae.test(e)),_=h.length>0&&g.length===0&&o.includes(p);return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||c()},children:(0,X.jsxs)(i,{className:`max-w-md`,children:[(0,X.jsxs)(t,{children:[(0,X.jsx)(O,{children:n===`edit`?`Edit routing rule`:`Add routing rule`}),(0,X.jsx)(f,{children:n===`edit`?`Update the tags or target agent for this rule.`:`Add a tag-matched routing rule using lowercase kebab-case tags.`})]}),(0,X.jsxs)(`div`,{className:`py-2 space-y-3`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Tags`}),(0,X.jsx)(I,{autoFocus:!0,value:l,onChange:e=>u(e.target.value),placeholder:`frontend, ui`,"aria-label":`Tags`,className:`text-sm font-mono`}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:[`Comma-separated. Use lowercase kebab-case like `,(0,X.jsx)(`code`,{children:`frontend`}),` or `,(0,X.jsx)(`code`,{children:`api-design`}),`.`]}),g.length>0&&(0,X.jsxs)(`p`,{className:`text-[11px] text-red-400 mt-1`,children:[`Invalid tag`,g.length===1?``:`s`,`: `,g.join(`, `),`. Tags must use lowercase letters, digits, and hyphens only.`]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Route to`}),(0,X.jsx)(`select`,{value:p,onChange:e=>m(e.target.value),"aria-label":`Route to`,className:`w-full h-9 px-2 text-sm rounded-md border border-border bg-background`,children:o.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))}),(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:`Only agents in this profile's chain can be routing targets.`})]})]}),(0,X.jsxs)(k,{children:[(0,X.jsx)(d,{variant:`ghost`,size:`sm`,onClick:c,children:`Cancel`}),(0,X.jsx)(d,{size:`sm`,onClick:()=>s(h,p),disabled:!_,children:n===`edit`?`Save changes`:`Add rule`})]})]})})}var Z=new Set([`sr-architect`,`sr-developer`,`sr-reviewer`,`sr-merge-resolver`]),se=[`sonnet`,`opus`,`haiku`],ce=/^[a-z0-9][a-z0-9-]*$/;function le({profile:e,onChange:t,footer:n,onValidityChange:r,onSoftWarningsChange:i}){let[a,s]=(0,Y.useState)([]),[c,l]=(0,Y.useState)(!1),[u,f]=(0,Y.useState)(!1),[p,g]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{let e=!1;return fetch(`${w()}/profiles/catalog`).then(e=>e.ok?e.json():{agents:[]}).then(t=>{e||s(t.agents)}).catch(()=>{e||s([])}),()=>{e=!0}},[]);let _=n=>{let r=JSON.parse(JSON.stringify(e));n(r),t(r)},v=new Set(e.agents.map(e=>e.id)),y=a.filter(e=>!v.has(e.id)),x=(0,Y.useMemo)(()=>{let t=[];for(let n of Z)e.agents.some(e=>e.id===n)||t.push(`Missing required baseline agent: ${n}`);let n=e.routing.filter(e=>`default`in e&&e.default===!0);if(n.length>1&&t.push(`Routing may have at most one default rule (found ${n.length})`),n.length===1){let n=e.routing[e.routing.length-1];`default`in n&&n.default===!0||t.push(`The default routing rule must be the last entry`)}for(let n of e.routing)if(e.agents.some(e=>e.id===n.agent)||t.push(`Routing references agent not in the chain: ${n.agent}`),`tags`in n){let e=n.tags.filter(e=>!ce.test(e));e.length>0&&t.push(`Routing rule ${n.agent} has invalid tags: ${e.join(`, `)} (use lowercase kebab-case)`)}return t},[e]),S=(0,Y.useMemo)(()=>{if(e.routing.length===0)return[];let t=new Set(e.routing.map(e=>e.agent));return e.agents.filter(e=>!Z.has(e.id)&&!t.has(e.id)).map(e=>e.id)},[e]),C=(0,Y.useMemo)(()=>e.routing.some(e=>`default`in e&&e.default===!0),[e.routing]);(0,Y.useEffect)(()=>{r&&r(x)},[x,r]),(0,Y.useEffect)(()=>{i&&i({agentsMissingRouting:S})},[S,i]);let D=e=>{_(t=>{let n={id:e,model:`sonnet`},r=t.agents.findIndex(e=>e.id===`sr-merge-resolver`);r>=0?t.agents.splice(r,0,n):t.agents.push(n)}),l(!1)},O=t=>{let n=e.agents[t];Z.has(n.id)||_(e=>{e.agents.splice(t,1),e.routing=e.routing.filter(e=>e.agent!==n.id)})},k=(t,n)=>{if(t===n)return;let r=e.agents.findIndex(e=>e.id===t),i=e.agents.findIndex(e=>e.id===n);if(r<0||i<0)return;let a=P(e.agents,r,i),o=a.findIndex(e=>e.id===`sr-architect`);if(o>0){let[e]=a.splice(o,1);a.unshift(e)}let s=a.findIndex(e=>e.id===`sr-merge-resolver`);if(s>=0&&s!==a.length-1){let[e]=a.splice(s,1);a.push(e)}_(e=>{e.agents=a})},A=m(H(te,{activationConstraint:{distance:4}}),H(B,{coordinateGetter:N})),j=e=>{let{active:t,over:n}=e;n&&k(String(t.id),String(n.id))},M=(e,t)=>{_(n=>{n.agents[e].model=t})},F=(e,t)=>{_(n=>{let r={tags:e,agent:t},i=n.routing.findIndex(e=>`default`in e&&e.default===!0);i>=0?n.routing.splice(i,0,r):n.routing.push(r)}),f(!1)},L=()=>{_(e=>{e.routing.some(e=>`default`in e&&e.default===!0)||e.agents.some(e=>e.id===`sr-developer`)&&e.routing.push({default:!0,agent:`sr-developer`})})},R=e=>`default`in e&&e.default===!0,z=(e,t)=>{_(n=>{let r=n.routing[e];r&&(R(r)||(r.agent=t))})},V=(e,t,n)=>{_(r=>{let i=r.routing[e];i&&(R(i)||(i.tags=t,i.agent=n))})},U=e=>{_(t=>{let n=t.routing[e];n&&(R(n)||t.routing.splice(e,1))})},W=(t,n)=>{let r=t+n;if(r<0||r>=e.routing.length)return;let i=e.routing[t],a=e.routing[r];R(i)||R(a)||_(e=>{let[n]=e.routing.splice(t,1);e.routing.splice(r,0,n)})};return(0,X.jsxs)(`div`,{className:`p-6 space-y-6 max-w-3xl`,children:[(0,X.jsx)(oe,{open:u,mode:`add`,chainAgents:e.agents.map(e=>e.id),onConfirm:F,onCancel:()=>f(!1)}),(0,X.jsx)(oe,{open:p!==null,mode:`edit`,initial:p!==null&&e.routing[p]&&!(`default`in e.routing[p])?{tags:e.routing[p].tags,agent:e.routing[p].agent}:void 0,chainAgents:e.agents.map(e=>e.id),onConfirm:(e,t)=>{p!==null&&(V(p,e,t),g(null))},onCancel:()=>g(null)}),x.length>0&&(0,X.jsxs)(`div`,{className:`px-3 py-2 text-xs rounded-md border border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[(0,X.jsxs)(`div`,{className:`font-medium mb-1`,children:[x.length,` validation `,x.length===1?`issue`:`issues`]}),(0,X.jsx)(`ul`,{className:`list-disc list-inside space-y-0.5`,children:x.map((e,t)=>(0,X.jsx)(`li`,{children:e},t))})]}),(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Name`}),(0,X.jsx)(I,{value:e.name,disabled:!0,className:`text-sm`})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Description`}),(0,X.jsx)(I,{value:e.description??``,onChange:e=>_(t=>{t.description=e.target.value}),className:`text-sm`,placeholder:`What is this profile for?`})]})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsx)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2`,children:`Orchestrator`}),(0,X.jsxs)(`div`,{className:`flex items-center gap-3 p-3 rounded-md border border-border`,children:[(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsx)(`div`,{className:`text-sm font-mono text-foreground truncate`,children:`/specrails:implement · /specrails:batch-implement`}),(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground mt-0.5`,children:`Top-level model for both commands. batch-implement delegates to implement per feature, so every rail it spawns inherits this profile's agent chain.`})]}),(0,X.jsx)(fe,{value:e.orchestrator.model,onChange:e=>_(t=>{t.orchestrator.model=e})})]})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,X.jsxs)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:[`Agent chain (`,e.agents.length,`)`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>l(e=>!e),disabled:y.length===0,title:y.length===0?`All catalog agents are already in the chain`:`Add an agent from the catalog`,children:[(0,X.jsx)(h,{className:`w-3.5 h-3.5 mr-1`}),` Add`]})]}),c&&(0,X.jsxs)(`div`,{className:`mb-2 p-2 rounded-md border border-border bg-muted/30`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5 px-1`,children:[(0,X.jsxs)(`span`,{className:`text-[11px] text-muted-foreground`,children:[`Pick from catalog (`,y.length,` available)`]}),(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:()=>l(!1),title:`Close`,children:(0,X.jsx)(o,{className:`w-3 h-3`})})]}),y.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground text-center`,children:`No more agents in the catalog. Add custom agents from the Agents Catalog tab.`}):(0,X.jsx)(`div`,{className:`space-y-0.5 max-h-64 overflow-auto`,children:y.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>D(e.id),className:`w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded hover:bg-accent transition-colors`,children:[(0,X.jsx)(`span`,{className:`text-sm font-mono`,children:e.id}),(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded `+(e.kind===`custom`?`bg-purple-500/15 text-purple-400`:`bg-muted text-muted-foreground`),children:e.kind})]},e.id))})]}),(0,X.jsx)(ee,{sensors:A,collisionDetection:b,onDragEnd:j,children:(0,X.jsx)(T,{items:e.agents.map(e=>e.id),strategy:E,children:(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.agents.map((e,t)=>(0,X.jsx)(ue,{agent:e,canRemove:!Z.has(e.id),onModel:e=>M(t,e),onRemove:()=>O(t)},e.id))})})})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,X.jsxs)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:[`Routing (`,e.routing.length,`)`]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1`,children:[!C&&(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:L,disabled:e.agents.length===0,title:e.agents.length===0?`Add at least one agent before creating routing rules`:void 0,children:[(0,X.jsx)(h,{className:`w-3.5 h-3.5 mr-1`}),` Add default`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>f(!0),disabled:e.agents.length===0,title:e.agents.length===0?`Add at least one agent before creating routing rules`:void 0,children:[(0,X.jsx)(h,{className:`w-3.5 h-3.5 mr-1`}),` Add rule`]})]})]}),(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground mb-2`,children:`First matching rule wins. Rules are editable and removable, and the default catch-all stays last when present. If you leave routing empty, the pipeline falls back to the first developer-shaped agent in the chain.`}),S.length>0&&(0,X.jsxs)(`div`,{className:`mb-2 px-3 py-2 text-xs rounded-md border border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[(0,X.jsx)(`div`,{className:`font-medium mb-1`,children:`Untargeted agents in the chain`}),(0,X.jsxs)(`div`,{children:[`No routing rule points to: `,(0,X.jsx)(`span`,{className:`font-mono`,children:S.join(`, `)}),`. Add a tag rule or retarget the default rule if you want them to run.`]})]}),(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.routing.map((t,n)=>{let r=`default`in t&&t.default===!0;return(0,X.jsx)(de,{rule:t,ordinal:n+1,isLast:n===e.routing.length-1,canMove:!r,canRemove:!r,canEdit:!r,chainAgents:e.agents.map(e=>e.id),onAgentChange:e=>z(n,e),onEdit:()=>g(n),onUp:()=>W(n,-1),onDown:()=>W(n,1),onRemove:()=>U(n)},n)})})]}),n&&(0,X.jsx)(`div`,{className:`pt-3 border-t border-border`,children:n})]})}function ue({agent:e,canRemove:t,onModel:n,onRemove:i}){let a=Z.has(e.id),s=e.id===`sr-architect`,c=e.id===`sr-merge-resolver`,{attributes:l,listeners:u,setNodeRef:d,transform:f,transition:p,isDragging:m}=D({id:e.id});return(0,X.jsxs)(`div`,{ref:d,style:{transform:r.Transform.toString(f),transition:p,opacity:m?.5:void 0,zIndex:m?10:void 0},className:`flex items-center gap-2 px-2 py-1.5 rounded-md border border-border group hover:bg-accent/30 transition-colors bg-background`,children:[(0,X.jsx)(`button`,{type:`button`,className:`flex-shrink-0 p-0.5 rounded text-muted-foreground cursor-grab active:cursor-grabbing hover:text-foreground`,title:`Drag to reorder`,"aria-label":`Drag handle`,...l,...u,children:(0,X.jsx)(F,{className:`w-3.5 h-3.5`})}),(0,X.jsx)(`span`,{className:`text-sm font-mono flex-1 truncate`,children:e.id}),s&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-dracula-purple/15 text-dracula-purple`,title:`Pinned to first position — pipeline always starts with sr-architect`,children:[(0,X.jsx)(J,{className:`w-2.5 h-2.5 rotate-[135deg]`}),` first`]}),c&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-dracula-purple/15 text-dracula-purple`,title:`Pinned to last position — merge phase always runs last`,children:[(0,X.jsx)(J,{className:`w-2.5 h-2.5 rotate-45`}),` last`]}),a&&!s&&!c&&(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`required`}),(0,X.jsx)(fe,{value:e.model??`sonnet`,onChange:n}),(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded disabled:opacity-30 disabled:cursor-not-allowed opacity-0 group-hover:opacity-100 transition-opacity`,onClick:i,disabled:!t,title:t?`Remove`:`Required baseline agent — the pipeline depends on this row`,children:(0,X.jsx)(o,{className:`w-3 h-3`})})]})}function de({rule:e,ordinal:t,isLast:n,canMove:r,canRemove:i,canEdit:a,chainAgents:s,onAgentChange:c,onEdit:l,onUp:u,onDown:d,onRemove:f}){let p=`default`in e&&e.default===!0;return(0,X.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 rounded-md border border-border group hover:bg-accent/30 transition-colors`,children:[(0,X.jsxs)(`span`,{className:`text-[10px] font-mono text-muted-foreground w-5 text-center flex-shrink-0`,children:[t,`.`]}),p?(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1`,children:`everything else`}):(0,X.jsx)(`span`,{className:`text-xs flex-1 flex gap-1 flex-wrap items-center`,children:e.tags.map(e=>(0,X.jsx)(`span`,{className:`px-1.5 py-0.5 rounded bg-muted font-mono text-[11px]`,children:e},e))}),(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`→`}),p?(0,X.jsx)(`span`,{className:`h-7 max-w-[15rem] px-2 text-xs font-mono rounded border border-border bg-muted/40 text-muted-foreground inline-flex items-center`,"aria-label":`Default routing target (core, read-only)`,title:`Core fallback — not editable`,children:e.agent}):(0,X.jsx)(`select`,{value:e.agent,onChange:e=>c(e.target.value),"aria-label":`Routing target for rule ${t}`,className:`h-7 max-w-[15rem] px-2 text-xs font-mono rounded border border-border bg-background`,children:s.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))}),(0,X.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity`,children:[a&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:l,title:`Edit rule`,"aria-label":`Edit rule ${t}`,children:(0,X.jsx)(g,{className:`w-3 h-3`})}),r&&!n&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:d,title:`Move down`,children:(0,X.jsx)(W,{className:`w-3 h-3`})}),r&&t>1&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:u,title:`Move up`,children:(0,X.jsx)(G,{className:`w-3 h-3`})}),i&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded`,onClick:f,title:`Remove`,children:(0,X.jsx)(o,{className:`w-3 h-3`})})]}),p&&(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,title:`Core fallback — the pipeline's last-resort rule, pinned to sr-developer`,children:`core · default`})]})}function fe({value:e,onChange:t}){return(0,X.jsx)(`select`,{value:e,onChange:e=>t(e.target.value),className:`h-7 px-2 text-xs rounded border border-border bg-background`,children:se.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))})}function Q({open:e,title:n,description:r,placeholder:o,initialValue:s=``,confirmLabel:c=`Confirm`,inputPattern:l,inputInvalidHint:u,onConfirm:f,onCancel:p}){let[m,h]=(0,Y.useState)(s);(0,Y.useEffect)(()=>{e&&h(s)},[e,s]);let g=m.trim(),_=!l||l.test(g),v=g.length>0&&_;return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||p()},children:(0,X.jsxs)(i,{className:`max-w-md`,children:[(0,X.jsx)(t,{children:(0,X.jsx)(O,{children:n})}),(0,X.jsxs)(`div`,{className:`py-2 space-y-2`,children:[r&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),(0,X.jsx)(I,{autoFocus:!0,value:m,placeholder:o,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&v&&f(g)},className:`text-sm font-mono`}),g.length>0&&!_&&u&&(0,X.jsx)(`p`,{className:`text-[11px] text-yellow-500`,children:u})]}),(0,X.jsxs)(k,{children:[(0,X.jsx)(d,{variant:`ghost`,size:`sm`,onClick:p,children:`Cancel`}),(0,X.jsx)(d,{size:`sm`,onClick:()=>f(g),disabled:!v,children:c})]})]})})}function pe({open:e,title:n,description:r,confirmLabel:o=`Confirm`,destructive:s=!1,onConfirm:c,onCancel:l}){return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||l()},children:(0,X.jsxs)(i,{className:`max-w-md`,children:[(0,X.jsx)(t,{children:(0,X.jsx)(O,{children:n})}),r&&(0,X.jsx)(`div`,{className:`py-2`,children:(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r})}),(0,X.jsxs)(k,{children:[(0,X.jsx)(d,{variant:`ghost`,size:`sm`,onClick:l,children:`Cancel`}),(0,X.jsx)(d,{size:`sm`,onClick:c,className:s?`bg-red-500 hover:bg-red-600 text-white`:void 0,children:o})]})]})})}function me(){let[e,t]=(0,Y.useState)([]),[r,i]=(0,Y.useState)(null),[a,o]=(0,Y.useState)(null),[s,c]=(0,Y.useState)(!0),[l,f]=(0,Y.useState)(null),[p,m]=(0,Y.useState)(!1),[g,_]=(0,Y.useState)([]),[ee,y]=(0,Y.useState)([]),[b,x]=(0,Y.useState)(!1),[S,C]=(0,Y.useState)(null),[T,E]=(0,Y.useState)(null),D=(0,Y.useCallback)(async()=>{c(!0),f(null);try{let e=await fetch(`${w()}/profiles`);if(!e.ok)throw Error(`List failed: ${e.status}`);let n=await e.json();t(n.profiles),n.profiles.length>0&&!r&&i(n.profiles[0].name)}catch(e){f(e.message)}finally{c(!1)}},[r]);(0,Y.useEffect)(()=>{D()},[D]),(0,Y.useEffect)(()=>{if(!r){o(null);return}let e=!1;return fetch(`${w()}/profiles/${encodeURIComponent(r)}`).then(e=>{if(!e.ok)throw Error(`Load failed: ${e.status}`);return e.json()}).then(t=>{e||o(t.profile)}).catch(t=>{e||f(t.message)}),()=>{e=!0}},[r]);let O=(0,Y.useCallback)(async()=>{m(!0),f(null);try{let e=await fetch(`${w()}/profiles/migrate-from-settings`,{method:`POST`});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Migration failed: ${e.status}`)}await D(),i(`default`),V.success(`Profile migrated`,{description:`default profile created from your current agents`})}catch(e){let t=e.message;f(t),V.error(`Migration failed`,{description:t})}finally{m(!1)}},[D]),k=(0,Y.useCallback)(async e=>{x(!1),m(!0),f(null);try{let t={schemaVersion:1,name:e,description:``,orchestrator:{model:`sonnet`},agents:[{id:`sr-architect`,model:`sonnet`,required:!0},{id:`sr-developer`,model:`sonnet`,required:!0},{id:`sr-reviewer`,model:`sonnet`,required:!0},{id:`sr-merge-resolver`,model:`sonnet`,required:!0}],routing:[{default:!0,agent:`sr-developer`}]},n=await fetch(`${w()}/profiles`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Create failed: ${n.status}`)}await D(),i(e),V.success(`Profile created`,{description:e})}catch(e){let t=e.message;f(t),V.error(`Failed to create profile`,{description:t})}finally{m(!1)}},[D]),A=(0,Y.useCallback)(async(e,t)=>{C(null),m(!0),f(null);try{let n=await fetch(`${w()}/profiles/${encodeURIComponent(e)}/duplicate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Duplicate failed: ${n.status}`)}await D(),i(t),V.success(`Profile duplicated`,{description:`${e} → ${t}`})}catch(e){let t=e.message;f(t),V.error(`Failed to duplicate profile`,{description:t})}finally{m(!1)}},[D]),j=(0,Y.useCallback)(async e=>{E(null),m(!0),f(null);try{let t=await fetch(`${w()}/profiles/${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Delete failed: ${t.status}`)}i(t=>t===e?null:t),await D(),V.success(`Profile deleted`,{description:e})}catch(e){let t=e.message;f(t),V.error(`Failed to delete profile`,{description:t})}finally{m(!1)}},[D]),M=(0,Y.useCallback)(()=>x(!0),[]),N=(0,Y.useCallback)(e=>C({from:e}),[]),P=(0,Y.useCallback)(e=>E({name:e}),[]),F=(0,Y.useCallback)(async(e,t)=>{m(!0),f(null);try{let n=await fetch(`${w()}/profiles/${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Save failed: ${n.status}`)}o(e),t.length>0?V.warning(`Profile saved with untargeted agents`,{description:`No routing rule points to: ${t.join(`, `)}. Add a tag rule or retarget the default rule if you want them to run.`,duration:6e3}):V.success(`Profile saved`,{description:e.name})}catch(e){let t=e.message;f(t),V.error(`Failed to save profile`,{description:t})}finally{m(!1)}},[]),I=(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Q,{open:b,title:`New profile`,description:`Pick a lowercase kebab-case name (letters, digits, and hyphens).`,placeholder:`my-profile`,confirmLabel:`Create`,inputPattern:/^[a-z0-9][a-z0-9-]*$/,inputInvalidHint:`Must start with a letter or digit and contain only lowercase letters, digits, and hyphens.`,onConfirm:e=>void k(e),onCancel:()=>x(!1)}),S&&(0,X.jsx)(Q,{open:!0,title:`Duplicate "${S.from}"`,description:`Name for the new profile.`,placeholder:`${S.from}-copy`,initialValue:`${S.from}-copy`,confirmLabel:`Duplicate`,inputPattern:/^[a-z0-9][a-z0-9-]*$/,inputInvalidHint:`Lowercase kebab-case only.`,onConfirm:e=>void A(S.from,e),onCancel:()=>C(null)}),T&&(0,X.jsx)(pe,{open:!0,title:`Delete profile "${T.name}"?`,description:`This cannot be undone. Jobs already launched with this profile keep their snapshot; future launches will fall back to the resolution order.`,confirmLabel:`Delete`,destructive:!0,onConfirm:()=>void j(T.name),onCancel:()=>E(null)})]});return s?(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading profiles…`})}):e.length===0?(0,X.jsxs)(X.Fragment,{children:[I,(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsxs)(`div`,{className:`text-center max-w-md`,children:[(0,X.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:`No profiles yet`}),(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 mb-4`,children:`Profiles let you save orchestrator + agent + routing combinations and pick one per rail.`}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2 justify-center`,children:[(0,X.jsxs)(d,{size:`sm`,onClick:O,disabled:p,children:[(0,X.jsx)(ie,{className:`w-3.5 h-3.5 mr-1.5`}),` Migrate from current agents`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:M,disabled:p,children:[(0,X.jsx)(h,{className:`w-3.5 h-3.5 mr-1.5`}),` Blank profile`]})]}),(0,X.jsxs)(`div`,{className:`text-[11px] text-muted-foreground/70 mt-3`,children:[`"Migrate" reads your existing `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`.claude/agents/`}),` `,`frontmatter models and creates a `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`default`}),` profile mirroring today's behavior — zero-loss.`]}),l&&(0,X.jsx)(`div`,{className:`mt-3 text-xs text-red-400`,children:l})]})})]}):(0,X.jsxs)(`div`,{className:`flex flex-col h-full`,children:[I,(0,X.jsxs)(`div`,{className:`flex flex-1 min-h-0`,children:[(0,X.jsxs)(`aside`,{className:`w-64 flex-shrink-0 border-r border-border flex flex-col`,children:[(0,X.jsxs)(`div`,{className:`p-3 flex items-center justify-between`,children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Profiles`}),(0,X.jsx)(d,{size:`sm`,variant:`ghost`,onClick:M,disabled:p,children:(0,X.jsx)(h,{className:`w-3.5 h-3.5`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-auto px-2 pb-3`,children:e.map(e=>(0,X.jsxs)(`div`,{className:`group mb-1 rounded-md px-2 py-1.5 text-xs cursor-pointer transition-colors flex items-center justify-between `+(e.name===r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),onClick:()=>i(e.name),role:`button`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&i(e.name)},children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,X.jsx)(`span`,{className:`truncate font-medium`,children:e.name}),e.isDefault&&(0,X.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`(team default)`})]}),(0,X.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity`,children:[(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,title:`Duplicate`,onClick:t=>{t.stopPropagation(),N(e.name)},children:(0,X.jsx)(v,{className:`w-3 h-3`})}),!e.isDefault&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded`,title:`Delete`,onClick:t=>{t.stopPropagation(),P(e.name)},children:(0,X.jsx)(u,{className:`w-3 h-3`})})]})]},e.name))})]}),(0,X.jsxs)(`main`,{className:`flex-1 overflow-auto`,children:[l&&(0,X.jsx)(`div`,{className:`mx-4 mt-4 px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:l}),a?(0,X.jsx)(le,{profile:a,onChange:o,onValidityChange:_,onSoftWarningsChange:e=>y(e.agentsMissingRouting),footer:(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsxs)(d,{size:`sm`,onClick:()=>void F(a,ee),disabled:p||g.length>0,title:g.length>0?`Fix validation issues before saving`:void 0,children:[(0,X.jsx)(n,{className:`w-3.5 h-3.5 mr-1.5`}),`Save`]}),p&&(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Saving…`}),g.length>0&&(0,X.jsxs)(`span`,{className:`text-xs text-yellow-500`,children:[g.length,` `,g.length===1?`issue`:`issues`,` to resolve`]})]})},a.name):(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select a profile to edit`})})]})]})]})}function $(e){let t=e.workflow.map((e,t)=>`${t+1}. ${e}`).join(`
1
+ import{r as e}from"./chunk-CilyBKbf.js";import{A as t,At as n,B as r,Ct as i,D as a,G as o,I as s,J as c,L as l,M as u,O as d,P as f,Q as p,R as m,St as h,Tt as g,V as _,W as v,X as y,Y as b,_t as x,bt as S,c as C,ct as w,d as T,dt as E,f as D,ft as O,gt as k,ht as A,j,k as M,l as N,lt as P,mt as F,ot as I,pt as L,q as R,u as z,ut as B,vt as V,wt as H,xt as U,yt as ee,z as W}from"./index-DXv4GvQj.js";var G=w(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),K=w(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),te=w(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),q=w(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),J=w(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),ne=w(`pin`,[[`path`,{d:`M12 17v5`,key:`bb1du9`}],[`path`,{d:`M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z`,key:`1nkz8b`}]]),re=w(`tag`,[[`path`,{d:`M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z`,key:`vktsd0`}],[`circle`,{cx:`7.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`kqv944`}]]),ie=w(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),Y=e(n(),1),X=E(),ae=/^[a-z0-9][a-z0-9-]*$/;function oe({open:e,mode:n=`add`,initial:r,chainAgents:i,onConfirm:o,onCancel:s}){let[c,l]=(0,Y.useState)(``),[p,m]=(0,Y.useState)(i[0]??``);(0,Y.useEffect)(()=>{e&&(n===`edit`&&r?(l(r.tags.join(`, `)),m(i.includes(r.agent)?r.agent:i[0]??``)):(l(``),m(i[0]??``)))},[e,n,r,i]);let h=c.split(`,`).map(e=>e.trim()).filter(Boolean),g=h.filter(e=>!ae.test(e)),_=h.length>0&&g.length===0&&i.includes(p);return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||s()},children:(0,X.jsxs)(d,{className:`max-w-md`,children:[(0,X.jsxs)(j,{children:[(0,X.jsx)(u,{children:n===`edit`?`Edit routing rule`:`Add routing rule`}),(0,X.jsx)(M,{children:n===`edit`?`Update the tags or target agent for this rule.`:`Add a tag-matched routing rule using lowercase kebab-case tags.`})]}),(0,X.jsxs)(`div`,{className:`py-2 space-y-3`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Tags`}),(0,X.jsx)(C,{autoFocus:!0,value:c,onChange:e=>l(e.target.value),placeholder:`frontend, ui`,"aria-label":`Tags`,className:`text-sm font-mono`}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:[`Comma-separated. Use lowercase kebab-case like `,(0,X.jsx)(`code`,{children:`frontend`}),` or `,(0,X.jsx)(`code`,{children:`api-design`}),`.`]}),g.length>0&&(0,X.jsxs)(`p`,{className:`text-[11px] text-red-400 mt-1`,children:[`Invalid tag`,g.length===1?``:`s`,`: `,g.join(`, `),`. Tags must use lowercase letters, digits, and hyphens only.`]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Route to`}),(0,X.jsx)(`select`,{value:p,onChange:e=>m(e.target.value),"aria-label":`Route to`,className:`w-full h-9 px-2 text-sm rounded-md border border-border bg-background`,children:i.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))}),(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:`Only agents in this profile's chain can be routing targets.`})]})]}),(0,X.jsxs)(t,{children:[(0,X.jsx)(f,{variant:`ghost`,size:`sm`,onClick:s,children:`Cancel`}),(0,X.jsx)(f,{size:`sm`,onClick:()=>o(h,p),disabled:!_,children:n===`edit`?`Save changes`:`Add rule`})]})]})})}var Z=new Set([`sr-architect`,`sr-developer`,`sr-reviewer`,`sr-merge-resolver`]),se=[`sonnet`,`opus`,`haiku`],ce=/^[a-z0-9][a-z0-9-]*$/;function le({profile:e,onChange:t,footer:n,onValidityChange:r,onSoftWarningsChange:a}){let[o,c]=(0,Y.useState)([]),[l,u]=(0,Y.useState)(!1),[d,p]=(0,Y.useState)(!1),[m,g]=(0,Y.useState)(null);(0,Y.useEffect)(()=>{let e=!1;return fetch(`${O()}/profiles/catalog`).then(e=>e.ok?e.json():{agents:[]}).then(t=>{e||c(t.agents)}).catch(()=>{e||c([])}),()=>{e=!0}},[]);let _=n=>{let r=JSON.parse(JSON.stringify(e));n(r),t(r)},y=new Set(e.agents.map(e=>e.id)),b=o.filter(e=>!y.has(e.id)),w=(0,Y.useMemo)(()=>{let t=[];for(let n of Z)e.agents.some(e=>e.id===n)||t.push(`Missing required baseline agent: ${n}`);let n=e.routing.filter(e=>`default`in e&&e.default===!0);if(n.length>1&&t.push(`Routing may have at most one default rule (found ${n.length})`),n.length===1){let n=e.routing[e.routing.length-1];`default`in n&&n.default===!0||t.push(`The default routing rule must be the last entry`)}for(let n of e.routing)if(e.agents.some(e=>e.id===n.agent)||t.push(`Routing references agent not in the chain: ${n.agent}`),`tags`in n){let e=n.tags.filter(e=>!ce.test(e));e.length>0&&t.push(`Routing rule ${n.agent} has invalid tags: ${e.join(`, `)} (use lowercase kebab-case)`)}return t},[e]),T=(0,Y.useMemo)(()=>{if(e.routing.length===0)return[];let t=new Set(e.routing.map(e=>e.agent));return e.agents.filter(e=>!Z.has(e.id)&&!t.has(e.id)).map(e=>e.id)},[e]),E=(0,Y.useMemo)(()=>e.routing.some(e=>`default`in e&&e.default===!0),[e.routing]);(0,Y.useEffect)(()=>{r&&r(w)},[w,r]),(0,Y.useEffect)(()=>{a&&a({agentsMissingRouting:T})},[T,a]);let D=e=>{_(t=>{let n={id:e,model:`sonnet`},r=t.agents.findIndex(e=>e.id===`sr-merge-resolver`);r>=0?t.agents.splice(r,0,n):t.agents.push(n)}),u(!1)},k=t=>{let n=e.agents[t];Z.has(n.id)||_(e=>{e.agents.splice(t,1),e.routing=e.routing.filter(e=>e.agent!==n.id)})},j=(t,n)=>{if(t===n)return;let r=e.agents.findIndex(e=>e.id===t),i=e.agents.findIndex(e=>e.id===n);if(r<0||i<0)return;let a=F(e.agents,r,i),o=a.findIndex(e=>e.id===`sr-architect`);if(o>0){let[e]=a.splice(o,1);a.unshift(e)}let s=a.findIndex(e=>e.id===`sr-merge-resolver`);if(s>=0&&s!==a.length-1){let[e]=a.splice(s,1);a.push(e)}_(e=>{e.agents=a})},M=i(h(S,{activationConstraint:{distance:4}}),h(ee,{coordinateGetter:A})),N=e=>{let{active:t,over:n}=e;n&&j(String(t.id),String(n.id))},P=(e,t)=>{_(n=>{n.agents[e].model=t})},I=(e,t)=>{_(n=>{let r={tags:e,agent:t},i=n.routing.findIndex(e=>`default`in e&&e.default===!0);i>=0?n.routing.splice(i,0,r):n.routing.push(r)}),p(!1)},R=()=>{_(e=>{e.routing.some(e=>`default`in e&&e.default===!0)||e.agents.some(e=>e.id===`sr-developer`)&&e.routing.push({default:!0,agent:`sr-developer`})})},z=e=>`default`in e&&e.default===!0,B=(e,t)=>{_(n=>{let r=n.routing[e];r&&(z(r)||(r.agent=t))})},H=(e,t,n)=>{_(r=>{let i=r.routing[e];i&&(z(i)||(i.tags=t,i.agent=n))})},W=e=>{_(t=>{let n=t.routing[e];n&&(z(n)||t.routing.splice(e,1))})},G=(t,n)=>{let r=t+n;if(r<0||r>=e.routing.length)return;let i=e.routing[t],a=e.routing[r];z(i)||z(a)||_(e=>{let[n]=e.routing.splice(t,1);e.routing.splice(r,0,n)})};return(0,X.jsxs)(`div`,{className:`p-6 space-y-6 max-w-3xl`,children:[(0,X.jsx)(oe,{open:d,mode:`add`,chainAgents:e.agents.map(e=>e.id),onConfirm:I,onCancel:()=>p(!1)}),(0,X.jsx)(oe,{open:m!==null,mode:`edit`,initial:m!==null&&e.routing[m]&&!(`default`in e.routing[m])?{tags:e.routing[m].tags,agent:e.routing[m].agent}:void 0,chainAgents:e.agents.map(e=>e.id),onConfirm:(e,t)=>{m!==null&&(H(m,e,t),g(null))},onCancel:()=>g(null)}),w.length>0&&(0,X.jsxs)(`div`,{className:`px-3 py-2 text-xs rounded-md border border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[(0,X.jsxs)(`div`,{className:`font-medium mb-1`,children:[w.length,` validation `,w.length===1?`issue`:`issues`]}),(0,X.jsx)(`ul`,{className:`list-disc list-inside space-y-0.5`,children:w.map((e,t)=>(0,X.jsx)(`li`,{children:e},t))})]}),(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Name`}),(0,X.jsx)(C,{value:e.name,disabled:!0,className:`text-sm`})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Description`}),(0,X.jsx)(C,{value:e.description??``,onChange:e=>_(t=>{t.description=e.target.value}),className:`text-sm`,placeholder:`What is this profile for?`})]})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsx)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2`,children:`Orchestrator`}),(0,X.jsxs)(`div`,{className:`flex items-center gap-3 p-3 rounded-md border border-border`,children:[(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsx)(`div`,{className:`text-sm font-mono text-foreground truncate`,children:`/specrails:implement · /specrails:batch-implement`}),(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground mt-0.5`,children:`Top-level model for both commands. batch-implement delegates to implement per feature, so every rail it spawns inherits this profile's agent chain.`})]}),(0,X.jsx)(fe,{value:e.orchestrator.model,onChange:e=>_(t=>{t.orchestrator.model=e})})]})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,X.jsxs)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:[`Agent chain (`,e.agents.length,`)`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>u(e=>!e),disabled:b.length===0,title:b.length===0?`All catalog agents are already in the chain`:`Add an agent from the catalog`,children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1`}),` Add`]})]}),l&&(0,X.jsxs)(`div`,{className:`mb-2 p-2 rounded-md border border-border bg-muted/30`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5 px-1`,children:[(0,X.jsxs)(`span`,{className:`text-[11px] text-muted-foreground`,children:[`Pick from catalog (`,b.length,` available)`]}),(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:()=>u(!1),title:`Close`,children:(0,X.jsx)(s,{className:`w-3 h-3`})})]}),b.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground text-center`,children:`No more agents in the catalog. Add custom agents from the Agents Catalog tab.`}):(0,X.jsx)(`div`,{className:`space-y-0.5 max-h-64 overflow-auto`,children:b.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>D(e.id),className:`w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded hover:bg-accent transition-colors`,children:[(0,X.jsx)(`span`,{className:`text-sm font-mono`,children:e.id}),(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded `+(e.kind===`custom`?`bg-purple-500/15 text-purple-400`:`bg-muted text-muted-foreground`),children:e.kind})]},e.id))})]}),(0,X.jsx)(V,{sensors:M,collisionDetection:U,onDragEnd:N,children:(0,X.jsx)(L,{items:e.agents.map(e=>e.id),strategy:x,children:(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.agents.map((e,t)=>(0,X.jsx)(ue,{agent:e,canRemove:!Z.has(e.id),onModel:e=>P(t,e),onRemove:()=>k(t)},e.id))})})})]}),(0,X.jsxs)(`section`,{children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,X.jsxs)(`h2`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:[`Routing (`,e.routing.length,`)`]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1`,children:[!E&&(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:R,disabled:e.agents.length===0,title:e.agents.length===0?`Add at least one agent before creating routing rules`:void 0,children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1`}),` Add default`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>p(!0),disabled:e.agents.length===0,title:e.agents.length===0?`Add at least one agent before creating routing rules`:void 0,children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1`}),` Add rule`]})]})]}),(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground mb-2`,children:`First matching rule wins. Rules are editable and removable, and the default catch-all stays last when present. If you leave routing empty, the pipeline falls back to the first developer-shaped agent in the chain.`}),T.length>0&&(0,X.jsxs)(`div`,{className:`mb-2 px-3 py-2 text-xs rounded-md border border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[(0,X.jsx)(`div`,{className:`font-medium mb-1`,children:`Untargeted agents in the chain`}),(0,X.jsxs)(`div`,{children:[`No routing rule points to: `,(0,X.jsx)(`span`,{className:`font-mono`,children:T.join(`, `)}),`. Add a tag rule or retarget the default rule if you want them to run.`]})]}),(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.routing.map((t,n)=>{let r=`default`in t&&t.default===!0;return(0,X.jsx)(de,{rule:t,ordinal:n+1,isLast:n===e.routing.length-1,canMove:!r,canRemove:!r,canEdit:!r,chainAgents:e.agents.map(e=>e.id),onAgentChange:e=>B(n,e),onEdit:()=>g(n),onUp:()=>G(n,-1),onDown:()=>G(n,1),onRemove:()=>W(n)},n)})})]}),n&&(0,X.jsx)(`div`,{className:`pt-3 border-t border-border`,children:n})]})}function ue({agent:e,canRemove:t,onModel:n,onRemove:r}){let i=Z.has(e.id),a=e.id===`sr-architect`,o=e.id===`sr-merge-resolver`,{attributes:l,listeners:u,setNodeRef:d,transform:f,transition:p,isDragging:m}=k({id:e.id});return(0,X.jsxs)(`div`,{ref:d,style:{transform:H.Transform.toString(f),transition:p,opacity:m?.5:void 0,zIndex:m?10:void 0},className:`flex items-center gap-2 px-2 py-1.5 rounded-md border border-border group hover:bg-accent/30 transition-colors bg-background`,children:[(0,X.jsx)(`button`,{type:`button`,className:`flex-shrink-0 p-0.5 rounded text-muted-foreground cursor-grab active:cursor-grabbing hover:text-foreground`,title:`Drag to reorder`,"aria-label":`Drag handle`,...l,...u,children:(0,X.jsx)(c,{className:`w-3.5 h-3.5`})}),(0,X.jsx)(`span`,{className:`text-sm font-mono flex-1 truncate`,children:e.id}),a&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-accent-primary/15 text-accent-primary`,title:`Pinned to first position — pipeline always starts with sr-architect`,children:[(0,X.jsx)(ne,{className:`w-2.5 h-2.5 rotate-[135deg]`}),` first`]}),o&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-accent-primary/15 text-accent-primary`,title:`Pinned to last position — merge phase always runs last`,children:[(0,X.jsx)(ne,{className:`w-2.5 h-2.5 rotate-45`}),` last`]}),i&&!a&&!o&&(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:`required`}),(0,X.jsx)(fe,{value:e.model??`sonnet`,onChange:n}),(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded disabled:opacity-30 disabled:cursor-not-allowed opacity-0 group-hover:opacity-100 transition-opacity`,onClick:r,disabled:!t,title:t?`Remove`:`Required baseline agent — the pipeline depends on this row`,children:(0,X.jsx)(s,{className:`w-3 h-3`})})]})}function de({rule:e,ordinal:t,isLast:n,canMove:r,canRemove:i,canEdit:a,chainAgents:c,onAgentChange:l,onEdit:u,onUp:d,onDown:f,onRemove:p}){let m=`default`in e&&e.default===!0;return(0,X.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 rounded-md border border-border group hover:bg-accent/30 transition-colors`,children:[(0,X.jsxs)(`span`,{className:`text-[10px] font-mono text-muted-foreground w-5 text-center flex-shrink-0`,children:[t,`.`]}),m?(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1`,children:`everything else`}):(0,X.jsx)(`span`,{className:`text-xs flex-1 flex gap-1 flex-wrap items-center`,children:e.tags.map(e=>(0,X.jsx)(`span`,{className:`px-1.5 py-0.5 rounded bg-muted font-mono text-[11px]`,children:e},e))}),(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`→`}),m?(0,X.jsx)(`span`,{className:`h-7 max-w-[15rem] px-2 text-xs font-mono rounded border border-border bg-muted/40 text-muted-foreground inline-flex items-center`,"aria-label":`Default routing target (core, read-only)`,title:`Core fallback — not editable`,children:e.agent}):(0,X.jsx)(`select`,{value:e.agent,onChange:e=>l(e.target.value),"aria-label":`Routing target for rule ${t}`,className:`h-7 max-w-[15rem] px-2 text-xs font-mono rounded border border-border bg-background`,children:c.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))}),(0,X.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity`,children:[a&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:u,title:`Edit rule`,"aria-label":`Edit rule ${t}`,children:(0,X.jsx)(o,{className:`w-3 h-3`})}),r&&!n&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:f,title:`Move down`,children:(0,X.jsx)(G,{className:`w-3 h-3`})}),r&&t>1&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,onClick:d,title:`Move up`,children:(0,X.jsx)(K,{className:`w-3 h-3`})}),i&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded`,onClick:p,title:`Remove`,children:(0,X.jsx)(s,{className:`w-3 h-3`})})]}),m&&(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,title:`Core fallback — the pipeline's last-resort rule, pinned to sr-developer`,children:`core · default`})]})}function fe({value:e,onChange:t}){return(0,X.jsx)(`select`,{value:e,onChange:e=>t(e.target.value),className:`h-7 px-2 text-xs rounded border border-border bg-background`,children:se.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))})}function Q({open:e,title:n,description:r,placeholder:i,initialValue:o=``,confirmLabel:s=`Confirm`,inputPattern:c,inputInvalidHint:l,onConfirm:p,onCancel:m}){let[h,g]=(0,Y.useState)(o);(0,Y.useEffect)(()=>{e&&g(o)},[e,o]);let _=h.trim(),v=!c||c.test(_),y=_.length>0&&v;return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||m()},children:(0,X.jsxs)(d,{className:`max-w-md`,children:[(0,X.jsx)(j,{children:(0,X.jsx)(u,{children:n})}),(0,X.jsxs)(`div`,{className:`py-2 space-y-2`,children:[r&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),(0,X.jsx)(C,{autoFocus:!0,value:h,placeholder:i,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&y&&p(_)},className:`text-sm font-mono`}),_.length>0&&!v&&l&&(0,X.jsx)(`p`,{className:`text-[11px] text-yellow-500`,children:l})]}),(0,X.jsxs)(t,{children:[(0,X.jsx)(f,{variant:`ghost`,size:`sm`,onClick:m,children:`Cancel`}),(0,X.jsx)(f,{size:`sm`,onClick:()=>p(_),disabled:!y,children:s})]})]})})}function pe({open:e,title:n,description:r,confirmLabel:i=`Confirm`,destructive:o=!1,onConfirm:s,onCancel:c}){return(0,X.jsx)(a,{open:e,onOpenChange:e=>{e||c()},children:(0,X.jsxs)(d,{className:`max-w-md`,children:[(0,X.jsx)(j,{children:(0,X.jsx)(u,{children:n})}),r&&(0,X.jsx)(`div`,{className:`py-2`,children:(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r})}),(0,X.jsxs)(t,{children:[(0,X.jsx)(f,{variant:`ghost`,size:`sm`,onClick:c,children:`Cancel`}),(0,X.jsx)(f,{size:`sm`,onClick:s,className:o?`bg-red-500 hover:bg-red-600 text-white`:void 0,children:i})]})]})})}function me(){let[e,t]=(0,Y.useState)([]),[n,r]=(0,Y.useState)(null),[i,a]=(0,Y.useState)(null),[o,s]=(0,Y.useState)(!0),[c,l]=(0,Y.useState)(null),[u,d]=(0,Y.useState)(!1),[h,y]=(0,Y.useState)([]),[b,x]=(0,Y.useState)([]),[S,C]=(0,Y.useState)(!1),[w,T]=(0,Y.useState)(null),[E,D]=(0,Y.useState)(null),k=(0,Y.useCallback)(async()=>{s(!0),l(null);try{let e=await fetch(`${O()}/profiles`);if(!e.ok)throw Error(`List failed: ${e.status}`);let i=await e.json();t(i.profiles),i.profiles.length>0&&!n&&r(i.profiles[0].name)}catch(e){l(e.message)}finally{s(!1)}},[n]);(0,Y.useEffect)(()=>{k()},[k]),(0,Y.useEffect)(()=>{if(!n){a(null);return}let e=!1;return fetch(`${O()}/profiles/${encodeURIComponent(n)}`).then(e=>{if(!e.ok)throw Error(`Load failed: ${e.status}`);return e.json()}).then(t=>{e||a(t.profile)}).catch(t=>{e||l(t.message)}),()=>{e=!0}},[n]);let A=(0,Y.useCallback)(async()=>{d(!0),l(null);try{let e=await fetch(`${O()}/profiles/migrate-from-settings`,{method:`POST`});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Migration failed: ${e.status}`)}await k(),r(`default`),g.success(`Profile migrated`,{description:`default profile created from your current agents`})}catch(e){let t=e.message;l(t),g.error(`Migration failed`,{description:t})}finally{d(!1)}},[k]),j=(0,Y.useCallback)(async e=>{C(!1),d(!0),l(null);try{let t={schemaVersion:1,name:e,description:``,orchestrator:{model:`sonnet`},agents:[{id:`sr-architect`,model:`sonnet`,required:!0},{id:`sr-developer`,model:`sonnet`,required:!0},{id:`sr-reviewer`,model:`sonnet`,required:!0},{id:`sr-merge-resolver`,model:`sonnet`,required:!0}],routing:[{default:!0,agent:`sr-developer`}]},n=await fetch(`${O()}/profiles`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Create failed: ${n.status}`)}await k(),r(e),g.success(`Profile created`,{description:e})}catch(e){let t=e.message;l(t),g.error(`Failed to create profile`,{description:t})}finally{d(!1)}},[k]),M=(0,Y.useCallback)(async(e,t)=>{T(null),d(!0),l(null);try{let n=await fetch(`${O()}/profiles/${encodeURIComponent(e)}/duplicate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Duplicate failed: ${n.status}`)}await k(),r(t),g.success(`Profile duplicated`,{description:`${e} → ${t}`})}catch(e){let t=e.message;l(t),g.error(`Failed to duplicate profile`,{description:t})}finally{d(!1)}},[k]),N=(0,Y.useCallback)(async e=>{D(null),d(!0),l(null);try{let t=await fetch(`${O()}/profiles/${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Delete failed: ${t.status}`)}r(t=>t===e?null:t),await k(),g.success(`Profile deleted`,{description:e})}catch(e){let t=e.message;l(t),g.error(`Failed to delete profile`,{description:t})}finally{d(!1)}},[k]),P=(0,Y.useCallback)(()=>C(!0),[]),F=(0,Y.useCallback)(e=>T({from:e}),[]),I=(0,Y.useCallback)(e=>D({name:e}),[]),L=(0,Y.useCallback)(async(e,t)=>{d(!0),l(null);try{let n=await fetch(`${O()}/profiles/${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Save failed: ${n.status}`)}a(e),t.length>0?g.warning(`Profile saved with untargeted agents`,{description:`No routing rule points to: ${t.join(`, `)}. Add a tag rule or retarget the default rule if you want them to run.`,duration:6e3}):g.success(`Profile saved`,{description:e.name})}catch(e){let t=e.message;l(t),g.error(`Failed to save profile`,{description:t})}finally{d(!1)}},[]),R=(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Q,{open:S,title:`New profile`,description:`Pick a lowercase kebab-case name (letters, digits, and hyphens).`,placeholder:`my-profile`,confirmLabel:`Create`,inputPattern:/^[a-z0-9][a-z0-9-]*$/,inputInvalidHint:`Must start with a letter or digit and contain only lowercase letters, digits, and hyphens.`,onConfirm:e=>void j(e),onCancel:()=>C(!1)}),w&&(0,X.jsx)(Q,{open:!0,title:`Duplicate "${w.from}"`,description:`Name for the new profile.`,placeholder:`${w.from}-copy`,initialValue:`${w.from}-copy`,confirmLabel:`Duplicate`,inputPattern:/^[a-z0-9][a-z0-9-]*$/,inputInvalidHint:`Lowercase kebab-case only.`,onConfirm:e=>void M(w.from,e),onCancel:()=>T(null)}),E&&(0,X.jsx)(pe,{open:!0,title:`Delete profile "${E.name}"?`,description:`This cannot be undone. Jobs already launched with this profile keep their snapshot; future launches will fall back to the resolution order.`,confirmLabel:`Delete`,destructive:!0,onConfirm:()=>void N(E.name),onCancel:()=>D(null)})]});return o?(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading profiles…`})}):e.length===0?(0,X.jsxs)(X.Fragment,{children:[R,(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsxs)(`div`,{className:`text-center max-w-md`,children:[(0,X.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:`No profiles yet`}),(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground mt-1 mb-4`,children:`Profiles let you save orchestrator + agent + routing combinations and pick one per rail.`}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2 justify-center`,children:[(0,X.jsxs)(f,{size:`sm`,onClick:A,disabled:u,children:[(0,X.jsx)(ie,{className:`w-3.5 h-3.5 mr-1.5`}),` Migrate from current agents`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:P,disabled:u,children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1.5`}),` Blank profile`]})]}),(0,X.jsxs)(`div`,{className:`text-[11px] text-muted-foreground/70 mt-3`,children:[`"Migrate" reads your existing `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`.claude/agents/`}),` `,`frontmatter models and creates a `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`default`}),` profile mirroring today's behavior — zero-loss.`]}),c&&(0,X.jsx)(`div`,{className:`mt-3 text-xs text-red-400`,children:c})]})})]}):(0,X.jsxs)(`div`,{className:`flex flex-col h-full`,children:[R,(0,X.jsxs)(`div`,{className:`flex flex-1 min-h-0`,children:[(0,X.jsxs)(`aside`,{className:`w-64 flex-shrink-0 border-r border-border flex flex-col`,children:[(0,X.jsxs)(`div`,{className:`p-3 flex items-center justify-between`,children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Profiles`}),(0,X.jsx)(f,{size:`sm`,variant:`ghost`,onClick:P,disabled:u,children:(0,X.jsx)(v,{className:`w-3.5 h-3.5`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-auto px-2 pb-3`,children:e.map(e=>(0,X.jsxs)(`div`,{className:`group mb-1 rounded-md px-2 py-1.5 text-xs cursor-pointer transition-colors flex items-center justify-between `+(e.name===n?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),onClick:()=>r(e.name),role:`button`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&r(e.name)},children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,X.jsx)(`span`,{className:`truncate font-medium`,children:e.name}),e.isDefault&&(0,X.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`(team default)`})]}),(0,X.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity`,children:[(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-accent rounded`,title:`Duplicate`,onClick:t=>{t.stopPropagation(),F(e.name)},children:(0,X.jsx)(p,{className:`w-3 h-3`})}),!e.isDefault&&(0,X.jsx)(`button`,{type:`button`,className:`p-1 hover:bg-red-500/20 text-red-400 rounded`,title:`Delete`,onClick:t=>{t.stopPropagation(),I(e.name)},children:(0,X.jsx)(m,{className:`w-3 h-3`})})]})]},e.name))})]}),(0,X.jsxs)(`main`,{className:`flex-1 overflow-auto`,children:[c&&(0,X.jsx)(`div`,{className:`mx-4 mt-4 px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:c}),i?(0,X.jsx)(le,{profile:i,onChange:a,onValidityChange:y,onSoftWarningsChange:e=>x(e.agentsMissingRouting),footer:(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsxs)(f,{size:`sm`,onClick:()=>void L(i,b),disabled:u||h.length>0,title:h.length>0?`Fix validation issues before saving`:void 0,children:[(0,X.jsx)(_,{className:`w-3.5 h-3.5 mr-1.5`}),`Save`]}),u&&(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Saving…`}),h.length>0&&(0,X.jsxs)(`span`,{className:`text-xs text-yellow-500`,children:[h.length,` `,h.length===1?`issue`:`issues`,` to resolve`]})]})},i.name):(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Select a profile to edit`})})]})]})]})}function $(e){let t=e.workflow.map((e,t)=>`${t+1}. ${e}`).join(`
2
2
  `);return`---
3
3
  name: ${e.id}
4
4
  description: "${e.descriptionOneLine}"
@@ -76,4 +76,4 @@ You are ...
76
76
  - **risk_tolerance**: conservative
77
77
  - **detail_level**: full
78
78
  - **focus_areas**: ...
79
- `;function ye({agentId:e,initialBody:t,initialName:r,draftFromRefine:i,onClose:a,onSaved:o,onResumeRefine:s}){let c=!e,[f,p]=(0,Y.useState)(e??r??``),[m,h]=(0,Y.useState)(t??ve),[g,_]=(0,Y.useState)(!c&&!t&&!i),[v,ee]=(0,Y.useState)(!!i&&!c),[b,x]=(0,Y.useState)(!1),[S,C]=(0,Y.useState)(null),[T,E]=(0,Y.useState)([]),[D,O]=(0,Y.useState)(!1),[k,A]=(0,Y.useState)(!!t&&c),[j,M]=(0,Y.useState)(!1),[N,P]=(0,Y.useState)(``),[F,L]=(0,Y.useState)(!1),[R,z]=(0,Y.useState)(null),[B,H]=(0,Y.useState)(null),[te,U]=(0,Y.useState)(!1);(0,Y.useEffect)(()=>{if(c||t!==void 0)return;if(i){let t=!1;return fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}/refine/${i}`).then(e=>{if(!e.ok)throw Error(`Load draft failed: ${e.status}`);return e.json()}).then(e=>{!t&&e.draftBody&&(h(e.draftBody),A(!0))}).catch(e=>{t||C(e.message)}).finally(()=>{t||ee(!1)}),()=>{t=!0}}let n=!1;return fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`).then(e=>{if(!e.ok)throw Error(`Load failed: ${e.status}`);return e.json()}).then(e=>{n||h(e.body)}).catch(e=>{n||C(e.message)}).finally(()=>{n||_(!1)}),()=>{n=!0}},[e,c,t,i]);let W=(0,Y.useCallback)(()=>{c||fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}/versions`).then(e=>e.ok?e.json():{versions:[]}).then(e=>E(e.versions)).catch(()=>E([]))},[e,c]);(0,Y.useEffect)(()=>{D&&W()},[D,W]);let G=/^custom-[a-z0-9][a-z0-9-]*$/.test(f),J=m.trim().length>0,re=/^---\s*\n[\s\S]*?\n---/.test(m),ae=J&&re&&(c?G:!0)&&k,oe=(0,Y.useCallback)(async()=>{x(!0),C(null);try{let t;if(t=c?await fetch(`${w()}/profiles/catalog`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:f,body:m})}):await fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({body:m})}),!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Save failed: ${t.status}`)}A(!1),V.success(c?`Agent created`:`Agent saved`,{description:c?f:e}),o&&o(c?f:e)}catch(e){let t=e.message;C(t),V.error(c?`Failed to create agent`:`Failed to save agent`,{description:t})}finally{x(!1)}},[e,m,f,c,o]),Z=(0,Y.useCallback)(async()=>{if(!c){U(!1),x(!0),C(null);try{let t=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Delete failed: ${t.status}`)}V.success(`Agent deleted`,{description:e}),o&&o(e),a()}catch(e){let t=e.message;C(t),V.error(`Failed to delete agent`,{description:t})}finally{x(!1)}}},[e,c,a,o]),se=(0,Y.useCallback)(e=>{h(e.body),A(!0),O(!1)},[]),ce=(0,Y.useCallback)(async()=>{L(!0),H(null),z(null);try{let t=await fetch(`${w()}/profiles/catalog/test`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:c?f||`draft`:e,draftBody:m,sampleTask:N})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Test failed: ${t.status}`)}z(await t.json())}catch(e){H(e.message)}finally{L(!1)}},[e,m,f,c,N]);return g?(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading agent…`})}):(0,X.jsxs)(`div`,{className:`flex flex-col h-full`,children:[!c&&(0,X.jsx)(pe,{open:te,title:`Delete agent "${e}"?`,description:`This removes the .md from disk. Version history stays in the DB — use a fresh custom agent if you want to recover the body later.`,confirmLabel:`Delete`,destructive:!0,onConfirm:Z,onCancel:()=>U(!1)}),(0,X.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2 border-b border-border`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:a,className:`p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground`,title:`Back`,children:(0,X.jsx)(y,{className:`w-4 h-4`})}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground uppercase tracking-wide`,children:c?`New custom agent`:`Edit custom agent`}),c?(0,X.jsx)(I,{value:f,onChange:e=>{p(e.target.value),A(!0)},placeholder:`custom-my-agent`,className:`text-sm font-mono mt-1 max-w-sm`}):(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`div`,{className:`text-sm font-mono`,children:e}),i&&(0,X.jsxs)(`button`,{type:`button`,onClick:async()=>{if(!(!s||!e))try{let t=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`);if(!t.ok)return;s(i,e,(await t.json()).body)}catch{}},className:`inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border border-dracula-purple/40 bg-dracula-purple/15 text-dracula-purple hover:bg-dracula-purple/25 focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none`,title:`Hand this draft back to the AI Edit overlay`,children:[(0,X.jsx)(ie,{className:`w-3 h-3`}),` Resume AI Edit`]}),v&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] text-muted-foreground`,children:[(0,X.jsx)(l,{className:`w-3 h-3 animate-spin`}),` loading AI draft…`]})]})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>{M(e=>!e),j||O(!1)},title:`Test this agent against a sample task`,children:[(0,X.jsx)(K,{className:`w-3.5 h-3.5 mr-1`}),`Test`]}),!c&&(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>{O(e=>!e),D||M(!1)},title:`Version history`,children:[(0,X.jsx)(q,{className:`w-3.5 h-3.5 mr-1`}),`History`]}),!c&&(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>U(!0),disabled:b,className:`text-red-400 hover:text-red-300`,children:[(0,X.jsx)(u,{className:`w-3.5 h-3.5 mr-1`}),`Delete`]}),(0,X.jsxs)(d,{size:`sm`,onClick:oe,disabled:!ae||b,children:[(0,X.jsx)(n,{className:`w-3.5 h-3.5 mr-1`}),b?`Saving…`:c?`Create`:`Save`]})]})]}),S&&(0,X.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2 text-xs border-b border-red-500/30 bg-red-500/10 text-red-400`,children:[(0,X.jsx)(ne,{className:`w-3.5 h-3.5 flex-shrink-0`}),S]}),c&&f.length>0&&!G&&(0,X.jsxs)(`div`,{className:`px-4 py-1.5 text-[11px] border-b border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[`Name must start with `,(0,X.jsx)(`code`,{children:`custom-`}),` and contain only lowercase letters, digits, and hyphens.`]}),!re&&(0,X.jsxs)(`div`,{className:`px-4 py-1.5 text-[11px] border-b border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[`Missing YAML frontmatter (needs opening `,(0,X.jsx)(`code`,{children:`---`}),` on the first line).`]}),(0,X.jsxs)(`div`,{className:`flex flex-1 min-h-0`,children:[(0,X.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0`,children:[(0,X.jsxs)(`div`,{className:`px-4 py-1.5 border-b border-border text-[11px] font-mono text-muted-foreground flex items-center justify-between`,children:[(0,X.jsxs)(`span`,{children:[`.claude/agents/`,c?f||`custom-…`:e,`.md`]}),k&&(0,X.jsx)(`span`,{className:`text-yellow-500`,children:`● unsaved`})]}),(0,X.jsx)(`textarea`,{value:m,onChange:e=>{h(e.target.value),A(!0)},spellCheck:!1,className:`flex-1 w-full p-4 text-xs font-mono bg-background text-foreground outline-none resize-none leading-relaxed`})]}),j&&(0,X.jsxs)(`aside`,{className:`w-96 flex-shrink-0 border-l border-border flex flex-col min-h-0`,children:[(0,X.jsxs)(`div`,{className:`px-3 py-2 border-b border-border text-xs font-medium text-muted-foreground uppercase tracking-wide flex items-center gap-2`,children:[(0,X.jsx)(K,{className:`w-3.5 h-3.5`}),` Test agent`]}),(0,X.jsxs)(`div`,{className:`p-3 border-b border-border`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,X.jsx)(`label`,{className:`text-[11px] text-muted-foreground`,children:`Sample task`}),(0,X.jsx)(`select`,{className:`h-6 text-[11px] rounded border border-border bg-background px-1`,value:``,onChange:e=>{let t=parseInt(e.target.value,10);!isNaN(t)&&t>0&&P(_e[t].prompt)},disabled:F,children:_e.map((e,t)=>(0,X.jsx)(`option`,{value:t,children:e.label},t))})]}),(0,X.jsx)(`textarea`,{value:N,onChange:e=>P(e.target.value),placeholder:`Describe what the agent should do, or pick a sample above.`,className:`w-full text-xs p-2 rounded border border-border bg-background min-h-[80px] resize-y font-mono`,disabled:F}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mt-2`,children:[(0,X.jsx)(d,{size:`sm`,onClick:ce,disabled:F||!N.trim()||!m.trim(),children:F?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(l,{className:`w-3.5 h-3.5 mr-1.5 animate-spin`}),` Running…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(K,{className:`w-3.5 h-3.5 mr-1.5`}),` Run`]})}),(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Sandboxed; no files written.`})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 overflow-auto p-3 min-h-0`,children:[B&&(0,X.jsx)(`div`,{className:`px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400 mb-2`,children:B}),R&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-muted-foreground mb-2`,children:[(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:R.tokens}),` tokens`]}),(0,X.jsx)(`span`,{children:(0,X.jsxs)(`span`,{className:`text-foreground font-mono`,children:[(R.durationMs/1e3).toFixed(1),`s`]})})]}),(0,X.jsx)(`pre`,{className:`text-xs font-mono whitespace-pre-wrap leading-relaxed rounded border border-border bg-background p-3`,children:R.output})]}),!F&&!R&&!B&&(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground italic`,children:`Run a sample task against the current draft. Output appears here.`})]})]}),D&&!c&&(0,X.jsxs)(`aside`,{className:`w-72 flex-shrink-0 border-l border-border flex flex-col`,children:[(0,X.jsx)(`div`,{className:`px-3 py-2 border-b border-border text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Version history`}),(0,X.jsx)(`div`,{className:`flex-1 overflow-auto p-2 space-y-1`,children:T.length===0?(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground italic px-2 py-2`,children:`No prior versions recorded for this agent.`}):T.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>se(e),className:`w-full text-left px-2 py-1.5 rounded hover:bg-accent/50 transition-colors`,children:[(0,X.jsxs)(`div`,{className:`text-xs font-mono text-foreground`,children:[`v`,e.version]}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.version))}),(0,X.jsx)(`div`,{className:`px-3 py-2 border-t border-border text-[11px] text-muted-foreground`,children:`Click a version to restore its body into the editor (you still need to Save).`})]})]})]})}var be={refineId:null,agentId:null,uiState:`closed`,phase:`idle`,history:[],streamingText:``,draftBody:null,baseBody:null,autoTest:!1,testResult:null,appliedVersion:null,errorMessage:null,applyConflict:null};function xe(e){return e.replace(/<!--tool:[^>]+-->/g,``)}function Se(e,t){switch(t.type){case`OPEN`:return{...be,agentId:t.agentId,baseBody:t.baseBody,uiState:`composing`};case`START_TURN`:return{...e,refineId:t.refineId,uiState:`streaming`,phase:`reading`,streamingText:``,errorMessage:null,applyConflict:null,history:[...e.history,t.userTurn]};case`STREAM_DELTA`:return e.refineId===t.refineId?{...e,streamingText:e.streamingText+t.delta}:e;case`PHASE`:return e.refineId===t.refineId?{...e,phase:t.phase}:e;case`READY`:return e.refineId===t.refineId?{...e,uiState:`reviewing`,phase:`done`,draftBody:t.draftBody,streamingText:``,history:[...e.history,{role:`assistant`,content:xe(t.draftBody),timestamp:Date.now()}]}:e;case`TEST_RESULT`:return e.refineId===t.refineId?{...e,testResult:t.result,history:[...e.history,{role:`system`,kind:`test_result`,content:t.result.output,timestamp:Date.now()}]}:e;case`APPLIED`:return e.refineId===t.refineId?{...e,uiState:`applied`,appliedVersion:t.version}:e;case`CANCELLED`:return{...e,uiState:`cancelled`};case`ERROR`:return t.refineId!==null&&e.refineId!==t.refineId?e:{...e,uiState:`error`,errorMessage:t.message};case`CONFLICT`:return e.refineId===t.refineId?{...e,applyConflict:t.reason}:e;case`TOGGLE_AUTO_TEST`:return{...e,autoTest:t.enabled};case`REHYDRATE`:return{...e,...t.payload};case`CLOSE`:return be;default:return e}}function Ce(e){switch(e.status){case`streaming`:return`streaming`;case`ready`:return`reviewing`;case`applied`:return`applied`;case`cancelled`:return`cancelled`;case`error`:return`error`;default:return e.draftBody?`reviewing`:`composing`}}function we(e){let[t,n]=(0,Y.useReducer)(Se,be),{registerHandler:r,unregisterHandler:i}=M(),a=(0,Y.useRef)(null);a.current=t.refineId;let o=(0,Y.useRef)(null);o.current=t.agentId;let s=(0,Y.useRef)(e);s.current=e;let c=(0,Y.useRef)(e);(0,Y.useEffect)(()=>{e!==c.current&&(c.current=e,n({type:`CLOSE`}))},[e]),(0,Y.useEffect)(()=>{let e=`agent-refine-${Math.random().toString(36).slice(2,9)}`;return r(e,e=>{let t=e;if(typeof t.type!=`string`||t.projectId!==s.current||t.refineId!==a.current)return;let r=t.refineId;switch(t.type){case`agent_refine_stream`:n({type:`STREAM_DELTA`,refineId:r,delta:t.delta});break;case`agent_refine_phase`:n({type:`PHASE`,refineId:r,phase:t.phase});break;case`agent_refine_ready`:n({type:`READY`,refineId:r,draftBody:t.draftBody});break;case`agent_refine_test`:n({type:`TEST_RESULT`,refineId:r,result:t.result});break;case`agent_refine_applied`:n({type:`APPLIED`,refineId:r,version:t.version});break;case`agent_refine_cancelled`:n({type:`CANCELLED`,refineId:r});break;case`agent_refine_error`:n({type:`ERROR`,refineId:r,message:t.error});break}}),()=>i(e)},[r,i]);let l=(0,Y.useCallback)((e,t)=>{n({type:`OPEN`,agentId:e,baseBody:t})},[]),u=(0,Y.useCallback)(()=>{n({type:`CLOSE`})},[]);return{state:t,open:l,start:(0,Y.useCallback)(async e=>{let r=o.current;if(r)try{let i=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(r)}/refine`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({instruction:e,autoTest:t.autoTest})});if(!i.ok){n({type:`ERROR`,refineId:null,message:(await i.json().catch(()=>({}))).error??`Server error (${i.status})`});return}let o=await i.json();a.current=o.refineId,n({type:`START_TURN`,refineId:o.refineId,userTurn:{role:`user`,content:e,timestamp:Date.now()}})}catch(e){n({type:`ERROR`,refineId:null,message:`Connection failed: ${e.message}`})}},[t.autoTest]),sendTurn:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(!(!t||!r)){n({type:`START_TURN`,refineId:t,userTurn:{role:`user`,content:e,timestamp:Date.now()}});try{let i=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}/turn`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({instruction:e})});i.ok||n({type:`ERROR`,refineId:t,message:(await i.json().catch(()=>({}))).error??`Server error (${i.status})`})}catch(e){n({type:`ERROR`,refineId:t,message:`Connection failed: ${e.message}`})}}},[]),cancel:(0,Y.useCallback)(async()=>{let e=a.current,t=o.current;if(!(!e||!t))try{await fetch(`${w()}/profiles/catalog/${encodeURIComponent(t)}/refine/${e}`,{method:`DELETE`})}catch{}},[]),apply:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(!(!t||!r))try{let i=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:!!e})});if(i.status===409){let e=await i.json().catch(()=>({}));if(e.reason===`disk_changed`||e.reason===`name_changed`){n({type:`CONFLICT`,refineId:t,reason:e.reason});return}}if(!i.ok){n({type:`ERROR`,refineId:t,message:(await i.json().catch(()=>({}))).error??`Apply failed (${i.status})`});return}n({type:`APPLIED`,refineId:t,version:(await i.json()).version})}catch(e){n({type:`ERROR`,refineId:t,message:`Connection failed: ${e.message}`})}},[]),toggleAutoTest:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(n({type:`TOGGLE_AUTO_TEST`,enabled:e}),!(!t||!r))try{await fetch(`${w()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({autoTest:e})})}catch{}},[]),rehydrate:(0,Y.useCallback)(async(e,t)=>{try{let r=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(t)}`);if(!r.ok)throw Error(`load agent failed: ${r.status}`);let i=await r.json(),s=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(t)}/refine/${e}`);if(!s.ok)throw Error(`load session failed: ${s.status}`);let c=await s.json();a.current=e,o.current=t,n({type:`REHYDRATE`,payload:{refineId:e,agentId:t,baseBody:i.body,draftBody:c.draftBody,history:c.history,autoTest:c.autoTest,phase:c.phase,uiState:Ce(c),streamingText:``}})}catch(e){n({type:`ERROR`,refineId:null,message:`Rehydrate failed: ${e.message}`})}},[]),close:u}}var Te=[`Tighten the tool list`,`Make the personality stricter`,`Add a Workflow protocol section`,`Shorten and sharpen the description`,`Match the sr-developer style`];function Ee({agentId:e,baseBody:t,resumeRefineId:n,onClose:r,onOpenInStudio:i,onApplied:a}){let{activeProjectId:o}=S(),s=we(o),[c,l]=(0,Y.useState)(``),u=(0,Y.useRef)(null),d=(0,Y.useRef)(!1);(0,Y.useEffect)(()=>{d.current||(d.current=!0,n?s.rehydrate(n,e):s.open(e,t))},[e,t,n,s]),(0,Y.useEffect)(()=>{let e=setTimeout(()=>u.current?.focus(),50);return()=>clearTimeout(e)},[]);let f=(0,Y.useRef)(null);(0,Y.useEffect)(()=>{s.state.uiState===`applied`&&s.state.appliedVersion!==null&&s.state.appliedVersion!==f.current&&(f.current=s.state.appliedVersion,a&&s.state.agentId&&a(s.state.agentId,s.state.appliedVersion))},[s.state.uiState,s.state.appliedVersion,s.state.agentId,a]);let p=(0,Y.useCallback)(async e=>{let t=e.trim();t&&(l(``),s.state.refineId?await s.sendTurn(t):await s.start(t))},[s]),m=(0,Y.useCallback)(()=>{p(c)},[c,p]),h=(0,Y.useCallback)(async()=>{s.state.refineId&&(s.state.uiState===`streaming`||s.state.uiState===`reviewing`)&&await s.cancel(),r()},[s,r]),g=De(s.state),v=(0,Y.useMemo)(()=>!s.state.draftBody||!s.state.baseBody?null:(0,X.jsx)(R,{hunks:C(s.state.baseBody,s.state.draftBody)}),[s.state.baseBody,s.state.draftBody]);return(0,X.jsx)(x,{uiPhase:g,errorMessage:s.state.errorMessage,applyConflict:s.state.applyConflict,eyebrow:`AI Edit`,targetLabel:e,targetLabelMono:!0,headline:`Refine your agent`,streamingHeadline:`Refining your agent…`,description:Oe(t),chips:Te,onChipSubmit:e=>void p(e),composer:(0,X.jsx)(j,{value:c,onChange:l,onSubmit:m,disabled:g===`streaming`||g===`applied`,placeholder:s.state.refineId?`Send a follow-up refinement…`:`Describe how to refine this agent…`,inputRef:u}),streamingText:s.state.streamingText,history:s.state.history,diff:v,diffHeaderLabel:`.claude/agents/${e}.md`,baseBody:t,baseBodyDisclosureLabel:`View current agent body`,appliedNotice:s.state.appliedVersion===null?void 0:(0,X.jsxs)(`div`,{className:`rounded-md border border-green-500/40 bg-green-500/10 p-3 text-xs text-green-300`,children:[`Applied as version `,s.state.appliedVersion,`.`]}),canApply:s.state.uiState===`reviewing`&&!!s.state.draftBody&&!s.state.applyConflict,onApply:()=>void s.apply(),onForceApply:()=>void s.apply(!0),onDiscard:()=>void h(),onClose:()=>void h(),secondaryAction:i&&s.state.draftBody&&s.state.refineId?{label:`Open draft in Studio for manual editing`,icon:(0,X.jsx)(_,{className:`w-3 h-3`}),onClick:()=>{s.state.refineId&&s.state.draftBody&&i&&i(s.state.refineId,s.state.draftBody)}}:void 0})}function De(e){switch(e.uiState){case`streaming`:return`streaming`;case`reviewing`:return`reviewing`;case`applied`:return`applied`;case`error`:return`error`;default:return`composing`}}function Oe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return null;let n=t[1].match(/^description:\s*([\s\S]*?)(?=^[a-z_]+:\s|\Z)/m);if(!n)return null;let r=n[1].trim();return(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))&&(r=r.slice(1,-1)),r=r.replace(/\\n/g,` `).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\'/g,`'`).replace(/\\\\/g,`\\`).replace(/\s+/g,` `).trim(),r.length>240&&(r=r.slice(0,237)+`…`),r||null}function ke(){let[e,n]=(0,Y.useState)([]),[r,s]=(0,Y.useState)(null),[u,f]=(0,Y.useState)(null),[m,_]=(0,Y.useState)(!0),[ee,y]=(0,Y.useState)(!1),[b,x]=(0,Y.useState)(null),[S,C]=(0,Y.useState)({kind:`closed`}),[T,E]=(0,Y.useState)({kind:`closed`}),[D,A]=(0,Y.useState)(!1),[j,M]=(0,Y.useState)(``),[N,P]=(0,Y.useState)(`all`),[F,L]=(0,Y.useState)(null),[R,z]=(0,Y.useState)(!1),[B,V]=(0,Y.useState)(``),[H,te]=(0,Y.useState)(``),[W,G]=(0,Y.useState)(!1),[ne,K]=(0,Y.useState)(null),q=(0,Y.useCallback)(()=>{let e=!1;return _(!0),fetch(`${w()}/profiles/catalog`).then(e=>{if(!e.ok)throw Error(`Catalog load failed: ${e.status}`);return e.json()}).then(t=>{e||(n(t.agents),t.agents.length>0&&!r&&s(t.agents[0].id))}).catch(t=>{e||x(t.message)}).finally(()=>{e||_(!1)}),()=>{e=!0}},[r]);(0,Y.useEffect)(()=>q(),[q]);let J=(0,Y.useCallback)(e=>{let t=!1;return y(!0),f(null),fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`).then(e=>{if(!e.ok)throw Error(`Agent body load failed: ${e.status}`);return e.json()}).then(e=>{t||f(e.body)}).catch(e=>{t||x(e.message)}).finally(()=>{t||y(!1)}),()=>{t=!0}},[]);if((0,Y.useEffect)(()=>{if(r)return J(r)},[r,J]),m)return(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading catalog…`})});if(S.kind!==`closed`)return(0,X.jsx)(ye,{agentId:S.kind===`edit`?S.agentId:void 0,initialBody:S.kind===`duplicate`||S.kind===`create`?S.initialBody:void 0,initialName:S.kind===`create`?S.initialName:void 0,draftFromRefine:S.kind===`edit`?S.draftFromRefine:void 0,onClose:()=>C({kind:`closed`}),onSaved:e=>{s(e),C({kind:`closed`}),q()},onResumeRefine:(e,t,n)=>{C({kind:`closed`}),E({kind:`open`,agentId:t,baseBody:n,resumeRefineId:e})}});if(T.kind===`open`)return(0,X.jsx)(Ee,{agentId:T.agentId,baseBody:T.baseBody,resumeRefineId:T.resumeRefineId,onClose:()=>E({kind:`closed`}),onApplied:e=>{E({kind:`closed`}),s(e),q()},onOpenInStudio:(e,t)=>{E({kind:`closed`}),C({kind:`edit`,agentId:T.agentId,draftFromRefine:e})}});let ae=(()=>{let e=j.trim().toLowerCase();return he.filter(t=>!(N!==`all`&&t.category!==N||F&&!t.tags.includes(F)||e&&!(t.label+` `+t.blurb+` `+t.tags.join(` `)+` `+t.category).toLowerCase().includes(e)))})(),oe=(()=>{let e=new Map;for(let t of he)e.set(t.category,(e.get(t.category)??0)+1);return e})(),Z=()=>{A(!1),M(``),P(`all`),L(null)},se=()=>(0,X.jsx)(a,{open:D,onOpenChange:e=>{e||Z()},children:(0,X.jsxs)(i,{className:`max-w-4xl p-0 h-[85vh] flex flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex-shrink-0 px-6 pt-5 pb-3 border-b border-border`,children:[(0,X.jsxs)(t,{children:[(0,X.jsxs)(O,{className:`flex items-center gap-2 text-base`,children:[(0,X.jsx)(c,{className:`w-4 h-4 text-dracula-purple`}),` Agent template library`,(0,X.jsxs)(`span`,{className:`text-[11px] font-normal text-muted-foreground ml-1`,children:[ae.length,` of `,he.length]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Start from a curated template across engineering, product, science, health, legal, and more. Pick one and open it in the Studio for review and editing before saving.`})]}),(0,X.jsxs)(`div`,{className:`mt-3 relative`,children:[(0,X.jsx)(U,{className:`w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none`}),(0,X.jsx)(`input`,{value:j,onChange:e=>M(e.target.value),placeholder:`Search by name, description, tag, or category…`,className:`w-full h-9 pl-8 pr-8 text-sm rounded-md border border-border bg-background focus:outline-none focus:ring-1 focus:ring-primary/40`,autoFocus:!0}),j&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>M(``),className:`absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded hover:bg-accent text-muted-foreground`,children:(0,X.jsx)(o,{className:`w-3.5 h-3.5`})})]}),(0,X.jsxs)(`div`,{className:`flex gap-1.5 overflow-x-auto mt-3 pb-1 scrollbar-thin`,children:[(0,X.jsx)(Ae,{label:`All`,count:he.length,active:N===`all`,onClick:()=>P(`all`)}),ge.map(e=>(0,X.jsx)(Ae,{label:e,count:oe.get(e)??0,active:N===e,onClick:()=>P(e)},e))]}),F&&(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mt-2`,children:[(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Tag filter:`}),(0,X.jsxs)(`button`,{type:`button`,onClick:()=>L(null),className:`inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-dracula-purple/20 text-dracula-purple hover:bg-dracula-purple/30`,children:[(0,X.jsx)(re,{className:`w-3 h-3`}),` `,F,(0,X.jsx)(o,{className:`w-3 h-3`})]})]})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-y-auto px-6 py-4`,children:ae.length===0?(0,X.jsx)(`div`,{className:`h-full flex items-center justify-center text-center`,children:(0,X.jsxs)(`div`,{className:`max-w-sm`,children:[(0,X.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No templates match your filters.`}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>{M(``),P(`all`),L(null)},className:`text-xs text-dracula-purple hover:underline mt-2`,children:`Clear filters`})]})}):(0,X.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:ae.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>{Z(),C({kind:`create`,initialBody:e.body,initialName:e.nameHint})},className:`group text-left p-4 rounded-lg border border-border bg-card/40 hover:border-dracula-purple/50 hover:bg-accent/40 hover:shadow-sm transition-all`,children:[(0,X.jsxs)(`div`,{className:`flex items-start gap-3 mb-2`,children:[(0,X.jsx)(`span`,{className:`text-2xl leading-none mt-0.5`,children:e.emoji}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`div`,{className:`text-sm font-semibold text-foreground group-hover:text-dracula-purple truncate`,children:e.label}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground mt-0.5`,children:e.category})]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed line-clamp-2 min-h-[2lh]`,children:e.blurb}),(0,X.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-3`,children:e.tags.slice(0,5).map(e=>(0,X.jsx)(`span`,{role:`button`,tabIndex:0,onClick:t=>{t.stopPropagation(),L(e)},onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),t.stopPropagation(),L(e))},className:`text-[10px] px-1.5 py-0.5 rounded bg-muted/50 text-muted-foreground hover:bg-dracula-purple/20 hover:text-dracula-purple cursor-pointer transition-colors `+(F===e?`bg-dracula-purple/20 text-dracula-purple`:``),children:e},e))}),(0,X.jsxs)(`div`,{className:`mt-3 pt-2 border-t border-border/40 flex items-center justify-between`,children:[(0,X.jsx)(`code`,{className:`text-[10px] font-mono text-muted-foreground/70 truncate`,children:e.nameHint}),(0,X.jsx)(`span`,{className:`text-[10px] text-dracula-purple opacity-0 group-hover:opacity-100 transition-opacity`,children:`Open in Studio →`})]})]},e.id))})}),(0,X.jsxs)(`div`,{className:`flex-shrink-0 px-6 py-3 border-t border-border flex items-center justify-between`,children:[(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Tip: click a tag pill on any card to filter by that tag.`}),(0,X.jsx)(d,{variant:`ghost`,size:`sm`,onClick:Z,children:`Cancel`})]})]})}),ce=()=>(0,X.jsx)(a,{open:R,onOpenChange:e=>{!e&&!W&&(z(!1),K(null))},children:(0,X.jsxs)(i,{className:`max-w-lg`,children:[(0,X.jsx)(t,{children:(0,X.jsxs)(O,{className:`flex items-center gap-2`,children:[(0,X.jsx)(p,{className:`w-4 h-4 text-dracula-purple`}),` Generate a custom agent`]})}),(0,X.jsxs)(`div`,{className:`space-y-3 py-2`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Agent id`}),(0,X.jsx)(I,{value:B,onChange:e=>V(e.target.value),placeholder:`custom-my-agent`,className:`text-sm font-mono`,disabled:W}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:[`Must start with `,(0,X.jsx)(`code`,{children:`custom-`}),`.`]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Describe what this agent should do`}),(0,X.jsx)(`textarea`,{value:H,onChange:e=>te(e.target.value),placeholder:`e.g. Review Terraform/IaC changes and flag security misconfigurations, excessive IAM permissions, and public S3 buckets before merging. Conservative and terse.`,className:`w-full text-sm p-2 rounded border border-border bg-background min-h-[120px] resize-y`,disabled:W})]}),ne&&(0,X.jsx)(`div`,{className:`px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:ne}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Claude will draft a full `,(0,X.jsx)(`code`,{children:`.md`}),` body. You'll review it in the Studio and can edit before saving. This spawns a one-shot claude invocation and can take up to 90 seconds.`]})]}),(0,X.jsxs)(k,{children:[(0,X.jsx)(d,{variant:`ghost`,size:`sm`,onClick:()=>z(!1),disabled:W,children:`Cancel`}),(0,X.jsx)(d,{size:`sm`,onClick:le,disabled:W||!B.trim()||!H.trim(),children:W?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(l,{className:`w-3.5 h-3.5 mr-1.5 animate-spin`}),` Generating…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(p,{className:`w-3.5 h-3.5 mr-1.5`}),` Generate`]})})]})]})}),le=async()=>{G(!0),K(null);try{let e=await fetch(`${w()}/profiles/catalog/generate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:B.trim(),description:H.trim()})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Generate failed: ${e.status}`)}let t=await e.json();z(!1),C({kind:`create`,initialBody:t.draft,initialName:B.trim()})}catch(e){K(e.message)}finally{G(!1)}},ue=async e=>{try{let t=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(e)}`);if(!t.ok)throw Error(`Load failed: ${t.status}`);C({kind:`duplicate`,from:e,initialBody:(await t.json()).body})}catch(e){x(e.message)}};if(e.length===0)return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsxs)(`div`,{className:`text-center max-w-sm`,children:[(0,X.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:`No agents installed`}),(0,X.jsxs)(`div`,{className:`text-xs text-muted-foreground mt-1 mb-4`,children:[`Run `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`npx specrails-core@latest update`}),` in this project to install the upstream agents, or create a custom agent now.`]}),(0,X.jsxs)(`div`,{className:`flex gap-2 justify-center flex-wrap`,children:[(0,X.jsxs)(d,{size:`sm`,onClick:()=>z(!0),children:[(0,X.jsx)(p,{className:`w-3.5 h-3.5 mr-1.5`}),` Generate with Claude`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>A(!0),children:[(0,X.jsx)(c,{className:`w-3.5 h-3.5 mr-1.5`}),` Template`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>C({kind:`create`}),children:[(0,X.jsx)(h,{className:`w-3.5 h-3.5 mr-1.5`}),` Blank`]})]})]})}),se(),ce()]});let de=e.filter(e=>e.kind===`upstream`),fe=e.filter(e=>e.kind===`custom`),Q=e.find(e=>e.id===r);return(0,X.jsxs)(X.Fragment,{children:[se(),ce(),(0,X.jsxs)(`div`,{className:`flex h-full`,children:[(0,X.jsxs)(`aside`,{className:`w-72 flex-shrink-0 border-r border-border flex flex-col`,children:[(0,X.jsxs)(`div`,{className:`px-3 py-2 border-b border-border`,children:[(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground uppercase tracking-wide mb-1.5`,children:`Catalog`}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground/70 mb-2`,children:`Create a custom agent:`}),(0,X.jsxs)(`div`,{className:`flex gap-1`,children:[(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>A(!0),title:`Start from a template`,children:[(0,X.jsx)(c,{className:`w-3 h-3 mr-1`}),` Template`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>z(!0),title:`Generate with Claude`,children:[(0,X.jsx)(p,{className:`w-3 h-3 mr-1`}),` Generate`]}),(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>C({kind:`create`}),title:`Start from a blank template`,children:[(0,X.jsx)(h,{className:`w-3 h-3 mr-1`}),` Blank`]})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 overflow-auto p-2`,children:[(0,X.jsx)(je,{title:`Upstream (${de.length})`,description:`Shipped by specrails-core; read-only.`,children:de.map(e=>(0,X.jsx)(Me,{agent:e,selected:e.id===r,onSelect:()=>s(e.id)},e.id))}),(0,X.jsx)(je,{title:`Custom (${fe.length})`,description:`Your project's custom-*.md files. Use Template / Generate / Blank above to create one.`,children:fe.length===0?(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground px-2 py-2 italic`,children:`No custom agents yet.`}):fe.map(e=>(0,X.jsx)(Me,{agent:e,selected:e.id===r,onSelect:()=>s(e.id)},e.id))})]})]}),(0,X.jsxs)(`main`,{className:`flex-1 min-w-0 overflow-auto`,children:[b&&(0,X.jsx)(`div`,{className:`m-4 px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:b}),Q&&(0,X.jsxs)(`div`,{className:`p-6 min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-start justify-between gap-4 mb-1`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,X.jsx)(`h2`,{className:`text-base font-mono font-semibold`,children:Q.id}),(0,X.jsx)(Ne,{kind:Q.kind}),Q.model&&(0,X.jsxs)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[`default model: `,Q.model]})]}),Q.description&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 break-words`,children:Q.description})]}),(0,X.jsxs)(`div`,{className:`flex gap-2 flex-shrink-0`,children:[(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>void ue(Q.id),children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1`}),` Duplicate`]}),Q.kind===`custom`&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(d,{size:`sm`,variant:`ghost`,onClick:()=>C({kind:`edit`,agentId:Q.id}),children:[(0,X.jsx)(g,{className:`w-3.5 h-3.5 mr-1`}),` Edit`]}),(0,X.jsxs)(d,{size:`sm`,onClick:async()=>{try{let e=await fetch(`${w()}/profiles/catalog/${encodeURIComponent(Q.id)}`);if(!e.ok)throw Error(`Load failed: ${e.status}`);let t=await e.json();E({kind:`open`,agentId:Q.id,baseBody:t.body})}catch(e){x(e.message)}},title:`Iteratively refine this agent with AI`,children:[(0,X.jsx)(ie,{className:`w-3.5 h-3.5 mr-1`}),` AI Edit`]})]})]})]}),(0,X.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/30 mt-4 min-w-0 overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1.5 border-b border-border`,children:[(0,X.jsxs)(`span`,{className:`text-[11px] font-mono text-muted-foreground truncate`,children:[`.claude/agents/`,Q.id,`.md`]}),(0,X.jsx)(`span`,{className:`text-[10px] text-muted-foreground flex-shrink-0 ml-2`,children:Q.kind===`upstream`?`read-only`:`editable — use Edit above`})]}),(0,X.jsx)(`pre`,{className:`p-4 text-xs font-mono overflow-auto max-h-[60vh] whitespace-pre-wrap break-all`,children:ee?`Loading…`:u??``})]})]})]})]})]})}function Ae({label:e,count:t,active:n,onClick:r}){return(0,X.jsxs)(`button`,{type:`button`,onClick:r,className:`flex-shrink-0 inline-flex items-center gap-1 h-7 px-2.5 text-[11px] rounded-full border transition-colors whitespace-nowrap `+(n?`bg-dracula-purple/20 border-dracula-purple/50 text-dracula-purple`:`bg-transparent border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[e,(0,X.jsx)(`span`,{className:`text-[9px] px-1 rounded `+(n?`bg-dracula-purple/30`:`bg-muted/60`),children:t})]})}function je({title:e,description:t,children:n}){return(0,X.jsxs)(`div`,{className:`mb-4`,children:[(0,X.jsxs)(`div`,{className:`px-2 pb-1`,children:[(0,X.jsx)(`div`,{className:`text-[11px] font-medium text-muted-foreground uppercase tracking-wide`,children:e}),t&&(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground/70 mt-0.5`,children:t})]}),(0,X.jsx)(`div`,{className:`space-y-0.5`,children:n})]})}function Me({agent:e,selected:t,onSelect:n}){return(0,X.jsxs)(`button`,{type:`button`,onClick:n,className:`w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded transition-colors `+(t?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,X.jsx)(`span`,{className:`text-sm font-mono truncate`,children:e.id}),(0,X.jsx)(Ne,{kind:e.kind})]})}function Ne({kind:e}){return(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded flex-shrink-0 `+(e===`custom`?`bg-purple-500/15 text-purple-400`:`bg-muted text-muted-foreground`),children:e})}var Pe=[{label:`7d`,days:7},{label:`30d`,days:30},{label:`90d`,days:90}];function Fe(){let[e,t]=(0,Y.useState)(null),[n,r]=(0,Y.useState)(30),[i,a]=(0,Y.useState)(!0);if((0,Y.useEffect)(()=>{let e=!1;return a(!0),fetch(`${w()}/profiles/analytics?windowDays=${n}`).then(e=>e.ok?e.json():null).then(n=>{!e&&n&&t(n)}).catch(()=>{}).finally(()=>{e||a(!1)}),()=>{e=!0}},[n]),i&&!e)return null;if(!e||e.rows.length===0)return(0,X.jsxs)(`div`,{className:`mx-6 my-4 rounded-md border border-border bg-muted/20`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-foreground`,children:`Profile usage`}),(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:`Jobs launched per profile in the selected window.`})]}),(0,X.jsx)(`div`,{className:`flex gap-0.5`,children:Pe.map(e=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>r(e.days),className:`text-[10px] px-2 py-1 rounded transition-colors `+(n===e.days?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:e.label},e.days))})]}),(0,X.jsx)(`div`,{className:`px-4 py-8 text-xs text-muted-foreground`,children:`No profile-scoped jobs yet.`})]});let o=Math.max(...e.rows.map(e=>e.jobs),1);return(0,X.jsxs)(`div`,{className:`mx-6 my-4 rounded-md border border-border bg-muted/20`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-foreground`,children:`Profile usage`}),(0,X.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Jobs launched per profile in the last `,e.windowDays,` days.`]})]}),(0,X.jsx)(`div`,{className:`flex gap-0.5`,children:Pe.map(e=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>r(e.days),className:`text-[10px] px-2 py-1 rounded transition-colors `+(n===e.days?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:e.label},e.days))})]}),(0,X.jsx)(`div`,{className:`p-4 space-y-2`,children:e.rows.map(e=>(0,X.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,X.jsx)(`div`,{className:`w-32 text-xs font-mono truncate`,children:e.profileName}),(0,X.jsx)(`div`,{className:`flex-1 h-4 bg-muted/50 rounded overflow-hidden`,children:(0,X.jsx)(`div`,{className:`h-full bg-dracula-purple/70`,style:{width:`${Math.max(6,Math.round(e.jobs/o*100))}%`}})}),(0,X.jsxs)(`div`,{className:`flex gap-4 text-[11px] text-muted-foreground min-w-0 flex-shrink-0`,children:[(0,X.jsxs)(`span`,{title:`jobs`,children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:e.jobs}),` jobs`]}),(0,X.jsxs)(`span`,{title:`success rate`,children:[(0,X.jsxs)(`span`,{className:`text-foreground font-mono`,children:[Math.round(e.successRate*100),`%`]}),` `,`ok`]}),e.avgDurationMs!=null&&(0,X.jsx)(`span`,{title:`avg duration`,children:(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:Ie(e.avgDurationMs)})}),e.avgTokens!=null&&(0,X.jsxs)(`span`,{title:`avg tokens`,children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:Le(e.avgTokens)}),` `,`tok`]})]})]},e.profileName))})]})}function Ie(e){let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m`:`${Math.floor(n/60)}h${n%60}m`}function Le(e){return e<1e3?Math.round(e).toString():e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}var Re=`specrails-hub:agents-tab`;function ze(){try{let e=localStorage.getItem(Re);if(e===`profiles`||e===`usage`||e===`catalog`)return e}catch{}return`profiles`}function Be(){let[e,t]=(0,Y.useState)(()=>ze()),n=e=>{t(e);try{localStorage.setItem(Re,e)}catch{}},[r,i]=(0,Y.useState)(null);return(0,Y.useEffect)(()=>{let e=!1;return fetch(`${w()}/profiles/core-version`).then(e=>e.ok?e.json():null).then(t=>{!e&&t&&i(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,X.jsxs)(`div`,{className:`flex flex-col h-full bg-background`,children:[r!==null&&!r.profileAware&&(0,X.jsxs)(`div`,{className:`flex-shrink-0 flex items-start gap-3 px-6 py-3 border-b border-yellow-500/30 bg-yellow-500/10`,children:[(0,X.jsx)(s,{className:`w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0`}),(0,X.jsxs)(`div`,{className:`text-xs`,children:[(0,X.jsxs)(`div`,{className:`font-medium text-yellow-500`,children:[`Profile-aware pipeline requires specrails-core `,r.required,`+`]}),(0,X.jsxs)(`div`,{className:`text-yellow-500/80 mt-0.5`,children:[`This project has`,` `,(0,X.jsx)(`code`,{className:`px-1 rounded bg-yellow-500/20`,children:r.version??`unknown`}),`. Run`,` `,(0,X.jsx)(`code`,{className:`px-1 rounded bg-yellow-500/20`,children:`npx specrails-core@latest update`}),` `,`inside the project to unlock profile mode. Profiles you create here will still save; they just won't affect the pipeline until core is updated.`]})]})]}),(0,X.jsxs)(`div`,{className:`flex-shrink-0 border-b border-border`,children:[(0,X.jsxs)(`div`,{className:`px-6 pt-4`,children:[(0,X.jsx)(`h1`,{className:`text-lg font-semibold`,children:`Agents`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:`Manage agent profiles and the catalog (upstream + custom) for this project.`})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 px-4 pt-3`,children:[(0,X.jsx)(He,{active:e===`profiles`,onClick:()=>n(`profiles`),children:`Profiles`}),(0,X.jsx)(He,{active:e===`usage`,onClick:()=>n(`usage`),children:`Usage`}),(0,X.jsx)(He,{active:e===`catalog`,onClick:()=>n(`catalog`),children:`Catalog`})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0 overflow-auto`,children:[e===`profiles`&&(0,X.jsx)(me,{}),e===`usage`&&(0,X.jsx)(Ve,{}),e===`catalog`&&(0,X.jsx)(ke,{})]})]})}function Ve(){return(0,X.jsx)(`div`,{className:`min-h-full`,children:(0,X.jsx)(Fe,{})})}function He({active:e,children:t,onClick:n}){return(0,X.jsx)(`button`,{type:`button`,onClick:n,className:`h-8 px-3 text-xs font-medium rounded-t-md border-b-2 transition-colors `+(e?`text-foreground border-foreground`:`text-muted-foreground border-transparent hover:text-foreground hover:border-border`),children:t})}export{Be as default};
79
+ `;function ye({agentId:e,initialBody:t,initialName:n,draftFromRefine:r,onClose:i,onSaved:a,onResumeRefine:o}){let s=!e,[c,l]=(0,Y.useState)(e??n??``),[u,d]=(0,Y.useState)(t??ve),[p,h]=(0,Y.useState)(!s&&!t&&!r),[v,y]=(0,Y.useState)(!!r&&!s),[b,x]=(0,Y.useState)(!1),[S,w]=(0,Y.useState)(null),[T,E]=(0,Y.useState)([]),[D,k]=(0,Y.useState)(!1),[A,j]=(0,Y.useState)(!!t&&s),[M,N]=(0,Y.useState)(!1),[P,F]=(0,Y.useState)(``),[L,z]=(0,Y.useState)(!1),[B,V]=(0,Y.useState)(null),[H,U]=(0,Y.useState)(null),[ee,W]=(0,Y.useState)(!1);(0,Y.useEffect)(()=>{if(s||t!==void 0)return;if(r){let t=!1;return fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}/refine/${r}`).then(e=>{if(!e.ok)throw Error(`Load draft failed: ${e.status}`);return e.json()}).then(e=>{!t&&e.draftBody&&(d(e.draftBody),j(!0))}).catch(e=>{t||w(e.message)}).finally(()=>{t||y(!1)}),()=>{t=!0}}let n=!1;return fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`).then(e=>{if(!e.ok)throw Error(`Load failed: ${e.status}`);return e.json()}).then(e=>{n||d(e.body)}).catch(e=>{n||w(e.message)}).finally(()=>{n||h(!1)}),()=>{n=!0}},[e,s,t,r]);let G=(0,Y.useCallback)(()=>{s||fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}/versions`).then(e=>e.ok?e.json():{versions:[]}).then(e=>E(e.versions)).catch(()=>E([]))},[e,s]);(0,Y.useEffect)(()=>{D&&G()},[D,G]);let K=/^custom-[a-z0-9][a-z0-9-]*$/.test(c),ne=u.trim().length>0,re=/^---\s*\n[\s\S]*?\n---/.test(u),ae=ne&&re&&(s?K:!0)&&A,oe=(0,Y.useCallback)(async()=>{x(!0),w(null);try{let t;if(t=s?await fetch(`${O()}/profiles/catalog`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:c,body:u})}):await fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({body:u})}),!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Save failed: ${t.status}`)}j(!1),g.success(s?`Agent created`:`Agent saved`,{description:s?c:e}),a&&a(s?c:e)}catch(e){let t=e.message;w(t),g.error(s?`Failed to create agent`:`Failed to save agent`,{description:t})}finally{x(!1)}},[e,u,c,s,a]),Z=(0,Y.useCallback)(async()=>{if(!s){W(!1),x(!0),w(null);try{let t=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Delete failed: ${t.status}`)}g.success(`Agent deleted`,{description:e}),a&&a(e),i()}catch(e){let t=e.message;w(t),g.error(`Failed to delete agent`,{description:t})}finally{x(!1)}}},[e,s,i,a]),se=(0,Y.useCallback)(e=>{d(e.body),j(!0),k(!1)},[]),ce=(0,Y.useCallback)(async()=>{z(!0),U(null),V(null);try{let t=await fetch(`${O()}/profiles/catalog/test`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:s?c||`draft`:e,draftBody:u,sampleTask:P})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Test failed: ${t.status}`)}V(await t.json())}catch(e){U(e.message)}finally{z(!1)}},[e,u,c,s,P]);return p?(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading agent…`})}):(0,X.jsxs)(`div`,{className:`flex flex-col h-full`,children:[!s&&(0,X.jsx)(pe,{open:ee,title:`Delete agent "${e}"?`,description:`This removes the .md from disk. Version history stays in the DB — use a fresh custom agent if you want to recover the body later.`,confirmLabel:`Delete`,destructive:!0,onConfirm:Z,onCancel:()=>W(!1)}),(0,X.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2 border-b border-border`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:i,className:`p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground`,title:`Back`,children:(0,X.jsx)(I,{className:`w-4 h-4`})}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground uppercase tracking-wide`,children:s?`New custom agent`:`Edit custom agent`}),s?(0,X.jsx)(C,{value:c,onChange:e=>{l(e.target.value),j(!0)},placeholder:`custom-my-agent`,className:`text-sm font-mono mt-1 max-w-sm`}):(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`div`,{className:`text-sm font-mono`,children:e}),r&&(0,X.jsxs)(`button`,{type:`button`,onClick:async()=>{if(!(!o||!e))try{let t=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`);if(!t.ok)return;o(r,e,(await t.json()).body)}catch{}},className:`inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border border-accent-primary/40 bg-accent-primary/15 text-accent-primary hover:bg-accent-primary/25 focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none`,title:`Hand this draft back to the AI Edit overlay`,children:[(0,X.jsx)(ie,{className:`w-3 h-3`}),` Resume AI Edit`]}),v&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-[10px] text-muted-foreground`,children:[(0,X.jsx)(R,{className:`w-3 h-3 animate-spin`}),` loading AI draft…`]})]})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>{N(e=>!e),M||k(!1)},title:`Test this agent against a sample task`,children:[(0,X.jsx)(q,{className:`w-3.5 h-3.5 mr-1`}),`Test`]}),!s&&(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>{k(e=>!e),D||N(!1)},title:`Version history`,children:[(0,X.jsx)(J,{className:`w-3.5 h-3.5 mr-1`}),`History`]}),!s&&(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>W(!0),disabled:b,className:`text-red-400 hover:text-red-300`,children:[(0,X.jsx)(m,{className:`w-3.5 h-3.5 mr-1`}),`Delete`]}),(0,X.jsxs)(f,{size:`sm`,onClick:oe,disabled:!ae||b,children:[(0,X.jsx)(_,{className:`w-3.5 h-3.5 mr-1`}),b?`Saving…`:s?`Create`:`Save`]})]})]}),S&&(0,X.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2 text-xs border-b border-red-500/30 bg-red-500/10 text-red-400`,children:[(0,X.jsx)(te,{className:`w-3.5 h-3.5 flex-shrink-0`}),S]}),s&&c.length>0&&!K&&(0,X.jsxs)(`div`,{className:`px-4 py-1.5 text-[11px] border-b border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[`Name must start with `,(0,X.jsx)(`code`,{children:`custom-`}),` and contain only lowercase letters, digits, and hyphens.`]}),!re&&(0,X.jsxs)(`div`,{className:`px-4 py-1.5 text-[11px] border-b border-yellow-500/30 bg-yellow-500/10 text-yellow-500`,children:[`Missing YAML frontmatter (needs opening `,(0,X.jsx)(`code`,{children:`---`}),` on the first line).`]}),(0,X.jsxs)(`div`,{className:`flex flex-1 min-h-0`,children:[(0,X.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0`,children:[(0,X.jsxs)(`div`,{className:`px-4 py-1.5 border-b border-border text-[11px] font-mono text-muted-foreground flex items-center justify-between`,children:[(0,X.jsxs)(`span`,{children:[`.claude/agents/`,s?c||`custom-…`:e,`.md`]}),A&&(0,X.jsx)(`span`,{className:`text-yellow-500`,children:`● unsaved`})]}),(0,X.jsx)(`textarea`,{value:u,onChange:e=>{d(e.target.value),j(!0)},spellCheck:!1,className:`flex-1 w-full p-4 text-xs font-mono bg-background text-foreground outline-none resize-none leading-relaxed`})]}),M&&(0,X.jsxs)(`aside`,{className:`w-96 flex-shrink-0 border-l border-border flex flex-col min-h-0`,children:[(0,X.jsxs)(`div`,{className:`px-3 py-2 border-b border-border text-xs font-medium text-muted-foreground uppercase tracking-wide flex items-center gap-2`,children:[(0,X.jsx)(q,{className:`w-3.5 h-3.5`}),` Test agent`]}),(0,X.jsxs)(`div`,{className:`p-3 border-b border-border`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,X.jsx)(`label`,{className:`text-[11px] text-muted-foreground`,children:`Sample task`}),(0,X.jsx)(`select`,{className:`h-6 text-[11px] rounded border border-border bg-background px-1`,value:``,onChange:e=>{let t=parseInt(e.target.value,10);!isNaN(t)&&t>0&&F(_e[t].prompt)},disabled:L,children:_e.map((e,t)=>(0,X.jsx)(`option`,{value:t,children:e.label},t))})]}),(0,X.jsx)(`textarea`,{value:P,onChange:e=>F(e.target.value),placeholder:`Describe what the agent should do, or pick a sample above.`,className:`w-full text-xs p-2 rounded border border-border bg-background min-h-[80px] resize-y font-mono`,disabled:L}),(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mt-2`,children:[(0,X.jsx)(f,{size:`sm`,onClick:ce,disabled:L||!P.trim()||!u.trim(),children:L?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(R,{className:`w-3.5 h-3.5 mr-1.5 animate-spin`}),` Running…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(q,{className:`w-3.5 h-3.5 mr-1.5`}),` Run`]})}),(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Sandboxed; no files written.`})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 overflow-auto p-3 min-h-0`,children:[H&&(0,X.jsx)(`div`,{className:`px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400 mb-2`,children:H}),B&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-3 text-[11px] text-muted-foreground mb-2`,children:[(0,X.jsxs)(`span`,{children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:B.tokens}),` tokens`]}),(0,X.jsx)(`span`,{children:(0,X.jsxs)(`span`,{className:`text-foreground font-mono`,children:[(B.durationMs/1e3).toFixed(1),`s`]})})]}),(0,X.jsx)(`pre`,{className:`text-xs font-mono whitespace-pre-wrap leading-relaxed rounded border border-border bg-background p-3`,children:B.output})]}),!L&&!B&&!H&&(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground italic`,children:`Run a sample task against the current draft. Output appears here.`})]})]}),D&&!s&&(0,X.jsxs)(`aside`,{className:`w-72 flex-shrink-0 border-l border-border flex flex-col`,children:[(0,X.jsx)(`div`,{className:`px-3 py-2 border-b border-border text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Version history`}),(0,X.jsx)(`div`,{className:`flex-1 overflow-auto p-2 space-y-1`,children:T.length===0?(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground italic px-2 py-2`,children:`No prior versions recorded for this agent.`}):T.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>se(e),className:`w-full text-left px-2 py-1.5 rounded hover:bg-accent/50 transition-colors`,children:[(0,X.jsxs)(`div`,{className:`text-xs font-mono text-foreground`,children:[`v`,e.version]}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.version))}),(0,X.jsx)(`div`,{className:`px-3 py-2 border-t border-border text-[11px] text-muted-foreground`,children:`Click a version to restore its body into the editor (you still need to Save).`})]})]})]})}var be={refineId:null,agentId:null,uiState:`closed`,phase:`idle`,history:[],streamingText:``,draftBody:null,baseBody:null,autoTest:!1,testResult:null,appliedVersion:null,errorMessage:null,applyConflict:null};function xe(e){return e.replace(/<!--tool:[^>]+-->/g,``)}function Se(e,t){switch(t.type){case`OPEN`:return{...be,agentId:t.agentId,baseBody:t.baseBody,uiState:`composing`};case`START_TURN`:return{...e,refineId:t.refineId,uiState:`streaming`,phase:`reading`,streamingText:``,errorMessage:null,applyConflict:null,history:[...e.history,t.userTurn]};case`STREAM_DELTA`:return e.refineId===t.refineId?{...e,streamingText:e.streamingText+t.delta}:e;case`PHASE`:return e.refineId===t.refineId?{...e,phase:t.phase}:e;case`READY`:return e.refineId===t.refineId?{...e,uiState:`reviewing`,phase:`done`,draftBody:t.draftBody,streamingText:``,history:[...e.history,{role:`assistant`,content:xe(t.draftBody),timestamp:Date.now()}]}:e;case`TEST_RESULT`:return e.refineId===t.refineId?{...e,testResult:t.result,history:[...e.history,{role:`system`,kind:`test_result`,content:t.result.output,timestamp:Date.now()}]}:e;case`APPLIED`:return e.refineId===t.refineId?{...e,uiState:`applied`,appliedVersion:t.version}:e;case`CANCELLED`:return{...e,uiState:`cancelled`};case`ERROR`:return t.refineId!==null&&e.refineId!==t.refineId?e:{...e,uiState:`error`,errorMessage:t.message};case`CONFLICT`:return e.refineId===t.refineId?{...e,applyConflict:t.reason}:e;case`TOGGLE_AUTO_TEST`:return{...e,autoTest:t.enabled};case`REHYDRATE`:return{...e,...t.payload};case`CLOSE`:return be;default:return e}}function Ce(e){switch(e.status){case`streaming`:return`streaming`;case`ready`:return`reviewing`;case`applied`:return`applied`;case`cancelled`:return`cancelled`;case`error`:return`error`;default:return e.draftBody?`reviewing`:`composing`}}function we(e){let[t,n]=(0,Y.useReducer)(Se,be),{registerHandler:r,unregisterHandler:i}=B(),a=(0,Y.useRef)(null);a.current=t.refineId;let o=(0,Y.useRef)(null);o.current=t.agentId;let s=(0,Y.useRef)(e);s.current=e;let c=(0,Y.useRef)(e);(0,Y.useEffect)(()=>{e!==c.current&&(c.current=e,n({type:`CLOSE`}))},[e]),(0,Y.useEffect)(()=>{let e=`agent-refine-${Math.random().toString(36).slice(2,9)}`;return r(e,e=>{let t=e;if(typeof t.type!=`string`||t.projectId!==s.current||t.refineId!==a.current)return;let r=t.refineId;switch(t.type){case`agent_refine_stream`:n({type:`STREAM_DELTA`,refineId:r,delta:t.delta});break;case`agent_refine_phase`:n({type:`PHASE`,refineId:r,phase:t.phase});break;case`agent_refine_ready`:n({type:`READY`,refineId:r,draftBody:t.draftBody});break;case`agent_refine_test`:n({type:`TEST_RESULT`,refineId:r,result:t.result});break;case`agent_refine_applied`:n({type:`APPLIED`,refineId:r,version:t.version});break;case`agent_refine_cancelled`:n({type:`CANCELLED`,refineId:r});break;case`agent_refine_error`:n({type:`ERROR`,refineId:r,message:t.error});break}}),()=>i(e)},[r,i]);let l=(0,Y.useCallback)((e,t)=>{n({type:`OPEN`,agentId:e,baseBody:t})},[]),u=(0,Y.useCallback)(()=>{n({type:`CLOSE`})},[]);return{state:t,open:l,start:(0,Y.useCallback)(async e=>{let r=o.current;if(r)try{let i=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(r)}/refine`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({instruction:e,autoTest:t.autoTest})});if(!i.ok){n({type:`ERROR`,refineId:null,message:(await i.json().catch(()=>({}))).error??`Server error (${i.status})`});return}let o=await i.json();a.current=o.refineId,n({type:`START_TURN`,refineId:o.refineId,userTurn:{role:`user`,content:e,timestamp:Date.now()}})}catch(e){n({type:`ERROR`,refineId:null,message:`Connection failed: ${e.message}`})}},[t.autoTest]),sendTurn:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(!(!t||!r)){n({type:`START_TURN`,refineId:t,userTurn:{role:`user`,content:e,timestamp:Date.now()}});try{let i=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}/turn`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({instruction:e})});i.ok||n({type:`ERROR`,refineId:t,message:(await i.json().catch(()=>({}))).error??`Server error (${i.status})`})}catch(e){n({type:`ERROR`,refineId:t,message:`Connection failed: ${e.message}`})}}},[]),cancel:(0,Y.useCallback)(async()=>{let e=a.current,t=o.current;if(!(!e||!t))try{await fetch(`${O()}/profiles/catalog/${encodeURIComponent(t)}/refine/${e}`,{method:`DELETE`})}catch{}},[]),apply:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(!(!t||!r))try{let i=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:!!e})});if(i.status===409){let e=await i.json().catch(()=>({}));if(e.reason===`disk_changed`||e.reason===`name_changed`){n({type:`CONFLICT`,refineId:t,reason:e.reason});return}}if(!i.ok){n({type:`ERROR`,refineId:t,message:(await i.json().catch(()=>({}))).error??`Apply failed (${i.status})`});return}n({type:`APPLIED`,refineId:t,version:(await i.json()).version})}catch(e){n({type:`ERROR`,refineId:t,message:`Connection failed: ${e.message}`})}},[]),toggleAutoTest:(0,Y.useCallback)(async e=>{let t=a.current,r=o.current;if(n({type:`TOGGLE_AUTO_TEST`,enabled:e}),!(!t||!r))try{await fetch(`${O()}/profiles/catalog/${encodeURIComponent(r)}/refine/${t}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({autoTest:e})})}catch{}},[]),rehydrate:(0,Y.useCallback)(async(e,t)=>{try{let r=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(t)}`);if(!r.ok)throw Error(`load agent failed: ${r.status}`);let i=await r.json(),s=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(t)}/refine/${e}`);if(!s.ok)throw Error(`load session failed: ${s.status}`);let c=await s.json();a.current=e,o.current=t,n({type:`REHYDRATE`,payload:{refineId:e,agentId:t,baseBody:i.body,draftBody:c.draftBody,history:c.history,autoTest:c.autoTest,phase:c.phase,uiState:Ce(c),streamingText:``}})}catch(e){n({type:`ERROR`,refineId:null,message:`Rehydrate failed: ${e.message}`})}},[]),close:u}}var Te=[`Tighten the tool list`,`Make the personality stricter`,`Add a Workflow protocol section`,`Shorten and sharpen the description`,`Match the sr-developer style`];function Ee({agentId:e,baseBody:t,resumeRefineId:n,onClose:r,onOpenInStudio:i,onApplied:a}){let{activeProjectId:o}=P(),s=we(o),[c,l]=(0,Y.useState)(``),u=(0,Y.useRef)(null),d=(0,Y.useRef)(!1);(0,Y.useEffect)(()=>{d.current||(d.current=!0,n?s.rehydrate(n,e):s.open(e,t))},[e,t,n,s]),(0,Y.useEffect)(()=>{let e=setTimeout(()=>u.current?.focus(),50);return()=>clearTimeout(e)},[]);let f=(0,Y.useRef)(null);(0,Y.useEffect)(()=>{s.state.uiState===`applied`&&s.state.appliedVersion!==null&&s.state.appliedVersion!==f.current&&(f.current=s.state.appliedVersion,a&&s.state.agentId&&a(s.state.agentId,s.state.appliedVersion))},[s.state.uiState,s.state.appliedVersion,s.state.agentId,a]);let p=(0,Y.useCallback)(async e=>{let t=e.trim();t&&(l(``),s.state.refineId?await s.sendTurn(t):await s.start(t))},[s]),m=(0,Y.useCallback)(()=>{p(c)},[c,p]),h=(0,Y.useCallback)(async()=>{s.state.refineId&&(s.state.uiState===`streaming`||s.state.uiState===`reviewing`)&&await s.cancel(),r()},[s,r]),g=De(s.state),_=(0,Y.useMemo)(()=>!s.state.draftBody||!s.state.baseBody?null:(0,X.jsx)(T,{hunks:D(s.state.baseBody,s.state.draftBody)}),[s.state.baseBody,s.state.draftBody]);return(0,X.jsx)(N,{uiPhase:g,errorMessage:s.state.errorMessage,applyConflict:s.state.applyConflict,eyebrow:`AI Edit`,targetLabel:e,targetLabelMono:!0,headline:`Refine your agent`,streamingHeadline:`Refining your agent…`,description:Oe(t),chips:Te,onChipSubmit:e=>void p(e),composer:(0,X.jsx)(z,{value:c,onChange:l,onSubmit:m,disabled:g===`streaming`||g===`applied`,placeholder:s.state.refineId?`Send a follow-up refinement…`:`Describe how to refine this agent…`,inputRef:u}),streamingText:s.state.streamingText,history:s.state.history,diff:_,diffHeaderLabel:`.claude/agents/${e}.md`,baseBody:t,baseBodyDisclosureLabel:`View current agent body`,appliedNotice:s.state.appliedVersion===null?void 0:(0,X.jsxs)(`div`,{className:`rounded-md border border-green-500/40 bg-green-500/10 p-3 text-xs text-green-300`,children:[`Applied as version `,s.state.appliedVersion,`.`]}),canApply:s.state.uiState===`reviewing`&&!!s.state.draftBody&&!s.state.applyConflict,onApply:()=>void s.apply(),onForceApply:()=>void s.apply(!0),onDiscard:()=>void h(),onClose:()=>void h(),secondaryAction:i&&s.state.draftBody&&s.state.refineId?{label:`Open draft in Studio for manual editing`,icon:(0,X.jsx)(y,{className:`w-3 h-3`}),onClick:()=>{s.state.refineId&&s.state.draftBody&&i&&i(s.state.refineId,s.state.draftBody)}}:void 0})}function De(e){switch(e.uiState){case`streaming`:return`streaming`;case`reviewing`:return`reviewing`;case`applied`:return`applied`;case`error`:return`error`;default:return`composing`}}function Oe(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return null;let n=t[1].match(/^description:\s*([\s\S]*?)(?=^[a-z_]+:\s|\Z)/m);if(!n)return null;let r=n[1].trim();return(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))&&(r=r.slice(1,-1)),r=r.replace(/\\n/g,` `).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\'/g,`'`).replace(/\\\\/g,`\\`).replace(/\s+/g,` `).trim(),r.length>240&&(r=r.slice(0,237)+`…`),r||null}function ke(){let[e,n]=(0,Y.useState)([]),[i,c]=(0,Y.useState)(null),[l,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(!0),[_,y]=(0,Y.useState)(!1),[x,S]=(0,Y.useState)(null),[w,T]=(0,Y.useState)({kind:`closed`}),[E,D]=(0,Y.useState)({kind:`closed`}),[k,A]=(0,Y.useState)(!1),[M,N]=(0,Y.useState)(``),[P,F]=(0,Y.useState)(`all`),[I,L]=(0,Y.useState)(null),[z,B]=(0,Y.useState)(!1),[V,H]=(0,Y.useState)(``),[U,ee]=(0,Y.useState)(``),[G,K]=(0,Y.useState)(!1),[te,q]=(0,Y.useState)(null),J=(0,Y.useCallback)(()=>{let e=!1;return g(!0),fetch(`${O()}/profiles/catalog`).then(e=>{if(!e.ok)throw Error(`Catalog load failed: ${e.status}`);return e.json()}).then(t=>{e||(n(t.agents),t.agents.length>0&&!i&&c(t.agents[0].id))}).catch(t=>{e||S(t.message)}).finally(()=>{e||g(!1)}),()=>{e=!0}},[i]);(0,Y.useEffect)(()=>J(),[J]);let ne=(0,Y.useCallback)(e=>{let t=!1;return y(!0),m(null),fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`).then(e=>{if(!e.ok)throw Error(`Agent body load failed: ${e.status}`);return e.json()}).then(e=>{t||m(e.body)}).catch(e=>{t||S(e.message)}).finally(()=>{t||y(!1)}),()=>{t=!0}},[]);if((0,Y.useEffect)(()=>{if(i)return ne(i)},[i,ne]),h)return(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading catalog…`})});if(w.kind!==`closed`)return(0,X.jsx)(ye,{agentId:w.kind===`edit`?w.agentId:void 0,initialBody:w.kind===`duplicate`||w.kind===`create`?w.initialBody:void 0,initialName:w.kind===`create`?w.initialName:void 0,draftFromRefine:w.kind===`edit`?w.draftFromRefine:void 0,onClose:()=>T({kind:`closed`}),onSaved:e=>{c(e),T({kind:`closed`}),J()},onResumeRefine:(e,t,n)=>{T({kind:`closed`}),D({kind:`open`,agentId:t,baseBody:n,resumeRefineId:e})}});if(E.kind===`open`)return(0,X.jsx)(Ee,{agentId:E.agentId,baseBody:E.baseBody,resumeRefineId:E.resumeRefineId,onClose:()=>D({kind:`closed`}),onApplied:e=>{D({kind:`closed`}),c(e),J()},onOpenInStudio:(e,t)=>{D({kind:`closed`}),T({kind:`edit`,agentId:E.agentId,draftFromRefine:e})}});let ae=(()=>{let e=M.trim().toLowerCase();return he.filter(t=>!(P!==`all`&&t.category!==P||I&&!t.tags.includes(I)||e&&!(t.label+` `+t.blurb+` `+t.tags.join(` `)+` `+t.category).toLowerCase().includes(e)))})(),oe=(()=>{let e=new Map;for(let t of he)e.set(t.category,(e.get(t.category)??0)+1);return e})(),Z=()=>{A(!1),N(``),F(`all`),L(null)},se=()=>(0,X.jsx)(a,{open:k,onOpenChange:e=>{e||Z()},children:(0,X.jsxs)(d,{className:`max-w-4xl p-0 h-[85vh] flex flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex-shrink-0 px-6 pt-5 pb-3 border-b border-border`,children:[(0,X.jsxs)(j,{children:[(0,X.jsxs)(u,{className:`flex items-center gap-2 text-base`,children:[(0,X.jsx)(b,{className:`w-4 h-4 text-accent-primary`}),` Agent template library`,(0,X.jsxs)(`span`,{className:`text-[11px] font-normal text-muted-foreground ml-1`,children:[ae.length,` of `,he.length]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Start from a curated template across engineering, product, science, health, legal, and more. Pick one and open it in the Studio for review and editing before saving.`})]}),(0,X.jsxs)(`div`,{className:`mt-3 relative`,children:[(0,X.jsx)(r,{className:`w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none`}),(0,X.jsx)(`input`,{value:M,onChange:e=>N(e.target.value),placeholder:`Search by name, description, tag, or category…`,className:`w-full h-9 pl-8 pr-8 text-sm rounded-md border border-border bg-background focus:outline-none focus:ring-1 focus:ring-primary/40`,autoFocus:!0}),M&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>N(``),className:`absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded hover:bg-accent text-muted-foreground`,children:(0,X.jsx)(s,{className:`w-3.5 h-3.5`})})]}),(0,X.jsxs)(`div`,{className:`flex gap-1.5 overflow-x-auto mt-3 pb-1 scrollbar-thin`,children:[(0,X.jsx)(Ae,{label:`All`,count:he.length,active:P===`all`,onClick:()=>F(`all`)}),ge.map(e=>(0,X.jsx)(Ae,{label:e,count:oe.get(e)??0,active:P===e,onClick:()=>F(e)},e))]}),I&&(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mt-2`,children:[(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Tag filter:`}),(0,X.jsxs)(`button`,{type:`button`,onClick:()=>L(null),className:`inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-accent-primary/20 text-accent-primary hover:bg-accent-primary/30`,children:[(0,X.jsx)(re,{className:`w-3 h-3`}),` `,I,(0,X.jsx)(s,{className:`w-3 h-3`})]})]})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-y-auto px-6 py-4`,children:ae.length===0?(0,X.jsx)(`div`,{className:`h-full flex items-center justify-center text-center`,children:(0,X.jsxs)(`div`,{className:`max-w-sm`,children:[(0,X.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No templates match your filters.`}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>{N(``),F(`all`),L(null)},className:`text-xs text-accent-primary hover:underline mt-2`,children:`Clear filters`})]})}):(0,X.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:ae.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>{Z(),T({kind:`create`,initialBody:e.body,initialName:e.nameHint})},className:`group text-left p-4 rounded-lg border border-border bg-card/40 hover:border-accent-primary/50 hover:bg-accent/40 hover:shadow-sm transition-all`,children:[(0,X.jsxs)(`div`,{className:`flex items-start gap-3 mb-2`,children:[(0,X.jsx)(`span`,{className:`text-2xl leading-none mt-0.5`,children:e.emoji}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`div`,{className:`text-sm font-semibold text-foreground group-hover:text-accent-primary truncate`,children:e.label}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground mt-0.5`,children:e.category})]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground leading-relaxed line-clamp-2 min-h-[2lh]`,children:e.blurb}),(0,X.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-3`,children:e.tags.slice(0,5).map(e=>(0,X.jsx)(`span`,{role:`button`,tabIndex:0,onClick:t=>{t.stopPropagation(),L(e)},onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),t.stopPropagation(),L(e))},className:`text-[10px] px-1.5 py-0.5 rounded bg-muted/50 text-muted-foreground hover:bg-accent-primary/20 hover:text-accent-primary cursor-pointer transition-colors `+(I===e?`bg-accent-primary/20 text-accent-primary`:``),children:e},e))}),(0,X.jsxs)(`div`,{className:`mt-3 pt-2 border-t border-border/40 flex items-center justify-between`,children:[(0,X.jsx)(`code`,{className:`text-[10px] font-mono text-muted-foreground/70 truncate`,children:e.nameHint}),(0,X.jsx)(`span`,{className:`text-[10px] text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity`,children:`Open in Studio →`})]})]},e.id))})}),(0,X.jsxs)(`div`,{className:`flex-shrink-0 px-6 py-3 border-t border-border flex items-center justify-between`,children:[(0,X.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Tip: click a tag pill on any card to filter by that tag.`}),(0,X.jsx)(f,{variant:`ghost`,size:`sm`,onClick:Z,children:`Cancel`})]})]})}),ce=()=>(0,X.jsx)(a,{open:z,onOpenChange:e=>{!e&&!G&&(B(!1),q(null))},children:(0,X.jsxs)(d,{className:`max-w-lg`,children:[(0,X.jsx)(j,{children:(0,X.jsxs)(u,{className:`flex items-center gap-2`,children:[(0,X.jsx)(W,{className:`w-4 h-4 text-accent-primary`}),` Generate a custom agent`]})}),(0,X.jsxs)(`div`,{className:`space-y-3 py-2`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Agent id`}),(0,X.jsx)(C,{value:V,onChange:e=>H(e.target.value),placeholder:`custom-my-agent`,className:`text-sm font-mono`,disabled:G}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground mt-1`,children:[`Must start with `,(0,X.jsx)(`code`,{children:`custom-`}),`.`]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-xs font-medium text-muted-foreground mb-1`,children:`Describe what this agent should do`}),(0,X.jsx)(`textarea`,{value:U,onChange:e=>ee(e.target.value),placeholder:`e.g. Review Terraform/IaC changes and flag security misconfigurations, excessive IAM permissions, and public S3 buckets before merging. Conservative and terse.`,className:`w-full text-sm p-2 rounded border border-border bg-background min-h-[120px] resize-y`,disabled:G})]}),te&&(0,X.jsx)(`div`,{className:`px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:te}),(0,X.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Claude will draft a full `,(0,X.jsx)(`code`,{children:`.md`}),` body. You'll review it in the Studio and can edit before saving. This spawns a one-shot claude invocation and can take up to 90 seconds.`]})]}),(0,X.jsxs)(t,{children:[(0,X.jsx)(f,{variant:`ghost`,size:`sm`,onClick:()=>B(!1),disabled:G,children:`Cancel`}),(0,X.jsx)(f,{size:`sm`,onClick:le,disabled:G||!V.trim()||!U.trim(),children:G?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(R,{className:`w-3.5 h-3.5 mr-1.5 animate-spin`}),` Generating…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(W,{className:`w-3.5 h-3.5 mr-1.5`}),` Generate`]})})]})]})}),le=async()=>{K(!0),q(null);try{let e=await fetch(`${O()}/profiles/catalog/generate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:V.trim(),description:U.trim()})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Generate failed: ${e.status}`)}let t=await e.json();B(!1),T({kind:`create`,initialBody:t.draft,initialName:V.trim()})}catch(e){q(e.message)}finally{K(!1)}},ue=async e=>{try{let t=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(e)}`);if(!t.ok)throw Error(`Load failed: ${t.status}`);T({kind:`duplicate`,from:e,initialBody:(await t.json()).body})}catch(e){S(e.message)}};if(e.length===0)return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,X.jsxs)(`div`,{className:`text-center max-w-sm`,children:[(0,X.jsx)(`div`,{className:`text-sm font-medium text-foreground`,children:`No agents installed`}),(0,X.jsxs)(`div`,{className:`text-xs text-muted-foreground mt-1 mb-4`,children:[`Run `,(0,X.jsx)(`code`,{className:`text-foreground`,children:`npx specrails-core@latest update`}),` in this project to install the upstream agents, or create a custom agent now.`]}),(0,X.jsxs)(`div`,{className:`flex gap-2 justify-center flex-wrap`,children:[(0,X.jsxs)(f,{size:`sm`,onClick:()=>B(!0),children:[(0,X.jsx)(W,{className:`w-3.5 h-3.5 mr-1.5`}),` Generate with Claude`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>A(!0),children:[(0,X.jsx)(b,{className:`w-3.5 h-3.5 mr-1.5`}),` Template`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>T({kind:`create`}),children:[(0,X.jsx)(v,{className:`w-3.5 h-3.5 mr-1.5`}),` Blank`]})]})]})}),se(),ce()]});let de=e.filter(e=>e.kind===`upstream`),fe=e.filter(e=>e.kind===`custom`),Q=e.find(e=>e.id===i);return(0,X.jsxs)(X.Fragment,{children:[se(),ce(),(0,X.jsxs)(`div`,{className:`flex h-full`,children:[(0,X.jsxs)(`aside`,{className:`w-72 flex-shrink-0 border-r border-border flex flex-col`,children:[(0,X.jsxs)(`div`,{className:`px-3 py-2 border-b border-border`,children:[(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground uppercase tracking-wide mb-1.5`,children:`Catalog`}),(0,X.jsx)(`div`,{className:`text-[10px] text-muted-foreground/70 mb-2`,children:`Create a custom agent:`}),(0,X.jsxs)(`div`,{className:`flex gap-1`,children:[(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>A(!0),title:`Start from a template`,children:[(0,X.jsx)(b,{className:`w-3 h-3 mr-1`}),` Template`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>B(!0),title:`Generate with Claude`,children:[(0,X.jsx)(W,{className:`w-3 h-3 mr-1`}),` Generate`]}),(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,className:`flex-1 h-7 text-[11px] px-2`,onClick:()=>T({kind:`create`}),title:`Start from a blank template`,children:[(0,X.jsx)(v,{className:`w-3 h-3 mr-1`}),` Blank`]})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 overflow-auto p-2`,children:[(0,X.jsx)(je,{title:`Upstream (${de.length})`,description:`Shipped by specrails-core; read-only.`,children:de.map(e=>(0,X.jsx)(Me,{agent:e,selected:e.id===i,onSelect:()=>c(e.id)},e.id))}),(0,X.jsx)(je,{title:`Custom (${fe.length})`,description:`Your project's custom-*.md files. Use Template / Generate / Blank above to create one.`,children:fe.length===0?(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground px-2 py-2 italic`,children:`No custom agents yet.`}):fe.map(e=>(0,X.jsx)(Me,{agent:e,selected:e.id===i,onSelect:()=>c(e.id)},e.id))})]})]}),(0,X.jsxs)(`main`,{className:`flex-1 min-w-0 overflow-auto`,children:[x&&(0,X.jsx)(`div`,{className:`m-4 px-3 py-2 text-xs rounded border border-red-500/30 bg-red-500/10 text-red-400`,children:x}),Q&&(0,X.jsxs)(`div`,{className:`p-6 min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-start justify-between gap-4 mb-1`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,X.jsx)(`h2`,{className:`text-base font-mono font-semibold`,children:Q.id}),(0,X.jsx)(Ne,{kind:Q.kind}),Q.model&&(0,X.jsxs)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[`default model: `,Q.model]})]}),Q.description&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 break-words`,children:Q.description})]}),(0,X.jsxs)(`div`,{className:`flex gap-2 flex-shrink-0`,children:[(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>void ue(Q.id),children:[(0,X.jsx)(p,{className:`w-3.5 h-3.5 mr-1`}),` Duplicate`]}),Q.kind===`custom`&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(f,{size:`sm`,variant:`ghost`,onClick:()=>T({kind:`edit`,agentId:Q.id}),children:[(0,X.jsx)(o,{className:`w-3.5 h-3.5 mr-1`}),` Edit`]}),(0,X.jsxs)(f,{size:`sm`,onClick:async()=>{try{let e=await fetch(`${O()}/profiles/catalog/${encodeURIComponent(Q.id)}`);if(!e.ok)throw Error(`Load failed: ${e.status}`);let t=await e.json();D({kind:`open`,agentId:Q.id,baseBody:t.body})}catch(e){S(e.message)}},title:`Iteratively refine this agent with AI`,children:[(0,X.jsx)(ie,{className:`w-3.5 h-3.5 mr-1`}),` AI Edit`]})]})]})]}),(0,X.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/30 mt-4 min-w-0 overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1.5 border-b border-border`,children:[(0,X.jsxs)(`span`,{className:`text-[11px] font-mono text-muted-foreground truncate`,children:[`.claude/agents/`,Q.id,`.md`]}),(0,X.jsx)(`span`,{className:`text-[10px] text-muted-foreground flex-shrink-0 ml-2`,children:Q.kind===`upstream`?`read-only`:`editable — use Edit above`})]}),(0,X.jsx)(`pre`,{className:`p-4 text-xs font-mono overflow-auto max-h-[60vh] whitespace-pre-wrap break-all`,children:_?`Loading…`:l??``})]})]})]})]})]})}function Ae({label:e,count:t,active:n,onClick:r}){return(0,X.jsxs)(`button`,{type:`button`,onClick:r,className:`flex-shrink-0 inline-flex items-center gap-1 h-7 px-2.5 text-[11px] rounded-full border transition-colors whitespace-nowrap `+(n?`bg-accent-primary/20 border-accent-primary/50 text-accent-primary`:`bg-transparent border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[e,(0,X.jsx)(`span`,{className:`text-[9px] px-1 rounded `+(n?`bg-accent-primary/30`:`bg-muted/60`),children:t})]})}function je({title:e,description:t,children:n}){return(0,X.jsxs)(`div`,{className:`mb-4`,children:[(0,X.jsxs)(`div`,{className:`px-2 pb-1`,children:[(0,X.jsx)(`div`,{className:`text-[11px] font-medium text-muted-foreground uppercase tracking-wide`,children:e}),t&&(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground/70 mt-0.5`,children:t})]}),(0,X.jsx)(`div`,{className:`space-y-0.5`,children:n})]})}function Me({agent:e,selected:t,onSelect:n}){return(0,X.jsxs)(`button`,{type:`button`,onClick:n,className:`w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left rounded transition-colors `+(t?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,X.jsx)(`span`,{className:`text-sm font-mono truncate`,children:e.id}),(0,X.jsx)(Ne,{kind:e.kind})]})}function Ne({kind:e}){return(0,X.jsx)(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded flex-shrink-0 `+(e===`custom`?`bg-purple-500/15 text-purple-400`:`bg-muted text-muted-foreground`),children:e})}var Pe=[{label:`7d`,days:7},{label:`30d`,days:30},{label:`90d`,days:90}];function Fe(){let[e,t]=(0,Y.useState)(null),[n,r]=(0,Y.useState)(30),[i,a]=(0,Y.useState)(!0);if((0,Y.useEffect)(()=>{let e=!1;return a(!0),fetch(`${O()}/profiles/analytics?windowDays=${n}`).then(e=>e.ok?e.json():null).then(n=>{!e&&n&&t(n)}).catch(()=>{}).finally(()=>{e||a(!1)}),()=>{e=!0}},[n]),i&&!e)return null;if(!e||e.rows.length===0)return(0,X.jsxs)(`div`,{className:`mx-6 my-4 rounded-md border border-border bg-muted/20`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-foreground`,children:`Profile usage`}),(0,X.jsx)(`div`,{className:`text-[11px] text-muted-foreground`,children:`Jobs launched per profile in the selected window.`})]}),(0,X.jsx)(`div`,{className:`flex gap-0.5`,children:Pe.map(e=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>r(e.days),className:`text-[10px] px-2 py-1 rounded transition-colors `+(n===e.days?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:e.label},e.days))})]}),(0,X.jsx)(`div`,{className:`px-4 py-8 text-xs text-muted-foreground`,children:`No profile-scoped jobs yet.`})]});let o=Math.max(...e.rows.map(e=>e.jobs),1);return(0,X.jsxs)(`div`,{className:`mx-6 my-4 rounded-md border border-border bg-muted/20`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`div`,{className:`text-xs font-medium text-foreground`,children:`Profile usage`}),(0,X.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[`Jobs launched per profile in the last `,e.windowDays,` days.`]})]}),(0,X.jsx)(`div`,{className:`flex gap-0.5`,children:Pe.map(e=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>r(e.days),className:`text-[10px] px-2 py-1 rounded transition-colors `+(n===e.days?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:e.label},e.days))})]}),(0,X.jsx)(`div`,{className:`p-4 space-y-2`,children:e.rows.map(e=>(0,X.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,X.jsx)(`div`,{className:`w-32 text-xs font-mono truncate`,children:e.profileName}),(0,X.jsx)(`div`,{className:`flex-1 h-4 bg-muted/50 rounded overflow-hidden`,children:(0,X.jsx)(`div`,{className:`h-full bg-accent-primary/70`,style:{width:`${Math.max(6,Math.round(e.jobs/o*100))}%`}})}),(0,X.jsxs)(`div`,{className:`flex gap-4 text-[11px] text-muted-foreground min-w-0 flex-shrink-0`,children:[(0,X.jsxs)(`span`,{title:`jobs`,children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:e.jobs}),` jobs`]}),(0,X.jsxs)(`span`,{title:`success rate`,children:[(0,X.jsxs)(`span`,{className:`text-foreground font-mono`,children:[Math.round(e.successRate*100),`%`]}),` `,`ok`]}),e.avgDurationMs!=null&&(0,X.jsx)(`span`,{title:`avg duration`,children:(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:Ie(e.avgDurationMs)})}),e.avgTokens!=null&&(0,X.jsxs)(`span`,{title:`avg tokens`,children:[(0,X.jsx)(`span`,{className:`text-foreground font-mono`,children:Le(e.avgTokens)}),` `,`tok`]})]})]},e.profileName))})]})}function Ie(e){let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m`:`${Math.floor(n/60)}h${n%60}m`}function Le(e){return e<1e3?Math.round(e).toString():e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}var Re=`specrails-hub:agents-tab`;function ze(){try{let e=localStorage.getItem(Re);if(e===`profiles`||e===`usage`||e===`catalog`)return e}catch{}return`profiles`}function Be(){let[e,t]=(0,Y.useState)(()=>ze()),n=e=>{t(e);try{localStorage.setItem(Re,e)}catch{}},[r,i]=(0,Y.useState)(null);return(0,Y.useEffect)(()=>{let e=!1;return fetch(`${O()}/profiles/core-version`).then(e=>e.ok?e.json():null).then(t=>{!e&&t&&i(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,X.jsxs)(`div`,{className:`flex flex-col h-full bg-background`,children:[r!==null&&!r.profileAware&&(0,X.jsxs)(`div`,{className:`flex-shrink-0 flex items-start gap-3 px-6 py-3 border-b border-yellow-500/30 bg-yellow-500/10`,children:[(0,X.jsx)(l,{className:`w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0`}),(0,X.jsxs)(`div`,{className:`text-xs`,children:[(0,X.jsxs)(`div`,{className:`font-medium text-yellow-500`,children:[`Profile-aware pipeline requires specrails-core `,r.required,`+`]}),(0,X.jsxs)(`div`,{className:`text-yellow-500/80 mt-0.5`,children:[`This project has`,` `,(0,X.jsx)(`code`,{className:`px-1 rounded bg-yellow-500/20`,children:r.version??`unknown`}),`. Run`,` `,(0,X.jsx)(`code`,{className:`px-1 rounded bg-yellow-500/20`,children:`npx specrails-core@latest update`}),` `,`inside the project to unlock profile mode. Profiles you create here will still save; they just won't affect the pipeline until core is updated.`]})]})]}),(0,X.jsxs)(`div`,{className:`flex-shrink-0 border-b border-border`,children:[(0,X.jsxs)(`div`,{className:`px-6 pt-4`,children:[(0,X.jsx)(`h1`,{className:`text-lg font-semibold`,children:`Agents`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:`Manage agent profiles and the catalog (upstream + custom) for this project.`})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 px-4 pt-3`,children:[(0,X.jsx)(He,{active:e===`profiles`,onClick:()=>n(`profiles`),children:`Profiles`}),(0,X.jsx)(He,{active:e===`usage`,onClick:()=>n(`usage`),children:`Usage`}),(0,X.jsx)(He,{active:e===`catalog`,onClick:()=>n(`catalog`),children:`Catalog`})]})]}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0 overflow-auto`,children:[e===`profiles`&&(0,X.jsx)(me,{}),e===`usage`&&(0,X.jsx)(Ve,{}),e===`catalog`&&(0,X.jsx)(ke,{})]})]})}function Ve(){return(0,X.jsx)(`div`,{className:`min-h-full`,children:(0,X.jsx)(Fe,{})})}function He({active:e,children:t,onClick:n}){return(0,X.jsx)(`button`,{type:`button`,onClick:n,className:`h-8 px-3 text-xs font-medium rounded-t-md border-b-2 transition-colors `+(e?`text-foreground border-foreground`:`text-muted-foreground border-transparent hover:text-foreground hover:border-border`),children:t})}export{Be as default};