@runfusion/fusion 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/bin.js +1991 -993
  2. package/dist/client/assets/AgentDetailView-BKKpbp1S.js +18 -0
  3. package/dist/client/assets/AgentDetailView-CeO_1MK7.css +1 -0
  4. package/dist/client/assets/AgentsView-BRXFmrcJ.js +527 -0
  5. package/dist/client/assets/AgentsView-Bs03ptrd.css +1 -0
  6. package/dist/client/assets/ChatView-D7L2e_qu.js +1 -0
  7. package/dist/client/assets/DevServerView-l8RCyL2k.js +1 -0
  8. package/dist/client/assets/DirectoryPicker-CS1dwqcC.js +1 -0
  9. package/dist/client/assets/DocumentsView-DmthQWDZ.js +1 -0
  10. package/dist/client/assets/{InsightsView-CqDethVs.js → InsightsView-DvXpMKmH.js} +2 -2
  11. package/dist/client/assets/{MemoryView-BLIm9Vr7.js → MemoryView-CPwlKnUI.js} +2 -2
  12. package/dist/client/assets/{NodesView-DEXvp3WT.js → NodesView-BLlfUfsy.js} +3 -3
  13. package/dist/client/assets/{PiExtensionsManager-C2YjI9o2.js → PiExtensionsManager-j8rPXqmB.js} +2 -2
  14. package/dist/client/assets/PluginManager-pW6RMz5z.js +1 -0
  15. package/dist/client/assets/ResearchView-D9DNJYDq.js +1 -0
  16. package/dist/client/assets/{RoadmapsView-DPcfX5MS.js → RoadmapsView-Djc_X35v.js} +2 -2
  17. package/dist/client/assets/SettingsModal-WGCF_pk8.js +31 -0
  18. package/dist/client/assets/{SettingsModal-BRNAPR1u.js → SettingsModal-fxvTFLtR.js} +1 -1
  19. package/dist/client/assets/SetupWizardModal-tG_MF_nA.js +1 -0
  20. package/dist/client/assets/SkillsView-Ddf0YL8z.js +1 -0
  21. package/dist/client/assets/agentSkills-DDHJnrkn.css +1 -0
  22. package/dist/client/assets/agentSkills-EwIwBlG8.js +1 -0
  23. package/dist/client/assets/folder-open-BiJpmnaT.js +6 -0
  24. package/dist/client/assets/index-D6ebxTPF.css +1 -0
  25. package/dist/client/assets/index-DYDLmOcK.js +694 -0
  26. package/dist/client/assets/{star-B314SwLA.js → star-BwRZmiuZ.js} +2 -2
  27. package/dist/client/assets/upload-D4NwZhPp.js +6 -0
  28. package/dist/client/assets/{users-Bu_ltePs.js → users-DNISDtI1.js} +2 -2
  29. package/dist/client/index.html +2 -2
  30. package/dist/client/version.json +1 -1
  31. package/dist/droid-cli/package.json +1 -1
  32. package/dist/extension.js +1154 -401
  33. package/dist/pi-claude-cli/package.json +1 -1
  34. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  35. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +480 -0
  36. package/dist/plugins/fusion-plugin-hermes-runtime/manifest.json +14 -0
  37. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +11 -0
  38. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +369 -0
  39. package/dist/plugins/fusion-plugin-openclaw-runtime/manifest.json +14 -0
  40. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +11 -0
  41. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +966 -0
  42. package/dist/plugins/fusion-plugin-paperclip-runtime/manifest.json +15 -0
  43. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +11 -0
  44. package/package.json +2 -1
  45. package/skill/fusion/references/engine-tools.md +1 -1
  46. package/dist/client/assets/AgentDetailView-CUtWvXBn.css +0 -1
  47. package/dist/client/assets/AgentDetailView-Dg7Qa1rG.js +0 -18
  48. package/dist/client/assets/ChatView-ODq-kBk6.js +0 -1
  49. package/dist/client/assets/DevServerView-6PS9Lvl7.js +0 -1
  50. package/dist/client/assets/DirectoryPicker-B3dza2Dq.js +0 -1
  51. package/dist/client/assets/DocumentsView-Bu9YYlki.js +0 -1
  52. package/dist/client/assets/PluginManager-Dnf-LhYw.js +0 -1
  53. package/dist/client/assets/ResearchView-Z0TZ7WGo.js +0 -1
  54. package/dist/client/assets/SettingsModal-B6RN9VYe.js +0 -31
  55. package/dist/client/assets/SetupWizardModal-BFc3xID2.js +0 -1
  56. package/dist/client/assets/SkillsView-CipGahOR.js +0 -1
  57. package/dist/client/assets/index-Df1bHDY4.css +0 -1
  58. package/dist/client/assets/index-NFptaeUQ.js +0 -1222
@@ -0,0 +1,15 @@
1
+ {
2
+ "id": "fusion-plugin-paperclip-runtime",
3
+ "name": "Paperclip Runtime Plugin",
4
+ "version": "1.0.0",
5
+ "description": "Provides Paperclip runtime for Fusion AI agents",
6
+ "author": "Fusion Team",
7
+ "homepage": "https://github.com/gsxdsm/fusion",
8
+ "fusionVersion": ">=0.1.0",
9
+ "runtime": {
10
+ "runtimeId": "paperclip",
11
+ "name": "Paperclip Runtime",
12
+ "description": "Paperclip-backed AI session via Paperclip REST API",
13
+ "version": "1.0.0"
14
+ }
15
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@fusion-plugin-examples/paperclip-runtime",
3
+ "version": "0.2.30",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "import": "./bundled.js"
8
+ }
9
+ },
10
+ "private": true
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runfusion/fusion",
3
- "version": "0.21.0",
3
+ "version": "0.22.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",
@@ -73,6 +73,7 @@
73
73
  "@types/react": "^19.0.0",
74
74
  "@vitest/coverage-v8": "^3.1.0",
75
75
  "cross-env": "^7.0.0",
76
+ "esbuild": "^0.25.12",
76
77
  "ink-testing-library": "^4.0.0",
77
78
  "tsup": "^8.5.1",
78
79
  "tsx": "^4.19.0",
@@ -16,7 +16,7 @@ These tools are **not** part of the user-invokable extension surface. They are i
16
16
  | `fn_task_document_read` | triage, executor, heartbeat | Read one task document or list all | `key?` (string) |
17
17
  | `fn_memory_search` | triage, executor, heartbeat | Search project memory plus per-agent layered memory snippets | `query` (string), `limit?` (number) |
18
18
  | `fn_memory_get` | triage, executor, heartbeat | Read a bounded memory file window (including bounded per-agent layered paths) | `path` (string), `startLine?` (number), `lineCount?` (number) |
19
- | `fn_memory_append` | executor, heartbeat (when writable backend enabled) | Append long-term/daily memory notes | `scope?` (`project` \| `agent`), `layer` (`long-term` \| `daily`), `content` (string) |
19
+ | `fn_memory_append` | executor, heartbeat (when writable backend enabled) | Append memory notes with explicit scope: `scope="agent"` for private operating context, `scope="project"` for workspace-wide durable knowledge | `scope?` (`project` \| `agent`), `layer` (`long-term` \| `daily`), `content` (string) |
20
20
  | `fn_research_run` | triage, executor | Start a bounded research run (optionally wait for completion) and return structured findings metadata | `query` (string), `wait_for_completion?` (boolean), `max_wait_ms?` (number) |
21
21
  | `fn_research_list` | triage, executor | List recent research runs with status/summary metadata | `status?` (`pending` \| `running` \| `completed` \| `failed` \| `cancelled`), `limit?` (number) |
22
22
  | `fn_research_get` | triage, executor | Read one research run's structured findings/citations payload | `id` (string) |
@@ -1 +0,0 @@
1
- .agent-detail-overlay{position:fixed;inset:0;background:color-mix(in srgb,var(--bg) 60%,transparent);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;z-index:100;padding:var(--space-lg)}.agent-detail-modal{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;min-width:calc(var(--space-xl) * 20);max-width:calc(100vw - var(--space-2xl) - var(--space-xs) * 2);min-height:calc(var(--space-xl) * 13 + var(--space-sm));max-height:calc(100dvh - var(--space-2xl) - var(--space-xs) * 2);display:flex;flex-direction:column;overflow:hidden;resize:both;box-shadow:var(--shadow-lg)}.agent-detail-modal:not([style*=width]){width:min(calc(var(--space-xl) * 37 + var(--space-md)),calc(100vw - var(--space-2xl) - var(--space-xs) * 2))}.agent-detail-modal:not([style*=height]){height:min(85vh,calc(100dvh - var(--space-2xl) - var(--space-xs) * 2))}.agent-detail-inline-shell{width:100%;height:100%;min-height:0;display:flex;flex-direction:column;overflow:hidden}.agent-detail-inline{width:100%;height:100%;min-height:0;display:flex;flex-direction:column;overflow:hidden;background:var(--surface);border:1px solid var(--border)}.agent-detail-inline-loading{width:100%;height:100%;min-height:0;display:flex;align-items:center;justify-content:center;overflow:hidden}.agent-detail-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-md);padding:calc(var(--space-xl) * 2 + var(--space-md));color:var(--text-muted)}.agent-detail-header{display:flex;align-items:center;justify-content:space-between;gap:var(--space-md);padding:var(--space-md) calc(var(--space-lg) + var(--space-xs));border-bottom:1px solid var(--border);background:var(--bg-secondary)}.agent-detail-identity{display:flex;align-items:center;gap:var(--space-md);flex-shrink:0;min-width:0}.agent-detail-inline-back{display:inline-flex;align-items:center;gap:var(--space-xs);min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs));padding:calc(var(--space-sm) - var(--space-xs) * .5) calc(var(--space-sm) + var(--space-xs) * .5);flex-shrink:0}.agent-detail-icon{width:calc(var(--space-lg) * 2 + var(--space-xs));height:calc(var(--space-lg) * 2 + var(--space-xs));border-radius:var(--radius-md);background:var(--todo);display:flex;align-items:center;justify-content:center;color:var(--text);flex-shrink:0}.agent-detail-info{min-width:0}.agent-detail-info h2{font-size:calc(var(--space-md) + var(--space-xs));font-weight:600;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.agent-detail-badges{display:flex;gap:var(--space-xs);margin-top:calc(var(--space-xs) * .5)}.agent-detail-header-actions{display:flex;align-items:center;justify-content:flex-end;gap:var(--space-sm);flex:1 1 auto;min-width:0}.agent-detail-controls{display:flex;align-items:center;gap:calc(var(--space-xs) + var(--space-sm) * .25);flex-shrink:0}.btn--compact{padding:calc(var(--space-xs) + var(--space-xs) * .25) calc(var(--space-sm) + var(--space-xs) * .5);font-size:var(--space-md);gap:var(--space-xs)}.agent-detail-utility-actions{display:flex;align-items:center;gap:var(--space-xs);flex-shrink:0}.agent-detail-import-btn{min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-title{display:flex;align-items:center;gap:var(--space-lg)}.agent-detail-actions{display:flex;align-items:center;gap:var(--space-sm)}.agent-detail-tabs{display:flex;gap:var(--space-xs);padding:0 calc(var(--space-lg) + var(--space-xs));border-bottom:1px solid var(--border);background:var(--bg-secondary)}.agent-detail-tab{display:flex;align-items:center;gap:var(--space-xs);padding:calc(var(--space-sm) + var(--space-xs) * .5) var(--space-md);background:none;border:none;border-bottom:calc(var(--space-xs) * .5) solid transparent;color:var(--text-muted);font-size:calc(var(--space-sm) + var(--space-xs) + var(--space-xs) * .25);cursor:pointer;transition:all var(--transition-fast)}.agent-detail-tab:hover{color:var(--text);background:var(--card-hover)}.agent-detail-tab.active{color:var(--todo);border-bottom-color:var(--todo)}.agent-detail-tab:focus-visible{outline:none;box-shadow:var(--focus-ring-strong);background:color-mix(in srgb,var(--todo) 12%,transparent);color:var(--text);border-radius:var(--radius-sm)}.agent-detail-content{flex:1;overflow-y:auto;padding:var(--space-xl)}.agent-detail-footer{display:flex;align-items:center;gap:var(--space-sm);padding:var(--space-md) var(--space-xl);border-top:1px solid var(--border);background:var(--bg-secondary);font-size:var(--space-md);color:var(--text-muted)}.agent-detail-id{font-family:var(--font-mono);cursor:pointer}.agent-detail-id:hover{color:var(--text)}.dashboard-tab{display:flex;flex-direction:column;gap:var(--space-xl)}.dashboard-summary-layout{padding-bottom:var(--space-md)}.dashboard-summary-health-reason{margin-left:var(--space-xs);font-size:calc(var(--space-sm) + var(--space-xs))}.dashboard-summary-card{background:var(--card);border:1px solid var(--border);border-radius:var(--radius-lg);padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-md)}.budget-warning-banner{display:flex;gap:var(--space-sm);align-items:flex-start;border:1px solid var(--color-warning);background:color-mix(in srgb,var(--color-warning) 12%,transparent);border-radius:var(--radius-md);padding:var(--space-md)}.dashboard-summary-hero__heading{display:flex;align-items:center;gap:var(--space-sm)}.dashboard-summary-hero__heading h3{margin:0;font-size:calc(var(--space-lg) + var(--space-xs) * .5);font-weight:600}.dashboard-summary-hero__meta{display:flex;flex-wrap:wrap;gap:var(--space-md);color:var(--text-muted)}.dashboard-summary-skills{display:inline-flex;align-items:center;gap:var(--space-sm)}.dashboard-summary-skill-badges{display:inline-flex;flex-wrap:wrap;gap:var(--space-xs)}.dashboard-summary-skill-badge{max-width:calc(var(--space-xl) * 8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dashboard-summary-skill-badge-btn{cursor:pointer}.dashboard-summary-skill-badge-btn:focus-visible{outline:none;box-shadow:var(--focus-ring-strong)}.dashboard-summary-skill-badge--selected{border-color:var(--todo);background:color-mix(in srgb,var(--todo) 20%,transparent)}.dashboard-summary-skill-detail{margin-top:var(--space-sm);border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface);padding:var(--space-md);display:flex;flex-direction:column;gap:var(--space-sm)}.dashboard-summary-skill-detail-header{display:flex;align-items:center;justify-content:space-between;gap:var(--space-sm)}.dashboard-summary-skill-detail-title{font-weight:600;color:var(--text)}.dashboard-summary-skill-detail-loading,.dashboard-summary-skill-detail-empty{display:inline-flex;align-items:center;gap:var(--space-xs);color:var(--text-muted)}.dashboard-summary-skill-detail-error{display:flex;align-items:center;flex-wrap:wrap;gap:var(--space-xs);color:var(--color-error)}.dashboard-summary-skill-detail-content{margin:0;padding:var(--space-sm);border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--card);color:var(--text);white-space:pre-wrap;word-break:break-word;max-height:calc(var(--space-2xl) * 6);overflow:auto}.dashboard-summary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(calc(var(--space-xl) * 6 + var(--space-sm)),1fr));gap:var(--space-md)}.dashboard-summary-grid p{margin:0}.dashboard-summary-label{font-size:calc(var(--space-sm) + var(--space-xs) * .5);color:var(--text-muted)}.dashboard-summary-health-row{display:inline-flex;align-items:center;gap:var(--space-xs)}.dashboard-summary-health-reason{margin-left:var(--space-xs);font-size:var(--space-md)}.runs-list{display:flex;flex-direction:column;gap:var(--space-sm)}.run-item{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:var(--space-sm)}.dashboard-section{background:var(--bg-secondary);border-radius:var(--radius-md);padding:calc(var(--space-lg) + var(--space-xs))}.dashboard-section h3{font-size:calc(var(--space-md) + var(--space-xs) * .5);font-weight:600;margin:0 0 var(--space-lg) 0;color:var(--text-muted);text-transform:uppercase;letter-spacing:calc(var(--space-xs) * .125)}.info-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(calc(var(--space-xl) * 7 + var(--space-sm)),1fr));gap:var(--space-lg)}.info-item{display:flex;flex-direction:column;gap:var(--space-xs)}.info-label{font-size:var(--space-md);color:var(--text-muted)}.info-value{font-size:calc(var(--space-md) + var(--space-xs) * .5);font-weight:500}.inline-badge{display:inline-block;padding:calc(var(--space-xs) * .5) var(--space-sm);border-radius:var(--radius-sm);font-size:var(--space-md);text-transform:capitalize}.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:var(--space-lg)}.stat-card{background:var(--surface);border-radius:var(--radius-md);padding:var(--space-lg);text-align:center}.stat-value{font-size:calc(var(--space-lg) + var(--space-xs) * .5);font-weight:700;color:var(--todo)}.stat-label{font-size:calc(var(--space-sm) + var(--space-xs) * .5);color:var(--text-muted);margin-top:var(--space-xs)}.current-task{display:flex;align-items:center;gap:var(--space-md)}.task-badge{font-family:var(--font-mono);background:var(--surface);padding:var(--space-sm) var(--space-md);border-radius:var(--radius-sm);font-size:calc(var(--space-md) + var(--space-xs) * .25)}.metadata-json{background:var(--surface);padding:var(--space-md);border-radius:var(--radius-sm);font-size:var(--space-md);overflow-x:auto;margin:0}.logs-tab{display:flex;flex-direction:column;height:100%}.logs-header{display:flex;align-items:center;justify-content:space-between;padding-bottom:var(--space-md);margin-bottom:var(--space-md);border-bottom:1px solid var(--border)}.logs-count{font-size:var(--space-md);color:var(--text-muted)}.streaming-indicator{display:flex;align-items:center;gap:calc(var(--space-xs) + var(--space-sm) * .25);font-size:var(--space-md);color:var(--color-success)}.streaming-dot{width:var(--space-sm);height:var(--space-sm);background:var(--color-success);border-radius:50%;animation:pulse 1.5s infinite}.logs-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:calc(var(--space-2xl) + var(--space-lg));color:var(--text-muted);text-align:center}.logs-empty p{margin:var(--space-sm) 0 0 0}.runs-tab{display:flex;flex-direction:column;gap:var(--space-md)}.runs-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:calc(var(--space-2xl) + var(--space-lg));color:var(--text-muted);text-align:center}.runs-empty p{margin:var(--space-sm) 0 0 0}.run-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-lg)}.run-card--active{border-color:var(--in-progress);background:color-mix(in srgb,var(--in-progress) 5%,transparent)}.run-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:var(--space-sm)}.run-live-indicator{display:flex;align-items:center;gap:calc(var(--space-xs) + var(--space-sm) * .25);font-weight:600;color:var(--in-progress)}.live-dot{width:var(--space-sm);height:var(--space-sm);background:var(--in-progress);border-radius:50%;animation:pulse 1.5s infinite}.run-id{font-family:var(--font-mono);font-size:calc(var(--space-md) + var(--space-xs) * .25);color:var(--text-muted)}.run-status{display:flex;align-items:center;gap:calc(var(--space-xs) + var(--space-sm) * .25);font-size:calc(var(--space-md) + var(--space-xs) * .25);text-transform:capitalize}.run-status.active{color:var(--in-progress)}.run-status.completed{color:var(--color-success)}.run-status.failed{color:var(--color-error)}.run-status.terminated{color:var(--text-muted)}.run-details{display:flex;gap:var(--space-sm);font-size:var(--space-md);color:var(--text-muted)}.run-logs-container{padding:var(--space-md);background:var(--bg-secondary);border-top:1px solid var(--border);border-bottom:1px solid var(--border)}.run-details-loading-state{display:flex;align-items:center;gap:var(--space-sm);padding:var(--space-sm) 0}.run-output-sections{margin-bottom:var(--space-md)}.run-output-section{margin-bottom:var(--space-sm)}.run-output-label{margin-bottom:var(--space-xs);color:var(--text-muted);font-size:calc(var(--space-sm) + var(--space-xs));font-weight:600;letter-spacing:calc(var(--space-xs) * .1);text-transform:uppercase}.run-output-label--error{color:var(--color-error)}.run-output-panel{margin:0;max-height:calc(var(--space-2xl) * 6.25);overflow:auto;border-radius:var(--radius-sm);padding:var(--space-sm) var(--space-md);background:var(--surface);border:1px solid var(--border);white-space:pre-wrap;word-break:break-word;font-size:calc(var(--space-sm) + var(--space-xs));line-height:1.5}.run-output-panel--error{color:var(--color-error);border-color:color-mix(in srgb,var(--color-error) 35%,var(--border));background:color-mix(in srgb,var(--color-error) 10%,transparent)}.run-context-grid{display:flex;flex-wrap:wrap;gap:var(--space-xs) var(--space-md);font-size:calc(var(--space-sm) + var(--space-xs))}.run-context-item{line-height:1.5}.run-output-empty{padding:var(--space-sm) 0;font-style:italic;font-size:calc(var(--space-sm) + var(--space-xs))}.run-agent-logs-section{margin-top:var(--space-xs);padding-top:var(--space-sm);border-top:1px solid var(--border)}.agent-tasks-list{display:flex;flex-direction:column;gap:var(--space-sm)}.agent-task-item{display:flex;flex-direction:column;gap:calc(var(--space-xs) + var(--space-sm) * .25);padding:var(--space-md) calc(var(--space-md) + var(--space-xs) * .5);border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-secondary);text-decoration:none;transition:background var(--transition-fast),border-color var(--transition-fast)}.agent-task-item:hover{background:var(--card-hover);border-color:var(--text-dim)}.agent-task-row{display:flex;align-items:center;justify-content:space-between;gap:var(--space-sm)}.agent-task-id{font-family:var(--font-mono);font-size:var(--space-md);font-weight:600;color:var(--todo)}.agent-task-title{font-size:calc(var(--space-md) + var(--space-xs) * .5);font-weight:500;color:var(--text);line-height:1.4}.agent-task-status{font-size:var(--space-md);color:var(--text-muted)}.agent-task-column{display:inline-flex;align-items:center;padding:calc(var(--space-xs) * .5) var(--space-sm);border-radius:var(--radius-pill);font-size:calc(var(--space-sm) + var(--space-xs) * .5);font-weight:700;text-transform:uppercase;letter-spacing:calc(var(--space-xs) * .1)}.agent-task-column.column-triage{color:var(--triage);background:color-mix(in srgb,var(--triage) 18%,transparent)}.agent-task-column.column-todo{color:var(--todo);background:color-mix(in srgb,var(--todo) 18%,transparent)}.agent-task-column.column-in-progress{color:var(--in-progress);background:color-mix(in srgb,var(--in-progress) 18%,transparent)}.agent-task-column.column-in-review{color:var(--in-review);background:color-mix(in srgb,var(--in-review) 18%,transparent)}.agent-task-column.column-done{color:var(--done);background:color-mix(in srgb,var(--done) 18%,transparent)}.agent-task-column.column-archived{color:var(--text-muted);background:color-mix(in srgb,var(--text-muted) 18%,transparent)}.agent-tasks-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-sm);padding:calc(var(--space-2xl) + var(--space-lg));color:var(--text-muted);text-align:center}.agent-tasks-empty p{margin:0}.config-tab{display:flex;flex-direction:column;gap:var(--space-xl)}.config-section{background:var(--bg-secondary);border-radius:var(--radius-md);padding:calc(var(--space-md) + var(--space-sm))}.config-section h3{font-size:calc(var(--space-md) + var(--space-xs));font-weight:600;margin:0 0 var(--space-sm) 0}.config-section--danger{border:1px solid color-mix(in srgb,var(--color-error) 40%,transparent)}.config-danger-note{font-size:calc(var(--space-sm) + var(--space-xs) * .75);color:var(--text-muted)}.agent-content-toolbar{display:flex;align-items:center;gap:var(--space-md);padding:var(--space-sm) var(--space-lg);border-bottom:1px solid var(--border);background:var(--surface);flex-shrink:0}.agent-content-mode-toggle{display:flex;align-items:center;gap:var(--space-xs)}.agent-content-mode-toggle .btn{display:inline-flex;align-items:center;gap:calc(var(--space-xs) + var(--space-sm) * .25)}.agent-content-preview{overflow-y:auto;padding:var(--space-lg);min-height:150px}.agent-content-placeholder{color:var(--text-muted);text-align:center;padding:var(--space-xl);min-height:150px;display:flex;align-items:center;justify-content:center}.config-description{font-size:calc(var(--space-md) + var(--space-xs) * .5);color:var(--text-muted);margin:0 0 calc(var(--space-md) + var(--space-sm)) 0}.config-fields{display:flex;flex-direction:column;gap:var(--space-lg)}.config-field{display:flex;flex-direction:column;gap:calc(var(--space-xs) + var(--space-sm) * .25)}.config-field label{font-size:calc(var(--space-md) + var(--space-xs) * .25);font-weight:500}.config-runtime-tabs{display:grid;grid-template-columns:1fr 1fr;gap:var(--space-sm);margin-bottom:var(--space-md)}.config-runtime-tab{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--card);color:var(--text-muted);padding:var(--space-sm) var(--space-md);font-size:calc(var(--space-sm) + var(--space-xs));font-weight:600;cursor:pointer;transition:border-color var(--transition-fast),background var(--transition-fast),color var(--transition-fast),box-shadow var(--transition-fast)}.config-runtime-tab:hover{border-color:var(--todo);color:var(--text);background:var(--card-hover)}.config-runtime-tab:focus-visible{outline:none;border-color:var(--todo);box-shadow:var(--focus-ring-strong)}.config-runtime-tab.active{border-color:var(--todo);color:var(--text);background:color-mix(in srgb,var(--todo) 12%,transparent)}.config-hint{font-size:calc(var(--space-sm) + var(--space-xs) * .75);color:var(--text-muted);font-style:italic}.config-error{font-size:calc(var(--space-sm) + var(--space-xs) * .75);color:var(--color-error)}.input--error{border-color:var(--color-error)!important}.config-actions{display:flex;align-items:center;gap:var(--space-md);margin-top:calc(var(--space-md) + var(--space-sm));padding-top:var(--space-lg);border-top:1px solid var(--border)}.config-saved-indicator{display:flex;align-items:center;gap:calc(var(--space-sm) - var(--space-xs) * .5);font-size:calc(var(--space-md) + var(--space-xs) * .25);color:var(--color-success)}.config-saved-indicator--error{color:var(--color-error)}.heartbeat-procedure-actions{margin-top:var(--space-sm)}.heartbeat-procedure-viewer{margin-top:var(--space-lg)}.heartbeat-procedure-status{display:inline-flex;align-items:center;gap:var(--space-xs);margin-left:auto}.heartbeat-procedure-status--warning{color:var(--color-warning)}.rating-summary-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius-md);padding:calc(var(--space-md) + var(--space-sm));display:flex;flex-direction:column;gap:var(--space-md)}.rating-score-display{display:flex;align-items:center;gap:var(--space-md)}.rating-average{font-size:var(--space-2xl);font-weight:700;line-height:1}.rating-stats{display:flex;align-items:center;gap:var(--space-md)}.rating-count{font-size:calc(var(--space-md) + var(--space-xs) * .5);color:var(--text-muted)}.rating-trend-badge{font-size:var(--space-md);padding:var(--space-xs) calc(var(--space-md) - var(--space-xs) * .5);border-radius:var(--radius-lg);font-weight:500}.trend-improving{background:color-mix(in srgb,var(--color-success) 15%,transparent);color:var(--color-success)}.trend-declining{background:color-mix(in srgb,var(--color-error) 15%,transparent);color:var(--color-error)}.trend-stable{background:color-mix(in srgb,var(--color-warning) 15%,transparent);color:var(--color-warning)}.trend-insufficient{background:var(--bg-tertiary);color:var(--text-muted)}.category-breakdown{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-lg)}.category-breakdown h4{margin:0 0 var(--space-md) 0;font-size:calc(var(--space-md) + var(--space-xs) * .25);font-weight:600}.category-breakdown .category-item{display:flex;justify-content:space-between;align-items:center;padding:var(--space-sm) 0;border-bottom:1px solid var(--border)}.category-breakdown .category-item:last-child{border-bottom:none}.category-name{text-transform:capitalize;font-size:calc(var(--space-md) + var(--space-xs) * .25)}.category-score{font-weight:600;font-size:calc(var(--space-md) + var(--space-xs) * .25)}.add-rating-form{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-md)}.add-rating-form h4{margin:0;font-size:calc(var(--space-md) + var(--space-xs) * .25);font-weight:600}.star-selector{display:flex;gap:var(--space-xs)}.star-btn{background:none;border:none;padding:var(--space-xs);cursor:pointer;border-radius:var(--radius-sm);color:var(--text-muted);transition:background-color var(--transition-fast),color var(--transition-fast)}.star-btn:hover{background:var(--card-hover)}.star-btn:focus-visible{outline:none;box-shadow:var(--focus-ring-strong)}.rating-stars{display:inline-flex;gap:var(--space-xs)}.rating-stars .star-filled{color:var(--color-warning)}.rating-stars .star-empty{color:var(--text-muted)}.add-rating-form .add-rating-category-select,.add-rating-form .add-rating-comment-input{width:100%}.add-rating-form .add-rating-comment-input{resize:vertical;min-height:calc(var(--space-xl) + var(--space-2xl))}.rating-history{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-lg);max-height:calc(var(--space-xl) * 12 + var(--space-md));overflow-y:auto}.rating-history h4{margin:0 0 var(--space-md) 0;font-size:calc(var(--space-md) + var(--space-xs) * .25);font-weight:600}.rating-history .no-ratings{color:var(--text-muted);font-size:calc(var(--space-md) + var(--space-xs) * .25);text-align:center;padding:var(--space-lg)}.rating-history-item{padding:var(--space-md) 0;border-bottom:1px solid var(--border)}.rating-history-item:last-child{border-bottom:none}.rating-item-header{display:flex;align-items:center;gap:var(--space-sm);flex-wrap:wrap}.rating-category-badge{font-size:calc(var(--space-sm) + var(--space-xs) * .5);padding:calc(var(--space-xs) * .5) var(--space-sm);background:var(--card-hover);border-radius:var(--radius-pill);text-transform:capitalize}.rating-time{font-size:calc(var(--space-sm) + var(--space-xs) * .5);color:var(--text-muted);margin-left:auto}.rating-delete-btn{background:none;border:none;padding:var(--space-xs);cursor:pointer;color:var(--text-muted);border-radius:var(--radius-sm);transition:color var(--transition-fast),background-color var(--transition-fast)}.rating-delete-btn:hover{color:var(--color-error);background:color-mix(in srgb,var(--color-error) 10%,transparent)}.rating-comment{margin:var(--space-sm) 0 0 0;font-size:calc(var(--space-sm) + var(--space-xs));color:var(--text-muted);line-height:1.4}.runs-loading-row{display:flex;align-items:center;justify-content:center;gap:var(--space-sm);padding:var(--space-xl)}.runs-toolbar{padding:var(--space-sm) var(--space-lg);border-bottom:1px solid var(--border)}.runs-toolbar--between{display:flex;justify-content:space-between;align-items:center}.runs-toolbar-meta{font-size:calc(var(--space-sm) + var(--space-xs));color:var(--text-muted)}.run-card--clickable{cursor:pointer}.run-card--clickable:focus-visible{outline:none;box-shadow:var(--focus-ring-strong)}.run-header-group{display:flex;align-items:center;gap:var(--space-sm)}.run-badge--compact{font-size:calc(var(--space-sm) + var(--space-xs) * .5);padding:calc(var(--space-xs) * .25) calc(var(--space-sm) * .75)}.run-output-summary{cursor:pointer;user-select:none}.run-live-indicator--with-margin{margin-left:var(--space-sm)}.detail-section-body--loading{display:flex;align-items:center;gap:var(--space-sm)}.agent-empty--padded{padding:var(--space-xl)}.logs-fallback-label{font-size:calc(var(--space-sm) + var(--space-xs))}.config-textarea-mono{font-family:var(--font-mono);font-size:calc(var(--space-md) + var(--space-xs) * .25);resize:vertical}.config-textarea-top-spacing{margin-top:var(--space-sm)}.config-hint--block-spacing{margin-bottom:var(--space-md)}.config-hint--block{display:block;margin-bottom:var(--space-sm)}.config-hint--top-spacing{margin-top:var(--space-sm)}.config-hint--inline-loader{display:inline-flex;gap:var(--space-xs);margin-top:var(--space-sm)}.config-inline-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--space-sm)}.config-hint--inline-tight{display:flex;align-items:center;gap:var(--space-xs)}.config-hint--warning{color:var(--color-warning)}@media(max-width:768px){.config-runtime-tabs{grid-template-columns:1fr}.agent-detail-overlay{padding:0;align-items:stretch}.agent-detail-modal{min-width:0!important;min-height:0!important;width:100vw!important;height:100dvh!important;max-width:100vw!important;max-height:100dvh;margin:0;border-radius:0;border:none;resize:none}.agent-detail-header{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;column-gap:var(--space-xs);row-gap:0;padding:var(--space-sm) var(--space-md);padding-top:max(var(--space-sm),env(safe-area-inset-top,0))}.agent-detail-identity{grid-column:1;grid-row:1;flex:1 1 auto;min-width:0;gap:var(--space-sm)}.agent-detail-icon{width:calc(var(--space-lg) * 2);height:calc(var(--space-lg) * 2);flex-shrink:0}.agent-detail-icon svg{width:calc(var(--space-sm) + var(--space-xs) * 2);height:calc(var(--space-sm) + var(--space-xs) * 2)}.agent-detail-info h2{font-size:calc(var(--space-md) + var(--space-xs) * .75);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.agent-detail-badges{flex-wrap:wrap}.agent-detail-header-actions{grid-column:2;grid-row:1;flex:0 0 auto;justify-content:flex-end;gap:calc(var(--space-xs) * .5)}.agent-detail-controls{flex:0 0 auto;gap:calc(var(--space-xs) * .5)}.agent-detail-controls .btn--compact{padding:calc(var(--space-sm) - var(--space-xs) * .5) calc(var(--space-md) - var(--space-xs) * .5);font-size:var(--space-md);min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-controls .agent-detail-mobile-icon-control{min-width:calc(var(--space-lg) + var(--space-md) + var(--space-xs));padding-left:calc(var(--space-sm) - var(--space-xs) * .5);padding-right:calc(var(--space-sm) - var(--space-xs) * .5)}.agent-detail-controls .agent-detail-mobile-icon-control .agent-detail-control-label{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.agent-detail-controls .btn--compact svg{width:calc(var(--space-md) + var(--space-xs) * .5);height:calc(var(--space-md) + var(--space-xs) * .5)}.agent-detail-utility-actions{flex-shrink:0;margin-left:0}.agent-detail-utility-actions .btn-icon{min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs));min-width:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-import-btn{min-width:calc(var(--space-xl) * 3 + var(--space-xs))}.agent-detail-title{flex:1 1 auto;min-width:0;gap:var(--space-md)}.agent-detail-actions{flex:1 1 100%;flex-wrap:wrap;gap:calc(var(--space-xs) + var(--space-sm) * .25)}.agent-detail-actions .btn{padding:calc(var(--space-sm) - var(--space-xs) * .5) calc(var(--space-md) - var(--space-xs) * .5);font-size:calc(var(--space-md) + var(--space-xs) * .25);min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-actions .btn svg{width:calc(var(--space-sm) + var(--space-xs) * 1.5);height:calc(var(--space-sm) + var(--space-xs) * 1.5)}.agent-detail-actions .btn-icon{min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs));min-width:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-tabs{padding:0;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none}.agent-detail-tabs::-webkit-scrollbar{display:none}.agent-detail-tab{padding:var(--space-md) calc(var(--space-md) + var(--space-xs) * .5);font-size:calc(var(--space-md) + var(--space-xs) * .25);white-space:nowrap;min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.agent-detail-content{padding:var(--space-lg)}.agent-detail-footer{flex-wrap:wrap;gap:var(--space-sm);padding:var(--space-sm) var(--space-lg);padding-bottom:max(var(--space-sm),env(safe-area-inset-bottom,0));font-size:calc(var(--space-sm) + var(--space-xs) * .75)}.agent-detail-id{max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dashboard-tab{gap:var(--space-lg)}.dashboard-summary-skills,.dashboard-summary-skill-detail-header{flex-direction:column;align-items:flex-start}.dashboard-section{padding:var(--space-lg)}.info-grid{grid-template-columns:repeat(2,1fr);gap:var(--space-md)}.stats-grid{grid-template-columns:repeat(3,1fr);gap:var(--space-md)}.stat-value{font-size:calc(var(--space-lg) + var(--space-xs) * .5)}.logs-empty{padding:var(--space-2xl) var(--space-lg)}.run-card{padding:var(--space-md)}.run-header{flex-wrap:wrap;gap:calc(var(--space-xs) + var(--space-sm) * .25)}.run-details{flex-wrap:wrap}.run-logs-container{padding:var(--space-sm)}.run-output-panel{max-height:calc(var(--space-2xl) * 5)}.run-context-grid{flex-direction:column;gap:var(--space-xs)}.run-details .text-muted{min-width:0;overflow-wrap:anywhere}.config-tab{gap:var(--space-lg)}.config-section{padding:var(--space-lg)}.config-section .input,.config-section .select,.config-section textarea{font-size:calc(var(--space-md) + var(--space-xs));min-height:calc(var(--space-lg) + var(--space-md) + var(--space-xs))}.config-actions{flex-direction:column;align-items:stretch;gap:var(--space-sm)}.config-actions .btn{width:100%;justify-content:center}.heartbeat-procedure-status{margin-left:0}}@media(max-width:480px){.info-grid,.stats-grid{grid-template-columns:1fr}.agent-detail-actions{flex-direction:column;width:100%}.agent-detail-actions .btn{width:100%;justify-content:center}.agent-detail-actions .btn-icon{align-self:flex-end}.agent-detail-footer .divider,.agent-detail-footer .text-muted,.agent-detail-footer .link{display:none}}@media(max-width:768px){.agent-dialog-overlay{padding:0;align-items:stretch}.agent-dialog{width:100vw!important;height:100dvh;max-width:100%!important;max-height:100dvh;border-radius:0;border:none}.agent-dialog-header{padding:max(var(--space-md),env(safe-area-inset-top,0px)) var(--space-lg) var(--space-md) var(--space-lg);flex-shrink:0}.agent-dialog-body{padding:var(--space-lg);-webkit-overflow-scrolling:touch}.agent-dialog-footer{padding:var(--space-md) var(--space-lg);padding-bottom:max(var(--space-md),env(safe-area-inset-bottom,0px));flex-wrap:wrap;gap:var(--space-sm)}.agent-dialog-field .input,.agent-dialog-field .select,.agent-dialog-field textarea{font-size:calc(var(--space-md) + var(--space-xs));min-height:calc(var(--space-lg) * 2 + var(--space-xs))}.agent-dialog-summary-row{flex-direction:column;gap:calc(var(--space-xs) * .5)}.agent-dialog-summary-row>span:first-child,.agent-dialog-summary-row-label{width:auto}.agent-dialog-steps{padding:var(--space-sm) var(--space-lg)}.agent-dialog-step{flex:1;width:auto;height:calc(var(--space-xs) - var(--space-xs) * .25)}.agent-dialog-tabs{grid-template-columns:1fr;gap:calc(var(--space-sm) - var(--space-xs) * .5);margin-bottom:var(--space-md)}.agent-dialog-tab{min-height:calc(var(--space-lg) * 2 + var(--space-xs));text-align:left}.agent-import-file-upload{flex-direction:column;align-items:stretch;gap:var(--space-sm)}.agent-import-textarea{font-size:calc(var(--space-md) + var(--space-xs));min-height:calc(var(--space-xl) * 4 + var(--space-xs))}.agent-import-agent-list{max-height:calc(100dvh - (var(--space-xl) * 10 + var(--space-lg)))}.agent-import-result-stats{flex-direction:column;gap:var(--space-sm);align-items:center}.agent-import-browse-list{max-height:calc(100dvh - (var(--space-xl) * 10 + var(--space-lg)))}.agent-import-skill-list{max-height:calc(100dvh - (var(--space-xl) * 15 + var(--space-md)))}}@media(max-width:480px){.agent-dialog-body{padding:var(--space-md)}.agent-dialog-footer{flex-direction:column}.agent-dialog-footer .btn{width:100%;justify-content:center}}.reflections-tab{padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-lg)}.reflections-header{display:flex;align-items:center;justify-content:space-between;gap:var(--space-md)}.reflections-header h3{display:flex;align-items:center;gap:var(--space-sm);font-size:1rem;font-weight:600;color:var(--text)}.reflections-stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:var(--space-md)}.reflections-stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-md);text-align:center}.reflections-stat-card .stat-value{display:flex;align-items:center;justify-content:center;gap:var(--space-sm);font-size:1.5rem;font-weight:700;color:var(--text);margin-bottom:var(--space-xs)}.reflections-stat-card .stat-label{font-size:.75rem;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.05em}.reflections-no-data{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-sm);padding:var(--space-xl);color:var(--text-secondary);text-align:center}.reflections-list{display:flex;flex-direction:column;gap:var(--space-md)}.reflections-loading-indicator{display:flex;align-items:center;justify-content:center;gap:var(--space-sm);padding:var(--space-lg)}.reflections-ratings-section{display:flex;flex-direction:column;gap:var(--space-md)}.reflections-ratings-section>h4,.reflections-list h4{font-size:.875rem;font-weight:600;color:var(--text);margin-bottom:var(--space-xs)}.reflection-cards{display:flex;flex-direction:column;gap:var(--space-sm)}.reflection-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-md);padding:var(--space-md);cursor:pointer;transition:border-color .15s,background-color .15s}.reflection-card:hover{border-color:var(--border-active);background:var(--card-hover)}.reflection-card:focus-visible{outline:none;box-shadow:var(--focus-ring-strong)}.reflection-card--expanded{border-color:var(--color-primary)}.reflection-card-header{display:flex;align-items:center;gap:var(--space-sm);margin-bottom:var(--space-sm)}.reflection-trigger-badge{font-size:.7rem;font-weight:600;padding:2px 6px;border-radius:var(--radius-sm);text-transform:uppercase;letter-spacing:.05em}.reflection-trigger-periodic{background:color-mix(in srgb,var(--color-info) 15%,transparent);color:var(--color-info)}.reflection-trigger-post-task{background:color-mix(in srgb,var(--color-success) 15%,transparent);color:var(--color-success)}.reflection-trigger-manual{background:color-mix(in srgb,var(--color-primary) 15%,transparent);color:var(--color-primary)}.reflection-trigger-user-requested{background:color-mix(in srgb,var(--color-warning) 15%,transparent);color:var(--color-warning)}.reflection-timestamp{font-size:.75rem;color:var(--text-muted);flex:1}.reflection-chevron{color:var(--text-muted)}.reflection-summary{font-size:.875rem;color:var(--text);line-height:1.5}.reflection-details{margin-top:var(--space-md);padding-top:var(--space-md);border-top:1px solid var(--border);display:flex;flex-direction:column;gap:var(--space-md)}.reflection-insights h5,.reflection-suggestions h5{display:flex;align-items:center;gap:var(--space-xs);font-size:.8rem;font-weight:600;color:var(--text);margin-bottom:var(--space-xs)}.reflection-insights ul,.reflection-suggestions ul{list-style:none;display:flex;flex-direction:column;gap:var(--space-xs)}.reflection-insights li,.reflection-suggestions li{font-size:.8rem;color:var(--text-secondary);padding-left:var(--space-md);position:relative}.reflection-insights li:before{content:"•";position:absolute;left:4px;color:var(--color-success)}.reflection-suggestions li:before{content:"→";position:absolute;left:0;color:var(--color-primary)}.reflection-metrics{background:var(--bg);border-radius:var(--radius-sm);padding:var(--space-sm)}.reflection-metrics h5{font-size:.75rem;font-weight:600;color:var(--text-muted);margin-bottom:var(--space-xs)}.metrics-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));gap:var(--space-sm)}.metric{display:flex;flex-direction:column;gap:2px}.metric-label{font-size:.7rem;color:var(--text-muted)}.metric-value{font-size:.875rem;font-weight:600;color:var(--text)}.reflection-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-sm);padding:var(--space-2xl);color:var(--text-secondary);text-align:center}.reflection-empty p{font-size:.875rem}@media(max-width:768px){.reflections-header{flex-wrap:wrap;align-items:flex-start}.reflections-header .btn{width:100%;justify-content:center}}.budget-progress-container{margin-top:4px}.budget-progress-bar{width:100%;height:8px;background:var(--bg-secondary, #161b22);border-radius:4px;overflow:hidden;margin-top:4px}.budget-progress-bar__fill{height:100%;border-radius:4px;transition:width .3s ease,background-color .3s ease}.budget-progress-bar__fill--green{background:var(--state-active-text, #3fb950)}.budget-progress-bar__fill--amber{background:var(--state-paused-text, #e3b541)}.budget-progress-bar__fill--red{background:var(--state-error-text, #f85149)}.budget-progress-label{font-size:.75rem;color:var(--text-secondary, #8b949e);margin-top:4px;display:block}.budget-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:12px;font-size:.75rem;font-weight:500}.budget-warning-banner{display:flex;align-items:center;gap:8px;padding:8px 12px;border-radius:6px;background:var(--state-error-bg, rgba(248,81,73,.15));color:var(--state-error-text, #f85149);border:1px solid var(--state-error-border, #f85149);font-size:.875rem;margin-bottom:12px}.btn-reset-budget{margin-top:8px}.chat-sidebar-footer{display:none}@media(max-width:768px){.chat-view{flex-direction:column}.chat-sidebar{width:100%;min-width:100%;height:100%;max-height:none;border-right:none;border-bottom:1px solid var(--border);flex-direction:column}.chat-sidebar-header,.chat-sidebar-search{display:none}.chat-sidebar-list{flex:1;min-height:0;overflow-y:auto}.chat-sidebar-footer{display:flex;padding:var(--space-md);border-top:1px solid var(--border);background:var(--bg-secondary)}.chat-sidebar-footer-btn{flex:1;justify-content:center}.chat-sidebar--hidden{display:none}.chat-message{max-width:90%}.chat-new-dialog{width:95vw;margin:16px}.chat-thread-header{padding:8px 12px}.chat-skill-menu{left:var(--space-md);right:calc(var(--space-md) + var(--mobile-nav-height));min-width:0;max-width:none}}@media(max-width:768px){.file-mention-popup{max-height:200px}.file-mention-popup-item{min-height:36px;padding:10px 12px}.agent-mention-popup{max-width:280px;min-width:200px}}
@@ -1,18 +0,0 @@
1
- import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{h as cs,c_ as et,c$ as st,d0 as tt,d1 as at,V as _,R as os,T as Ss,d2 as nt,L as ss,a7 as $e,C as Es,e as Ls,d3 as it,d4 as rt,d5 as lt,b1 as $s,c7 as ct,d6 as ot,cb as Z,d7 as dt,d8 as Ds,d9 as Ps,z as Ue,aA as ut,aB as is,a4 as Ve,da as ks,a5 as De,a8 as mt,X as zs,F as Pe,a2 as Je,db as Bs,dc as Hs,dd as ht,c1 as ft,a3 as gt,b4 as xt,s as Os,de as bt,df as vt,dg as pt,dh as jt,di as rs,dj as Is,dk as Nt,dl as ts,b7 as yt,dm as St,q as kt,dn as _s,dp as Ct,p as re,dq as Vs,dr as Rt,ds as wt,dt as Ft,du as We,d as Ke,M as Ye,r as Xe,c as Us,dv as Mt,dw as At,ak as Tt,aJ as Et,aK as Cs,dx as Lt,dy as $t,aL as Dt,dz as ls,dA as Pt,dB as zt,dC as Bt,dD as Ht,dE as Js,dF as Ot,dG as It,dH as _t,dI as Vt}from"./index-NFptaeUQ.js";import{S as Gs}from"./star-B314SwLA.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 Ut=[["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"}]],Ge=cs("chart-column",Ut);/**
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 Jt=[["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"}]],Gt=cs("square-activity",Jt);/**
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 qt=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Wt=cs("trending-down",qt);function Rs(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 Kt(s){return`${Math.round(s*100)}%`}function ws(s){const n=Date.now(),i=new Date(s).getTime(),c=n-i;if(c<0){const u=Math.abs(c);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 c<6e4?"just now":c<36e5?`${Math.floor(c/6e4)}m ago`:c<864e5?`${Math.floor(c/36e5)}h ago`:`${Math.floor(c/864e5)}d ago`}function Yt(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 Ee(s){return s instanceof Error&&s.message?s.message:String(s)}function Xt(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Zt(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function Fs(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,c)=>e.jsx(Gs,{size:14,className:c<s?"star-filled":"star-empty",fill:c<s?"currentColor":"none"},c))})}function Qt({agentId:s,projectId:n,addToast:i}){const[c,u]=t.useState([]),[f,F]=t.useState(null),[h,k]=t.useState(null),[L,C]=t.useState([]),[o,b]=t.useState(!0),[D,P]=t.useState(!0),[M,z]=t.useState(!1),[G,y]=t.useState(!1),[J,j]=t.useState(null),[T,E]=t.useState(0),[x,R]=t.useState(""),[q,B]=t.useState(""),V=t.useCallback(async()=>{try{const[l,r]=await Promise.all([et(s,20,n),st(s,void 0,n)]);u(l),F(r)}catch(l){i(`Failed to load reflections: ${Ee(l)}`,"error")}finally{b(!1)}},[s,n,i]),S=t.useCallback(async()=>{try{const[l,r]=await Promise.all([tt(s,n),at(s,{limit:50},n)]);k(l),C(r)}catch(l){i(`Failed to load ratings: ${Ee(l)}`,"error")}finally{P(!1)}},[s,n,i]);t.useEffect(()=>{V(),S()},[V,S]);const Y=async()=>{z(!0);try{if(!await it(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),b(!0),await V()}catch(l){const r=Ee(l),p=r.toLowerCase();p.includes("agent not found")||p.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):p.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${r}`,"error")}finally{z(!1)}},v=async l=>{if(l.preventDefault(),T!==0){y(!0);try{await rt(s,{score:T,category:x||void 0,comment:q||void 0,raterType:"user"},n),E(0),R(""),B(""),i("Rating added","success"),await S()}catch(r){i(`Failed to add rating: ${Ee(r)}`,"error")}finally{y(!1)}}},U=async l=>{try{await lt(s,l,n),i("Rating deleted","success"),await S()}catch(r){i(`Failed to delete rating: ${Ee(r)}`,"error")}},d=l=>{j(r=>r===l?null:l)};if(o&&D)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 g=f&&f.totalTasksCompleted===0&&f.totalTasksFailed===0&&f.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(Ge,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:Y,disabled:M,title:"Generate a manual reflection",children:M?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(os,{size:14}),"Reflect Now"]})})]}),f&&!g&&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(Ss,{size:16,style:{color:"var(--color-success)"}}),f.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(Wt,{size:16,style:{color:"var(--color-error)"}}),f.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(nt,{size:16,style:{color:"var(--in-progress)"}}),Rs(f.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(Ge,{size:16,style:{color:f.successRate>=.8?"var(--color-success)":f.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Kt(f.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(ss,{size:16,style:{color:"var(--color-info)"}}),f.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),g&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(Ge,{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"}),D?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:[h&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:h.averageScore.toFixed(1)}),Fs(Math.round(h.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[h.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${Zt(h.trend)}`,children:Xt(h.trend)})]})]}),h&&Object.keys(h.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(h.categoryAverages).map(([l,r])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:l}),e.jsx("span",{className:"category-score",children:r.toFixed(1)})]},l))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:v,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(l=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>E(l),title:`${l} star${l>1?"s":""}`,children:e.jsx(Gs,{size:24,fill:l<=T?"currentColor":"none",className:l<=T?"star-filled":"star-empty"})},l))}),e.jsxs("select",{value:x,onChange:l=>R(l.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:q,onChange:l=>B(l.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:T===0||G,children:G?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),L.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):L.map(l=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[Fs(l.score),l.category&&e.jsx("span",{className:"rating-category-badge",children:l.category}),e.jsx("span",{className:"rating-time",children:ws(l.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void U(l.id),title:"Delete rating",children:e.jsx($e,{size:14})})]}),l.comment&&e.jsx("p",{className:"rating-comment",children:l.comment})]},l.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),o?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):c.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(ss,{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:c.map(l=>{const r=J===l.id;return e.jsxs("div",{className:`reflection-card ${r?"reflection-card--expanded":""}`,onClick:()=>d(l.id),role:"button",tabIndex:0,onKeyDown:p=>p.key==="Enter"&&d(l.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${l.trigger}`,children:Yt(l.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:ws(l.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:r?e.jsx(Es,{size:16}):e.jsx(Ls,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:l.summary}),r&&e.jsxs("div",{className:"reflection-details",children:[l.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(ss,{size:14})," Insights"]}),e.jsx("ul",{children:l.insights.map((p,Q)=>e.jsx("li",{children:p},Q))})]}),l.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(Ss,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:l.suggestedImprovements.map((p,Q)=>e.jsx("li",{children:p},Q))})]}),l.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[l.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:l.metrics.tasksCompleted})]}),l.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:l.metrics.tasksFailed})]}),l.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:Rs(l.metrics.avgDurationMs)})]}),l.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:l.metrics.errorCount})]})]})]})]})]},l.id)})})]})]})}function ne(...s){return s.filter(Boolean).join(" ")}function we(s){const n=Date.now(),i=new Date(s).getTime(),c=n-i;if(c<0){const u=Math.abs(c);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 c<6e4?"just now":c<36e5?`${Math.floor(c/6e4)}m ago`:c<864e5?`${Math.floor(c/36e5)}h ago`:`${Math.floor(c/864e5)}d ago`}const ea=[{id:"dashboard",label:"Dashboard",icon:Gt},{id:"logs",label:"Logs",icon:Pe},{id:"runs",label:"Runs",icon:Je},{id:"tasks",label:"Tasks",icon:Bs},{id:"employees",label:"Employees",icon:Hs},{id:"soul",label:"Soul",icon:ht},{id:"instructions",label:"Instructions",icon:ft},{id:"memory",label:"Agent Memory",icon:Pe},{id:"reflections",label:"Evaluation",icon:Ge},{id:"config",label:"Settings",icon:gt}],ds={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)"},terminated:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},qe={completed:{icon:re,color:"var(--color-success)"},failed:{icon:Ct,color:"var(--color-error)"},active:{icon:_,color:"var(--in-progress)"},terminated:{icon:De,color:"var(--text-muted)"}},Ms={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},sa={"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."},ta=_s(ls),aa=700;function na(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function Sa({agentId:s,projectId:n,onClose:i,addToast:c,onChildClick:u,inline:f=!1,showInlineBackButton:F=!1,initialTab:h,initialRunId:k,preferActiveRun:L=!1,onMutationSuccess:C}){const[o,b]=t.useState(null),{confirm:D}=$s(),[P,M]=t.useState([]),[z,G]=t.useState(!1),[y,J]=t.useState(!0),[j,T]=t.useState(h??"dashboard"),[E,x]=t.useState(!1),[R,q]=t.useState(!1),[B,V]=t.useState(null),S=t.useRef(null),Y=t.useRef(!1);ct(S,!f,"fusion:agent-detail-modal-size");const v=t.useRef(i),U=t.useRef(c),d=t.useRef(null),g=t.useRef(!1),l=t.useRef(null),r=t.useRef(0),p=t.useRef(s),Q=t.useRef(n);v.current=i,U.current=c,d.current=o;const X=t.useCallback(async()=>{d.current===null&&J(!0);try{const ee=await ot(s,n);b(ee)}catch(ee){U.current(`Failed to load agent: ${Z(ee)}`,"error"),v.current()}finally{J(!1)}},[s,n]),be=t.useCallback(async()=>{const N=r.current,ee=s,se=n,W=()=>r.current!==N||s!==ee||n!==se;try{if(o?.taskId){V(null),l.current=null;const Ce=await dt(o.taskId,se,{limit:100});if(W())return;M(Ce.entries);return}const te=await Ds(ee,1,se);if(W())return;const de=te[0]??null;if(V(de),!de){l.current=null,M([]);return}if(l.current===de.id)return;const ce=await Ps(ee,de.id,se);if(W())return;M(ce),l.current=de.id}catch(te){if(W())return;console.error("Failed to load agent logs:",te)}},[o?.taskId,s,n]),ye=t.useCallback(N=>{g.current=N},[]),A=t.useCallback(async(N=!1)=>{await C?.({agentId:s,deleted:N})},[s,C]),H=t.useCallback(async()=>{await X(),await A(!1)},[X,A]);t.useEffect(()=>{X()},[X]),t.useEffect(()=>{const N=setInterval(()=>{X()},3e4);return()=>{clearInterval(N)}},[X]),t.useEffect(()=>{o&&j==="logs"&&be()},[o,j,be]),t.useEffect(()=>{j!=="logs"&&(l.current=null)},[j]),t.useEffect(()=>{if(j!=="logs"||o?.taskId||!B||B.status!=="active")return;const N=r.current,ee=s,se=B.id,W=n?`?projectId=${encodeURIComponent(n)}`:"",te=Ue(`/api/agents/${encodeURIComponent(ee)}/runs/${encodeURIComponent(se)}/logs/stream${W}`,{events:{"agent:log":de=>{if(r.current===N)try{const ce=JSON.parse(de.data);M(Ce=>[...Ce,ce])}catch{}}},onOpen:()=>{r.current===N&&x(!0)},onError:()=>{r.current===N&&x(!1)}});return()=>{te(),r.current===N&&x(!1)}},[j,o?.taskId,s,n,B]),t.useEffect(()=>{(p.current!==s||Q.current!==n)&&(p.current=s,Q.current=n,r.current++,M([]),x(!1),V(null),l.current=null,g.current=!1)},[s,n]),t.useEffect(()=>{const N=n?`?projectId=${encodeURIComponent(n)}`:"",ee=r.current;return Ue(`/api/events${N}`,{events:{"agent:updated":se=>{if(r.current===ee)try{const W=JSON.parse(se.data);if(!W||typeof W!="object"||W.id!==s||g.current)return;X()}catch{}}}})},[s,n,X]),t.useEffect(()=>{if(j!=="logs"||!o?.taskId){x(!1);return}const N=r.current,ee=o.taskId,se=n?`?projectId=${encodeURIComponent(n)}`:"",W=Ue(`/api/tasks/${encodeURIComponent(ee)}/logs/stream${se}`,{events:{"agent:log":te=>{if(r.current===N)try{const de=JSON.parse(te.data);M(ce=>[...ce,de])}catch{}}},onOpen:()=>{r.current===N&&x(!0)},onError:()=>{r.current===N&&x(!1)}});return()=>{W(),r.current===N&&x(!1)}},[o?.taskId,j,n]);const le=async N=>{if(R||!d.current)return;const ee=d.current.state;if(ee!==N){q(!0),b(se=>se&&{...se,state:N});try{await pt(s,N,n),c(`Agent state updated to ${N}`,"success"),await H()}catch(se){b(W=>W&&{...W,state:ee}),c(`Failed to update state: ${Z(se)}`,"error")}finally{q(!1)}}},he=async()=>{if(!(!o||!await D({title:"Delete Agent",message:`Delete agent "${o.name}"? This cannot be undone.`,danger:!0})))try{await jt(s,n),c(`Agent "${o.name}" deleted`,"success"),await A(!0),i()}catch(ee){c(`Failed to delete agent: ${Z(ee)}`,"error")}},Fe=()=>o?vt(o):{label:"Unknown",icon:e.jsx(is,{size:14}),color:"var(--text-muted)",stateDerived:!1},ve=()=>{o&&(navigator.clipboard.writeText(o.id),c("Agent ID copied to clipboard","success"))};if(y)return f?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:N=>{N.target===N.currentTarget&&(Y.current=!0)},onMouseUp:N=>{Y.current&&N.target===N.currentTarget&&i(),Y.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:S,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(_,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!o)return null;const Se=ds[o.state],fe=Fe(),ze=f?"agent-detail-inline":"agent-detail-modal";return e.jsxs("div",{className:f?"agent-detail-inline-shell":"agent-detail-overlay",onClick:N=>!f&&N.target===N.currentTarget&&i(),role:f?"region":"dialog","aria-label":f?"Agent detail":void 0,"aria-modal":f?void 0:"true",children:[e.jsxs("div",{className:ze,ref:S,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[f&&F?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(ut,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(is,{size:20})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:o.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Se.bg,color:Se.text,border:`1px solid ${Se.border}`},children:o.state}),e.jsxs("span",{className:"badge",style:{color:fe.color},title:fe.reason??fe.label,children:[fe.icon,!fe.stateDerived&&fe.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[o.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void le("active"),disabled:R,children:[e.jsx(Ve,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:he,children:[e.jsx($e,{size:14}),"Delete"]})]}),o.state==="active"&&e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void le("paused"),disabled:R,"aria-label":"Pause",children:[e.jsx(ks,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),o.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void le("active"),disabled:R,"aria-label":"Resume",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:he,children:[e.jsx($e,{size:14}),"Delete"]})]}),o.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void le("paused"),disabled:R,"aria-label":"Pause",children:[e.jsx(ks,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void le("terminated"),disabled:R,children:[e.jsx(De,{size:14}),"Stop"]})]}),o.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void le("active"),disabled:R,children:[e.jsx(Ve,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void le("terminated"),disabled:R,children:[e.jsx(De,{size:14}),"Stop"]})]}),o.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void le("active"),disabled:R,children:[e.jsx(Ve,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:he,children:[e.jsx($e,{size:14}),"Delete"]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("button",{type:"button",className:"btn btn--compact agent-detail-import-btn",onClick:()=>G(!0),"aria-label":"Import agents",children:[e.jsx(mt,{size:14}),"Import"]}),e.jsx("button",{className:"btn-icon",onClick:()=>void X(),title:"Refresh","aria-label":"Refresh",children:e.jsx(os,{size:16})}),!f&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(zs,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:ea.map(N=>e.jsxs("button",{className:ne("agent-detail-tab",j===N.id&&"active"),onClick:()=>T(N.id),children:[e.jsx(N.icon,{size:16}),N.label]},N.id))}),e.jsxs("div",{className:"agent-detail-content",children:[j==="dashboard"&&e.jsx(ia,{agent:o,health:fe,onChildClick:u,projectId:n}),j==="logs"&&e.jsx(ra,{logs:P,isStreaming:E,hasTask:!!o.taskId||P.length>0||B!==null,fallbackLabel:!o.taskId&&B?`Latest run · ${B.id.slice(0,8)}`:null}),j==="runs"&&e.jsx(la,{addToast:c,agentId:o.id,projectId:n,agentState:o.state,agentName:o.name,initialRunId:k,preferActiveRun:L}),j==="tasks"&&e.jsx(ua,{agentId:o.id,projectId:n,addToast:c}),j==="employees"&&e.jsx(va,{agentId:o.id,projectId:n,onChildClick:u}),j==="soul"&&e.jsx(ha,{agent:o,projectId:n,addToast:c,onSaved:H}),j==="instructions"&&e.jsx(ga,{agent:o,projectId:n,addToast:c,onSaved:H}),j==="memory"&&e.jsx(fa,{agent:o,projectId:n,addToast:c,onSaved:H}),j==="reflections"&&e.jsx(Qt,{agentId:o.id,projectId:n,addToast:c}),j==="config"&&e.jsx(ba,{agent:o,projectId:n,addToast:c,onSaved:H,onHasChangesChange:ye,onDelete:he},o.id)]}),!f&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:ve,title:"Copy Agent ID",children:e.jsx(xt,{})}),e.jsx("span",{className:"agent-detail-id",onClick:ve,children:o.id}),o.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/${o.taskId}`,className:"link",children:[o.taskId,e.jsx(Os,{size:12})]})]})]})]}),e.jsx(bt,{isOpen:z,onClose:()=>G(!1),onImported:()=>{H()},projectId:n,initialInputMethod:"browse"})]})}function ia({agent:s,health:n,onChildClick:i,projectId:c}){const u=ds[s.state],[f,F]=t.useState([]),[h,k]=t.useState(!0),[L,C]=t.useState(null),[o,b]=t.useState([]),[D,P]=t.useState(null),[M,z]=t.useState(null),[G,y]=t.useState(!1),[J,j]=t.useState(null),T=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",E=(()=>{const d=s.runtimeConfig??{};if(T){const g=o.find(l=>l.runtimeId===T);return g?g.name:T}if(d.modelProvider&&d.modelId)return`${d.modelProvider}/${d.modelId}`;if(typeof d.model=="string"&&d.model.includes("/")){const g=d.model.indexOf("/");return d.model.slice(g+1)}return null})();t.useEffect(()=>{rs(s.id,c).then(C).catch(()=>C(null))},[s.id,c]),t.useEffect(()=>{Is(c).then(b).catch(()=>b([]))},[c]),t.useEffect(()=>{let d=!1;return k(!0),Nt(s.id,c).then(g=>{if(d)return;const l=g.length>0&&g[0]?.id===s.id?[...g].reverse():g;F(l)}).catch(()=>{d||F([])}).finally(()=>{d||k(!1)}),()=>{d=!0}},[s.id,c]);const x=t.useMemo(()=>{const d=s.completedRuns||[],g=new Date;g.setHours(0,0,0,0);const l=d.filter(p=>new Date(p.startedAt)>=g),r=d.filter(p=>p.status==="completed");return{totalRuns:d.length,todayRuns:l.length,successfulRuns:r.length,successRate:d.length>0?Math.round(r.length/d.length*100):0}},[s]),R=(s.completedRuns||[]).slice(0,5),q=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],B=D?ts(D):null,V=t.useCallback(async d=>{y(!0),j(null),z(null);try{const g=await yt(d,c);z(g)}catch(g){j(Z(g))}finally{y(!1)}},[c]),S=t.useCallback(d=>{if(D===d){P(null),z(null),j(null),y(!1);return}P(d),V(d)},[V,D]),Y=s.state==="active"||s.state==="running",v=St(s.runtimeConfig?.heartbeatIntervalMs),U=Y&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+v).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[L?.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(is,{}),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]}),e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:T?"Runtime":"Model"}),e.jsxs("span",{children:[" ",E??"Auto"]})]}),q.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:q.map(d=>{const g=D===d;return e.jsx("button",{type:"button",className:ne("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",g&&"dashboard-summary-skill-badge--selected"),title:d,onClick:()=>S(d),"aria-expanded":g,"aria-label":`View details for ${ts(d)}`,children:ts(d)},d)})})]}):e.jsx("span",{children:"Skills: —"})]}),D?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:B}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>S(D),children:[e.jsx(zs,{size:14}),"Close"]})]}),G?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..."]}):J?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(kt,{size:14}),e.jsx("span",{children:J}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void V(D),children:"Retry"})]}):M?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:M.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?we(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:U?we(U):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:_s(v)})]}),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:ne("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(Os,{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:[x.successfulRuns,"/",x.totalRuns," successful (",x.successRate,"%)"]}),R.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:R.map(d=>{const g=qe[d.status]||qe.terminated,l=g.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(l,{size:14,style:{color:g.color}}),e.jsx("span",{children:we(d.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(d.endedAt||d.startedAt).getTime()-new Date(d.startedAt).getTime())/1e3)),"s"]})]},d.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:x.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:x.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[x.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"}),h?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..."})]}):f.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:f.map((d,g)=>{const l=g===f.length-1,r=!l;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${l?" chain-of-command-node--current":""}`,onClick:()=>r&&i?.(d.id),disabled:!r||!i,title:l?"Current agent":`View ${d.name}`,children:d.name}),!l&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},d.id)})})]})]})}function ra({logs:s,isStreaming:n,hasTask:i,fallbackLabel:c}){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"]}),c&&e.jsx("span",{className:"text-muted logs-fallback-label",children:c}),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(Pe,{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(Vs,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(Pe,{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 la({addToast:s,agentId:n,projectId:i,agentState:c,agentName:u,initialRunId:f,preferActiveRun:F}){const[h,k]=t.useState([]),{confirm:L}=$s(),[C,o]=t.useState(!0),[b,D]=t.useState(null),[P,M]=t.useState([]),[z,G]=t.useState(!1),[y,J]=t.useState(null),[j,T]=t.useState(!1),E=t.useRef(!1),x=t.useCallback(async()=>{try{const r=await Ds(n,50,i);k(r)}catch(r){s(`Failed to load runs: ${Z(r)}`,"error")}finally{o(!1)}},[n,i,s]);t.useEffect(()=>{x()},[x]);const R=h.some(r=>r.status==="active"),q=b?h.find(r=>r.id===b)?.status:void 0;t.useEffect(()=>{if(!R)return;const r=setInterval(()=>{x()},5e3);return()=>clearInterval(r)},[R,x]),t.useEffect(()=>{if(!b||q!=="active")return;const r=i?`?projectId=${encodeURIComponent(i)}`:"";return Ue(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(b)}/logs/stream${r}`,{events:{"agent:log":p=>{try{const Q=JSON.parse(p.data);M(X=>[...X,Q])}catch{}}}})},[b,q,n,i]);const B=t.useCallback(async r=>{if(b===r){D(null),M([]),J(null);return}D(r),G(!0),T(!0),M([]),J(null);try{const[p,Q]=await Promise.all([Ps(n,r,i),Rt(n,r,i)]);M(p),J(Q)}catch(p){s(`Failed to load run details: ${Z(p)}`,"error"),M([]),J(null)}finally{G(!1),T(!1)}},[b,n,i,s]);t.useEffect(()=>{E.current=!1},[n,f,F]),t.useEffect(()=>{if(h.length===0||C||E.current)return;const r=f?h.find(p=>p.id===f):F?h.find(p=>p.status==="active"):null;E.current=!0,r&&B(r.id)},[f,F,h,C,B]);const V=async()=>{try{await Pt(n,i,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),s(`Heartbeat run started for ${u??n}`,"success"),o(!0),x()}catch(r){s(`Failed to start heartbeat run: ${Z(r)}`,"error")}},S=async()=>{if(await L({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await zt(n,i),s("Run stopped","success"),o(!0),x()}catch(p){s(`Failed to stop run: ${Z(p)}`,"error")}},Y=c==="active"||c==="idle";if(C&&h.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(h.length===0)return e.jsxs("div",{className:"runs-tab",children:[Y&&e.jsx("div",{className:"runs-toolbar",children:e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void V(),"aria-label":`Run now for ${u??n}`,children:[e.jsx(Je,{size:14})," Run Now"]})}),e.jsxs("div",{className:"runs-empty",children:[e.jsx(Je,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})]});const v=[...h].sort((r,p)=>new Date(p.startedAt).getTime()-new Date(r.startedAt).getTime()),U=v.filter(r=>r.status==="active"),d=v.filter(r=>r.status!=="active"),g=r=>r?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",r.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",r.outputTokens.toLocaleString()]}),r.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",r.cachedTokens.toLocaleString()]})]}):null,l=(r,p,Q)=>{const X=qe[r.status]||qe.completed,be=X.icon,ye=r.endedAt?ca(new Date(r.startedAt),new Date(r.endedAt)):"In progress",A=b===r.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ne("run-card",Q&&"run-card--active",A&&"run-card--selected","run-card--clickable"),onClick:()=>void B(r.id),role:"button",tabIndex:0,"aria-expanded":A,"aria-label":`${Q?"Active":""} run ${r.id.slice(0,8)}, ${r.status}`,onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),B(r.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[A?e.jsx(Es,{size:14}):e.jsx(Ls,{size:14}),Q?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",p+1," ",r.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[r.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:r.invocationSource}),Q&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:H=>{H.preventDefault(),H.stopPropagation(),S()},"aria-label":"Stop active run",children:[e.jsx(De,{size:12})," Stop"]}),e.jsxs("span",{className:ne("run-status",r.status),children:[e.jsx(be,{size:14,style:{color:X.color}}),r.status]}),r.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 ",we(r.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ye}),r.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:r.triggerDetail})]})]})]}),A&&e.jsxs("div",{className:"run-logs-container",children:[j?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..."})]}):y&&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"}),y.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:y.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"}),y.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:y.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),y.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),g(y.usageJson)]}),y.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:y.stdoutExcerpt.length>2e3?`${y.stdoutExcerpt.slice(0,2e3)}
17
-
18
- ... (truncated, ${y.stdoutExcerpt.length} chars total)`:y.stdoutExcerpt})]}),y.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx("pre",{className:"run-output-panel run-output-panel--error",children:y.stderrExcerpt})]}),y.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(y.resultJson,null,2)})]}),y.contextSnapshot&&Object.keys(y.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(y.contextSnapshot).map(([H,le])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[H,":"]})," ",e.jsx("span",{children:String(le)})]},H))})]}),!y.stdoutExcerpt&&!y.stderrExcerpt&&!y.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"}),z?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..."})]}):P.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(Vs,{entries:P,loading:!1})]})]})]},r.id)};return e.jsxs("div",{className:"runs-tab",children:[Y&&e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[h.length," run",h.length!==1?"s":"",R&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsxs("div",{className:"run-header-group",children:[R&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(),"aria-label":`Stop active run for ${u??n}`,children:[e.jsx(De,{size:14})," Stop Run"]}),e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void V(),"aria-label":`Run now for ${u??n}`,children:[e.jsx(Je,{size:14})," Run Now"]})]})]}),U.map((r,p)=>l(r,p,!0)),d.map((r,p)=>l(r,U.length+p,!1))]})}function ca(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 oa={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function da(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function ua({agentId:s,projectId:n,addToast:i}){const[c,u]=t.useState([]),[f,F]=t.useState(!0);return t.useEffect(()=>{let h=!1;return F(!0),wt(s,n).then(k=>{h||u(k)}).catch(k=>{h||(u([]),i(`Failed to load assigned tasks: ${Z(k)}`,"error"))}).finally(()=>{h||F(!1)}),()=>{h=!0}},[s,n,i]),f?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(_,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):c.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(Bs,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:c.map(h=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${h.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:h.id}),e.jsx("span",{className:`agent-task-column column-${h.column}`,children:oa[h.column]})]}),e.jsx("div",{className:"agent-task-title",title:h.title||h.description||h.id,children:da(h)}),e.jsxs("div",{className:"agent-task-status",children:[h.status??"idle"," · Updated ",we(h.updatedAt)]})]},h.id))})}const Le=[{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 ma(s){const n={};for(const i of Le){const c=s[i.key]?.trim();if(c){if(i.type==="number"){const u=Number(c);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(f=>f.value)??[];u.length>0&&!u.includes(c)&&(n[i.key]=`"${i.label}" must be one of: ${u.join(", ")}`)}}}return n}function ha({agent:s,projectId:n,addToast:i,onSaved:c}){const[u,f]=t.useState(s.soul??""),[F,h]=t.useState(!1),[k,L]=t.useState(!1),[C,o]=t.useState(!1),b=t.useRef(null);t.useEffect(()=>{f(s.soul??""),L(!1),o(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const D=u!==(s.soul??""),P=async()=>{if(u.length>1e4){i("Soul must be at most 10,000 characters","error");return}h(!0);try{await Bt(s.id,u,n),i("Soul saved","success"),L(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>L(!1),3e3),await c()}catch(M){i(`Failed to save soul: ${Z(M)}`,"error")}finally{h(!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 ${C?"":"btn-primary"}`,onClick:()=>o(!1),disabled:!C,"aria-label":"Edit mode",children:[e.jsx(We,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>o(!0),disabled:C,"aria-label":"Preview mode",children:[e.jsx(Ke,{size:14}),"Preview"]})]})}),C?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ye,{remarkPlugins:[Xe],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:M=>{f(M.target.value),L(!1)}}),!C&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!D||F,onClick:()=>void P(),children:F?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Soul"]})}),!D&&k&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"Soul saved"]})]})]})})}function fa({agent:s,projectId:n,addToast:i,onSaved:c}){const[u,f]=t.useState(s.memory??""),[F,h]=t.useState(!1),[k,L]=t.useState(!1),[C,o]=t.useState(!1),[b,D]=t.useState([]),[P,M]=t.useState(!1),[z,G]=t.useState(""),[y,J]=t.useState(""),[j,T]=t.useState(!1),[E,x]=t.useState(!1),[R,q]=t.useState(!1),[B,V]=t.useState(!1),[S,Y]=t.useState(""),v=t.useRef(null),U=t.useRef(null),d=s.state==="running",g=u!==(s.memory??""),l=t.useMemo(()=>b.find(A=>A.path===z),[b,z]),r=l?sa[l.layer]:"Select a memory file to view or edit.",p=t.useCallback(async A=>{x(!0);try{const H=await Mt(s.id,A,n);G(H.path),J(H.content),T(!1),V(!1)}catch(H){i(`Failed to load agent memory file: ${Z(H)}`,"error")}finally{x(!1)}},[s.id,n,i]),Q=t.useCallback(async(A="")=>{M(!0);try{const{files:H}=await At(s.id,n);if(D(H),H.length===0){G(""),J(""),T(!1);return}const le=na(H,A);await p(le)}catch(H){i(`Failed to load memory files: ${Z(H)}`,"error"),D([]),G(""),J(""),T(!1)}finally{M(!1)}},[s.id,n,i,p]);t.useEffect(()=>{f(s.memory??""),L(!1),o(!1),Y(""),V(!1),Q()},[s.id,s.memory,Q]),t.useEffect(()=>()=>{v.current&&clearTimeout(v.current),U.current&&clearTimeout(U.current)},[]);const X=async()=>{if(u.length>5e4){i("Memory must be at most 50,000 characters","error");return}h(!0);try{await Ot(s.id,u,n),i("Memory saved","success"),L(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>L(!1),3e3),await c()}catch(A){i(`Failed to save memory: ${Z(A)}`,"error")}finally{h(!1)}},be=async A=>{if(!(!A||A===z)){if(j){Y("Save the current file before switching to another file.");return}Y(""),await p(A)}},ye=async()=>{if(z){q(!0);try{await It(s.id,z,y,n),T(!1),V(!0),U.current&&clearTimeout(U.current),U.current=setTimeout(()=>V(!1),3e3),Y(""),await Q(z),i("Agent memory file saved","success"),await c()}catch(A){i(`Failed to save agent memory file: ${Z(A)}`,"error")}finally{q(!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."}),d&&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:[!d&&e.jsxs("button",{className:`btn btn-sm ${C?"":"btn-primary"}`,onClick:()=>o(!1),disabled:!C,"aria-label":"Edit mode",children:[e.jsx(We,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>o(!0),disabled:C,"aria-label":"Preview mode",children:[e.jsx(Ke,{size:14}),"Preview"]})]})}),C?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ye,{remarkPlugins:[Xe],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:d,onChange:A=>{f(A.target.value),L(!1)}}),!C&&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:z,disabled:P||E||R||b.length===0,onChange:A=>{be(A.target.value)},children:b.length===0?e.jsx("option",{value:"",children:"No memory files found"}):b.map(A=>e.jsxs("option",{value:A.path,children:[Ms[A.layer]," • ",A.label]},A.path))}),P&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(_,{size:14,className:"animate-spin"}),"Loading memory files…"]}),l&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:Ms[l.layer]})," · ",r,e.jsx("br",{}),l.size.toLocaleString()," bytes · Updated ",we(l.updatedAt)]}),e.jsx("textarea",{className:"input config-textarea-mono config-textarea-top-spacing",rows:14,placeholder:"Select a memory file to view and edit its content...",value:y,readOnly:d||!z||E,onChange:A=>{J(A.target.value),T(!0),V(!1),Y("")}}),E&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(_,{size:14,className:"animate-spin"}),"Loading file content…"]}),S&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:S})]})]}),e.jsxs("div",{className:"config-actions",children:[!C&&e.jsx("button",{className:"btn btn-task-create",disabled:!g||F||d,onClick:()=>void X(),children:F?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Memory"]})}),e.jsx("button",{className:"btn",disabled:!j||R||!z||d,onClick:()=>void ye(),children:R?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Memory File"]})}),!g&&k&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"Memory saved"]}),!j&&B&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"Memory file saved"]})]})]})})}function ga({agent:s,projectId:n,addToast:i,onSaved:c}){const[u,f]=t.useState(s.instructionsText??""),[F,h]=t.useState(s.instructionsPath??""),[k,L]=t.useState(!1),[C,o]=t.useState(""),[b,D]=t.useState(!1),[P,M]=t.useState(!1),[z,G]=t.useState(!1),[y,J]=t.useState(!1),[j,T]=t.useState(!1),[E,x]=t.useState(!1),R=t.useRef(null),q=t.useRef(null);t.useEffect(()=>{const v=F.trim();if(!v){o(""),M(!1);return}D(!0),Us("project",v).then(U=>{o(U.content),M(!1)}).catch(U=>{const d=Z(U);d.includes("ENOENT")||d.includes("Not found")||d.includes("not found")?(o(""),M(!1)):(i(`Failed to load instructions file: ${d}`,"error"),o(""))}).finally(()=>{D(!1)})},[F,i]),t.useEffect(()=>{f(s.instructionsText??""),h(s.instructionsPath??""),T(!1),x(!1),L(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{R.current&&clearTimeout(R.current),q.current&&clearTimeout(q.current)},[]);const B=(()=>{const v=u??"",U=s.instructionsText??"",d=F?.trim()??"",g=s.instructionsPath?.trim()??"";return v!==U||d!==g})(),V=async()=>{G(!0);try{await Ht(s.id,{instructionsText:u||void 0,instructionsPath:F.trim()||void 0},n),i("Instructions saved","success"),T(!0),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>T(!1),3e3),await c()}catch(v){i(`Failed to save instructions: ${Z(v)}`,"error")}finally{G(!1)}},S=async()=>{const v=F.trim();if(!v){i("No instructions file path set","error");return}J(!0);try{await Js("project",v,C),i("Instructions file saved","success"),M(!1),x(!0),q.current&&clearTimeout(q.current),q.current=setTimeout(()=>x(!1),3e3),await c()}catch(U){i(`Failed to save instructions file: ${Z(U)}`,"error")}finally{J(!1)}},Y=!!F.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 ${k?"":"btn-primary"}`,onClick:()=>L(!1),disabled:!k,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(We,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>L(!0),disabled:k,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(Ke,{size:14}),"Preview"]})]})}),k?u.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ye,{remarkPlugins:[Xe],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:v=>{f(v.target.value),T(!1)}}),!k&&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:F,onChange:v=>{h(v.target.value),T(!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."})]})]}),!k&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!B||z,onClick:()=>void V(),children:z?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Instructions"]})}),!B&&j&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"Instructions saved"]})]})]}),Y&&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"}),b&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(_,{size:12,className:"animate-spin"}),"Loading..."]}),P&&!b&&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:C,readOnly:b,onChange:v=>{o(v.target.value),M(!0),x(!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||y,onClick:()=>void S(),children:y?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save File"]})}),!P&&E&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"File saved"]})]})]})]})}function As(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 as(s){return s?.enabled!==!1}function ns(s){return s?.autoClaimRelevantTasks!==!1}function Ts(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 xa({agent:s,projectId:n,addToast:i,onSaved:c}){const[u,f]=t.useState(!1),[F,h]=t.useState(!1),[k,L]=t.useState(!1),[C,o]=t.useState(!1),[b,D]=t.useState(!1),[P,M]=t.useState(""),[z,G]=t.useState(!1),[y,J]=t.useState(null),[j,T]=t.useState(!1),E=t.useRef(null),x=s.heartbeatProcedurePath?.trim(),R=`.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`,q=`.fusion/agents/${s.id}/HEARTBEAT.md`,B=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",V=!!(x&&(x===R||x===q||new RegExp(`^\\.fusion/agents/[^/]+-${B}/HEARTBEAT\\.md$`).test(x))),S=!!x,Y=t.useCallback(async g=>{L(!0),J(null);try{const l=await Us("project",g,n);M(l.content),G(!1)}catch(l){const r=Z(l);J(r),i(`Failed to load heartbeat procedure file: ${r}`,"error")}finally{L(!1)}},[i,n]);t.useEffect(()=>{h(!1),D(!1),M(""),G(!1),J(null),L(!1),o(!1),T(!1)},[s.id,x]),t.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const v=async()=>{x&&(h(!0),await Y(x))},U=async()=>{if(x){o(!0);try{await Js("project",x,P,n),G(!1),T(!0),i("Heartbeat procedure file saved","success"),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>T(!1),3e3),await c()}catch(g){i(`Failed to save heartbeat procedure file: ${Z(g)}`,"error")}finally{o(!1)}}},d=async()=>{f(!0);try{const g=await Vt(s.id,n);i(g.procedureFileSeeded?`Heartbeat procedure file ready at ${g.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${g.heartbeatProcedurePath}`,"success"),await c()}catch(g){i(`Failed to upgrade heartbeat procedure: ${Z(g)}`,"error")}finally{f(!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:x||"(none — using built-in default)"})]}),S&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void v(),disabled:k,children:k?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:u||V,onClick:()=>void d(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:u?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Upgrading…"]}):V?e.jsxs(e.Fragment,{children:[e.jsx(re,{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:R})," ","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."]})]})]}),F&&S&&x&&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 ${b?"":"btn-primary"}`,onClick:()=>D(!1),disabled:!b,"aria-label":"Heartbeat file edit mode",children:[e.jsx(We,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${b?"btn-primary":""}`,onClick:()=>D(!0),disabled:b,"aria-label":"Heartbeat file preview mode",children:[e.jsx(Ke,{size:14}),"Preview"]})]}),k&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(_,{size:12,className:"animate-spin"}),"Loading..."]}),z&&!k&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),b?P.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ye,{remarkPlugins:[Xe],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:k,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:g=>{M(g.target.value),G(!0),T(!1)}}),y&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",y]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:x}),"."]})]}),!b&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!z||C||k,onClick:()=>void U(),children:C?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Heartbeat File"]})}),!z&&j&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(re,{size:14}),"File saved"]})]})]})]})}function ba({agent:s,projectId:n,addToast:i,onSaved:c,onHasChangesChange:u,onDelete:f}){const[F,h]=t.useState(s.name),[k,L]=t.useState(s.role),[C,o]=t.useState(s.title??""),[b,D]=t.useState(s.icon??""),[P,M]=t.useState(s.reportsTo??""),[z,G]=t.useState([]),[y,J]=t.useState(!1),[j,T]=t.useState(()=>{const a={};for(const m of Le){const w=s.metadata[m.key];w!=null&&(a[m.key]=String(w))}return a}),[E,x]=t.useState(()=>As(s.runtimeConfig)),[R,q]=t.useState(()=>as(s.runtimeConfig)),[B,V]=t.useState(()=>ns(s.runtimeConfig)),[S,Y]=t.useState(()=>Ts(s.runtimeConfig)),[v,U]=t.useState(s.bundleConfig?.mode??""),[d,g]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[l,r]=t.useState(s.bundleConfig?.externalPath??""),[p,Q]=t.useState(s.bundleConfig?.files??[]),[X,be]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[ye,A]=t.useState([]),[H,le]=t.useState(!1),[he,Fe]=t.useState([]),[ve,Se]=t.useState([]),[fe,ze]=t.useState([]),[N,ee]=t.useState(!1),se=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),W=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[te,de]=t.useState(W?"runtime":"model"),[ce,Ce]=t.useState(se),[Me,Ze]=t.useState(W),Be=P.trim(),us=t.useMemo(()=>z.filter(a=>a.id!==s.id),[z,s.id]),qs=!!Be&&!us.some(a=>a.id===Be);t.useEffect(()=>{let a=!1;return J(!0),Tt(void 0,n).then(m=>{a||G(m)}).catch(()=>{a||G([])}).finally(()=>{a||J(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{le(!0),Et().then(a=>{A(a.models),Fe(a.favoriteProviders),Se(a.favoriteModels)}).catch(()=>{}).finally(()=>le(!1))},[]);const Ws=t.useCallback(async a=>{const m=he,I=m.includes(a)?m.filter(ie=>ie!==a):[a,...m];Fe(I);try{await Cs({favoriteProviders:I,favoriteModels:ve})}catch{Fe(m)}},[he,ve]),Ks=t.useCallback(async a=>{const m=ve,I=m.includes(a)?m.filter(ie=>ie!==a):[a,...m];Se(I);try{await Cs({favoriteProviders:he,favoriteModels:I})}catch{Se(m)}},[he,ve]);t.useEffect(()=>{ee(!0),Is(n).then(ze).catch(()=>ze([])).finally(()=>ee(!1))},[n]);const[pe,Qe]=t.useState(null),[ms,hs]=t.useState(!1);t.useEffect(()=>{rs(s.id,n).then(Qe).catch(()=>Qe(null))},[s.id,n]);const Ys=async()=>{hs(!0);try{await _t(s.id,n),i("Budget usage reset successfully","success");const a=await rs(s.id,n);Qe(a)}catch(a){i(`Failed to reset budget: ${Z(a)}`,"error")}finally{hs(!1)}},[je,fs]=t.useState(!1),[O,ke]=t.useState({}),[Xs,Re]=t.useState(!1),[es,He]=t.useState(null),gs=s.state==="idle"||s.state==="terminated"||s.state==="paused",Ae=t.useRef(null),xs=t.useRef(null),bs=t.useRef(null),Oe=t.useRef(0);t.useEffect(()=>()=>{Ae.current&&clearTimeout(Ae.current)},[]);const ue=(()=>{if(F!==s.name||k!==s.role||C!==(s.title??"")||b!==(s.icon??"")||P!==(s.reportsTo??"")||v!==(s.bundleConfig?.mode??"")||d!==(s.bundleConfig?.entryFile??"AGENTS.md")||l!==(s.bundleConfig?.externalPath??"")||JSON.stringify(p)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const K of Le){const oe=j[K.key]?.trim()??"",$=s.metadata[K.key]!==void 0&&s.metadata[K.key]!==null?String(s.metadata[K.key]):"";if(oe!==$)return!0}const a=s.runtimeConfig??{};if(R!==as(s.runtimeConfig)||B!==ns(s.runtimeConfig))return!0;for(const K of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const oe=E[K]?.trim()??"";let $=a[K]!==void 0&&a[K]!==null?String(a[K]):"";if((K==="heartbeatIntervalMs"||K==="heartbeatTimeoutMs")&&$&&($=String(Number($)/1e3)),oe!==$)return!0}const m=a.budgetConfig;for(const K of["tokenBudget","budgetPeriod","resetDay"]){const oe=S[K]?.trim()??"",$=m?.[K]!==void 0&&m?.[K]!==null?String(m[K]):"";if(oe!==$)return!0}const w=S.usageThreshold?.trim()??"",I=m?.usageThreshold!==void 0&&m?.usageThreshold!==null?String(Number(m.usageThreshold)*100):"";if(w!==I)return!0;const ie=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(X)!==JSON.stringify(ie)||te!==(W?"runtime":"model")||ce!==se||Me!==W})(),vs=t.useRef(null);t.useEffect(()=>{u&&vs.current!==ue&&(vs.current=ue,u(ue))},[ue,u]),t.useEffect(()=>()=>{u?.(!1)},[u]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},m=xs.current;(!m||m.id!==a.id||m.updatedAt!==a.updatedAt)&&(ue||(xs.current=a,x(As(s.runtimeConfig)),q(as(s.runtimeConfig)),V(ns(s.runtimeConfig)),Y(Ts(s.runtimeConfig)),Ce(se),Ze(W),de(W?"runtime":"model")))},[s,ue,se,W]);const ps=(a,m)=>{T(w=>({...w,[a]:m})),Re(!1),O[a]&&ke(w=>{const I={...w};return delete I[a],I})},Ie=(a,m)=>{x(w=>({...w,[a]:m})),Re(!1),O[a]&&ke(w=>{const I={...w};return delete I[a],I})},Zs=a=>{q(a),Re(!1)},_e=(a,m)=>{Y(w=>({...w,[a]:m})),Re(!1),O[a]&&ke(w=>{const I={...w};return delete I[a],I})},ge=t.useMemo(()=>{const a=ma(j);for(const[$,Ne]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const ae=E[$]?.trim();if(!ae)continue;const xe=Number(ae);Number.isNaN(xe)||!Number.isFinite(xe)?a[$]=`"${Ne.label}" must be a valid number`:xe<Ne.min&&(a[$]=`"${Ne.label}" must be at least ${Ne.min.toLocaleString()}`)}const m=E.messageResponseMode?.trim();m&&!["immediate","on-heartbeat"].includes(m)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const w=S.tokenBudget?.trim();if(w){const $=Number(w);Number.isNaN($)||!Number.isFinite($)?a.tokenBudget='"Token Budget" must be a valid number':$<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const I=S.usageThreshold?.trim();if(I){const $=Number(I);Number.isNaN($)||!Number.isFinite($)?a.usageThreshold='"Usage Threshold" must be a valid number':($<1||$>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ie=S.budgetPeriod?.trim();ie&&!["daily","weekly","monthly","lifetime"].includes(ie)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const K=S.resetDay?.trim(),oe=ie||"lifetime";if(K){const $=Number(K);Number.isNaN($)||!Number.isFinite($)?a.resetDay='"Reset Day" must be a valid number':oe==="weekly"?($<0||$>6||!Number.isInteger($))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):oe==="monthly"&&($<1||$>31||!Number.isInteger($))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[j,E,S]),js=t.useCallback(()=>{if(Object.keys(ge).length>0)return null;const a={...s.metadata};for(const ae of Le){const xe=j[ae.key]?.trim();xe?ae.type==="number"?a[ae.key]=Number(xe):a[ae.key]=xe:delete a[ae.key]}X.length>0?a.skills=X:delete a.skills;const m={...s.runtimeConfig};m.enabled=R,m.autoClaimRelevantTasks=B;for(const ae of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const xe=E[ae]?.trim();if(!xe)delete m[ae];else{const ys=Number(xe);m[ae]=ae==="maxConcurrentRuns"?ys:ys*1e3}}const w=E.messageResponseMode?.trim();if(w?m.messageResponseMode=w:delete m.messageResponseMode,te==="runtime")Me.trim()?m.runtimeHint=Me.trim():delete m.runtimeHint,delete m.modelProvider,delete m.modelId,delete m.model;else if(delete m.runtimeHint,ce.trim()){const ae=ce.indexOf("/");ae!==-1&&(m.modelProvider=ce.slice(0,ae),m.modelId=ce.slice(ae+1),m.model=ce.trim())}else delete m.modelProvider,delete m.modelId,delete m.model;const I={},ie=S.tokenBudget?.trim(),K=S.usageThreshold?.trim(),oe=S.budgetPeriod?.trim(),$=S.resetDay?.trim();ie&&(I.tokenBudget=Number(ie)),K&&(I.usageThreshold=Number(K)/100),oe&&(I.budgetPeriod=oe),$&&(I.resetDay=Number($)),Object.keys(I).length>0?m.budgetConfig=I:delete m.budgetConfig;let Ne;return v&&(Ne={mode:v,entryFile:d||"AGENTS.md",files:p.length>0?p:["AGENTS.md"]},v==="external"&&l.trim()&&(Ne.externalPath=l.trim())),{name:F.trim()||void 0,role:k,title:C.trim()||void 0,icon:b.trim()||void 0,reportsTo:P.trim()||void 0,metadata:a,runtimeConfig:m,bundleConfig:Ne}},[s.metadata,s.runtimeConfig,B,S,d,l,p,v,j,R,E,b,ce,F,P,k,te,Me,X,C,ge]),Te=t.useCallback(async(a,m)=>{const w=js();if(!w)return ke(ge),a&&i("Please fix validation errors before saving","error"),m==="auto"&&He("Fix validation errors to save changes"),!1;const I=JSON.stringify(w);if(I===bs.current)return!1;const ie=++Oe.current;ke({}),He(null),fs(!0);try{return await Lt(s.id,w,n),ie!==Oe.current?!1:(bs.current=I,m==="manual"&&i("Settings saved","success"),He(null),Re(!0),Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>Re(!1),3e3),await c(),!0)}catch(K){if(ie===Oe.current){const oe=Z(K);He(oe),i(`Failed to save settings: ${oe}`,"error")}return!1}finally{ie===Oe.current&&fs(!1)}},[i,s.id,js,c,n,ge]),Qs=async()=>{await Te(!0,"manual")},me=t.useCallback(()=>{if(!(!ue||je)){if(Object.keys(ge).length>0){ke(ge);return}Te(!1,"auto")}},[ue,je,Te,ge]);t.useEffect(()=>{if(!ue||je)return;if(Object.keys(ge).length>0){ke(ge);return}const a=setTimeout(()=>{Te(!1,"auto")},aa);return()=>clearTimeout(a)},[ue,je,Te,ge]);const Ns=je?"Saving changes…":es?`Save failed: ${es}`:!ue&&Xs?"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.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=>h(a.target.value),onBlur:()=>{me()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:k,onChange:a=>{L(a.target.value),me()},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=>o(a.target.value),onBlur:()=>{me()}})]}),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:b,onChange:a=>D(a.target.value),onBlur:()=>{me()}})]}),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:P,onChange:a=>{M(a.target.value),me()},disabled:y,children:[e.jsx("option",{value:"",children:"No manager"}),qs&&e.jsxs("option",{value:Be,children:["Unknown manager (",Be,")"]}),us.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($t,{id:"agent-skills",label:"Skills",value:X,onChange:a=>{be(a),me()},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${te==="model"?" active":""}`,role:"tab","aria-selected":te==="model",tabIndex:te==="model"?0:-1,onClick:()=>{de("model"),Ze(""),me()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${te==="runtime"?" active":""}`,role:"tab","aria-selected":te==="runtime",tabIndex:te==="runtime"?0:-1,onClick:()=>{de("runtime"),me()},children:"Plugin Runtime"})]})]}),te==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Dt,{models:ye,value:ce,onChange:a=>{Ce(a),me()},placeholder:"Use global default",label:"Agent Model",disabled:H,favoriteProviders:he,onToggleFavorite:Ws,favoriteModels:ve,onToggleModelFavorite:Ks})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),N?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:Me,onChange:a=>{Ze(a.target.value),me()},children:[e.jsx("option",{value:"",children:fe.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),fe.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:R,onChange:a=>{Zs(a.target.checked),me()}}),"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:B,onChange:a=>{V(a.target.checked),me()}}),"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.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ne("input",!!O.heartbeatIntervalMs&&"input--error"),placeholder:String(ls/1e3),value:E.heartbeatIntervalMs??"",onChange:a=>Ie("heartbeatIntervalMs",a.target.value)}),O.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:O.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",ls/1e3,"s / ",ta,")."]})]}),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:ne("input",!!O.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:E.heartbeatTimeoutMs??"",onChange:a=>Ie("heartbeatTimeoutMs",a.target.value)}),O.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:O.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:ne("input",!!O.maxConcurrentRuns&&"input--error"),placeholder:"1",value:E.maxConcurrentRuns??"",onChange:a=>Ie("maxConcurrentRuns",a.target.value)}),O.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:O.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:ne("select",!!O.messageResponseMode&&"input--error"),value:E.messageResponseMode??"",onChange:a=>Ie("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"})]}),O.messageResponseMode?e.jsx("span",{className:"config-error",children:O.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:ne("input",!!O.tokenBudget&&"input--error"),placeholder:"No limit",value:S.tokenBudget??"",onChange:a=>_e("tokenBudget",a.target.value)}),O.tokenBudget?e.jsx("span",{className:"config-error",children:O.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:ne("input",!!O.usageThreshold&&"input--error"),placeholder:"80",value:S.usageThreshold??"",onChange:a=>_e("usageThreshold",a.target.value)}),O.usageThreshold?e.jsx("span",{className:"config-error",children:O.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:ne("select",!!O.budgetPeriod&&"input--error"),value:S.budgetPeriod??"",onChange:a=>_e("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"})]}),O.budgetPeriod?e.jsx("span",{className:"config-error",children:O.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:ne("input",!!O.resetDay&&"input--error"),placeholder:"Auto",value:S.resetDay??"",onChange:a=>_e("resetDay",a.target.value)}),O.resetDay?e.jsx("span",{className:"config-error",children:O.resetDay}):e.jsx("span",{className:"config-hint",children:S.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":S.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),pe?.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:ne("budget-progress-bar__fill",(pe.usagePercent??0)>=100?"budget-progress-bar__fill--red":(pe.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(pe.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(pe.currentUsage??0).toLocaleString()," / ",(pe.budgetLimit??0).toLocaleString()," tokens (",Math.round(pe.usagePercent??0),"% used)"]})]})]}),pe?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Ys(),disabled:ms,children:ms?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(os,{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:v,onChange:a=>U(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:[v==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",v==="external"&&"Specify an external directory path for the instruction files",!v&&"Select a mode to enable instruction bundling"]})]}),v&&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:d,onChange:a=>g(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),v==="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:l,onChange:a=>r(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:p.join(", "),onChange:a=>Q(a.target.value.split(",").map(m=>m.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:Le.map(a=>{const m=!!O[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:ne("select",m&&"input--error"),value:j[a.key]??"",onChange:w=>ps(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:ne("input",m&&"input--error"),placeholder:a.placeholder,value:j[a.key]??"",onChange:w=>ps(a.key,w.target.value)}),m&&e.jsx("span",{className:"config-error",children:O[a.key]}),!m&&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:!ue||je,onClick:()=>void Qs(),children:je?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(re,{size:16}),"Save Settings"]})}),Ns&&e.jsxs("span",{className:ne("config-saved-indicator",es&&"config-saved-indicator--error"),children:[je?e.jsx(_,{size:14,className:"animate-spin"}):e.jsx(re,{size:14}),Ns]})]})]}),e.jsx(xa,{agent:s,projectId:n,addToast:i,onSaved:c}),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:!gs||!f,onClick:()=>void f?.(),children:[e.jsx($e,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:gs?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle, terminated, or paused (current state: ${s.state}).`})]})})]})]})}function va({agentId:s,projectId:n,onChildClick:i}){const[c,u]=t.useState([]),[f,F]=t.useState(!0);return t.useEffect(()=>{F(!0),Ft(s,n).then(u).finally(()=>F(!1))},[s,n]),f?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:["(",c.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:c.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Hs,{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:c.map(h=>{const k=ds[h.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(h.id),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.key===" "&&L.preventDefault(),i?.(h.id))},style:{cursor:i?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:h.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:h.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:k?.bg??"var(--state-idle-bg)",color:k?.text??"var(--state-idle-text)",border:`1px solid ${k?.border??"var(--state-idle-border)"}`},children:h.state})]},h.id)})})})]})}export{Sa as AgentDetailView,we as relativeTime};
@@ -1 +0,0 @@
1
- import{r as s,j as t}from"./vendor-react-K0fH_qHe.js";import{ak as st,al as dt,am as Bt,an as Gt,ao as Vt,ap as Kt,aq as qt,ar as Xt,as as Jt,at as Yt,au as Qt,av as Zt,z as es,aw as ts,ax as ss,ay as ns,N as as,az as rs,M as vt,r as wt,S as is,a7 as ut,P as Ze,o as ls,aA as cs,aB as Oe,E as os,d as ds,aC as us,aD as hs,aE as ms,a5 as fs,aF as gs,aG as ps,aH as ht,aI as xs,aJ as vs,aK as mt,aL as ws}from"./index-NFptaeUQ.js";import"./vendor-xterm-DzcZoU0P.js";const et="kb-chat-active-session";function bs(a){const r=typeof a=="string"?a.trim():"",l=r.indexOf("/");return!r||l<=0||l>=r.length-1?{}:{modelProvider:r.slice(0,l),modelId:r.slice(l+1)}}function Ss(a){const r=a?.toolCalls;if(!Array.isArray(r))return;const l=r.map(d=>{if(!d||typeof d!="object")return null;const i=d,w=typeof i.toolName=="string"?i.toolName:"";if(!w)return null;const y=i.args;return{toolName:w,...y&&typeof y=="object"?{args:y}:{},isError:!!i.isError,result:i.result,status:"completed"}}).filter(d=>d!==null);return l.length>0?l:void 0}function ks(a){const r=a?.fallback;if(!r||typeof r!="object")return;const l=r,d=typeof l.primaryModel=="string"?l.primaryModel:"",i=typeof l.fallbackModel=="string"?l.fallbackModel:"",w=l.triggerPoint;if(!(!d||!i||w!=="session-creation"&&w!=="prompt-time"))return{primaryModel:d,fallbackModel:i,triggerPoint:w}}function tt(a){return{id:a.id,sessionId:a.sessionId,role:a.role,content:a.content,thinkingOutput:a.thinkingOutput,toolCalls:Ss(a.metadata),fallbackInfo:ks(a.metadata),attachments:a.attachments,createdAt:a.createdAt}}function ys(a,r){const[l,d]=s.useState([]),[i,w]=s.useState(null),[y,T]=s.useState(!0),[$,x]=s.useState([]),[V,S]=s.useState(!1),[P,b]=s.useState(!1),[F,h]=s.useState(""),[N,v]=s.useState(""),[E,D]=s.useState([]),[L,ee]=s.useState(""),[z,_]=s.useState(""),[J,m]=s.useState(!0),[C,ce]=s.useState(new Map),g=s.useRef(null),se=s.useRef(!1),Y=s.useRef(""),Q=s.useRef(null),ye=s.useRef(l),I=s.useRef(i),ve=s.useRef(P);ye.current=l,I.current=i,ve.current=P,s.useEffect(()=>{Y.current=L},[L]);const fe=s.useRef(new Set),oe=s.useRef(0),De=s.useRef(a);De.current!==a&&(De.current=a,oe.current++),s.useEffect(()=>{const o=oe.current;st(void 0,a).then(f=>{if(oe.current!==o)return;const p=new Map;for(const k of f)p.set(k.id,k);ce(p)}).catch(()=>{})},[a]);const de=s.useCallback(async()=>{T(!0);try{const f=[...(await dt(a)).sessions].sort((p,k)=>new Date(k.updatedAt).getTime()-new Date(p.updatedAt).getTime());d(f)}catch{}finally{T(!1)}},[a]);s.useEffect(()=>{de()},[de]);const re=s.useRef(()=>{}),Z=s.useRef(!1);s.useEffect(()=>{Z.current=!1},[a]),s.useEffect(()=>{if(y||Z.current||I.current)return;const o=Bt(et,a);if(!o){Z.current=!0;return}const f=l.find(p=>p.id===o);if(f){Z.current=!0,re.current(o,f);return}Z.current=!0},[y,l,a]);const ne=s.useCallback(async(o,f)=>{S(!0);try{const p=await Gt(o,{limit:50,...f},a),k=p.messages.map(tt);f?.offset&&f.offset>0?x(q=>[...k,...q]):x(k),m(p.messages.length>=50)}catch{}finally{S(!1)}},[a]),ie=s.useCallback(()=>{Q.current?.(),Q.current=null,Y.current="",ee(""),h(""),v(""),D([]),b(!1)},[]),le=s.useCallback((o,f)=>{const p=I.current?.id??null;if(o&&p===o&&!f)return;g.current&&(g.current.close(),g.current=null);const k=f??l.find(q=>q.id===o);w(k||null),ie(),m(!0),o?ne(o):x([]),k?.isGenerating&&(b(!0),h("")),o?Vt(et,o,a):Kt(et,a)},[l,ne,a,ie]);re.current=le;const ge=s.useCallback(async o=>{const f=await qt(o,a);g.current&&(g.current.close(),g.current=null);const p={id:f.session.id,title:f.session.title,agentId:f.session.agentId,status:f.session.status,modelProvider:f.session.modelProvider,modelId:f.session.modelId,createdAt:f.session.createdAt,updatedAt:f.session.updatedAt};return d(k=>k.some(q=>q.id===p.id)?k:[p,...k]),ie(),le(p.id,p),x([]),p},[a,ie,le]),we=s.useCallback(async o=>{await Xt(o,{status:"archived"},a),d(f=>f.filter(p=>p.id!==o)),i?.id===o&&(w(null),x([]))},[i,a]),ue=s.useCallback(async o=>{i?.id===o&&g.current&&(g.current.close(),g.current=null),await Jt(o,a),d(f=>f.filter(p=>p.id!==o)),i?.id===o&&(w(null),x([]))},[i,a]),ae=s.useCallback(async()=>{!i||!J||await ne(i.id,{offset:$.length})},[i,J,ne,$.length]),he=s.useCallback(()=>{i&&(se.current=!0,Q.current?.(),Q.current=null,g.current?.close(),g.current=null,Yt(i.id,a).catch(()=>{}),b(!1),h(""),v(""),D([]))},[i,a]),Ce=s.useCallback(()=>{Y.current="",ee("")},[]),me=s.useCallback((o,f)=>{if(!i)return;if(P){Y.current=o,ee(o);return}se.current=!1,g.current&&(g.current.close(),g.current=null);const p=`temp-${Date.now()}`,k={id:p,sessionId:i.id,role:"user",content:o,createdAt:new Date().toISOString()};x(K=>[...K,k]),h(""),v(""),D([]),b(!0);const{handlers:q}=Qt({sessionId:i.id,tempUserMessageId:p,setStreamingText:h,setStreamingThinking:v,setStreamingToolCalls:D,cancelStreamingFlushesRef:Q,addToast:r,onFallbackSession:(K,X)=>{const M=bs(K.fallbackModel);d(H=>H.map(R=>R.id===X?{...R,...M}:R)),w(H=>H&&H.id===X?{...H,...M}:H)},onDone:({messageId:K,message:X,accumulated:M})=>{const H=X?tt(X):{id:K||`msg-${Date.now()}`,sessionId:i.id,role:"assistant",content:M.text,thinkingOutput:M.thinking,toolCalls:M.toolCalls.length>0?M.toolCalls:void 0,fallbackInfo:M.fallbackInfo,createdAt:new Date().toISOString()};fe.current.add(H.id),x(u=>[...u,H]),h(""),v(""),D([]),b(!1),g.current=null,setTimeout(()=>{fe.current.delete(H.id)},1e3),de();const R=Y.current.trim();R&&(Y.current="",ee(""),me(R))},onError:(K,X)=>{if(x(M=>M.filter(H=>H.id!==X)),h(""),v(""),D([]),b(!1),g.current=null,console.error("[useChat] Stream error:",K),r?.(typeof K=="string"&&K.trim()?K:"Failed to get response","error"),!se.current){const M=Y.current.trim();M&&(Y.current="",ee(""),me(M))}}});g.current=Zt(i.id,o,q,f,a)},[i,P,a,de,r]),Ne=z?l.filter(o=>o.title?.toLowerCase().includes(z.toLowerCase())||o.agentId.toLowerCase().includes(z.toLowerCase())):l;return s.useEffect(()=>{if(!P||g.current||!I.current)return;const o=setInterval(async()=>{if(!ve.current||g.current||!I.current){clearInterval(o);return}try{(await dt(a)).sessions.find(k=>k.id===I.current?.id)?.isGenerating||(clearInterval(o),await ne(I.current.id),h(""),v(""),D([]),b(!1))}catch{}},3e3);return()=>clearInterval(o)},[P,ne,a]),s.useEffect(()=>{const o=oe.current,f=a?`?projectId=${encodeURIComponent(a)}`:"",p=()=>oe.current!==o,k=R=>{if(p())return;const u=JSON.parse(R.data);d(j=>j.some(U=>U.id===u.id)?j:[u,...j])},q=R=>{if(p())return;const u=JSON.parse(R.data);d(j=>[...j.map(O=>O.id===u.id?u:O)]),I.current?.id===u.id&&w(u)},K=R=>{if(p())return;const{id:u}=JSON.parse(R.data);d(j=>j.filter(U=>U.id!==u)),I.current?.id===u&&(w(null),x([]))},X=R=>{if(p())return;const u=JSON.parse(R.data),j=tt(u);if(!fe.current.has(j.id)){if(I.current?.id===j.sessionId&&ve.current&&!g.current&&j.role==="assistant"){x(U=>U.some(O=>O.id===j.id)?U:[...U,j]),h(""),v(""),D([]),b(!1);return}I.current?.id===j.sessionId&&!ve.current&&x(U=>U.some(O=>O.id===j.id)?U:[...U,j])}},M=R=>{if(p())return;const{id:u}=JSON.parse(R.data);x(j=>j.filter(U=>U.id!==u))};return es(`/api/events${f}`,{events:{"chat:session:created":k,"chat:session:updated":q,"chat:session:deleted":K,"chat:message:added":X,"chat:message:deleted":M}})},[a]),s.useEffect(()=>()=>{g.current&&(g.current.close(),g.current=null)},[]),{sessions:l,activeSession:i,sessionsLoading:y,messages:$,messagesLoading:V,isStreaming:P,streamingText:F,streamingThinking:N,streamingToolCalls:E,pendingMessage:L,selectSession:le,createSession:ge,archiveSession:we,deleteSession:ue,sendMessage:me,stopStreaming:he,clearPendingMessage:Ce,loadMoreMessages:ae,hasMoreMessages:J,searchQuery:z,setSearchQuery:_,filteredSessions:Ne,refreshSessions:de,agentsMap:C}}function bt(a){const r=new Date(a),d=new Date().getTime()-r.getTime(),i=Math.floor(d/1e3),w=Math.floor(i/60),y=Math.floor(w/60),T=Math.floor(y/24);return i<60?"just now":w<60?`${w}m ago`:y<24?`${y}h ago`:T<7?`${T}d ago`:r.toLocaleDateString()}function ft(a,r){if(!a||!r)return null;const l=r.toLowerCase();if(l.includes("claude")){let i=r.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return i=i.replace(/\s+/g," "),i.length>30?i.slice(0,30)+"…":i}if(l.includes("gpt")||l.includes("openai")){const i=r.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return i.length>30?i.slice(0,30)+"…":i}if(l.includes("gemini")){const i=r.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return i.length>30?i.slice(0,30)+"…":i}const d=r.replace(/-/g," ").replace(/^\w/,i=>i.toUpperCase()).replace(/\s+/g," ").trim();return d.length>30?d.slice(0,30)+"…":d}function Ue(a,r){return a.length<=r?a:`${a.slice(0,r)}…`}function Cs(a){if(!a)return null;const r=Object.entries(a);return r.length===0?null:r.map(([l,d])=>{const i=typeof d=="string"?d:(()=>{try{return JSON.stringify(d)}catch{return String(d)}})();return`${l}=${Ue(i,50)}`}).join(", ")}function Ns(a){if(a===void 0)return null;if(typeof a=="string")return Ue(a,200);try{return Ue(JSON.stringify(a),200)}catch{return Ue(String(a),200)}}function St(a){if(!a||a.length===0)return null;const r=(S,P)=>{const b=S.status==="running",F=S.status==="completed"&&S.isError,h=Cs(S.args),N=Ns(S.result),v=b?h:N?`result: ${N}`:h?`args: ${h}`:null,E=b?"running":F?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${b?" chat-tool-call--running":""}${F?" chat-tool-call--error":""}`,open:b,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:S.toolName}),v&&t.jsx("span",{className:"chat-tool-call-preview",title:v,children:v}),t.jsx("span",{className:"chat-tool-call-status-text",children:E})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[h&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:h})]}),N&&t.jsxs("div",{className:`chat-tool-call-row${F?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:N})]})]})]},`${S.toolName}-${P}`)},l="chat-tool-calls";if(a.length===1)return t.jsxs("div",{className:l,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(ht,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),r(a[0],0)]});const d=a.filter(S=>S.status==="running").length,i=a.filter(S=>S.status==="completed"&&S.isError).length,w=d>0,y=Array.from(new Set(a.map(S=>S.toolName))),T=y.slice(0,5),$=Math.max(0,y.length-T.length),x=$>0?`${T.join(", ")}, +${$} more`:T.join(", "),V=w?`(${d} running)`:i>0?`(${i} ${i===1?"error":"errors"})`:null;return t.jsx("div",{className:l,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:w,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(ht,{size:12,"aria-hidden":"true"}),t.jsxs("span",{children:[a.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:x,children:x}),V&&t.jsx("span",{className:"chat-tool-calls-group-status",children:V})]}),a.map((S,P)=>r(S,P))]})})}const kt={pre:({children:a,...r})=>t.jsx("pre",{...r,className:"chat-markdown-pre",children:a}),table:({children:a,...r})=>t.jsx("table",{...r,className:"chat-markdown-table",children:a})},Pe="__fn_agent__",js=280,Le=180,ze=500,gt="fusion:chat-sidebar-width",Ms=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function pt(a){const r=/(^|[\s])\/([^\s]*)$/.exec(a);if(!r)return null;const l=r[1]??"",d=r[2]??"",i=r.index+l.length;return{filter:d,start:i,end:a.length}}function As(a,r){const l=a.slice(0,r),d=/(^|[\s\n])@([\w-]*)$/.exec(l);if(!d)return null;const i=d[2]??"",w=l.length-i.length-1;return{filter:i,start:w,end:r}}function Ts({projectId:a,onClose:r,onCreate:l}){const[d,i]=s.useState("agent"),[w,y]=s.useState([]),[T,$]=s.useState(!0),[x,V]=s.useState(""),[S,P]=s.useState([]),[b,F]=s.useState(!0),[h,N]=s.useState(""),[v,E]=s.useState([]),[D,L]=s.useState([]);s.useEffect(()=>{let m=!1;return $(!0),st(void 0,a).then(C=>{m||y(C)}).catch(()=>{m||y([])}).finally(()=>{m||$(!1)}),()=>{m=!0}},[a]),s.useEffect(()=>{F(!0),vs().then(m=>{P(m.models),E(m.favoriteProviders),L(m.favoriteModels)}).catch(()=>{P([]),E([]),L([])}).finally(()=>{F(!1)})},[]);const ee=s.useCallback(async m=>{const C=v,g=C.includes(m)?C.filter(se=>se!==m):[m,...C];E(g);try{await mt({favoriteProviders:g,favoriteModels:D})}catch{E(C)}},[v,D]),z=s.useCallback(async m=>{const C=D,g=C.includes(m)?C.filter(se=>se!==m):[m,...C];L(g);try{await mt({favoriteProviders:v,favoriteModels:g})}catch{L(C)}},[D,v]),_=m=>{if(m.preventDefault(),d==="agent"){if(!x)return;l({agentId:x});return}if(!h)return;const C=h.indexOf("/");if(C<=0)return;const ce=h.slice(0,C),g=h.slice(C+1);l({agentId:Pe,modelProvider:ce,modelId:g})},J=d==="agent"?!x:!h;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:m=>m.stopPropagation(),children:[t.jsx("h3",{children:"New Chat"}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${d==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{i("agent"),N("")},children:"Agent"}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${d==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{i("model"),V("")},children:"Model"})]}),t.jsxs("form",{onSubmit:_,children:[d==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",T?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):w.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:w.map(m=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${x===m.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>V(m.id),"data-testid":`agent-option-${m.id}`,children:[t.jsx(Oe,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:m.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:m.role})]},m.id))})]}),d==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:b?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):t.jsx(ws,{models:S,value:h,onChange:N,label:"Model",placeholder:"Select a model",favoriteProviders:v,onToggleFavorite:ee,favoriteModels:D,onToggleModelFavorite:z})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:r,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:J,children:"Create"})]})]})]})})}const xt=s.memo(function({message:r,forcePlain:l,agentName:d,hideAssistantIdentity:i,showAssistantModelTag:w,activeModelTag:y,activeSessionId:T,mentionAgentsByName:$}){const x=r.role==="assistant",V=s.useMemo(()=>{if(x)return null;const b=r.content,F=/@([\w-]+)/g,h=[];let N=0,v=F.exec(b);for(;v;){const[E,D=""]=v,L=v.index;L>N&&h.push(b.slice(N,L));const ee=D.replace(/_/g," ").toLowerCase(),z=$.get(ee);z?h.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",z.name.replace(/\s+/g,"_")]},`${z.id}-${L}`)):h.push(E),N=L+E.length,v=F.exec(b)}return N<b.length&&h.push(b.slice(N)),h.length===0?b:h},[x,r.content,$]),S=s.useMemo(()=>{const b=r.attachments;if(!b||b.length===0||!T)return null;const F=`/api/chat/sessions/${encodeURIComponent(T)}/attachments/`;return t.jsx("div",{className:"chat-message-attachments",children:b.map(h=>{const N=h.mimeType.startsWith("image/"),v=h.id||h.filename,E=`${F}${encodeURIComponent(h.filename)}`;return N?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:E,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:E,alt:h.originalName})},v):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:E,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(ps,{size:14}),t.jsx("span",{children:h.originalName})]},v)})})},[r.attachments,T]),P=s.useMemo(()=>x?l?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:r.content}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(vt,{remarkPlugins:[wt],components:kt,children:r.content})}):null,[x,l,r.content]);return t.jsxs("div",{className:`chat-message chat-message--${r.role}`,"data-testid":`chat-message-${r.id}`,children:[x&&!i&&t.jsxs("div",{className:"chat-message-avatar",children:[t.jsx(Oe,{size:14}),t.jsx("span",{children:d}),w&&y&&t.jsx("span",{className:"chat-model-tag",children:y})]}),x?P:t.jsx("div",{className:"chat-message-content",children:V}),St(r.toolCalls),r.thinkingOutput&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:r.thinkingOutput})]}),S,t.jsx("div",{className:"chat-message-time",children:bt(r.createdAt)})]})});function Es({projectId:a,addToast:r}){const{activeSession:l,sessionsLoading:d,messages:i,messagesLoading:w,isStreaming:y,streamingText:T,streamingThinking:$,streamingToolCalls:x,selectSession:V,createSession:S,archiveSession:P,deleteSession:b,sendMessage:F,stopStreaming:h,pendingMessage:N,clearPendingMessage:v,searchQuery:E,setSearchQuery:D,filteredSessions:L}=ys(a,r),[ee,z]=s.useState(!1),[_,J]=s.useState(""),[m,C]=s.useState(null),[ce,g]=s.useState(null),[se,Y]=s.useState(!0),[Q,ye]=s.useState(js),[I,ve]=s.useState(new Map),[fe,oe]=s.useState([]),[De,de]=s.useState(!0),[re,Z]=s.useState(!1),[ne,ie]=s.useState(""),[le,ge]=s.useState(0),[we,ue]=s.useState(""),[ae,he]=s.useState(!1),[Ce,me]=s.useState(0),[Ne,o]=s.useState(-1),[f,p]=s.useState(!1),[k,q]=s.useState([]),[K,X]=s.useState(!1),[,M]=s.useState(!1),[H,R]=s.useState({top:0,left:0}),u=ts({projectId:a}),j=s.useCallback(e=>{if(!e||!u.mentionActive)return;const n=e.getBoundingClientRect();R({top:n.top-260,left:n.left+8})},[u.mentionActive]),U=s.useRef(null),O=s.useRef(null),_e=s.useRef(null),W=s.useRef(null),Re=s.useRef(!1),$e=s.useRef(!1),nt=s.useRef(null),at=s.useRef([]),je=s.useRef(0),B=ss()==="mobile";s.useEffect(()=>{try{const e=localStorage.getItem(gt);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const c=Math.max(Le,Math.min(ze,n));ye(c)}catch{}},[]);const{keyboardOverlap:He,viewportHeight:rt,viewportOffsetTop:yt,keyboardOpen:it}=ns({enabled:B&&!!l}),Ct=it?{"--keyboard-overlap":`${He}px`,"--vv-offset-top":`${yt}px`,...rt!==null?{"--vv-height":`${rt}px`}:{}}:{},te=s.useMemo(()=>{const e=ne.trim().toLowerCase();return(e?fe.filter(c=>c.name.toLowerCase().includes(e)):fe).slice(0,10)},[fe,ne]),be=s.useMemo(()=>Array.from(I.values()),[I]),pe=s.useMemo(()=>{const e=we.trim().toLowerCase();return e?be.filter(n=>n.name.toLowerCase().includes(e)):be},[be,we]),lt=s.useMemo(()=>{const e=new Map;for(const n of be)e.set(n.name.toLowerCase(),n);return e},[be]);s.useEffect(()=>{ge(0)},[te]),s.useEffect(()=>{me(0)},[we,ae]),s.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]),s.useEffect(()=>{const e=_e.current;e&&(e.scrollTop=e.scrollHeight)},[i,T,$,y]),s.useEffect(()=>{if(He<=0)return;const e=_e.current;e&&(e.scrollTop=e.scrollHeight)},[He]),as(B&&it),s.useEffect(()=>{const e=()=>C(null);if(m)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[m]),s.useEffect(()=>{let e=!1;const n=a;return st(void 0,a).then(c=>{if(e||n!==a)return;const A=new Map;for(const G of c)A.set(G.id,G);ve(A)}).catch(()=>{}),()=>{e=!0}},[a]),s.useEffect(()=>{let e=!1;return de(!0),rs(a).then(n=>{e||oe(n)}).catch(()=>{e||oe([])}).finally(()=>{e||de(!1)}),()=>{e=!0}},[a]),s.useEffect(()=>{at.current=k},[k]),s.useEffect(()=>()=>{for(const e of at.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl)},[]);const Ee=s.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const c of Array.from(e)){if(!Ms.includes(c.type))continue;const A=c.type.startsWith("image/");n.push({file:c,previewUrl:A?URL.createObjectURL(c):""})}n.length>0&&q(c=>[...c,...n])},[]),Nt=s.useCallback(e=>{q(n=>{const c=n[e];return c?.previewUrl&&URL.revokeObjectURL(c.previewUrl),n.filter((A,G)=>G!==e)})},[]),jt=s.useCallback(e=>{const n=e.clipboardData?.files;if(!n||n.length===0)return;const c=Array.from(n).filter(A=>A.type.startsWith("image/"));c.length!==0&&Ee(c)},[Ee]),Mt=s.useCallback(async e=>{try{await S(e),z(!1),B&&Y(!1)}catch{r("Failed to create chat session","error")}},[S,r,B]),We=s.useCallback(()=>{J(""),Z(!1),ie(""),he(!1),ue(""),o(-1),q(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[]),Me=s.useCallback(()=>{const e=_.trim(),n=k.map(c=>c.file);if(!(!e&&n.length===0||!l)){if(e==="/clear"){We(),h(),v(),S({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0}).catch(()=>{r("Failed to clear conversation","error")});return}We(),F(e,n)}},[_,k,l,We,h,v,S,r,F]),Ie=s.useCallback(()=>{if(typeof window>"u"||window.innerWidth>768)return;const e=W.current;if(!e||e.disabled)return;const n=window.scrollX,c=window.scrollY;e.focus({preventScroll:!0}),window.requestAnimationFrame(()=>{(window.scrollX!==n||window.scrollY!==c)&&window.scrollTo(n,c)})},[]),ct=s.useCallback(()=>{typeof window>"u"||window.innerWidth>768||(Re.current=!0)},[]),Be=s.useCallback(e=>{J(n=>{const c=pt(n);if(!c)return n;const A=`/skill:${e.name} `,G=n.slice(0,c.start)+A+n.slice(c.end);return window.requestAnimationFrame(()=>{W.current&&(W.current.style.height="auto",W.current.style.height=`${Math.min(W.current.scrollHeight,120)}px`,W.current.focus())}),G}),Z(!1),ie(""),ge(0)},[]),Ge=s.useCallback(e=>{const n=W.current;if(!n||Ne<0)return;const c=n.selectionStart??je.current,A=n.selectionEnd??c,G=Math.max(c,A),Te=Math.min(Ne,G),Se=`${`@${e.name.replace(/\s+/g,"_")}`} `,Qe=_.slice(0,Te)+Se+_.slice(G),ke=Te+Se.length;J(Qe),he(!1),ue(""),me(0),o(-1),window.requestAnimationFrame(()=>{W.current&&(W.current.style.height="auto",W.current.style.height=`${Math.min(W.current.scrollHeight,120)}px`,W.current.focus(),W.current.setSelectionRange(ke,ke))})},[Ne,_]),At=s.useCallback(e=>{if(je.current=e.currentTarget.selectionStart??je.current,u.mentionActive&&u.files.length>0){if(u.handleKeyDown(e,_),e.key==="Enter"||e.key==="Tab"){const n=u.files[u.selectedIndex];if(n){const c=u.selectFile(n,_);J(c),u.dismissMention(),M(!1)}}return}if(ae&&e.key==="ArrowDown"){e.preventDefault(),pe.length>0&&me(n=>(n+1)%pe.length);return}if(ae&&e.key==="ArrowUp"){e.preventDefault(),pe.length>0&&me(n=>n===0?pe.length-1:n-1);return}if(ae&&e.key==="Enter"){e.preventDefault();const n=pe[Ce]??pe[0];n&&Ge(n);return}if(ae&&e.key==="Escape"){e.preventDefault(),he(!1),ue(""),o(-1);return}if(re&&e.key==="ArrowDown"){e.preventDefault(),te.length>0&&ge(n=>(n+1)%te.length);return}if(re&&e.key==="ArrowUp"){e.preventDefault(),te.length>0&&ge(n=>n===0?te.length-1:n-1);return}if(re&&(e.key==="Enter"||e.key==="Tab")&&te.length>0){e.preventDefault();const n=te[le]??te[0];n&&Be(n);return}if(re&&e.key==="Escape"){e.preventDefault(),Z(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Me())},[ae,pe,Ce,Ge,re,te,le,Be,Me,u,_]),Fe=s.useCallback((e,n)=>{const c=As(e,n);if(c){he(!0),ue(c.filter),o(c.start);return}he(!1),ue(""),o(-1)},[]),Tt=s.useCallback(e=>{const n=e.target,c=n.value,A=n.selectionStart??c.length;je.current=A,J(c);const G=pt(c);G?(Z(!0),ie(G.filter)):(Z(!1),ie("")),Fe(c,A),u.detectMention(c,A),M(u.mentionActive),u.mentionActive&&j(n),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,120)}px`},[Fe]),Ve=s.useCallback(e=>{const n=e.currentTarget,c=n.selectionStart??n.value.length;je.current=c,Fe(n.value,c),u.detectMention(n.value,c),M(u.mentionActive),u.mentionActive&&j(n)},[Fe,u,j]),Pt=s.useCallback(e=>{e.key!=="Escape"&&Ve(e)},[Ve]),Dt=s.useCallback(()=>{if(Re.current){window.requestAnimationFrame(()=>{Ie()});return}O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{Z(!1),he(!1),ue(""),o(-1),M(!1),u.dismissMention(),O.current=null},120)},[u,Ie]),Rt=s.useCallback(()=>{O.current!==null&&(window.clearTimeout(O.current),O.current=null)},[]),$t=s.useCallback(async e=>{C(null);try{await P(e),r("Conversation archived","success")}catch{r("Failed to archive conversation","error")}},[P,r]),Et=s.useCallback(async e=>{g(null),C(null);try{await b(e),r("Conversation deleted","success")}catch{r("Failed to delete conversation","error")}},[b,r]),Ae=s.useCallback(e=>{try{localStorage.setItem(gt,String(e))}catch{}},[]),It=s.useCallback(e=>{if(B)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const c=e.clientX,A=Q;let G=A;document.body.style.userSelect="none";const Te=Se=>{const Qe=Se.clientX-c,ke=Math.max(Le,Math.min(ze,A+Qe));G=ke,ye(ke),Ae(ke)},Ye=Se=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(Se.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Te),document.removeEventListener("pointerup",Ye),Ae(G)};document.addEventListener("pointermove",Te),document.addEventListener("pointerup",Ye)},[B,Ae,Q]),Ft=s.useCallback(e=>{if(B||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,c=e.key==="ArrowLeft"?-n:n,A=Math.max(Le,Math.min(ze,Q+c));ye(A),Ae(A)},[B,Ae,Q]),Lt=s.useCallback(e=>{V(e),B&&Y(!1)},[V,B]),zt=s.useCallback(()=>{V(""),Y(!0)},[V]),Ut=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(xs,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>z(!0),children:[t.jsx(Ze,{size:16}),"New Chat"]})]}),xe=ft(l?.modelProvider,l?.modelId),Ke=!!(l||y||i.length>0),ot=l?.agentId===Pe?xe??"Fusion":l?.title||I.get(l?.agentId??"")?.name||l?.agentId||"Chat",Ot=!!(xe&&xe!==ot),qe=I.get(l?.agentId??"")?.name||(l?.agentId===Pe?xe??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),Xe=!1,Je=l?.agentId===Pe,_t=N.length>50?`${N.slice(0,50)}…`:N,Ht=s.useCallback(()=>{p(e=>!e)},[]),Wt=s.useCallback((e,n=!1)=>n?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:e}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(vt,{remarkPlugins:[wt],components:kt,children:e})}),[]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${se?"":" chat-sidebar--hidden"}`,style:B?void 0:{width:`${Q}px`},children:[t.jsx("div",{className:"chat-sidebar-search",children:t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(is,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:E,onChange:e=>D(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:d?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"Loading..."}):L.length===0?t.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"No conversations yet"}):L.map(e=>t.jsxs("div",{className:`chat-session-item${l?.id===e.id?" chat-session-item--active":""}`,onClick:()=>Lt(e.id),onContextMenu:n=>{n.preventDefault(),C({sessionId:e.id,x:n.clientX,y:n.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:n=>{n.stopPropagation(),g(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(ut,{size:14})}),t.jsx("div",{className:"chat-session-title",children:e.title||"Untitled"}),t.jsx("div",{className:"chat-session-preview",children:e.lastMessagePreview||"No messages"}),t.jsxs("div",{className:"chat-session-meta",children:[t.jsx("span",{children:I.get(e.agentId)?.name||(e.agentId===Pe?ft(e.modelProvider,e.modelId)??"Fusion":e.agentId.slice(0,30))}),t.jsx("span",{children:e.updatedAt?bt(e.updatedAt):""})]})]},e.id))}),t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>z(!0),"data-testid":"chat-new-btn",children:[t.jsx(Ze,{size:14}),"New Chat"]})})]}),!B&&se&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Le,"aria-valuemax":ze,"aria-valuenow":Q,"aria-label":"Resize chat sidebar",tabIndex:0,onPointerDown:It,onKeyDown:Ft}),m&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:m.y,left:m.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>$t(m.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(ls,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{C(null),g(m.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(ut,{size:14}),"Delete"]})]}),ce&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>g(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Conversation?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. All messages in this conversation will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>g(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Et(ce),children:"Delete"})]})]})}),t.jsxs("div",{className:"chat-thread",style:Ct,children:[(Ke||!B)&&t.jsxs("div",{className:"chat-thread-header",children:[B&&Ke&&t.jsx("button",{className:"btn-icon",onClick:zt,"data-testid":"chat-back-btn",children:t.jsx(cs,{size:16})}),t.jsx(Oe,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:ot}),Ot&&t.jsx("span",{className:"chat-model-tag",children:xe}),Ke&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${f?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":f?"Show all messages as rendered Markdown":"Show all messages as plain text",onClick:Ht,children:f?t.jsx(os,{size:14}):t.jsx(ds,{size:14})}),!B&&t.jsxs("button",{className:"btn btn-sm btn-primary chat-thread-header-new-chat",onClick:()=>z(!0),"data-testid":"chat-thread-new-chat-btn",children:[t.jsx(Ze,{size:14}),"New Chat"]})]}),t.jsxs("div",{className:"chat-messages",ref:_e,children:[y?t.jsxs(t.Fragment,{children:[i.map(e=>t.jsx(xt,{message:e,forcePlain:f,agentName:qe,hideAssistantIdentity:Je,showAssistantModelTag:Xe,activeModelTag:xe,activeSessionId:l?.id??null,mentionAgentsByName:lt},e.id)),t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!Je&&t.jsxs("div",{className:"chat-message-avatar",children:[t.jsx(Oe,{size:14}),t.jsx("span",{children:qe}),Xe]}),T?Wt(T,f):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:$?"Thinking…":"Connecting…"}),St(x),$&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:$})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}):w?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Loading messages..."}):i.length===0&&!l?Ut():i.length===0&&l?t.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:i.map(e=>t.jsx(xt,{message:e,forcePlain:f,agentName:qe,hideAssistantIdentity:Je,showAssistantModelTag:Xe,activeModelTag:xe,activeSessionId:l?.id??null,mentionAgentsByName:lt},e.id))}),t.jsx("div",{ref:U})]}),l&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:nt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{Ee(e.target.files),e.target.value=""}}),re&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:De?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):te.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ne?"No skills found":"No skills available"}):te.map((e,n)=>t.jsxs("button",{type:"button",role:"option","aria-selected":n===le,className:`chat-skill-menu-item${n===le?" chat-skill-menu-item--highlighted":""}`,onMouseDown:c=>c.preventDefault(),onMouseEnter:()=>ge(n),onClick:()=>Be(e),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.relativePath,children:e.relativePath})]},e.id))}),k.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:k.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>Nt(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":"Attach files",onClick:()=>nt.current?.click(),children:t.jsx(us,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${K?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),X(!0)},onDragLeave:()=>X(!1),onDrop:e=>{e.preventDefault(),X(!1),Ee(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:W,className:"chat-input-textarea",placeholder:"Type a message...",value:_,onChange:Tt,onKeyDown:At,onKeyUp:Pt,onClick:Ve,onBlur:Dt,onFocus:Rt,onPaste:jt,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(hs,{agents:be,filter:we,highlightedIndex:Ce,visible:ae,onSelect:Ge,position:"below"}),t.jsx(ms,{visible:u.mentionActive&&!ae,position:H,files:u.files,selectedIndex:u.selectedIndex,onSelect:e=>{const n=u.selectFile(e,_);J(n),u.dismissMention(),M(!1),W.current?.focus()},loading:u.loading}),N&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${_t}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:v,children:"×"})]})]}),y?t.jsx("button",{className:"chat-input-stop",onClick:h,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(fs,{size:14})}):t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{typeof window>"u"||window.innerWidth>768||(e.preventDefault(),e.pointerType&&e.pointerType!=="mouse"&&($e.current=!0,ct(),Ie(),Me(),window.setTimeout(()=>{Re.current=!1},1500)))},onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||(e.preventDefault(),$e.current=!0,ct(),Ie(),Me(),window.setTimeout(()=>{Re.current=!1},1500))},onMouseDown:e=>{typeof window>"u"||window.innerWidth>768||e.preventDefault()},onClick:()=>{if($e.current){$e.current=!1;return}Me()},disabled:!_.trim()&&k.length===0,"data-testid":"chat-send-btn",children:t.jsx(gs,{size:16})})]})]})]}),ee&&t.jsx(Ts,{projectId:a,onClose:()=>z(!1),onCreate:Mt})]})}export{Es as ChatView};