@runfusion/fusion 0.29.0 → 0.30.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.
- package/dist/bin.js +10858 -3408
- package/dist/client/assets/AgentDetailView-CY-O6VkV.css +1 -0
- package/dist/client/assets/AgentDetailView-Cu4TgvBn.js +18 -0
- package/dist/client/assets/AgentPermissionPolicyEditor-Ceg2Dszn.js +6 -0
- package/dist/client/assets/AgentPermissionPolicyEditor-CthjqUL_.css +1 -0
- package/dist/client/assets/AgentsView-CIH4Acck.js +34 -0
- package/dist/client/assets/ChatView-DqJoFquZ.js +1 -0
- package/dist/client/assets/DevServerView-Bd8JZ-3C.js +1 -0
- package/dist/client/assets/{DirectoryPicker-Bb3TIWEa.js → DirectoryPicker-BOGqZNiq.js} +1 -1
- package/dist/client/assets/DocumentsView-B-ELcw4o.js +1 -0
- package/dist/client/assets/EvalsView-Ccl9QBYN.js +1 -0
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-AsmRLMxm.js → ExperimentalAgentOnboardingModal-BM7EnSvJ.js} +1 -1
- package/dist/client/assets/{InsightsView-j7J_vUME.js → InsightsView-DLF49bzu.js} +3 -3
- package/dist/client/assets/{MemoryView-QWiqVDuQ.js → MemoryView-CE1D9euM.js} +2 -2
- package/dist/client/assets/{NodesView-Cr4CXr7b.js → NodesView-Zxusnhxu.js} +2 -2
- package/dist/client/assets/{PiExtensionsManager-CPZ-82Wl.js → PiExtensionsManager-BlMmxtLZ.js} +2 -2
- package/dist/client/assets/PluginManager-D4eZ0zA4.js +1 -0
- package/dist/client/assets/ReliabilityView-KmH60I_5.js +1 -0
- package/dist/client/assets/ReliabilityView-rxA_HgEG.css +1 -0
- package/dist/client/assets/ResearchView-C14Zh7c9.js +1 -0
- package/dist/client/assets/ResearchView-DTh8FLUm.css +1 -0
- package/dist/client/assets/{SettingsModal-8l8vfXns.js → SettingsModal-DRnZ6eBW.js} +1 -1
- package/dist/client/assets/SettingsModal-c1QwWno0.js +31 -0
- package/dist/client/assets/{SettingsModal-ChnabMhF.css → SettingsModal-sp7SNwS9.css} +1 -1
- package/dist/client/assets/SetupWizardModal-BmmRM3g-.js +1 -0
- package/dist/client/assets/SkillsView-DWVtT2-8.js +1 -0
- package/dist/client/assets/StashRecoveryView-CKkaWzzc.js +1 -0
- package/dist/client/assets/{TodoView-rSn0aPsb.js → TodoView-hbD0NOCY.js} +2 -2
- package/dist/client/assets/dashboard-view-VNPB3ca0.js +21 -0
- package/dist/client/assets/{folder-open-Bq_TweLR.js → folder-open-BTN2_Wuv.js} +1 -1
- package/dist/client/assets/index-CZFBq256.css +1 -0
- package/dist/client/assets/index-DzSLVOnp.js +695 -0
- package/dist/client/assets/{upload-D1y22Www.js → upload-euJEs_N2.js} +1 -1
- package/dist/client/assets/{users-UQdBpweI.js → users-B7miEHCZ.js} +1 -1
- package/dist/client/assets/vendor-codemirror-jBKmHyH0.js +27 -0
- package/dist/client/index.html +3 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +7898 -1725
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-steps-verdict-contract.test.ts +42 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/SKILL.md +2 -2
- package/skill/fusion/references/extension-tools.md +23 -0
- package/skill/fusion/references/fusion-capabilities.md +2 -0
- package/dist/client/assets/AgentDetailView-CWyOv8HJ.js +0 -18
- package/dist/client/assets/AgentDetailView-ChIKbcEi.css +0 -1
- package/dist/client/assets/AgentsView-DljrBNE1.js +0 -34
- package/dist/client/assets/ChatView-BklDUi5_.js +0 -1
- package/dist/client/assets/DevServerView-BqcI1wXr.js +0 -1
- package/dist/client/assets/DocumentsView-BhrdTTh3.js +0 -1
- package/dist/client/assets/EvalsView-DrFp2cLg.js +0 -1
- package/dist/client/assets/PluginManager-DShC4UiM.js +0 -1
- package/dist/client/assets/ResearchView-B5wYC1KE.js +0 -1
- package/dist/client/assets/ResearchView-C7uXon3o.css +0 -1
- package/dist/client/assets/SettingsModal-CYetgxZj.js +0 -31
- package/dist/client/assets/SetupWizardModal-_IK6hTA7.js +0 -1
- package/dist/client/assets/SkillsView-Dilmj1nh.js +0 -1
- package/dist/client/assets/StashRecoveryView-BtL9aAn3.js +0 -1
- package/dist/client/assets/dashboard-view-C_G8JVU7.js +0 -21
- package/dist/client/assets/index-DjfAYMGG.css +0 -1
- package/dist/client/assets/index-tbwUVj8p.js +0 -696
- package/dist/client/assets/star-Dn0V0Cnq.js +0 -6
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fusion/pi-claude-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.0",
|
|
4
4
|
"description": "Fusion vendored fork: pi coding-agent extension that routes LLM calls through the Claude Code CLI. Forked from rchern/pi-claude-cli (MIT). See UPSTREAM.md.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"private": true,
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { CLI_PRINTING_PRESS_WORKFLOW_STEPS } from "../workflow-steps.js";
|
|
3
|
+
|
|
4
|
+
describe("cli-printing-press workflow step verdict contract", () => {
|
|
5
|
+
it("exports a non-empty workflow step contribution list", () => {
|
|
6
|
+
expect(CLI_PRINTING_PRESS_WORKFLOW_STEPS.length).toBeGreaterThan(0);
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it("requires script-mode steps to declare a non-empty scriptName", () => {
|
|
10
|
+
const scriptSteps = CLI_PRINTING_PRESS_WORKFLOW_STEPS.filter((step) => step.mode === "script");
|
|
11
|
+
expect(scriptSteps.length).toBeGreaterThan(0);
|
|
12
|
+
|
|
13
|
+
for (const step of scriptSteps) {
|
|
14
|
+
expect(step.scriptName?.trim().length ?? 0).toBeGreaterThan(0);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const promptSteps = CLI_PRINTING_PRESS_WORKFLOW_STEPS.filter((step) => step.mode === "prompt");
|
|
19
|
+
|
|
20
|
+
// Prompt-mode slice may be empty today; invariant activates automatically when prompt entries are added.
|
|
21
|
+
if (promptSteps.length === 0) {
|
|
22
|
+
it("has no prompt-mode steps today; invariant guard is dormant", () => {
|
|
23
|
+
expect(promptSteps).toHaveLength(0);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
it.each(promptSteps.map((step) => [step.stepId, step] as const))(
|
|
28
|
+
"enforces structured verdict prompt contract for %s",
|
|
29
|
+
(_stepId, step) => {
|
|
30
|
+
expect(typeof step.prompt).toBe("string");
|
|
31
|
+
expect(step.prompt?.trim().length ?? 0).toBeGreaterThan(0);
|
|
32
|
+
|
|
33
|
+
const prompt = step.prompt ?? "";
|
|
34
|
+
expect(prompt).toMatch(/\{\s*"verdict"\s*:\s*"APPROVE\|APPROVE_WITH_NOTES\|REVISE"\s*,\s*"notes"\s*:/);
|
|
35
|
+
expect(prompt).not.toContain('"verdict":"PASS"');
|
|
36
|
+
expect(prompt).not.toContain('"verdict":"FAIL"');
|
|
37
|
+
expect(prompt).not.toContain("task_done(");
|
|
38
|
+
expect(prompt).not.toContain("task_log(");
|
|
39
|
+
expect(prompt).toMatch(/out of scope|Diff Scope/i);
|
|
40
|
+
},
|
|
41
|
+
);
|
|
42
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runfusion/fusion",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Fusion CLI: HTTP API server, daemon, dashboard launcher, and task tooling for the Fusion AI coding agent.",
|
|
6
6
|
"homepage": "https://github.com/Runfusion/Fusion#readme",
|
package/skill/fusion/SKILL.md
CHANGED
|
@@ -29,11 +29,11 @@ Mission → Milestone → Slice → Feature → Task
|
|
|
29
29
|
<!-- BEGIN: tool-categories (auto-generated by scripts/sync-fusion-skill-tools.mjs — do not edit by hand) -->
|
|
30
30
|
- **Task tools** — `fn_task_create`, `fn_task_update`, `fn_task_list`, `fn_task_show`, `fn_task_attach`, `fn_task_pause`, `fn_task_unpause`, `fn_task_retry`, `fn_task_duplicate`, `fn_task_refine`, `fn_task_archive`, `fn_task_unarchive`, `fn_task_delete`, `fn_task_plan`
|
|
31
31
|
- **GitHub tools** — `fn_task_import_github`, `fn_task_import_github_issue`, `fn_task_browse_github_issues`
|
|
32
|
-
- **Mission tools** — `fn_mission_create`, `fn_mission_list`, `fn_mission_show`, `fn_mission_delete`, `fn_milestone_add`, `fn_slice_add`, `fn_feature_add`, `fn_slice_activate`, `fn_feature_link_task`
|
|
32
|
+
- **Mission tools** — `fn_mission_create`, `fn_mission_list`, `fn_mission_show`, `fn_mission_delete`, `fn_milestone_add`, `fn_slice_add`, `fn_feature_add`, `fn_slice_activate`, `fn_feature_link_task`, `fn_feature_update`
|
|
33
33
|
- **Agent tools** — `fn_agent_stop`, `fn_agent_start`, `fn_agent_create`, `fn_agent_delete`, `fn_list_agents`, `fn_delegate_task`, `fn_agent_show`, `fn_agent_org_chart`
|
|
34
34
|
- **Skills tools** — `fn_skills_search`, `fn_skills_install`
|
|
35
35
|
- **Insight tools** — `fn_insight_list`, `fn_insight_show`, `fn_insight_run_list`, `fn_insight_run_show`
|
|
36
|
-
- **Other tools** — `fn_web_fetch`, `fn_research_run`, `fn_research_list`, `fn_research_get`, `fn_research_cancel`, `fn_research_retry`
|
|
36
|
+
- **Other tools** — `fn_web_fetch`, `fn_research_run`, `fn_research_list`, `fn_research_get`, `fn_research_cancel`, `fn_research_retry`, `fn_experiment_finalize`
|
|
37
37
|
<!-- END: tool-categories -->
|
|
38
38
|
- **Dashboard** — Use `/fn` command to start/stop the dashboard
|
|
39
39
|
|
|
@@ -248,6 +248,17 @@ Link a feature to a fn task for implementation. Updates the feature status to 't
|
|
|
248
248
|
| `featureId` | string | ✓ | Feature ID to link (e.g., F-001) |
|
|
249
249
|
| `taskId` | string | ✓ | Task ID to link to (e.g., FN-001) |
|
|
250
250
|
|
|
251
|
+
### fn_feature_update
|
|
252
|
+
|
|
253
|
+
Update an existing feature's title, description, or acceptance criteria. Partial patches leave untouched fields intact.
|
|
254
|
+
|
|
255
|
+
| Parameter | Type | Required | Description |
|
|
256
|
+
|-----------|------|----------|-------------|
|
|
257
|
+
| `id` | string | ✓ | Feature ID to update (e.g., F-001) |
|
|
258
|
+
| `title` | string | — | Updated feature title |
|
|
259
|
+
| `description` | string | — | Updated feature description |
|
|
260
|
+
| `acceptanceCriteria` | string | — | Updated acceptance criteria for completing the feature |
|
|
261
|
+
|
|
251
262
|
## Agent Tools
|
|
252
263
|
|
|
253
264
|
### fn_agent_stop
|
|
@@ -448,6 +459,18 @@ Cited-research pipeline: retry a failed run when lifecycle marks it retryable (n
|
|
|
448
459
|
|-----------|------|----------|-------------|
|
|
449
460
|
| `id` | string | ✓ | Research run ID |
|
|
450
461
|
|
|
462
|
+
### fn_experiment_finalize
|
|
463
|
+
|
|
464
|
+
Group kept experiment runs into reviewable branches and finalize the session. Use dryRun=true to preview the plan without touching git.
|
|
465
|
+
|
|
466
|
+
| Parameter | Type | Required | Description |
|
|
467
|
+
|-----------|------|----------|-------------|
|
|
468
|
+
| `sessionId` | string | ✓ | Experiment session ID |
|
|
469
|
+
| `integrationBranch` | string | — | Integration branch to compute merge-base against (default: main) |
|
|
470
|
+
| `dryRun` | boolean | — | Preview plan only; do not create branches |
|
|
471
|
+
| `planOverride` | unknown | — | Optional plan override payload |
|
|
472
|
+
| `summary` | string | — | Optional finalize summary |
|
|
473
|
+
|
|
451
474
|
<!-- END: extension-tools -->
|
|
452
475
|
## Dashboard Command
|
|
453
476
|
|
|
@@ -35,6 +35,7 @@ All skill/extension tool invocations in this catalog use the public `fn_*` names
|
|
|
35
35
|
| `fn_research_get` | Cited-research pipeline: get one run with structured findings and citations (not experiment-loop state). |
|
|
36
36
|
| `fn_research_cancel` | Cited-research pipeline: cancel an in-flight run; terminal runs return INVALID_TRANSITION (does not control experiment loops). |
|
|
37
37
|
| `fn_research_retry` | Cited-research pipeline: retry a failed run when lifecycle marks it retryable (not an autonomous experiment loop retry). |
|
|
38
|
+
| `fn_experiment_finalize` | Group kept experiment runs into reviewable branches and finalize the session. Use dryRun=true to preview the plan without touching git. |
|
|
38
39
|
| `fn_insight_list` | List persisted project insights with optional category/status filters. |
|
|
39
40
|
| `fn_insight_show` | Show a single persisted insight by ID. |
|
|
40
41
|
| `fn_insight_run_list` | List recent insight-generation runs with optional status/trigger filters. |
|
|
@@ -48,6 +49,7 @@ All skill/extension tool invocations in this catalog use the public `fn_*` names
|
|
|
48
49
|
| `fn_feature_add` | Add a feature to a slice. Features are deliverables that can be linked to tasks. |
|
|
49
50
|
| `fn_slice_activate` | Activate a pending slice for implementation. Sets status to 'active' and enables task linking for its features. |
|
|
50
51
|
| `fn_feature_link_task` | Link a feature to a fn task for implementation. Updates the feature status to 'triaged' and associates it with the task. |
|
|
52
|
+
| `fn_feature_update` | Update an existing feature's title, description, or acceptance criteria. Partial patches leave untouched fields intact. |
|
|
51
53
|
| `fn_agent_stop` | Stop a running agent — pauses its execution. Transitions the agent from running/active to paused state. |
|
|
52
54
|
| `fn_agent_start` | Start a stopped agent — resumes its execution. Transitions the agent from paused to active state. |
|
|
53
55
|
| `fn_agent_create` | Create a new non-ephemeral agent. |
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Ls,dG as Mt,dH as At,dI as Ft,dJ as Et,L as _,R as Ss,ar as Ws,Z as Tt,as as Cs,W as vs,a as it,b as lt,dK as $t,dL as Pt,dM as Lt,v as rt,cO as Dt,dN as zt,z as q,dO as Ht,dP as ot,dQ as ct,dR as Bt,i as js,D as Gs,s as bs,bu as dt,k as ut,U as ws,A as Ns,V as qs,aS as Ge,dS as Ot,X as mt,F as as,dT as It,cl as ht,dU as ft,dV as Ut,cI as _t,ap as Vt,bt as Jt,at as gt,B as Ds,Y as Wt,a2 as Ks,a3 as Gt,a4 as qt,dW as $s,l as xt,dX as Kt,bF as Yt,r as Zt,aq as bt,a1 as pt,dY as Xt,C as me,dZ as vt,d_ as Ys,bw as Zs,d$ as Qt,e0 as ea,e1 as sa,e2 as ns,a9 as is,ab as ls,ac as rs,a7 as jt,e3 as ta,e4 as aa,h as na,j as Xs,$ as ia,e5 as la,e6 as ra,m as oa,e7 as Ps,e8 as ca,e9 as da,O as ua,ea as ma,eb as ha,ec as Nt,ed as fa,ee as ga,ef as xa,eg as ba,eh as pa}from"./index-tbwUVj8p.js";import{S as yt}from"./star-Dn0V0Cnq.js";import{f as Rs,S as va,E as ja}from"./ExperimentalAgentOnboardingModal-AsmRLMxm.js";import"./vendor-xterm-DzcZoU0P.js";/**
|
|
2
|
-
* @license lucide-react v1.7.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const Na=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],ps=Ls("chart-column",Na);/**
|
|
7
|
-
* @license lucide-react v1.7.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const ya=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]],Sa=Ls("square-activity",ya);/**
|
|
12
|
-
* @license lucide-react v1.7.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const ka=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ca=Ls("trending-down",ka);function Qs(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m`:`${(s/36e5).toFixed(1)}h`}function wa(s){return`${Math.round(s*100)}%`}function et(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const u=Math.abs(l);return u<6e4?"in a moment":u<36e5?`in ${Math.floor(u/6e4)}m`:u<864e5?`in ${Math.floor(u/36e5)}h`:`in ${Math.floor(u/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}function Ra(s){switch(s){case"periodic":return"Periodic";case"post-task":return"Post-Task";case"manual":return"Manual";case"user-requested":return"User Requested";default:return s}}function ss(s){return s instanceof Error&&s.message?s.message:String(s)}function Ma(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Aa(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function st(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,l)=>e.jsx(yt,{size:14,className:l<s?"star-filled":"star-empty",fill:l<s?"currentColor":"none"},l))})}function Fa({agentId:s,projectId:n,addToast:i}){const[l,u]=t.useState([]),[x,M]=t.useState(null),[f,v]=t.useState(null),[A,$]=t.useState([]),[c,C]=t.useState(!0),[y,P]=t.useState(!0),[j,V]=t.useState(!1),[Y,p]=t.useState(!1),[m,O]=t.useState(null),[N,F]=t.useState(0),[R,J]=t.useState(""),[H,E]=t.useState(""),K=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Mt(s,20,n),At(s,void 0,n)]);u(r),M(o)}catch(r){i(`Failed to load reflections: ${ss(r)}`,"error")}finally{C(!1)}},[s,n,i]),S=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Ft(s,n),Et(s,{limit:50},n)]);v(r),$(o)}catch(r){i(`Failed to load ratings: ${ss(r)}`,"error")}finally{P(!1)}},[s,n,i]);t.useEffect(()=>{K(),S()},[K,S]);const ee=async()=>{V(!0);try{if(!await $t(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),C(!0),await K()}catch(r){const o=ss(r),k=o.toLowerCase();k.includes("agent not found")||k.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):k.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${o}`,"error")}finally{V(!1)}},T=async r=>{if(r.preventDefault(),N!==0){p(!0);try{await Pt(s,{score:N,category:R||void 0,comment:H||void 0,raterType:"user"},n),F(0),J(""),E(""),i("Rating added","success"),await S()}catch(o){i(`Failed to add rating: ${ss(o)}`,"error")}finally{p(!1)}}},W=async r=>{try{await Lt(s,r,n),i("Rating deleted","success"),await S()}catch(o){i(`Failed to delete rating: ${ss(o)}`,"error")}},h=r=>{O(o=>o===r?null:r)};if(c&&y)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const b=x&&x.totalTasksCompleted===0&&x.totalTasksFailed===0&&x.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(ps,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:ee,disabled:j,title:"Generate a manual reflection",children:j?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ss,{size:14}),"Reflect Now"]})})]}),x&&!b&&e.jsxs("div",{className:"reflections-stats-grid",children:[e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ws,{size:16,style:{color:"var(--color-success)"}}),x.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:"Tasks Completed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ca,{size:16,style:{color:"var(--color-error)"}}),x.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:"Tasks Failed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Tt,{size:16,style:{color:"var(--in-progress)"}}),Qs(x.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:"Avg Duration"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(ps,{size:16,style:{color:x.successRate>=.8?"var(--color-success)":x.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),wa(x.successRate)]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Cs,{size:16,style:{color:"var(--color-info)"}}),x.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),b&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(ps,{size:24,opacity:.3}),e.jsx("p",{children:"No performance data yet"})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:"User Ratings"}),y?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading ratings..."})]}):e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:f.averageScore.toFixed(1)}),st(Math.round(f.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[f.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${Aa(f.trend)}`,children:Ma(f.trend)})]})]}),f&&Object.keys(f.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(f.categoryAverages).map(([r,o])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:r}),e.jsx("span",{className:"category-score",children:o.toFixed(1)})]},r))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:T,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>F(r),title:`${r} star${r>1?"s":""}`,children:e.jsx(yt,{size:24,fill:r<=N?"currentColor":"none",className:r<=N?"star-filled":"star-empty"})},r))}),e.jsxs("select",{value:R,onChange:r=>J(r.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:"Select category..."}),e.jsx("option",{value:"quality",children:"Quality"}),e.jsx("option",{value:"speed",children:"Speed"}),e.jsx("option",{value:"communication",children:"Communication"}),e.jsx("option",{value:"reliability",children:"Reliability"}),e.jsx("option",{value:"other",children:"Other"})]}),e.jsx("textarea",{value:H,onChange:r=>E(r.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:N===0||Y,children:Y?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),A.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):A.map(r=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[st(r.score),r.category&&e.jsx("span",{className:"rating-category-badge",children:r.category}),e.jsx("span",{className:"rating-time",children:et(r.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void W(r.id),title:"Delete rating",children:e.jsx(vs,{size:14})})]}),r.comment&&e.jsx("p",{className:"rating-comment",children:r.comment})]},r.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),c?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):l.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(Cs,{size:32,opacity:.3}),e.jsx("p",{children:"No reflections yet"}),e.jsx("p",{className:"text-secondary",children:"Trigger a reflection to get started"})]}):e.jsx("div",{className:"reflection-cards",children:l.map(r=>{const o=m===r.id;return e.jsxs("div",{className:`reflection-card ${o?"reflection-card--expanded":""}`,onClick:()=>h(r.id),role:"button",tabIndex:0,onKeyDown:k=>k.key==="Enter"&&h(r.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${r.trigger}`,children:Ra(r.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:et(r.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:o?e.jsx(it,{size:16}):e.jsx(lt,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:r.summary}),o&&e.jsxs("div",{className:"reflection-details",children:[r.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Cs,{size:14})," Insights"]}),e.jsx("ul",{children:r.insights.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(Ws,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:r.suggestedImprovements.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[r.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Tasks:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksCompleted})]}),r.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Failed:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksFailed})]}),r.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Avg Duration:"}),e.jsx("span",{className:"metric-value",children:Qs(r.metrics.avgDurationMs)})]}),r.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Errors:"}),e.jsx("span",{className:"metric-value",children:r.metrics.errorCount})]})]})]})]})]},r.id)})})]})]})}function ae(...s){return s.filter(Boolean).join(" ")}function qe(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const u=Math.abs(l);return u<6e4?"in a moment":u<36e5?`in ${Math.floor(u/6e4)}m`:u<864e5?`in ${Math.floor(u/36e5)}h`:`in ${Math.floor(u/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}const Ea=[{id:"dashboard",label:"Dashboard",icon:Sa},{id:"logs",label:"Logs",icon:as},{id:"mail",label:"Mail",icon:It},{id:"runs",label:"Runs",icon:Ns},{id:"tasks",label:"Tasks",icon:ht},{id:"employees",label:"Employees",icon:ft},{id:"soul",label:"Soul",icon:Ut},{id:"instructions",label:"Instructions",icon:_t},{id:"memory",label:"Agent Memory",icon:as},{id:"reflections",label:"Evaluation",icon:ps},{id:"config",label:"Settings",icon:Vt}],zs={idle:{bg:"var(--state-idle-bg)",text:"var(--state-idle-text)",border:"var(--state-idle-border)"},active:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},running:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},paused:{bg:"var(--state-paused-bg)",text:"var(--state-paused-text)",border:"var(--state-paused-border)"},error:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},ys={completed:{icon:me,color:"var(--color-success)"},failed:{icon:Xt,color:"var(--color-error)"},active:{icon:_,color:"var(--in-progress)"},terminated:{icon:Ge,color:"var(--text-muted)"}},tt={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Ta={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.",daily:"Raw daily observations and open loops recorded by this agent.",dreams:"Synthesized patterns and emerging themes distilled from this agent's daily memory."},$a=pt(Ps),Pa=700;function La(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function an({agentId:s,projectId:n,onClose:i,addToast:l,onChildClick:u,inline:x=!1,showInlineBackButton:M=!1,initialTab:f,initialRunId:v,preferActiveRun:A=!1,onMutationSuccess:$}){const[c,C]=t.useState(null),{confirm:y}=rt(),[P,j]=t.useState([]),[V,Y]=t.useState(!0),[p,m]=t.useState(f??"dashboard"),[O,N]=t.useState(!1),[F,R]=t.useState(!1),[J,H]=t.useState(!1),[E,K]=t.useState(!1),[S,ee]=t.useState(!1),[T,W]=t.useState(!1),[h,b]=t.useState(0),[r,o]=t.useState(0),[k,ne]=t.useState(0),[se,ve]=t.useState(null),[X,be]=t.useState(null),[Z,I]=t.useState(!1),[re,He]=t.useState(null),Ae=t.useRef(null),os=t.useRef(null),Fe=t.useRef(!1);Dt(Ae,!x,"fusion:agent-detail-modal-size");const cs=t.useRef(i),ke=t.useRef(l),Be=t.useRef(null),Ke=t.useRef(!1),Te=t.useRef(null),le=t.useRef(0),Ye=t.useRef(s),$e=t.useRef(n);cs.current=i,ke.current=l,Be.current=c;const ge=t.useCallback(async()=>{Be.current===null&&Y(!0);try{const D=await zt(s,n);C(D)}catch(D){ke.current(`Failed to load agent: ${q(D)}`,"error"),cs.current()}finally{Y(!1)}},[s,n]),Pe=t.useCallback(async()=>{const g=le.current,D=s,U=n,B=()=>le.current!==g||s!==D||n!==U;try{if(c?.taskId){ve(null),Te.current=null;const we=await Ht(c.taskId,U,{limit:100});if(B())return;j(we.entries);return}const ie=await ot(D,1,U);if(B())return;const te=ie[0]??null;if(ve(te),!te){Te.current=null,j([]);return}if(Te.current===te.id)return;const je=await ct(D,te.id,U);if(B())return;j(je),Te.current=te.id}catch(ie){if(B())return;console.error("Failed to load agent logs:",ie)}},[c?.taskId,s,n]),Oe=t.useCallback(async()=>{I(!0),He(null);try{const g=await Bt(s,n);be(g)}catch(g){He(q(g)),be(null)}finally{I(!1)}},[s,n]),ds=t.useCallback(g=>{Ke.current=g},[]),Je=t.useCallback(async(g=!1)=>{await $?.({agentId:s,deleted:g})},[s,$]),Le=t.useCallback(async()=>{await ge(),await Je(!1)},[ge,Je]);t.useEffect(()=>{ge()},[ge]),t.useEffect(()=>{const g=setInterval(()=>{ge()},3e4);return()=>{clearInterval(g)}},[ge]),t.useEffect(()=>{c&&p==="logs"&&Pe()},[c,p,Pe]),t.useEffect(()=>{p!=="logs"&&(Te.current=null)},[p]),t.useEffect(()=>{c&&p==="mail"&&Oe()},[c,p,Oe]),t.useEffect(()=>{if(!E)return;const g=U=>{os.current?.contains(U.target)||K(!1)},D=U=>{U.key==="Escape"&&K(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",D),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",D)}},[E]),t.useEffect(()=>{if(!E)return;let g=!1;return W(!0),js(void 0,n).then(D=>{if(g)return;const U=D.filter(B=>!Gs(B));b(U.filter(B=>B.state==="active"||B.state==="running").length),o(U.filter(B=>B.state==="paused").length)}).catch(()=>{g||(b(0),o(0))}).finally(()=>{g||W(!1)}),()=>{g=!0}},[E,n]),t.useEffect(()=>{if(p!=="logs"||c?.taskId||!se||se.status!=="active")return;const g=le.current,D=s,U=se.id,B=n?`?projectId=${encodeURIComponent(n)}`:"",ie=bs(`/api/agents/${encodeURIComponent(D)}/runs/${encodeURIComponent(U)}/logs/stream${B}`,{events:{"agent:log":te=>{if(le.current===g)try{const je=JSON.parse(te.data);j(we=>[...we,je])}catch{}}},onOpen:()=>{le.current===g&&N(!0)},onError:()=>{le.current===g&&N(!1)}});return()=>{ie(),le.current===g&&N(!1)}},[p,c?.taskId,s,n,se]),t.useEffect(()=>{(Ye.current!==s||$e.current!==n)&&(Ye.current=s,$e.current=n,le.current++,j([]),N(!1),ve(null),be(null),He(null),Te.current=null,Ke.current=!1)},[s,n]),t.useEffect(()=>{const g=n?`?projectId=${encodeURIComponent(n)}`:"",D=le.current,U=B=>{if(le.current===D)try{const ie=JSON.parse(B.data);if(!ie||typeof ie!="object"||ie.agentId!==s)return;ge()}catch{}};return bs(`/api/events${g}`,{events:{"agent:updated":B=>{if(le.current===D)try{const ie=JSON.parse(B.data);if(!ie||typeof ie!="object"||ie.id!==s||Ke.current)return;ge()}catch{}},"approval:requested":U,"approval:updated":U,"approval:decided":U}})},[s,n,ge]),t.useEffect(()=>{if(p!=="logs"||!c?.taskId){N(!1);return}const g=le.current,D=c.taskId,U=n?`?projectId=${encodeURIComponent(n)}`:"",B=bs(`/api/tasks/${encodeURIComponent(D)}/logs/stream${U}`,{events:{"agent:log":ie=>{if(le.current===g)try{const te=JSON.parse(ie.data);j(je=>[...je,te])}catch{}}},onOpen:()=>{le.current===g&&N(!0)},onError:()=>{le.current===g&&N(!1)}});return()=>{B(),le.current===g&&N(!1)}},[c?.taskId,p,n]);const ye=async g=>{if(F||!Be.current)return;const D=Be.current.state;if(D!==g){R(!0),C(U=>U&&{...U,state:g});try{await Ks(s,g,n),l(`Agent state updated to ${g}`,"success"),await Le()}catch(U){C(B=>B&&{...B,state:D}),l(`Failed to update state: ${q(U)}`,"error")}finally{R(!1)}}},Ie=async g=>{if(!S){K(!1),ee(!0);try{const U=(await js(void 0,n)).filter(oe=>!Gs(oe)),B=U.filter(oe=>g==="paused"?oe.state==="active"||oe.state==="running":oe.state==="paused"),ie=U.length-B.length;if(B.length===0){l(`No agents eligible to ${g==="paused"?"pause":"resume"}`,"error");return}if(!await y({title:g==="paused"?"Pause All Agents":"Resume All Agents",message:`${g==="paused"?"Pause":"Resume"} ${B.length} agent${B.length===1?"":"s"} in this project?`,danger:g==="paused"}))return;const je=await Promise.allSettled(B.map(oe=>Ks(oe.id,g,n))),we=je.map((oe,L)=>({result:oe,agent:B[L]})).filter(oe=>oe.result.status==="rejected"),Xe=je.length-we.length,us=we.length,Se=`${g==="paused"?"Paused":"Resumed"} ${Xe} agent${Xe===1?"":"s"}; skipped ${ie}`;if(us>0){const oe=we.slice(0,3).map(({agent:L,result:Ee})=>`${L.name||L.id}: ${q(Ee.reason)}`).join("; ");l(`${Se}; failed ${us}${oe?` (${oe})`:""}`,"error")}else l(Se,"success");await Le()}catch(D){l(`Failed to ${g==="paused"?"pause":"resume"} agents: ${q(D)}`,"error")}finally{ee(!1)}}},Ce=async()=>{if(!J){H(!0);try{await Gt(s,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(`Heartbeat run started for ${c?.name??s}`,"success"),ne(g=>g+1)}catch(g){l(`Failed to start heartbeat run: ${q(g)}`,"error")}finally{H(!1)}}},de=async()=>{if(!(!c||!await y({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await qt(s,n),l(`Agent "${c.name}" deleted`,"success"),await Je(!0),i()}catch(D){l(`Failed to delete agent: ${q(D)}`,"error")}},Ue=()=>c?Wt(c):{label:"Unknown",icon:e.jsx(Ds,{size:14}),color:"var(--text-muted)",stateDerived:!1},pe=()=>{c&&(navigator.clipboard.writeText(c.id),l("Agent ID copied to clipboard","success"))};if(V)return x?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":"Agent detail loading",children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(_,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:g=>{g.target===g.currentTarget&&(Fe.current=!0)},onMouseUp:g=>{Fe.current&&g.target===g.currentTarget&&i(),Fe.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:Ae,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(_,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const De=zs[c.state],he=Ue(),_e=x?"agent-detail-inline":"agent-detail-modal",Ve=T||h===0,Ze=T||r===0;return e.jsx("div",{className:x?"agent-detail-inline-shell":"agent-detail-overlay",onClick:g=>!x&&g.target===g.currentTarget&&i(),role:x?"region":"dialog","aria-label":x?"Agent detail":void 0,"aria-modal":x?void 0:"true",children:e.jsxs("div",{className:_e,ref:Ae,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[x&&M?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(dt,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(ut,{agent:c,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:c.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:De.bg,color:De.text,border:`1px solid ${De.border}`},children:c.state}),e.jsxs("span",{className:"badge",style:{color:he.color},title:he.reason??he.label,children:[he.icon,!he.stateDerived&&he.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[c.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ye("active"),disabled:F,children:[e.jsx(ws,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Ce(),"aria-label":`Run now for ${c.name}`,disabled:J||F,children:[e.jsx(Ns,{size:14}),"Run Now"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:de,children:[e.jsx(vs,{size:14}),"Delete"]})]}),c.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(qs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ge,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ce(),"aria-label":`Run now for ${c.name}`,disabled:J||F,children:[e.jsx(Ns,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Run Now"})]})]}),c.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("active"),disabled:F,"aria-label":"Resume",children:[e.jsx(ws,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:de,children:[e.jsx(vs,{size:14}),"Delete"]})]}),c.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(qs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ge,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]}),c.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ye("active"),disabled:F,children:[e.jsx(ws,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ye("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ge,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:os,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>K(g=>!g),"aria-haspopup":"menu","aria-expanded":E,"aria-label":"Bulk agent actions",title:"Bulk agent actions",disabled:F||S,children:e.jsx(Ot,{size:16})}),E&&e.jsxs("div",{className:"agent-detail-bulk-menu-popover",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void Ie("paused"),disabled:Ve||S,children:["Pause All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:T?"Loading eligible agents...":Ve?"No active agents eligible":`Pause ${h} active/running agent${h===1?"":"s"}`})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void Ie("active"),disabled:Ze||S,children:["Resume All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:T?"Loading eligible agents...":Ze?"No paused agents eligible":`Resume ${r} paused agent${r===1?"":"s"}`})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void ge(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Ss,{size:16})}),!x&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(mt,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ea.map(g=>e.jsxs("button",{className:ae("agent-detail-tab",p===g.id&&"active"),onClick:()=>m(g.id),children:[e.jsx(g.icon,{size:16}),g.label]},g.id))}),e.jsxs("div",{className:"agent-detail-content",children:[p==="dashboard"&&e.jsx(Da,{agent:c,health:he,onChildClick:u,projectId:n}),p==="logs"&&e.jsx(za,{logs:P,isStreaming:O,hasTask:!!c.taskId||P.length>0||se!==null,fallbackLabel:!c.taskId&&se?`Latest run · ${se.id.slice(0,8)}`:null}),p==="mail"&&e.jsx(Ba,{agent:c,mailbox:X,isLoading:Z,error:re,projectId:n,addToast:l,onRefresh:()=>void Oe()}),p==="runs"&&e.jsx(Oa,{addToast:l,agentId:c.id,projectId:n,agentState:c.state,agentName:c.name,initialRunId:v,preferActiveRun:A,runNowRefreshToken:k}),p==="tasks"&&e.jsx(Va,{agentId:c.id,projectId:n,addToast:l}),p==="employees"&&e.jsx(Za,{agentId:c.id,projectId:n,onChildClick:u}),p==="soul"&&e.jsx(Wa,{agent:c,projectId:n,addToast:l,onSaved:Le}),p==="instructions"&&e.jsx(qa,{agent:c,projectId:n,addToast:l,onSaved:Le}),p==="memory"&&e.jsx(Ga,{agent:c,projectId:n,addToast:l,onSaved:Le}),p==="reflections"&&e.jsx(Fa,{agentId:c.id,projectId:n,addToast:l}),p==="config"&&e.jsx(Ya,{agent:c,projectId:n,addToast:l,onSaved:Le,onHasChangesChange:ds,onDelete:de,onAgentDraftApplied:g=>{C(D=>D&&{...D,...g})}},c.id)]}),!x&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:pe,title:"Copy Agent ID",children:e.jsx(Jt,{})}),e.jsx("span",{className:"agent-detail-id",onClick:pe,children:c.id}),c.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:"Working on:"}),e.jsxs("a",{href:`/tasks/${c.taskId}`,className:"link",children:[c.taskId,e.jsx(gt,{size:12})]})]})]})]})})}function Da({agent:s,health:n,onChildClick:i,projectId:l}){const u=zs[s.state],[x,M]=t.useState([]),[f,v]=t.useState(!0),[A,$]=t.useState(null),[c,C]=t.useState([]),[y,P]=t.useState(null),[j,V]=t.useState(null),[Y,p]=t.useState(!1),[m,O]=t.useState(null),N=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",F=(()=>{const h=s.runtimeConfig??{};if(N){const b=c.find(r=>r.runtimeId===N);return b?b.name:N}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const b=h.model.indexOf("/");return h.model.slice(b+1)}return null})();t.useEffect(()=>{$s(s.id,l).then($).catch(()=>$(null))},[s.id,l]),t.useEffect(()=>{xt(l).then(C).catch(()=>C([]))},[l]),t.useEffect(()=>{let h=!1;return v(!0),Kt(s.id,l).then(b=>{if(h)return;const r=b.length>0&&b[0]?.id===s.id?[...b].reverse():b;M(r)}).catch(()=>{h||M([])}).finally(()=>{h||v(!1)}),()=>{h=!0}},[s.id,l]);const R=t.useMemo(()=>{const h=s.completedRuns||[],b=new Date;b.setHours(0,0,0,0);const r=h.filter(k=>new Date(k.startedAt)>=b),o=h.filter(k=>k.status==="completed");return{totalRuns:h.length,todayRuns:r.length,successfulRuns:o.length,successRate:h.length>0?Math.round(o.length/h.length*100):0}},[s]),J=(s.completedRuns||[]).slice(0,5),H=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],E=y?Rs(y):null,K=t.useCallback(async h=>{p(!0),O(null),V(null);try{const b=await Yt(h,l);V(b)}catch(b){O(q(b))}finally{p(!1)}},[l]),S=t.useCallback(h=>{if(y===h){P(null),V(null),O(null),p(!1);return}P(h),K(h)},[K,y]),ee=s.state==="active"||s.state==="running",T=Zt(s.runtimeConfig?.heartbeatIntervalMs),W=ee&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+T).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[A?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Budget Exhausted:"})," This agent has exceeded its token budget and may operate with limited functionality."]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(Ds,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:u.bg,color:u.text},children:s.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:n.reason??n.label,children:[n.icon," ",n.label]}),(s.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s.pendingApprovalCount," pending approvals"]}):null,e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:N?"Runtime":"Model"}),e.jsxs("span",{children:[" ",F??"Auto"]})]}),H.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:"Skills"}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":"Assigned skills",children:H.map(h=>{const b=y===h;return e.jsx("button",{type:"button",className:ae("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",b&&"dashboard-summary-skill-badge--selected"),title:h,onClick:()=>S(h),"aria-expanded":b,"aria-label":`View details for ${Rs(h)}`,children:Rs(h)},h)})})]}):e.jsx("span",{children:"Skills: —"})]}),y?e.jsxs("div",{className:"dashboard-summary-skill-detail","data-testid":"agent-skill-detail",children:[e.jsxs("div",{className:"dashboard-summary-skill-detail-header",children:[e.jsx("span",{className:"dashboard-summary-skill-detail-title",children:E}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>S(y),children:[e.jsx(mt,{size:14}),"Close"]})]}),Y?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(_,{size:14,className:"animate-spin"}),"Loading skill content..."]}):m?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(bt,{size:14}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void K(y),children:"Retry"})]}):j?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:j.skillMd||"(No SKILL.md found)"}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:"No skill content available"})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Heartbeat & Health"}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Last heartbeat"}),e.jsx("p",{children:s.lastHeartbeatAt?qe(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:W?qe(W):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:pt(T)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Status"}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:ae("status-dot",s.state==="running"&&"status-dot--running")}),n.label,n.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:n.reason,children:["(",n.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Current Work"}),s.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${s.taskId}`,className:"task-badge",children:s.taskId}),e.jsxs("a",{href:`/tasks/${s.taskId}`,className:"btn btn-sm",children:["View Task ",e.jsx(gt,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:"No active assignment"})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Recent Runs"}),e.jsxs("p",{className:"dashboard-summary-label",children:[R.successfulRuns,"/",R.totalRuns," successful (",R.successRate,"%)"]}),J.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:J.map(h=>{const b=ys[h.status]||ys.terminated,r=b.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(r,{size:14,style:{color:b.color}}),e.jsx("span",{children:qe(h.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(h.endedAt||h.startedAt).getTime()-new Date(h.startedAt).getTime())/1e3)),"s"]})]},h.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Throughput"}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[R.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Chain of Command"}),f?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(_,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):x.length<=1?e.jsx("p",{className:"text-muted",children:"No reporting chain"}):e.jsx("div",{className:"chain-of-command-path","aria-label":"Chain of command",children:x.map((h,b)=>{const r=b===x.length-1,o=!r;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${r?" chain-of-command-node--current":""}`,onClick:()=>o&&i?.(h.id),disabled:!o||!i,title:r?"Current agent":`View ${h.name}`,children:h.name}),!r&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},h.id)})})]})]})}function za({logs:s,isStreaming:n,hasTask:i,fallbackLabel:l}){return i?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsxs("span",{className:"logs-count",children:[s.length," entries"]}),l&&e.jsx("span",{className:"text-muted logs-fallback-label",children:l}),n&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),"Live"]})]}),s.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(as,{size:48,opacity:.3}),e.jsx("p",{children:"No log entries yet"}),e.jsx("p",{className:"text-muted",children:n?"Waiting for activity...":"Logs will appear here when the agent is active"})]}):e.jsx(vt,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(as,{size:48,opacity:.3}),e.jsx("p",{children:"No activity yet"}),e.jsx("p",{className:"text-muted",children:"Agent logs will appear here from the current task or most recent run"})]})})}function Ha(s){const n=new Date(s),l=new Date().getTime()-n.getTime(),u=Math.floor(l/6e4),x=Math.floor(l/36e5),M=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:x<24?`${x}h ago`:M<7?`${M}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function xs(s,n,i){if(n==="user")return s==="dashboard"?"You":`User: ${s}`;if(n==="agent"){const l=i?.get(s)?.trim();return!l||l===s?`Agent: ${s}`:`Agent: ${l}`}return"System"}function Ba({agent:s,mailbox:n,isLoading:i,error:l,projectId:u,addToast:x,onRefresh:M}){const[f,v]=t.useState("inbox"),[A,$]=t.useState([]);t.useEffect(()=>{let m=!1;return js(void 0,u).then(O=>{m||$(O)}).catch(()=>{m||$([])}),()=>{m=!0}},[u]);const c=t.useMemo(()=>{const m=new Map;for(const N of A){if(!N.id)continue;const F=typeof N.name=="string"?N.name.trim():"";F.length>0&&m.set(N.id,F)}const O=typeof s.name=="string"?s.name.trim():"";return O.length>0&&m.set(s.id,O),m},[A,s.id,s.name]),[C,y]=t.useState(null),P=f==="inbox"?n?.inbox??[]:n?.outbox??[],j=C?P.find(m=>m.id===C)??null:null;t.useEffect(()=>{y(null)},[f,s.id]);const V=async m=>{if(y(m.id),!(f!=="inbox"||m.read))try{await ba(m.id,u),M()}catch(O){const N=`Failed to mark message as read: ${q(O)}`;x?x(N,"error"):console.warn(N)}},Y=()=>{y(null),M()},p=m=>e.jsxs("button",{type:"button",className:ae("mailbox-item","agent-mail-tab-message",f==="inbox"&&!m.read&&"unread",C===m.id&&"agent-mail-tab-message--selected"),onClick:()=>void V(m),"aria-pressed":C===m.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?m.fromType:m.toType)==="agent"?e.jsx(Ds,{size:16}):e.jsx(ca,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[f==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:xs(m.fromId,m.fromType,c)}):e.jsxs("span",{className:"mailbox-item-to",children:["To: ",xs(m.toId,m.toType,c)]}),e.jsx("span",{className:"mailbox-item-time",children:Ha(m.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[m.content.slice(0,80),m.content.length>80?"…":""]})]}),f==="inbox"&&!m.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":"Unread message"}):null]},m.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsxs("h3",{children:[s.name," Mail"]}),e.jsxs("button",{className:"btn btn-sm",onClick:Y,disabled:i,children:[e.jsx(Ss,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="inbox"&&"active"),onClick:()=>v("inbox"),children:[e.jsx(Ys,{size:12}),e.jsx("span",{children:"Inbox"}),(n?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:n?.unreadCount}):null]}),e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="outbox"&&"active"),onClick:()=>v("outbox"),children:[e.jsx(Zs,{size:12}),e.jsx("span",{children:"Outbox"})]})]}),i&&!n?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(_,{className:"animate-spin",size:16}),e.jsx("span",{children:"Loading mailbox..."})]}):null,!i&&l?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(bt,{size:16}),e.jsxs("span",{children:["Failed to load mailbox: ",l]})]}):null,!i&&!l?j?e.jsxs("div",{className:"agent-mail-tab-detail","data-testid":"agent-detail-mail-message",children:[e.jsxs("button",{type:"button",className:"btn btn-sm agent-mail-tab-back","data-testid":"agent-detail-mail-back",onClick:()=>y(null),children:[e.jsx(dt,{size:14}),"Back to ",f==="inbox"?"Inbox":"Outbox"]}),e.jsxs("div",{className:"agent-mail-tab-detail-meta",children:[e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"From"}),e.jsx("span",{children:xs(j.fromId,j.fromType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"To"}),e.jsx("span",{children:xs(j.toId,j.toType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Type"}),e.jsx("span",{children:j.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Sent"}),e.jsx("span",{children:new Date(j.createdAt).toLocaleString()})]}),j.metadata?.replyTo?.messageId?e.jsxs("div",{className:"agent-mail-tab-reply-context",children:["↪ Replying to message ",j.metadata.replyTo.messageId]}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:j.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:P.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(Ys,{size:32}):e.jsx(Zs,{size:32}),e.jsx("p",{children:f==="inbox"?"No received messages for this agent":"No sent messages for this agent"})]}):P.map(p)}):null]})}function Oa({addToast:s,agentId:n,projectId:i,agentState:l,agentName:u,initialRunId:x,preferActiveRun:M,runNowRefreshToken:f}){const[v,A]=t.useState([]),{confirm:$}=rt(),[c,C]=t.useState(!0),[y,P]=t.useState(null),[j,V]=t.useState([]),[Y,p]=t.useState(!1),[m,O]=t.useState(null),[N,F]=t.useState(!1),R=t.useRef(!1),J=t.useRef(!1),H=t.useCallback(async()=>{try{const o=await ot(n,50,i);A(o)}catch(o){s(`Failed to load runs: ${q(o)}`,"error")}finally{C(!1)}},[n,i,s]);t.useEffect(()=>{H()},[H]),t.useEffect(()=>{if(!J.current){J.current=!0;return}C(!0),H()},[H,f]);const E=v.some(o=>o.status==="active"),K=y?v.find(o=>o.id===y)?.status:void 0;t.useEffect(()=>{if(!E)return;const o=setInterval(()=>{H()},5e3);return()=>clearInterval(o)},[E,H]),t.useEffect(()=>{if(!y||K!=="active")return;const o=i?`?projectId=${encodeURIComponent(i)}`:"";return bs(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(y)}/logs/stream${o}`,{events:{"agent:log":k=>{try{const ne=JSON.parse(k.data);V(se=>[...se,ne])}catch{}}}})},[y,K,n,i]);const S=t.useCallback(async o=>{if(y===o){P(null),V([]),O(null);return}P(o),p(!0),F(!0),V([]),O(null);try{const[k,ne]=await Promise.all([ct(n,o,i),Qt(n,o,i)]);V(k),O(ne)}catch(k){s(`Failed to load run details: ${q(k)}`,"error"),V([]),O(null)}finally{p(!1),F(!1)}},[y,n,i,s]);t.useEffect(()=>{R.current=!1},[n,x,M]),t.useEffect(()=>{if(v.length===0||c||R.current)return;const o=x?v.find(k=>k.id===x):M?v.find(k=>k.status==="active"):null;R.current=!0,o&&S(o.id)},[x,M,v,c,S]);const ee=async()=>{if(await $({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await da(n,i),s("Run stopped","success"),C(!0),H()}catch(k){s(`Failed to stop run: ${q(k)}`,"error")}};if(c&&v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Ns,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})});const T=[...v].sort((o,k)=>new Date(k.startedAt).getTime()-new Date(o.startedAt).getTime()),W=T.filter(o=>o.status==="active"),h=T.filter(o=>o.status!=="active"),b=o=>o?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",o.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",o.outputTokens.toLocaleString()]}),o.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",o.cachedTokens.toLocaleString()]})]}):null,r=(o,k,ne)=>{const se=ys[o.status]||ys.completed,ve=se.icon,X=o.endedAt?Ia(new Date(o.startedAt),new Date(o.endedAt)):"In progress",be=y===o.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ae("run-card",ne&&"run-card--active",be&&"run-card--selected","run-card--clickable"),onClick:()=>void S(o.id),role:"button",tabIndex:0,"aria-expanded":be,"aria-label":`${ne?"Active":""} run ${o.id.slice(0,8)}, ${o.status}`,onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),S(o.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[be?e.jsx(it,{size:14}):e.jsx(lt,{size:14}),ne?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",k+1," ",o.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[o.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:o.invocationSource}),ne&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),ee()},"aria-label":"Stop active run",children:[e.jsx(Ge,{size:12})," Stop"]}),e.jsxs("span",{className:ae("run-status",o.status),children:[e.jsx(ve,{size:14,style:{color:se.color}}),o.status]}),o.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:"Heartbeat: custom"})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsxs("span",{children:["Started ",qe(o.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:X}),o.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:o.triggerDetail})]})]})]}),be&&e.jsxs("div",{className:"run-logs-container",children:[N?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(_,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):m&&e.jsxs("div",{className:"run-output-sections",children:[e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"System Prompt"}),m.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:m.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"System prompt not captured for this run"})]})}),e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"Execution Prompt"}),m.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:m.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),m.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),b(m.usageJson)]}),m.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Output"}),e.jsx("pre",{className:"run-output-panel",children:m.stdoutExcerpt.length>2e3?`${m.stdoutExcerpt.slice(0,2e3)}
|
|
17
|
-
|
|
18
|
-
... (truncated, ${m.stdoutExcerpt.length} chars total)`:m.stdoutExcerpt})]}),m.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx(ua,{errorText:m.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:n,agentName:u,agentState:l,runId:m.id,taskId:void 0,timestamp:m.startedAt}})]}),m.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Result"}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(m.resultJson,null,2)})]}),m.contextSnapshot&&Object.keys(m.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Context"}),e.jsx("div",{className:"run-context-grid",children:Object.entries(m.contextSnapshot).map(([Z,I])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[Z,":"]})," ",e.jsx("span",{children:String(I)})]},Z))})]}),!m.stdoutExcerpt&&!m.stderrExcerpt&&!m.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:"No output captured"})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:"Agent Logs"}),Y?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(_,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):j.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(vt,{entries:j,loading:!1})]})]})]},o.id)};return e.jsxs("div",{className:"runs-tab",children:[e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[v.length," run",v.length!==1?"s":"",E&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsx("div",{className:"run-header-group",children:E&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void ee(),"aria-label":`Stop active run for ${u??n}`,children:[e.jsx(Ge,{size:14})," Stop Run"]})})]}),W.map((o,k)=>r(o,k,!0)),h.map((o,k)=>r(o,W.length+k,!1))]})}function Ia(s,n){const i=Math.floor((n.getTime()-s.getTime())/1e3);return i<60?`${i}s`:i<3600?`${Math.floor(i/60)}m ${i%60}s`:`${Math.floor(i/3600)}h ${Math.floor(i%3600/60)}m`}const Ua={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function _a(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function Va({agentId:s,projectId:n,addToast:i}){const[l,u]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{let f=!1;return M(!0),ea(s,n).then(v=>{f||u(v)}).catch(v=>{f||(u([]),i(`Failed to load assigned tasks: ${q(v)}`,"error"))}).finally(()=>{f||M(!1)}),()=>{f=!0}},[s,n,i]),x?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):l.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ht,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:l.map(f=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${f.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:f.id}),e.jsx("span",{className:`agent-task-column column-${f.column}`,children:Ua[f.column]})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:_a(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · Updated ",qe(f.updatedAt)]})]},f.id))})}const ts=[{key:"maxRetries",label:"Max Retries",type:"number",placeholder:"3",hint:"Maximum number of automatic retries on task failure (0–10, default 3)",min:0,max:10},{key:"timeoutMs",label:"Task Timeout (ms)",type:"number",placeholder:"600000",hint:"Maximum time in ms before a task is considered timed out (minimum 60000ms, default 600000ms)",min:6e4,max:864e5},{key:"logLevel",label:"Log Level",type:"select",hint:"Verbosity of agent log output",options:[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warning"},{value:"error",label:"Error"}]}];function Ja(s){const n={};for(const i of ts){const l=s[i.key]?.trim();if(l){if(i.type==="number"){const u=Number(l);if(Number.isNaN(u)||!Number.isFinite(u)){n[i.key]=`"${i.label}" must be a valid number`;continue}i.min!==void 0&&u<i.min&&(n[i.key]=`"${i.label}" must be at least ${i.min.toLocaleString()}`),i.max!==void 0&&u>i.max&&(n[i.key]=`"${i.label}" must be at most ${i.max.toLocaleString()}`)}if(i.type==="select"){const u=i.options?.map(x=>x.value)??[];u.length>0&&!u.includes(l)&&(n[i.key]=`"${i.label}" must be one of: ${u.join(", ")}`)}}}return n}function Wa({agent:s,projectId:n,addToast:i,onSaved:l}){const[u,x]=t.useState(s.soul??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[$,c]=t.useState(!1),C=t.useRef(null);t.useEffect(()=>{x(s.soul??""),A(!1),c(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const y=u!==(s.soul??""),P=async()=>{if(u.length>1e4){i("Soul must be at most 10,000 characters","error");return}f(!0);try{await ma(s.id,u,n),i("Soul saved","success"),A(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>A(!1),3e3),await l()}catch(j){i(`Failed to save soul: ${q(j)}`,"error")}finally{f(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Soul"}),e.jsx("p",{className:"config-description",children:"Define this agent's personality and identity."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:"Agent Soul"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${$?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!$,"aria-label":"Edit mode",children:[e.jsx(ns,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${$?"btn-primary":""}`,onClick:()=>c(!0),disabled:$,"aria-label":"Preview mode",children:[e.jsx(is,{size:14}),"Preview"]})]})}),$?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ls,{remarkPlugins:[rs],children:u})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No soul defined yet. Switch to Edit mode to define the agent's personality."}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:"Describe this agent's personality, tone, and behavioral traits...",value:u,onChange:j=>{x(j.target.value),A(!1)}}),!$&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!$&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!y||M,onClick:()=>void P(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Soul"]})}),!y&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Soul saved"]})]})]})})}function Ga({agent:s,projectId:n,addToast:i,onSaved:l}){const[u,x]=t.useState(s.memory??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[$,c]=t.useState(!1),[C,y]=t.useState(!1),[P,j]=t.useState([]),[V,Y]=t.useState(!1),[p,m]=t.useState(""),[O,N]=t.useState(""),[F,R]=t.useState(!1),[J,H]=t.useState(!1),[E,K]=t.useState(!1),[S,ee]=t.useState(!1),[T,W]=t.useState(""),h=t.useRef(null),b=t.useRef(null),r=s.state==="running",o=u!==(s.memory??""),k=t.useMemo(()=>P.find(I=>I.path===p),[P,p]),ne=k?Ta[k.layer]:"Select a memory file to view or edit.",se=t.useCallback(async I=>{H(!0);try{const re=await ta(s.id,I,n);m(re.path),N(re.content),R(!1),ee(!1)}catch(re){i(`Failed to load agent memory file: ${q(re)}`,"error")}finally{H(!1)}},[s.id,n,i]),ve=t.useCallback(async(I="")=>{Y(!0);try{const{files:re}=await aa(s.id,n);if(j(re),re.length===0){m(""),N(""),R(!1);return}const He=La(re,I);await se(He)}catch(re){i(`Failed to load memory files: ${q(re)}`,"error"),j([]),m(""),N(""),R(!1)}finally{Y(!1)}},[s.id,n,i,se]);t.useEffect(()=>{x(s.memory??""),A(!1),c(!1),y(!1),W(""),ee(!1),ve()},[s.id,s.memory,ve]),t.useEffect(()=>()=>{h.current&&clearTimeout(h.current),b.current&&clearTimeout(b.current)},[]);const X=async()=>{if(u.length>5e4){i("Memory must be at most 50,000 characters","error");return}f(!0);try{await fa(s.id,u,n),i("Memory saved","success"),A(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>A(!1),3e3),await l()}catch(I){i(`Failed to save memory: ${q(I)}`,"error")}finally{f(!1)}},be=async I=>{if(!(!I||I===p)){if(F){W("Save the current file before switching to another file.");return}W(""),await se(I)}},Z=async()=>{if(p){K(!0);try{await ga(s.id,p,O,n),R(!1),ee(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>ee(!1),3e3),W(""),await ve(p),i("Agent memory file saved","success"),await l()}catch(I){i(`Failed to save agent memory file: ${q(I)}`,"error")}finally{K(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Memory"}),e.jsx("p",{className:"config-description",children:"Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory."}),r&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:"Read-only while this agent is running."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:"Inline Memory"}),e.jsx("span",{className:"config-hint config-hint--block",children:"Short-form memory stored directly on the agent record and injected into prompts."}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!r&&e.jsxs("button",{className:`btn btn-sm ${$?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!$,"aria-label":"Edit mode",children:[e.jsx(ns,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${$?"btn-primary":""}`,onClick:()=>c(!0),disabled:$,"aria-label":"Preview mode",children:[e.jsx(is,{size:14}),"Preview"]})]})}),$?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ls,{remarkPlugins:[rs],children:u})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No agent memory defined yet. Switch to Edit mode to add memory content."}):e.jsx("textarea",{id:"agent-memory","aria-label":"Agent Memory",className:"input config-textarea-mono",rows:10,placeholder:"Durable preferences, operating habits, and context this agent should carry across tasks...",value:u,readOnly:r,onChange:I=>{x(I.target.value),A(!1)}}),!$&&e.jsx("span",{className:"config-hint",children:"This is the inline memory field on the agent JSON record. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:"Memory Files"}),e.jsxs("span",{className:"config-hint config-hint--block",children:["Full OpenClaw memory files at ",e.jsxs("code",{children:["agent/",s.name||s.id,"/memory/"]})," (MEMORY.md, DREAMS.md, and daily notes)."]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:p,disabled:V||J||E||P.length===0,onChange:I=>{be(I.target.value)},children:P.length===0?e.jsx("option",{value:"",children:"No memory files found"}):P.map(I=>e.jsxs("option",{value:I.path,children:[tt[I.layer]," • ",I.label]},I.path))}),V&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(_,{size:14,className:"animate-spin"}),"Loading memory files…"]}),k&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:tt[k.layer]})," · ",ne,e.jsx("br",{}),k.size.toLocaleString()," bytes · Updated ",qe(k.updatedAt)]}),e.jsx("div",{className:"agent-content-toolbar config-textarea-top-spacing",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!r&&e.jsxs("button",{className:`btn btn-sm ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Memory file edit mode",children:[e.jsx(ns,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Memory file preview mode",children:[e.jsx(is,{size:14}),"Preview"]})]})}),C?O.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ls,{remarkPlugins:[rs],children:O})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No memory file content yet. Switch to Edit mode to add content."}):e.jsx("textarea",{className:"input config-textarea-mono",rows:14,placeholder:"Select a memory file to view and edit its content...",value:O,readOnly:r||!p||J,onChange:I=>{N(I.target.value),R(!0),ee(!1),W("")}}),J&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(_,{size:14,className:"animate-spin"}),"Loading file content…"]}),T&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:T})]})]}),e.jsxs("div",{className:"config-actions",children:[!$&&e.jsx("button",{className:"btn btn-task-create",disabled:!o||M||r,onClick:()=>void X(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory"]})}),!C&&e.jsx("button",{className:"btn",disabled:!F||E||!p||r,onClick:()=>void Z(),children:E?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory File"]})}),!o&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory saved"]}),!F&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory file saved"]})]})]})})}function qa({agent:s,projectId:n,addToast:i,onSaved:l}){const[u,x]=t.useState(s.instructionsText??""),[M,f]=t.useState(s.instructionsPath??""),[v,A]=t.useState(!1),[$,c]=t.useState(""),[C,y]=t.useState(!1),[P,j]=t.useState(!1),[V,Y]=t.useState(!1),[p,m]=t.useState(!1),[O,N]=t.useState(!1),[F,R]=t.useState(!1),J=t.useRef(null),H=t.useRef(null);t.useEffect(()=>{const T=M.trim();if(!T){c(""),j(!1);return}y(!0),jt("project",T).then(W=>{c(W.content),j(!1)}).catch(W=>{const h=q(W);h.includes("ENOENT")||h.includes("Not found")||h.includes("not found")?(c(""),j(!1)):(i(`Failed to load instructions file: ${h}`,"error"),c(""))}).finally(()=>{y(!1)})},[M,i]),t.useEffect(()=>{x(s.instructionsText??""),f(s.instructionsPath??""),N(!1),R(!1),A(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{J.current&&clearTimeout(J.current),H.current&&clearTimeout(H.current)},[]);const E=(()=>{const T=u??"",W=s.instructionsText??"",h=M?.trim()??"",b=s.instructionsPath?.trim()??"";return T!==W||h!==b})(),K=async()=>{Y(!0);try{await ha(s.id,{instructionsText:u||void 0,instructionsPath:M.trim()||void 0},n),i("Instructions saved","success"),N(!0),J.current&&clearTimeout(J.current),J.current=setTimeout(()=>N(!1),3e3),await l()}catch(T){i(`Failed to save instructions: ${q(T)}`,"error")}finally{Y(!1)}},S=async()=>{const T=M.trim();if(!T){i("No instructions file path set","error");return}m(!0);try{await Nt("project",T,$),i("Instructions file saved","success"),j(!1),R(!0),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>R(!1),3e3),await l()}catch(W){i(`Failed to save instructions file: ${q(W)}`,"error")}finally{m(!1)}},ee=!!M.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Custom Instructions"}),e.jsx("p",{className:"config-description",children:"Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:()=>A(!1),disabled:!v,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ns,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>A(!0),disabled:v,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(is,{size:14}),"Preview"]})]})}),v?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ls,{remarkPlugins:[rs],children:u})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No inline instructions defined yet. Switch to Edit mode to add instructions."}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:"Enter custom instructions to append to this agent's system prompt...",value:u,onChange:T=>{x(T.target.value),N(!1)}}),!v&&e.jsx("span",{className:"config-hint",children:"Markdown formatting supported. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:"Instructions File Path"}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:"e.g., .fusion/agents/my-agent-instructions.md",value:M,onChange:T=>{f(T.target.value),N(!1)}}),e.jsx("span",{className:"config-hint",children:"Path to a .md file (relative to project root). Contents are read and appended at execution time."})]})]}),!v&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!E||V,onClick:()=>void K(),children:V?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Instructions"]})}),!E&&O&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Instructions saved"]})]})]}),ee&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instructions File Editor"}),e.jsx("p",{className:"config-description",children:"Edit the instructions file directly. Changes are saved separately from the path configuration."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:"File Content"}),C&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(_,{size:12,className:"animate-spin"}),"Loading..."]}),P&&!C&&e.jsx("span",{className:"config-hint config-hint--warning",children:"Unsaved changes"})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:"File content will appear here when loaded...",value:$,readOnly:C,onChange:T=>{c(T.target.value),j(!0),R(!1)}}),e.jsx("span",{className:"config-hint",children:"Edit the markdown file content directly. Save separately using the button below."})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!P||p,onClick:()=>void S(),children:p?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save File"]})}),!P&&F&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function at(s){const n=s??{},i={};return n.heartbeatIntervalMs!==void 0&&n.heartbeatIntervalMs!==null&&(i.heartbeatIntervalMs=String(Number(n.heartbeatIntervalMs)/1e3)),n.heartbeatTimeoutMs!==void 0&&n.heartbeatTimeoutMs!==null&&(i.heartbeatTimeoutMs=String(Number(n.heartbeatTimeoutMs)/1e3)),n.maxConcurrentRuns!==void 0&&n.maxConcurrentRuns!==null&&(i.maxConcurrentRuns=String(n.maxConcurrentRuns)),(n.messageResponseMode==="immediate"||n.messageResponseMode==="on-heartbeat")&&(i.messageResponseMode=n.messageResponseMode),i}function Ms(s){return s?.enabled!==!1}function As(s){return s?.autoClaimRelevantTasks!==!1}function Fs(s){return s?.runMissedHeartbeatOnStartup===!0}function Es(s){return s?.allowParallelExecution!==!1}function Ts(s){return s?.skipHeartbeatWhenIdle===!0}function nt(s){const n=(s??{}).budgetConfig,i={};return n&&(n.tokenBudget!==void 0&&n.tokenBudget!==null&&(i.tokenBudget=String(n.tokenBudget)),n.usageThreshold!==void 0&&n.usageThreshold!==null&&(i.usageThreshold=String(Number(n.usageThreshold)*100)),n.budgetPeriod!==void 0&&n.budgetPeriod!==null&&(i.budgetPeriod=String(n.budgetPeriod)),n.resetDay!==void 0&&n.resetDay!==null&&(i.resetDay=String(n.resetDay))),i}function Ka({agent:s,projectId:n,addToast:i,onSaved:l}){const[u,x]=t.useState(!1),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[$,c]=t.useState(!1),[C,y]=t.useState(!1),[P,j]=t.useState(""),[V,Y]=t.useState(!1),[p,m]=t.useState(null),[O,N]=t.useState(!1),F=t.useRef(null),R=s.heartbeatProcedurePath?.trim(),J=`.fusion/agents/${s.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,H=`.fusion/agents/${s.id}/HEARTBEAT.md`,E=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",K=!!(R&&(R===J||R===H||new RegExp(`^\\.fusion/agents/[^/]+-${E}/HEARTBEAT\\.md$`).test(R))),S=!!R,ee=t.useCallback(async b=>{A(!0),m(null);try{const r=await jt("project",b,n);j(r.content),Y(!1)}catch(r){const o=q(r);m(o),i(`Failed to load heartbeat procedure file: ${o}`,"error")}finally{A(!1)}},[i,n]);t.useEffect(()=>{f(!1),y(!1),j(""),Y(!1),m(null),A(!1),c(!1),N(!1)},[s.id,R]),t.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]);const T=async()=>{R&&(f(!0),await ee(R))},W=async()=>{if(R){c(!0);try{await Nt("project",R,P,n),Y(!1),N(!0),i("Heartbeat procedure file saved","success"),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>N(!1),3e3),await l()}catch(b){i(`Failed to save heartbeat procedure file: ${q(b)}`,"error")}finally{c(!1)}}},h=async()=>{x(!0);try{const b=await pa(s.id,n);i(b.procedureFileSeeded?`Heartbeat procedure file ready at ${b.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${b.heartbeatProcedurePath}`,"success"),await l()}catch(b){i(`Failed to upgrade heartbeat procedure: ${q(b)}`,"error")}finally{x(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Procedure"}),e.jsxs("p",{className:"config-description",children:["The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing."]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:["Current path: ",e.jsx("code",{children:R||"(none — using built-in default)"})]}),S&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void T(),disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(as,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:u||K,onClick:()=>void h(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:u?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Upgrading…"]}):K?e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Already on default"]}):"Upgrade to Default Heartbeat Procedure"}),e.jsxs("span",{className:"config-hint",children:["Sets ",e.jsx("code",{children:"heartbeatProcedurePath"})," to"," ",e.jsx("code",{children:J})," ","and seeds the file from the built-in template if it doesn't exist. Each agent gets its own per-agent file, so edits stay scoped to this agent. Operator edits to the file are preserved."]})]})]}),M&&S&&R&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:"Heartbeat Procedure File"}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ns,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Heartbeat file preview mode",children:[e.jsx(is,{size:14}),"Preview"]})]}),v&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(_,{size:12,className:"animate-spin"}),"Loading..."]}),V&&!v&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),C?P.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ls,{remarkPlugins:[rs],children:P})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No heartbeat procedure markdown content yet."}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:P,readOnly:v,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:b=>{j(b.target.value),Y(!0),N(!1)}}),p&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",p]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:R}),"."]})]}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!V||$||v,onClick:()=>void W(),children:$?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Heartbeat File"]})}),!V&&O&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function Ya({agent:s,projectId:n,addToast:i,onSaved:l,onHasChangesChange:u,onDelete:x,onAgentDraftApplied:M}){const[f,v]=t.useState(s.name),[A,$]=t.useState(s.role),[c,C]=t.useState(s.title??""),[y,P]=t.useState(s.icon??""),[j,V]=t.useState(s.reportsTo??""),[Y,p]=t.useState([]),[m,O]=t.useState(!1),[N,F]=t.useState(!1),[R,J]=t.useState(!1),H=t.useRef(null),[E,K]=t.useState(()=>{const a={};for(const d of ts){const w=s.metadata[d.key];w!=null&&(a[d.key]=String(w))}return a}),[S,ee]=t.useState(()=>at(s.runtimeConfig)),[T,W]=t.useState(()=>Ms(s.runtimeConfig)),[h,b]=t.useState(()=>As(s.runtimeConfig)),[r,o]=t.useState(()=>Fs(s.runtimeConfig)),[k,ne]=t.useState(()=>Es(s.runtimeConfig)),[se,ve]=t.useState(()=>Ts(s.runtimeConfig)),[X,be]=t.useState(()=>nt(s.runtimeConfig)),[Z,I]=t.useState(s.bundleConfig?.mode??""),[re,He]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[Ae,os]=t.useState(s.bundleConfig?.externalPath??""),[Fe,cs]=t.useState(s.bundleConfig?.files??[]),[ke,Be]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[Ke,Te]=t.useState([]),[le,Ye]=t.useState(!1),[$e,ge]=t.useState([]),[Pe,Oe]=t.useState([]),[ds,Je]=t.useState([]),[Le,ye]=t.useState(!1),Ie=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),Ce=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[de,Ue]=t.useState(Ce?"runtime":"model"),[pe,De]=t.useState(Ie),[he,_e]=t.useState(Ce),Ve=j.trim(),Ze=t.useMemo(()=>Y.filter(a=>a.id!==s.id),[Y,s.id]),g=!!Ve&&!Ze.some(a=>a.id===Ve),D=t.useMemo(()=>({name:f,role:A,title:c||void 0,instructionsText:s.instructionsText,soul:s.soul,memory:s.memory,reportsTo:j||void 0,skills:ke,model:pe||void 0,runtimeHint:de==="runtime"&&he||void 0,thinkingLevel:E.thinkingLevel??void 0,maxTurns:E.maxTurns?Number(E.maxTurns):void 0,heartbeatIntervalMs:S.heartbeatIntervalMs?Number(S.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:S.heartbeatTimeoutMs?Number(S.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:S.maxConcurrentRuns?Number(S.maxConcurrentRuns):void 0,messageResponseMode:S.messageResponseMode}),[s.instructionsText,s.memory,s.soul,E.maxTurns,E.thinkingLevel,S.heartbeatIntervalMs,S.heartbeatTimeoutMs,S.maxConcurrentRuns,S.messageResponseMode,pe,f,j,A,de,he,ke,c]),U=t.useCallback(a=>{v(a.name),$(a.role),C(a.title??""),P(a.icon??""),V(a.reportsTo??""),a.skills&&Be(a.skills),a.thinkingLevel&&K(w=>({...w,thinkingLevel:a.thinkingLevel})),a.maxTurns!==void 0&&K(w=>({...w,maxTurns:String(a.maxTurns)})),a.runtimeHint!==void 0?(Ue("runtime"),_e(a.runtimeHint??""),a.runtimeHint&&De("")):a.model!==void 0&&(Ue("model"),De(a.model??""),_e(""));const d=Object.fromEntries(Object.entries({name:a.name,role:a.role,title:a.title,icon:a.icon,reportsTo:a.reportsTo,instructionsText:a.instructionsText,soul:a.soul,memory:a.memory}).filter(([,w])=>w!==void 0));M?.(d),J(!1),i("Interview draft applied. Review and save when ready.","success")},[i,M]);t.useEffect(()=>{let a=!1;return O(!0),js(void 0,n).then(d=>{a||p(d)}).catch(()=>{a||p([])}).finally(()=>{a||O(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{Ye(!0),na().then(a=>{Te(a.models),ge(a.favoriteProviders),Oe(a.favoriteModels)}).catch(()=>{}).finally(()=>Ye(!1))},[]);const B=t.useCallback(async a=>{const d=$e,G=d.includes(a)?d.filter(ue=>ue!==a):[a,...d];ge(G);try{await Xs({favoriteProviders:G,favoriteModels:Pe})}catch{ge(d)}},[$e,Pe]),ie=t.useCallback(async a=>{const d=Pe,G=d.includes(a)?d.filter(ue=>ue!==a):[a,...d];Oe(G);try{await Xs({favoriteProviders:$e,favoriteModels:G})}catch{Oe(d)}},[$e,Pe]);t.useEffect(()=>{ye(!0),xt(n).then(Je).catch(()=>Je([])).finally(()=>ye(!1))},[n]);const[te,je]=t.useState(null),[we,Xe]=t.useState(!1);t.useEffect(()=>{$s(s.id,n).then(je).catch(()=>je(null))},[s.id,n]);const us=async()=>{Xe(!0);try{await xa(s.id,n),i("Budget usage reset successfully","success");const a=await $s(s.id,n);je(a)}catch(a){i(`Failed to reset budget: ${q(a)}`,"error")}finally{Xe(!1)}},[Se,oe]=t.useState(!1),[L,Ee]=t.useState({}),[St,We]=t.useState(!1),[ks,ms]=t.useState(null),Hs=s.state==="idle"||s.state==="paused",Qe=t.useRef(null),Bs=t.useRef(null),Os=t.useRef(null),hs=t.useRef(0);t.useEffect(()=>()=>{Qe.current&&clearTimeout(Qe.current)},[]);const Ne=(()=>{if(f!==s.name||A!==s.role||c!==(s.title??"")||y!==(s.icon??"")||j!==(s.reportsTo??"")||Z!==(s.bundleConfig?.mode??"")||re!==(s.bundleConfig?.entryFile??"AGENTS.md")||Ae!==(s.bundleConfig?.externalPath??"")||JSON.stringify(Fe)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const Q of ts){const xe=E[Q.key]?.trim()??"",z=s.metadata[Q.key]!==void 0&&s.metadata[Q.key]!==null?String(s.metadata[Q.key]):"";if(xe!==z)return!0}const a=s.runtimeConfig??{};if(T!==Ms(s.runtimeConfig)||h!==As(s.runtimeConfig)||r!==Fs(s.runtimeConfig)||k!==Es(s.runtimeConfig)||se!==Ts(s.runtimeConfig))return!0;for(const Q of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const xe=S[Q]?.trim()??"";let z=a[Q]!==void 0&&a[Q]!==null?String(a[Q]):"";if((Q==="heartbeatIntervalMs"||Q==="heartbeatTimeoutMs")&&z&&(z=String(Number(z)/1e3)),xe!==z)return!0}const d=a.budgetConfig;for(const Q of["tokenBudget","budgetPeriod","resetDay"]){const xe=X[Q]?.trim()??"",z=d?.[Q]!==void 0&&d?.[Q]!==null?String(d[Q]):"";if(xe!==z)return!0}const w=X.usageThreshold?.trim()??"",G=d?.usageThreshold!==void 0&&d?.usageThreshold!==null?String(Number(d.usageThreshold)*100):"";if(w!==G)return!0;const ue=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(ke)!==JSON.stringify(ue)||de!==(Ce?"runtime":"model")||pe!==Ie||he!==Ce})(),Is=t.useRef(null);t.useEffect(()=>{u&&Is.current!==Ne&&(Is.current=Ne,u(Ne))},[Ne,u]),t.useEffect(()=>()=>{u?.(!1)},[u]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},d=Bs.current;(!d||d.id!==a.id||d.updatedAt!==a.updatedAt)&&(Ne||(Bs.current=a,ee(at(s.runtimeConfig)),W(Ms(s.runtimeConfig)),b(As(s.runtimeConfig)),o(Fs(s.runtimeConfig)),ne(Es(s.runtimeConfig)),ve(Ts(s.runtimeConfig)),be(nt(s.runtimeConfig)),De(Ie),_e(Ce),Ue(Ce?"runtime":"model")))},[s,Ne,Ie,Ce]);const Us=(a,d)=>{K(w=>({...w,[a]:d})),We(!1),L[a]&&Ee(w=>{const G={...w};return delete G[a],G})},fs=(a,d)=>{ee(w=>({...w,[a]:d})),We(!1),L[a]&&Ee(w=>{const G={...w};return delete G[a],G})},kt=a=>{W(a),We(!1)},gs=(a,d)=>{be(w=>({...w,[a]:d})),We(!1),L[a]&&Ee(w=>{const G={...w};return delete G[a],G})},Re=t.useMemo(()=>{const a=Ja(E);for(const[z,ze]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const ce=S[z]?.trim();if(!ce)continue;const Me=Number(ce);Number.isNaN(Me)||!Number.isFinite(Me)?a[z]=`"${ze.label}" must be a valid number`:Me<ze.min&&(a[z]=`"${ze.label}" must be at least ${ze.min.toLocaleString()}`)}const d=S.messageResponseMode?.trim();d&&!["immediate","on-heartbeat"].includes(d)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const w=X.tokenBudget?.trim();if(w){const z=Number(w);Number.isNaN(z)||!Number.isFinite(z)?a.tokenBudget='"Token Budget" must be a valid number':z<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const G=X.usageThreshold?.trim();if(G){const z=Number(G);Number.isNaN(z)||!Number.isFinite(z)?a.usageThreshold='"Usage Threshold" must be a valid number':(z<1||z>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ue=X.budgetPeriod?.trim();ue&&!["daily","weekly","monthly","lifetime"].includes(ue)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const Q=X.resetDay?.trim(),xe=ue||"lifetime";if(Q){const z=Number(Q);Number.isNaN(z)||!Number.isFinite(z)?a.resetDay='"Reset Day" must be a valid number':xe==="weekly"?(z<0||z>6||!Number.isInteger(z))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):xe==="monthly"&&(z<1||z>31||!Number.isInteger(z))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[E,S,X]),_s=t.useCallback(()=>{if(Object.keys(Re).length>0)return null;const a={...s.metadata};for(const ce of ts){const Me=E[ce.key]?.trim();Me?ce.type==="number"?a[ce.key]=Number(Me):a[ce.key]=Me:delete a[ce.key]}ke.length>0?a.skills=ke:delete a.skills;const d={...s.runtimeConfig};d.enabled=T,d.autoClaimRelevantTasks=h,d.runMissedHeartbeatOnStartup=r,d.allowParallelExecution=k,d.skipHeartbeatWhenIdle=se;for(const ce of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const Me=S[ce]?.trim();if(!Me)delete d[ce];else{const Js=Number(Me);d[ce]=ce==="maxConcurrentRuns"?Js:Js*1e3}}const w=S.messageResponseMode?.trim();if(w?d.messageResponseMode=w:delete d.messageResponseMode,de==="runtime")he.trim()?d.runtimeHint=he.trim():delete d.runtimeHint,delete d.modelProvider,delete d.modelId,delete d.model;else if(delete d.runtimeHint,pe.trim()){const ce=pe.indexOf("/");ce!==-1&&(d.modelProvider=pe.slice(0,ce),d.modelId=pe.slice(ce+1),d.model=pe.trim())}else delete d.modelProvider,delete d.modelId,delete d.model;const G={},ue=X.tokenBudget?.trim(),Q=X.usageThreshold?.trim(),xe=X.budgetPeriod?.trim(),z=X.resetDay?.trim();ue&&(G.tokenBudget=Number(ue)),Q&&(G.usageThreshold=Number(Q)/100),xe&&(G.budgetPeriod=xe),z&&(G.resetDay=Number(z)),Object.keys(G).length>0?d.budgetConfig=G:delete d.budgetConfig;let ze;return Z&&(ze={mode:Z,entryFile:re||"AGENTS.md",files:Fe.length>0?Fe:["AGENTS.md"]},Z==="external"&&Ae.trim()&&(ze.externalPath=Ae.trim())),{name:f.trim()||void 0,role:A,title:c.trim()||void 0,icon:y.trim()||void 0,reportsTo:j.trim()||void 0,metadata:a,runtimeConfig:d,bundleConfig:ze}},[s.metadata,s.runtimeConfig,k,h,X,re,Ae,Fe,Z,E,T,S,y,pe,f,j,A,r,de,he,ke,se,c,Re]),es=t.useCallback(async(a,d)=>{const w=_s();if(!w)return Ee(Re),a&&i("Please fix validation errors before saving","error"),d==="auto"&&ms("Fix validation errors to save changes"),!1;const G=JSON.stringify(w);if(G===Os.current)return!1;const ue=++hs.current;Ee({}),ms(null),oe(!0);try{return await ia(s.id,w,n),ue!==hs.current?!1:(Os.current=G,d==="manual"&&i("Settings saved","success"),ms(null),We(!0),Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>We(!1),3e3),await l(),!0)}catch(Q){if(ue===hs.current){const xe=q(Q);ms(xe),i(`Failed to save settings: ${xe}`,"error")}return!1}finally{ue===hs.current&&oe(!1)}},[i,s.id,_s,l,n,Re]),Ct=async()=>{await es(!0,"manual")},fe=t.useCallback(()=>{if(!(!Ne||Se)){if(Object.keys(Re).length>0){Ee(Re);return}es(!1,"auto")}},[Ne,Se,es,Re]);t.useEffect(()=>{if(!Ne||Se)return;if(Object.keys(Re).length>0){Ee(Re);return}const a=setTimeout(()=>{es(!1,"auto")},Pa);return()=>clearTimeout(a)},[Ne,Se,es,Re]);const wt=t.useCallback(async a=>{F(!0);try{await la(s.id,a,n),await l(),i("Avatar uploaded","success")}catch(d){i(q(d),"error")}finally{F(!1),H.current&&(H.current.value="")}},[i,s.id,l,n]),Rt=t.useCallback(async()=>{F(!0);try{await ra(s.id,n),await l(),i("Avatar removed","success")}catch(a){i(q(a),"error")}finally{F(!1)}},[i,s.id,l,n]),Vs=Se?"Saving changes…":ks?`Save failed: ${ks}`:!Ne&&St?"All changes saved":null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Configuration"}),e.jsx("p",{className:"config-description",children:"Configure agent settings and behavior."}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>J(!0),children:"AI Interview"})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:"Name"}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:f,onChange:a=>v(a.target.value),onBlur:()=>{fe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:A,onChange:a=>{$(a.target.value),fe()},children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"executor",children:"Executor"}),e.jsx("option",{value:"reviewer",children:"Reviewer"}),e.jsx("option",{value:"merger",children:"Merger"}),e.jsx("option",{value:"scheduler",children:"Scheduler"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:"Title"}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:c,onChange:a=>C(a.target.value),onBlur:()=>{fe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Avatar"}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(ut,{agent:s,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:H,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:N,onChange:a=>{const d=a.target.files?.[0];d&&wt(d)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:N,onClick:()=>H.current?.click(),children:"Upload Avatar"}),s.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Rt(),disabled:N,children:"Remove Avatar"}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:"Icon"}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:y,onChange:a=>P(a.target.value),onBlur:()=>{fe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:"Reports To"}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:j,onChange:a=>{V(a.target.value),fe()},disabled:m,children:[e.jsx("option",{value:"",children:"No manager"}),g&&e.jsxs("option",{value:Ve,children:["Unknown manager (",Ve,")"]}),Ze.map(a=>e.jsxs("option",{value:a.id,children:[a.name," (",a.id,")"]},a.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Skills"}),e.jsx("p",{className:"config-description",children:"Assign skills to this agent for specialized behavior."}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(va,{id:"agent-skills",label:"Skills",value:ke,onChange:a=>{Be(a),fe()},projectId:n})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Model"}),e.jsx("p",{className:"config-description",children:"Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Runtime Source"}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":"Runtime source",children:[e.jsx("button",{type:"button",className:`config-runtime-tab${de==="model"?" active":""}`,role:"tab","aria-selected":de==="model",tabIndex:de==="model"?0:-1,onClick:()=>{Ue("model"),_e(""),fe()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${de==="runtime"?" active":""}`,role:"tab","aria-selected":de==="runtime",tabIndex:de==="runtime"?0:-1,onClick:()=>{Ue("runtime"),fe()},children:"Plugin Runtime"})]})]}),de==="model"?e.jsx("div",{className:"config-field",children:e.jsx(oa,{models:Ke,value:pe,onChange:a=>{De(a),fe()},placeholder:"Use global default",label:"Agent Model",disabled:le,favoriteProviders:$e,onToggleFavorite:B,favoriteModels:Pe,onToggleModelFavorite:ie})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),Le?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:he,onChange:a=>{_e(a.target.value),fe()},children:[e.jsx("option",{value:"",children:ds.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),ds.map(a=>e.jsx("option",{value:a.runtimeId,children:a.description?`${a.name} — ${a.description}`:a.name},`${a.pluginId}:${a.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Settings"}),e.jsx("p",{className:"config-description",children:"Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:T,onChange:a=>{kt(a.target.checked),fe()}}),"Heartbeat Enabled"]}),e.jsx("span",{className:"config-hint",children:"When enabled, this agent receives scheduled heartbeat runs based on its interval."})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:h,onChange:a=>{b(a.target.checked),fe()}}),"Auto-Claim Relevant Tasks"]}),e.jsx("span",{className:"config-hint",children:"When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul."})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:r,onChange:a=>{o(a.target.checked),fe()}}),"Run Missed Heartbeat On Startup"]}),e.jsx("span",{className:"config-hint",children:"When enabled, if the server was down across this agent's scheduled heartbeat tick, fire a single catch-up heartbeat at startup. Default: off."})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-allowParallelExecution",children:[e.jsx("input",{id:"hb-allowParallelExecution",type:"checkbox",checked:k,onChange:a=>{ne(a.target.checked),fe()}}),"Allow Parallel Execution"]}),e.jsx("span",{className:"config-hint",children:"When disabled, the heartbeat and task execution paths serialize for this agent (heartbeat will not start while the agent's task is executing, and vice versa). Permanent agents only."})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:se,onChange:a=>{ve(a.target.checked),fe()}}),"Skip heartbeat when idle"]}),e.jsx("span",{className:"config-hint",children:"When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ae("input",!!L.heartbeatIntervalMs&&"input--error"),placeholder:String(Ps/1e3),value:S.heartbeatIntervalMs??"",onChange:a=>fs("heartbeatIntervalMs",a.target.value)}),L.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:L.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",Ps/1e3,"s / ",$a,")."]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:"Heartbeat Timeout (s)"}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:ae("input",!!L.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:S.heartbeatTimeoutMs??"",onChange:a=>fs("heartbeatTimeoutMs",a.target.value)}),L.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:L.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:"Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:"Max Concurrent Runs"}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:ae("input",!!L.maxConcurrentRuns&&"input--error"),placeholder:"1",value:S.maxConcurrentRuns??"",onChange:a=>fs("maxConcurrentRuns",a.target.value)}),L.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:L.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:"Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1)."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:"Message Response Mode"}),e.jsxs("select",{id:"hb-messageResponseMode",className:ae("select",!!L.messageResponseMode&&"input--error"),value:S.messageResponseMode??"",onChange:a=>fs("messageResponseMode",a.target.value),children:[e.jsx("option",{value:"",children:"System Default (On Heartbeat)"}),e.jsx("option",{value:"on-heartbeat",children:"On Heartbeat"}),e.jsx("option",{value:"immediate",children:"Immediate"})]}),L.messageResponseMode?e.jsx("span",{className:"config-error",children:L.messageResponseMode}):e.jsx("span",{className:"config-hint",children:"How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat."})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Budget Settings"}),e.jsx("p",{className:"config-description",children:"Configure token budget limits for this agent. Leave all fields empty to disable budget tracking."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:"Token Budget"}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:ae("input",!!L.tokenBudget&&"input--error"),placeholder:"No limit",value:X.tokenBudget??"",onChange:a=>gs("tokenBudget",a.target.value)}),L.tokenBudget?e.jsx("span",{className:"config-error",children:L.tokenBudget}):e.jsx("span",{className:"config-hint",children:"Total token cap (input + output) for this agent. Leave empty for no limit."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:"Usage Threshold (%)"}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:ae("input",!!L.usageThreshold&&"input--error"),placeholder:"80",value:X.usageThreshold??"",onChange:a=>gs("usageThreshold",a.target.value)}),L.usageThreshold?e.jsx("span",{className:"config-error",children:L.usageThreshold}):e.jsx("span",{className:"config-hint",children:"Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:"Budget Period"}),e.jsxs("select",{id:"budget-budgetPeriod",className:ae("select",!!L.budgetPeriod&&"input--error"),value:X.budgetPeriod??"",onChange:a=>gs("budgetPeriod",a.target.value),children:[e.jsx("option",{value:"",children:"No reset (lifetime)"}),e.jsx("option",{value:"daily",children:"Daily"}),e.jsx("option",{value:"weekly",children:"Weekly"}),e.jsx("option",{value:"monthly",children:"Monthly"})]}),L.budgetPeriod?e.jsx("span",{className:"config-error",children:L.budgetPeriod}):e.jsx("span",{className:"config-hint",children:"How often the budget counter resets. Leave empty for lifetime budget."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:"Reset Day"}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:ae("input",!!L.resetDay&&"input--error"),placeholder:"Auto",value:X.resetDay??"",onChange:a=>gs("resetDay",a.target.value)}),L.resetDay?e.jsx("span",{className:"config-error",children:L.resetDay}):e.jsx("span",{className:"config-hint",children:X.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":X.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),te?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Current Usage"}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:ae("budget-progress-bar__fill",(te.usagePercent??0)>=100?"budget-progress-bar__fill--red":(te.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(te.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(te.currentUsage??0).toLocaleString()," / ",(te.budgetLimit??0).toLocaleString()," tokens (",Math.round(te.usagePercent??0),"% used)"]})]})]}),te?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void us(),disabled:we,children:we?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ss,{size:14}),"Reset Budget Usage"]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instruction Bundle"}),e.jsx("p",{className:"config-description",children:"Configure the agent's instruction bundle. Leave empty to use inline instructions only."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:"Bundle Mode"}),e.jsxs("select",{id:"bundle-mode",className:"select",value:Z,onChange:a=>I(a.target.value),children:[e.jsx("option",{value:"",children:"None (use inline instructions)"}),e.jsx("option",{value:"managed",children:"Managed (system-managed directory)"}),e.jsx("option",{value:"external",children:"External (user-specified path)"})]}),e.jsxs("span",{className:"config-hint",children:[Z==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",Z==="external"&&"Specify an external directory path for the instruction files",!Z&&"Select a mode to enable instruction bundling"]})]}),Z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:"Entry File"}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:re,onChange:a=>He(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),Z==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:"External Path"}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent",value:Ae,onChange:a=>os(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Absolute or relative path to the external directory"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:"Files (comma-separated)"}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:Fe.join(", "),onChange:a=>cs(a.target.value.split(",").map(d=>d.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:"List of file names in the bundle directory"})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Advanced Settings"}),e.jsx("p",{className:"config-description",children:"Advanced configuration options for this agent. Leave a field empty to use system defaults."}),e.jsx("div",{className:"config-fields",children:ts.map(a=>{const d=!!L[a.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${a.key}`,children:a.label}),a.type==="select"?e.jsxs("select",{id:`adv-${a.key}`,className:ae("select",d&&"input--error"),value:E[a.key]??"",onChange:w=>Us(a.key,w.target.value),children:[e.jsx("option",{value:"",children:"System Default"}),a.options?.map(w=>e.jsx("option",{value:w.value,children:w.label},w.value))]}):e.jsx("input",{id:`adv-${a.key}`,type:"text",inputMode:a.type==="number"?"numeric":void 0,className:ae("input",d&&"input--error"),placeholder:a.placeholder,value:E[a.key]??"",onChange:w=>Us(a.key,w.target.value)}),d&&e.jsx("span",{className:"config-error",children:L[a.key]}),!d&&a.hint&&e.jsx("span",{className:"config-hint",children:a.hint})]},a.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Ne||Se,onClick:()=>void Ct(),children:Se?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Settings"]})}),Vs&&e.jsxs("span",{className:ae("config-saved-indicator",ks&&"config-saved-indicator--error"),children:[Se?e.jsx(_,{size:14,className:"animate-spin"}):e.jsx(me,{size:14}),Vs]})]})]}),e.jsx(Ka,{agent:s,projectId:n,addToast:i,onSaved:l}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:"Danger Zone"}),e.jsx("p",{className:"config-description",children:"Permanently delete this agent from the project."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!Hs||!x,onClick:()=>void x?.(),children:[e.jsx(vs,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:Hs?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or paused (current state: ${s.state}).`})]})})]}),e.jsx(ja,{isOpen:R,onClose:()=>J(!1),onUseDraft:U,projectId:n,existingAgents:Y,mode:"edit",existingAgentConfig:D})]})}function Za({agentId:s,projectId:n,onChildClick:i}){const[l,u]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{M(!0),sa(s,n).then(u).finally(()=>M(!1))},[s,n]),x?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:"Employees"})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(_,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:"Loading employees..."})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:"Employees"}),e.jsxs("span",{className:"text-muted",children:["(",l.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:l.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(ft,{size:32,opacity:.3}),e.jsx("p",{children:"No employees"}),e.jsx("p",{className:"text-muted",children:"This agent has no employees"})]}):e.jsx("div",{className:"agent-tree__children",children:l.map(f=>{const v=zs[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(f.id),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.key===" "&&A.preventDefault(),i?.(f.id))},style:{cursor:i?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:f.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:f.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:v?.bg??"var(--state-idle-bg)",color:v?.text??"var(--state-idle-text)",border:`1px solid ${v?.border??"var(--state-idle-border)"}`},children:f.state})]},f.id)})})})]})}export{an as AgentDetailView,qe as relativeTime};
|