@contractspec/example.agent-console 3.8.9 → 3.8.10

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 (228) hide show
  1. package/.turbo/turbo-build.log +225 -222
  2. package/CHANGELOG.md +18 -0
  3. package/dist/agent/agent.entity.js +1 -127
  4. package/dist/agent/agent.enum.js +1 -25
  5. package/dist/agent/agent.event.js +1 -116
  6. package/dist/agent/agent.handler.js +1 -1030
  7. package/dist/agent/agent.operation.js +1 -735
  8. package/dist/agent/agent.presentation.js +1 -282
  9. package/dist/agent/agent.schema.js +1 -215
  10. package/dist/agent/agent.test-spec.js +1 -58
  11. package/dist/agent/index.js +1 -1248
  12. package/dist/agent.capability.js +1 -19
  13. package/dist/agent.feature.js +1 -305
  14. package/dist/browser/agent/agent.entity.js +1 -127
  15. package/dist/browser/agent/agent.enum.js +1 -25
  16. package/dist/browser/agent/agent.event.js +1 -116
  17. package/dist/browser/agent/agent.handler.js +1 -1030
  18. package/dist/browser/agent/agent.operation.js +1 -735
  19. package/dist/browser/agent/agent.presentation.js +1 -282
  20. package/dist/browser/agent/agent.schema.js +1 -215
  21. package/dist/browser/agent/agent.test-spec.js +1 -58
  22. package/dist/browser/agent/index.js +1 -1248
  23. package/dist/browser/agent.capability.js +1 -19
  24. package/dist/browser/agent.feature.js +1 -305
  25. package/dist/browser/docs/agent-console.docblock.js +5 -49
  26. package/dist/browser/docs/index.js +5 -49
  27. package/dist/browser/example.js +1 -41
  28. package/dist/browser/handlers/agent.handlers.js +6 -2143
  29. package/dist/browser/handlers/index.js +6 -2943
  30. package/dist/browser/index.js +14 -6828
  31. package/dist/browser/presentations/index.js +1 -693
  32. package/dist/browser/run/index.js +1 -1363
  33. package/dist/browser/run/run.entity.js +1 -160
  34. package/dist/browser/run/run.enum.js +1 -34
  35. package/dist/browser/run/run.event.js +1 -217
  36. package/dist/browser/run/run.handler.js +1 -919
  37. package/dist/browser/run/run.operation.js +1 -667
  38. package/dist/browser/run/run.presentation.js +1 -223
  39. package/dist/browser/run/run.schema.js +1 -179
  40. package/dist/browser/run/run.test-spec.js +1 -58
  41. package/dist/browser/seeders/index.js +2 -21
  42. package/dist/browser/shared/index.js +1 -626
  43. package/dist/browser/shared/mock-agents.js +1 -82
  44. package/dist/browser/shared/mock-runs.js +1 -113
  45. package/dist/browser/shared/mock-tools.js +1 -146
  46. package/dist/browser/tool/index.js +1 -949
  47. package/dist/browser/tool/tool.entity.js +1 -90
  48. package/dist/browser/tool/tool.enum.js +1 -26
  49. package/dist/browser/tool/tool.event.js +1 -99
  50. package/dist/browser/tool/tool.handler.js +1 -699
  51. package/dist/browser/tool/tool.operation.js +1 -482
  52. package/dist/browser/tool/tool.presentation.js +1 -188
  53. package/dist/browser/tool/tool.schema.js +1 -141
  54. package/dist/browser/tool/tool.test-spec.js +1 -58
  55. package/dist/browser/ui/AgentDashboard.js +1 -2527
  56. package/dist/browser/ui/AgentDashboard.visualizations.js +1 -217
  57. package/dist/browser/ui/AgentRunList.js +1 -482
  58. package/dist/browser/ui/AgentToolRegistry.js +1 -212
  59. package/dist/browser/ui/ExecutionConsoleHost.js +1 -0
  60. package/dist/browser/ui/hooks/index.js +1 -740
  61. package/dist/browser/ui/hooks/useAgentList.js +1 -55
  62. package/dist/browser/ui/hooks/useAgentMutations.js +1 -530
  63. package/dist/browser/ui/hooks/useRunList.js +1 -70
  64. package/dist/browser/ui/hooks/useToolList.js +1 -85
  65. package/dist/browser/ui/index.js +5 -3018
  66. package/dist/browser/ui/modals/AgentActionsModal.js +1 -304
  67. package/dist/browser/ui/modals/CreateAgentModal.js +1 -243
  68. package/dist/browser/ui/modals/index.js +1 -546
  69. package/dist/browser/ui/overlays/demo-overlays.js +1 -64
  70. package/dist/browser/ui/overlays/index.js +1 -64
  71. package/dist/browser/ui/renderers/agent-list.markdown.js +2 -64
  72. package/dist/browser/ui/renderers/agent-list.renderer.js +1 -180
  73. package/dist/browser/ui/renderers/dashboard.markdown.js +2 -288
  74. package/dist/browser/ui/renderers/index.js +5 -642
  75. package/dist/browser/ui/renderers/run-list.markdown.js +2 -50
  76. package/dist/browser/ui/renderers/tool-registry.markdown.js +2 -64
  77. package/dist/browser/ui/views/AgentListView.js +1 -165
  78. package/dist/browser/ui/views/RunDataTable.js +1 -326
  79. package/dist/browser/ui/views/RunListView.js +1 -479
  80. package/dist/browser/ui/views/ToolRegistryView.js +1 -209
  81. package/dist/browser/ui/views/index.js +1 -851
  82. package/dist/browser/ui/views/run-data-table.columns.js +1 -271
  83. package/dist/browser/ui/views/run-list.shared.js +1 -177
  84. package/dist/browser/visualizations/catalog.js +1 -134
  85. package/dist/browser/visualizations/index.js +1 -187
  86. package/dist/browser/visualizations/selectors.js +1 -181
  87. package/dist/docs/agent-console.docblock.js +5 -49
  88. package/dist/docs/index.js +5 -49
  89. package/dist/example.js +1 -41
  90. package/dist/handlers/agent.handlers.js +6 -2143
  91. package/dist/handlers/index.js +6 -2943
  92. package/dist/index.js +14 -6828
  93. package/dist/node/agent/agent.entity.js +1 -127
  94. package/dist/node/agent/agent.enum.js +1 -25
  95. package/dist/node/agent/agent.event.js +1 -116
  96. package/dist/node/agent/agent.handler.js +1 -1030
  97. package/dist/node/agent/agent.operation.js +1 -735
  98. package/dist/node/agent/agent.presentation.js +1 -282
  99. package/dist/node/agent/agent.schema.js +1 -215
  100. package/dist/node/agent/agent.test-spec.js +1 -58
  101. package/dist/node/agent/index.js +1 -1248
  102. package/dist/node/agent.capability.js +1 -19
  103. package/dist/node/agent.feature.js +1 -305
  104. package/dist/node/docs/agent-console.docblock.js +5 -49
  105. package/dist/node/docs/index.js +5 -49
  106. package/dist/node/example.js +1 -41
  107. package/dist/node/handlers/agent.handlers.js +6 -2143
  108. package/dist/node/handlers/index.js +6 -2943
  109. package/dist/node/index.js +14 -6828
  110. package/dist/node/presentations/index.js +1 -693
  111. package/dist/node/run/index.js +1 -1363
  112. package/dist/node/run/run.entity.js +1 -160
  113. package/dist/node/run/run.enum.js +1 -34
  114. package/dist/node/run/run.event.js +1 -217
  115. package/dist/node/run/run.handler.js +1 -919
  116. package/dist/node/run/run.operation.js +1 -667
  117. package/dist/node/run/run.presentation.js +1 -223
  118. package/dist/node/run/run.schema.js +1 -179
  119. package/dist/node/run/run.test-spec.js +1 -58
  120. package/dist/node/seeders/index.js +2 -21
  121. package/dist/node/shared/index.js +1 -626
  122. package/dist/node/shared/mock-agents.js +1 -82
  123. package/dist/node/shared/mock-runs.js +1 -113
  124. package/dist/node/shared/mock-tools.js +1 -146
  125. package/dist/node/tool/index.js +1 -949
  126. package/dist/node/tool/tool.entity.js +1 -90
  127. package/dist/node/tool/tool.enum.js +1 -26
  128. package/dist/node/tool/tool.event.js +1 -99
  129. package/dist/node/tool/tool.handler.js +1 -699
  130. package/dist/node/tool/tool.operation.js +1 -482
  131. package/dist/node/tool/tool.presentation.js +1 -188
  132. package/dist/node/tool/tool.schema.js +1 -141
  133. package/dist/node/tool/tool.test-spec.js +1 -58
  134. package/dist/node/ui/AgentDashboard.js +1 -2527
  135. package/dist/node/ui/AgentDashboard.visualizations.js +1 -217
  136. package/dist/node/ui/AgentRunList.js +1 -482
  137. package/dist/node/ui/AgentToolRegistry.js +1 -212
  138. package/dist/node/ui/ExecutionConsoleHost.js +1 -0
  139. package/dist/node/ui/hooks/index.js +1 -740
  140. package/dist/node/ui/hooks/useAgentList.js +1 -55
  141. package/dist/node/ui/hooks/useAgentMutations.js +1 -530
  142. package/dist/node/ui/hooks/useRunList.js +1 -70
  143. package/dist/node/ui/hooks/useToolList.js +1 -85
  144. package/dist/node/ui/index.js +5 -3018
  145. package/dist/node/ui/modals/AgentActionsModal.js +1 -304
  146. package/dist/node/ui/modals/CreateAgentModal.js +1 -243
  147. package/dist/node/ui/modals/index.js +1 -546
  148. package/dist/node/ui/overlays/demo-overlays.js +1 -64
  149. package/dist/node/ui/overlays/index.js +1 -64
  150. package/dist/node/ui/renderers/agent-list.markdown.js +2 -64
  151. package/dist/node/ui/renderers/agent-list.renderer.js +1 -180
  152. package/dist/node/ui/renderers/dashboard.markdown.js +2 -288
  153. package/dist/node/ui/renderers/index.js +5 -642
  154. package/dist/node/ui/renderers/run-list.markdown.js +2 -50
  155. package/dist/node/ui/renderers/tool-registry.markdown.js +2 -64
  156. package/dist/node/ui/views/AgentListView.js +1 -165
  157. package/dist/node/ui/views/RunDataTable.js +1 -326
  158. package/dist/node/ui/views/RunListView.js +1 -479
  159. package/dist/node/ui/views/ToolRegistryView.js +1 -209
  160. package/dist/node/ui/views/index.js +1 -851
  161. package/dist/node/ui/views/run-data-table.columns.js +1 -271
  162. package/dist/node/ui/views/run-list.shared.js +1 -177
  163. package/dist/node/visualizations/catalog.js +1 -134
  164. package/dist/node/visualizations/index.js +1 -187
  165. package/dist/node/visualizations/selectors.js +1 -181
  166. package/dist/presentations/index.js +1 -693
  167. package/dist/run/index.js +1 -1363
  168. package/dist/run/run.entity.js +1 -160
  169. package/dist/run/run.enum.js +1 -34
  170. package/dist/run/run.event.js +1 -217
  171. package/dist/run/run.handler.js +1 -919
  172. package/dist/run/run.operation.js +1 -667
  173. package/dist/run/run.presentation.js +1 -223
  174. package/dist/run/run.schema.js +1 -179
  175. package/dist/run/run.test-spec.js +1 -58
  176. package/dist/seeders/index.js +2 -21
  177. package/dist/shared/index.js +1 -626
  178. package/dist/shared/mock-agents.js +1 -82
  179. package/dist/shared/mock-runs.js +1 -113
  180. package/dist/shared/mock-tools.js +1 -146
  181. package/dist/tool/index.js +1 -949
  182. package/dist/tool/tool.entity.js +1 -90
  183. package/dist/tool/tool.enum.js +1 -26
  184. package/dist/tool/tool.event.js +1 -99
  185. package/dist/tool/tool.handler.js +1 -699
  186. package/dist/tool/tool.operation.js +1 -482
  187. package/dist/tool/tool.presentation.js +1 -188
  188. package/dist/tool/tool.schema.js +1 -141
  189. package/dist/tool/tool.test-spec.js +1 -58
  190. package/dist/ui/AgentDashboard.js +1 -2527
  191. package/dist/ui/AgentDashboard.visualizations.js +1 -217
  192. package/dist/ui/AgentRunList.js +1 -482
  193. package/dist/ui/AgentToolRegistry.js +1 -212
  194. package/dist/ui/ExecutionConsoleHost.d.ts +1 -0
  195. package/dist/ui/ExecutionConsoleHost.js +2 -0
  196. package/dist/ui/ExecutionConsoleHost.test.d.ts +1 -0
  197. package/dist/ui/hooks/index.js +1 -740
  198. package/dist/ui/hooks/useAgentList.js +1 -55
  199. package/dist/ui/hooks/useAgentMutations.js +1 -530
  200. package/dist/ui/hooks/useRunList.js +1 -70
  201. package/dist/ui/hooks/useToolList.js +1 -85
  202. package/dist/ui/index.d.ts +1 -0
  203. package/dist/ui/index.js +5 -3018
  204. package/dist/ui/modals/AgentActionsModal.js +1 -304
  205. package/dist/ui/modals/CreateAgentModal.js +1 -243
  206. package/dist/ui/modals/index.js +1 -546
  207. package/dist/ui/overlays/demo-overlays.js +1 -64
  208. package/dist/ui/overlays/index.js +1 -64
  209. package/dist/ui/renderers/agent-list.markdown.js +2 -64
  210. package/dist/ui/renderers/agent-list.renderer.js +1 -180
  211. package/dist/ui/renderers/dashboard.markdown.js +2 -288
  212. package/dist/ui/renderers/index.js +5 -642
  213. package/dist/ui/renderers/run-list.markdown.js +2 -50
  214. package/dist/ui/renderers/tool-registry.markdown.js +2 -64
  215. package/dist/ui/views/AgentListView.js +1 -165
  216. package/dist/ui/views/RunDataTable.js +1 -326
  217. package/dist/ui/views/RunListView.js +1 -479
  218. package/dist/ui/views/ToolRegistryView.js +1 -209
  219. package/dist/ui/views/index.js +1 -851
  220. package/dist/ui/views/run-data-table.columns.js +1 -271
  221. package/dist/ui/views/run-list.shared.js +1 -177
  222. package/dist/visualizations/catalog.js +1 -134
  223. package/dist/visualizations/index.js +1 -187
  224. package/dist/visualizations/selectors.js +1 -181
  225. package/package.json +26 -10
  226. package/src/ui/ExecutionConsoleHost.test.tsx +110 -0
  227. package/src/ui/ExecutionConsoleHost.tsx +14 -0
  228. package/src/ui/index.ts +1 -1
@@ -1,2527 +1 @@
1
- // src/visualizations/catalog.ts
2
- import {
3
- defineVisualization,
4
- VisualizationRegistry
5
- } from "@contractspec/lib.contracts-spec/visualizations";
6
- var RUN_LIST_REF = { key: "agent.run.list", version: "1.0.0" };
7
- var META = {
8
- version: "1.0.0",
9
- domain: "ai-ops",
10
- stability: "experimental",
11
- owners: ["@example.agent-console"],
12
- tags: ["agent-console", "visualization", "operations"]
13
- };
14
- var AgentRunStatusVisualization = defineVisualization({
15
- meta: {
16
- ...META,
17
- key: "agent-console.visualization.run-status",
18
- title: "Run Status Breakdown",
19
- description: "Distribution of run outcomes across the current sample.",
20
- goal: "Make operational success and failure mix visible at a glance.",
21
- context: "Agent operations overview."
22
- },
23
- source: { primary: RUN_LIST_REF, resultPath: "data" },
24
- visualization: {
25
- kind: "pie",
26
- nameDimension: "status",
27
- valueMeasure: "runs",
28
- dimensions: [
29
- { key: "status", label: "Status", dataPath: "status", type: "category" }
30
- ],
31
- measures: [
32
- { key: "runs", label: "Runs", dataPath: "runs", format: "number" }
33
- ],
34
- table: { caption: "Run counts by status." }
35
- }
36
- });
37
- var AgentRunActivityVisualization = defineVisualization({
38
- meta: {
39
- ...META,
40
- key: "agent-console.visualization.run-activity",
41
- title: "Recent Run Activity",
42
- description: "Daily run volume across the current sample.",
43
- goal: "Show whether agent activity is rising or slowing down.",
44
- context: "Operations trend monitoring."
45
- },
46
- source: { primary: RUN_LIST_REF, resultPath: "data" },
47
- visualization: {
48
- kind: "cartesian",
49
- variant: "line",
50
- xDimension: "day",
51
- yMeasures: ["runs"],
52
- dimensions: [{ key: "day", label: "Day", dataPath: "day", type: "time" }],
53
- measures: [
54
- {
55
- key: "runs",
56
- label: "Runs",
57
- dataPath: "runs",
58
- format: "number",
59
- color: "#0f766e"
60
- }
61
- ],
62
- table: { caption: "Daily run counts." }
63
- }
64
- });
65
- var AgentRunEfficiencyVisualization = defineVisualization({
66
- meta: {
67
- ...META,
68
- key: "agent-console.visualization.run-efficiency",
69
- title: "Duration vs Tokens",
70
- description: "Scatter chart comparing token consumption and runtime.",
71
- goal: "Reveal outlier runs that are slow relative to their token usage.",
72
- context: "Operational performance diagnostics."
73
- },
74
- source: { primary: RUN_LIST_REF, resultPath: "data" },
75
- visualization: {
76
- kind: "cartesian",
77
- variant: "scatter",
78
- xDimension: "totalTokens",
79
- yMeasures: ["durationMs"],
80
- dimensions: [
81
- {
82
- key: "totalTokens",
83
- label: "Total Tokens",
84
- dataPath: "totalTokens",
85
- type: "number"
86
- }
87
- ],
88
- measures: [
89
- {
90
- key: "durationMs",
91
- label: "Duration",
92
- dataPath: "durationMs",
93
- format: "duration",
94
- color: "#7c3aed"
95
- },
96
- {
97
- key: "estimatedCostUsd",
98
- label: "Cost",
99
- dataPath: "estimatedCostUsd",
100
- format: "currency"
101
- }
102
- ],
103
- series: [
104
- {
105
- key: "runs",
106
- label: "Runs",
107
- measure: "durationMs",
108
- type: "scatter",
109
- color: "#7c3aed"
110
- }
111
- ],
112
- table: { caption: "Run duration versus token usage." }
113
- }
114
- });
115
- var AgentVisualizationSpecs = [
116
- AgentRunStatusVisualization,
117
- AgentRunActivityVisualization,
118
- AgentRunEfficiencyVisualization
119
- ];
120
- var AgentVisualizationRegistry = new VisualizationRegistry([
121
- ...AgentVisualizationSpecs
122
- ]);
123
- var AgentVisualizationRefs = AgentVisualizationSpecs.map((spec) => ({
124
- key: spec.meta.key,
125
- version: spec.meta.version
126
- }));
127
-
128
- // src/visualizations/selectors.ts
129
- function dayKey(value) {
130
- if (!value)
131
- return "unknown";
132
- return value.toISOString().slice(0, 10);
133
- }
134
- function createAgentVisualizationItems(runs) {
135
- const statusCounts = new Map;
136
- const activityCounts = new Map;
137
- for (const run of runs) {
138
- statusCounts.set(run.status, (statusCounts.get(run.status) ?? 0) + 1);
139
- activityCounts.set(dayKey(run.startedAt ?? run.queuedAt), (activityCounts.get(dayKey(run.startedAt ?? run.queuedAt)) ?? 0) + 1);
140
- }
141
- return [
142
- {
143
- key: "run-status",
144
- spec: AgentRunStatusVisualization,
145
- data: {
146
- data: Array.from(statusCounts.entries()).map(([status, count]) => ({
147
- status,
148
- runs: count
149
- }))
150
- },
151
- title: "Run Status Breakdown",
152
- description: "Completed, failed, running, and cancelled runs in the sample.",
153
- height: 260
154
- },
155
- {
156
- key: "run-activity",
157
- spec: AgentRunActivityVisualization,
158
- data: {
159
- data: Array.from(activityCounts.entries()).sort(([left], [right]) => left.localeCompare(right)).map(([day, count]) => ({ day, runs: count }))
160
- },
161
- title: "Recent Run Activity",
162
- description: "Daily run volume derived from run start times."
163
- },
164
- {
165
- key: "run-efficiency",
166
- spec: AgentRunEfficiencyVisualization,
167
- data: {
168
- data: runs.filter((run) => typeof run.durationMs === "number").map((run) => ({
169
- totalTokens: run.totalTokens,
170
- durationMs: run.durationMs ?? 0,
171
- estimatedCostUsd: run.estimatedCostUsd
172
- }))
173
- },
174
- title: "Duration vs Tokens",
175
- description: "Operational scatter plot for spotting inefficient runs."
176
- }
177
- ];
178
- }
179
- // src/shared/mock-agents.ts
180
- var MOCK_AGENTS = [
181
- {
182
- id: "agent-1",
183
- organizationId: "demo-org",
184
- name: "Customer Support Bot",
185
- slug: "customer-support-bot",
186
- description: "Handles tier-1 customer inquiries and routes complex issues.",
187
- status: "ACTIVE",
188
- modelProvider: "OPENAI",
189
- modelName: "gpt-4o-mini",
190
- modelConfig: { temperature: 0.7 },
191
- systemPrompt: "You are a helpful customer support assistant.",
192
- toolChoice: "auto",
193
- maxIterations: 10,
194
- timeoutMs: 120000,
195
- version: "1.0.0",
196
- tags: ["support", "tier-1"],
197
- createdAt: new Date("2024-01-15T10:00:00Z"),
198
- updatedAt: new Date("2024-03-20T14:30:00Z")
199
- },
200
- {
201
- id: "agent-2",
202
- organizationId: "demo-org",
203
- name: "Code Review Assistant",
204
- slug: "code-review-assistant",
205
- description: "Reviews pull requests and provides actionable feedback.",
206
- status: "ACTIVE",
207
- modelProvider: "ANTHROPIC",
208
- modelName: "claude-sonnet-4-20250514",
209
- modelConfig: { temperature: 0.3 },
210
- systemPrompt: "You are a code review expert.",
211
- toolChoice: "auto",
212
- maxIterations: 15,
213
- timeoutMs: 180000,
214
- version: "2.1.0",
215
- tags: ["code", "review", "dev"],
216
- createdAt: new Date("2024-02-10T09:00:00Z"),
217
- updatedAt: new Date("2024-04-05T11:15:00Z")
218
- },
219
- {
220
- id: "agent-3",
221
- organizationId: "demo-org",
222
- name: "Data Analyst",
223
- slug: "data-analyst",
224
- description: "Queries databases and generates insights from data.",
225
- status: "PAUSED",
226
- modelProvider: "OPENAI",
227
- modelName: "gpt-4o",
228
- modelConfig: { temperature: 0.5 },
229
- systemPrompt: "You are a data analyst expert in SQL and analytics.",
230
- toolChoice: "required",
231
- maxIterations: 20,
232
- timeoutMs: 300000,
233
- version: "1.2.0",
234
- tags: ["data", "analytics", "sql"],
235
- createdAt: new Date("2024-03-01T08:00:00Z"),
236
- updatedAt: new Date("2024-04-10T16:45:00Z")
237
- },
238
- {
239
- id: "agent-4",
240
- organizationId: "demo-org",
241
- name: "Meeting Scheduler",
242
- slug: "meeting-scheduler",
243
- description: "Schedules meetings and manages calendar conflicts.",
244
- status: "DRAFT",
245
- modelProvider: "GOOGLE",
246
- modelName: "gemini-2.0-flash",
247
- modelConfig: { temperature: 0.2 },
248
- systemPrompt: "You help schedule and organize meetings efficiently.",
249
- toolChoice: "auto",
250
- maxIterations: 5,
251
- timeoutMs: 60000,
252
- version: "0.1.0",
253
- tags: ["calendar", "scheduling"],
254
- createdAt: new Date("2024-04-01T12:00:00Z"),
255
- updatedAt: new Date("2024-04-01T12:00:00Z")
256
- }
257
- ];
258
-
259
- // src/shared/mock-tools.ts
260
- var MOCK_TOOLS = [
261
- {
262
- id: "tool-1",
263
- organizationId: "demo-org",
264
- name: "Web Search",
265
- slug: "web-search",
266
- description: "Search the web for real-time information using Brave API.",
267
- category: "RETRIEVAL",
268
- status: "ACTIVE",
269
- parametersSchema: {
270
- type: "object",
271
- properties: {
272
- query: { type: "string", description: "Search query" },
273
- numResults: { type: "number", default: 10 }
274
- },
275
- required: ["query"]
276
- },
277
- outputSchema: { type: "array", items: { type: "object" } },
278
- implementationType: "http",
279
- implementationConfig: {
280
- url: "https://api.brave.com/search",
281
- method: "GET"
282
- },
283
- maxInvocationsPerMinute: 60,
284
- timeoutMs: 30000,
285
- version: "1.0.0",
286
- tags: ["search", "web"],
287
- createdAt: new Date("2024-01-01T00:00:00Z"),
288
- updatedAt: new Date("2024-02-15T10:00:00Z")
289
- },
290
- {
291
- id: "tool-2",
292
- organizationId: "demo-org",
293
- name: "SQL Query",
294
- slug: "sql-query",
295
- description: "Execute read-only SQL queries against the data warehouse.",
296
- category: "RETRIEVAL",
297
- status: "ACTIVE",
298
- parametersSchema: {
299
- type: "object",
300
- properties: {
301
- query: { type: "string", description: "SQL query" },
302
- maxRows: { type: "number", default: 100 }
303
- },
304
- required: ["query"]
305
- },
306
- outputSchema: { type: "object" },
307
- implementationType: "function",
308
- implementationConfig: { handler: "executeSqlQuery" },
309
- maxInvocationsPerMinute: 30,
310
- timeoutMs: 60000,
311
- version: "1.1.0",
312
- tags: ["sql", "database"],
313
- createdAt: new Date("2024-01-05T00:00:00Z"),
314
- updatedAt: new Date("2024-03-10T14:00:00Z")
315
- },
316
- {
317
- id: "tool-3",
318
- organizationId: "demo-org",
319
- name: "Email Sender",
320
- slug: "email-sender",
321
- description: "Send emails via SMTP or API.",
322
- category: "COMMUNICATION",
323
- status: "ACTIVE",
324
- parametersSchema: {
325
- type: "object",
326
- properties: {
327
- to: { type: "string" },
328
- subject: { type: "string" },
329
- body: { type: "string" }
330
- },
331
- required: ["to", "subject", "body"]
332
- },
333
- implementationType: "http",
334
- implementationConfig: { url: "/api/send-email", method: "POST" },
335
- maxInvocationsPerMinute: 10,
336
- timeoutMs: 30000,
337
- version: "1.0.0",
338
- tags: ["email", "communication"],
339
- createdAt: new Date("2024-02-01T00:00:00Z"),
340
- updatedAt: new Date("2024-02-01T00:00:00Z")
341
- },
342
- {
343
- id: "tool-4",
344
- organizationId: "demo-org",
345
- name: "GitHub Integration",
346
- slug: "github-integration",
347
- description: "Interact with GitHub repositories, PRs, and issues.",
348
- category: "INTEGRATION",
349
- status: "ACTIVE",
350
- parametersSchema: {
351
- type: "object",
352
- properties: {
353
- action: {
354
- type: "string",
355
- enum: ["list_prs", "get_pr", "create_comment"]
356
- },
357
- repo: { type: "string" },
358
- params: { type: "object" }
359
- },
360
- required: ["action", "repo"]
361
- },
362
- implementationType: "http",
363
- implementationConfig: { url: "https://api.github.com", auth: "token" },
364
- maxInvocationsPerMinute: 100,
365
- timeoutMs: 15000,
366
- version: "2.0.0",
367
- tags: ["github", "integration", "code"],
368
- createdAt: new Date("2024-02-20T00:00:00Z"),
369
- updatedAt: new Date("2024-04-01T09:00:00Z")
370
- },
371
- {
372
- id: "tool-5",
373
- organizationId: "demo-org",
374
- name: "Calculator",
375
- slug: "calculator",
376
- description: "Perform mathematical calculations.",
377
- category: "COMPUTATION",
378
- status: "ACTIVE",
379
- parametersSchema: {
380
- type: "object",
381
- properties: {
382
- expression: {
383
- type: "string",
384
- description: "Math expression to evaluate"
385
- }
386
- },
387
- required: ["expression"]
388
- },
389
- outputSchema: {
390
- type: "object",
391
- properties: { result: { type: "number" } }
392
- },
393
- implementationType: "function",
394
- implementationConfig: { handler: "evaluateMath" },
395
- timeoutMs: 5000,
396
- version: "1.0.0",
397
- tags: ["math", "utility"],
398
- createdAt: new Date("2024-01-10T00:00:00Z"),
399
- updatedAt: new Date("2024-01-10T00:00:00Z")
400
- }
401
- ];
402
-
403
- // src/shared/mock-runs.ts
404
- var MOCK_RUNS = [
405
- {
406
- id: "run-1",
407
- organizationId: "demo-org",
408
- projectId: "demo-project",
409
- agentId: "agent-1",
410
- agentName: "Customer Support Bot",
411
- userId: "user-1",
412
- sessionId: "session-1",
413
- input: { message: "How do I reset my password?", context: {} },
414
- output: { response: "You can reset your password by clicking..." },
415
- status: "COMPLETED",
416
- totalTokens: 1250,
417
- promptTokens: 800,
418
- completionTokens: 450,
419
- totalIterations: 3,
420
- durationMs: 4500,
421
- estimatedCostUsd: 0.0025,
422
- queuedAt: new Date("2024-04-15T10:00:00Z"),
423
- startedAt: new Date("2024-04-15T10:00:01Z"),
424
- completedAt: new Date("2024-04-15T10:00:05Z"),
425
- steps: [],
426
- logs: []
427
- },
428
- {
429
- id: "run-2",
430
- organizationId: "demo-org",
431
- projectId: "demo-project",
432
- agentId: "agent-2",
433
- agentName: "Code Review Assistant",
434
- userId: "user-2",
435
- input: { message: "Review PR #123", context: { prNumber: 123 } },
436
- status: "IN_PROGRESS",
437
- totalTokens: 3500,
438
- promptTokens: 3000,
439
- completionTokens: 500,
440
- totalIterations: 5,
441
- queuedAt: new Date("2024-04-15T10:30:00Z"),
442
- startedAt: new Date("2024-04-15T10:30:02Z"),
443
- steps: [],
444
- logs: []
445
- },
446
- {
447
- id: "run-3",
448
- organizationId: "demo-org",
449
- projectId: "demo-project",
450
- agentId: "agent-1",
451
- agentName: "Customer Support Bot",
452
- userId: "user-1",
453
- input: { message: "What are your business hours?" },
454
- output: { response: "Our business hours are 9 AM to 5 PM EST..." },
455
- status: "COMPLETED",
456
- totalTokens: 800,
457
- promptTokens: 500,
458
- completionTokens: 300,
459
- totalIterations: 2,
460
- durationMs: 2100,
461
- estimatedCostUsd: 0.0012,
462
- queuedAt: new Date("2024-04-15T09:00:00Z"),
463
- startedAt: new Date("2024-04-15T09:00:01Z"),
464
- completedAt: new Date("2024-04-15T09:00:03Z"),
465
- steps: [],
466
- logs: []
467
- },
468
- {
469
- id: "run-4",
470
- organizationId: "demo-org",
471
- projectId: "demo-project",
472
- agentId: "agent-3",
473
- agentName: "Data Analyst",
474
- userId: "user-3",
475
- input: { message: "Generate sales report for Q1" },
476
- status: "FAILED",
477
- errorMessage: "Database connection timeout",
478
- errorCode: "DB_TIMEOUT",
479
- totalTokens: 2000,
480
- promptTokens: 1500,
481
- completionTokens: 500,
482
- totalIterations: 8,
483
- durationMs: 45000,
484
- queuedAt: new Date("2024-04-14T15:00:00Z"),
485
- startedAt: new Date("2024-04-14T15:00:05Z"),
486
- completedAt: new Date("2024-04-14T15:00:50Z"),
487
- steps: [],
488
- logs: []
489
- },
490
- {
491
- id: "run-5",
492
- organizationId: "demo-org",
493
- projectId: "demo-project",
494
- agentId: "agent-2",
495
- agentName: "Code Review Assistant",
496
- userId: "user-2",
497
- input: { message: "Review PR #120" },
498
- output: { response: "Code review complete. 3 suggestions..." },
499
- status: "COMPLETED",
500
- totalTokens: 5200,
501
- promptTokens: 4000,
502
- completionTokens: 1200,
503
- totalIterations: 7,
504
- durationMs: 15000,
505
- estimatedCostUsd: 0.0156,
506
- queuedAt: new Date("2024-04-14T11:00:00Z"),
507
- startedAt: new Date("2024-04-14T11:00:03Z"),
508
- completedAt: new Date("2024-04-14T11:00:18Z"),
509
- steps: [],
510
- logs: []
511
- }
512
- ];
513
-
514
- // src/ui/AgentDashboard.visualizations.tsx
515
- import {
516
- VisualizationCard,
517
- VisualizationGrid
518
- } from "@contractspec/lib.design-system";
519
- import { jsxDEV } from "react/jsx-dev-runtime";
520
- "use client";
521
- function AgentVisualizationOverview({ runs }) {
522
- const items = createAgentVisualizationItems(runs);
523
- return /* @__PURE__ */ jsxDEV("section", {
524
- className: "space-y-3",
525
- children: [
526
- /* @__PURE__ */ jsxDEV("div", {
527
- children: [
528
- /* @__PURE__ */ jsxDEV("h3", {
529
- className: "font-semibold text-lg",
530
- children: "Operational Visualizations"
531
- }, undefined, false, undefined, this),
532
- /* @__PURE__ */ jsxDEV("p", {
533
- className: "text-muted-foreground text-sm",
534
- children: "Contract-backed charts derived from recent run activity."
535
- }, undefined, false, undefined, this)
536
- ]
537
- }, undefined, true, undefined, this),
538
- /* @__PURE__ */ jsxDEV(VisualizationGrid, {
539
- children: items.map((item) => /* @__PURE__ */ jsxDEV(VisualizationCard, {
540
- data: item.data,
541
- description: item.description,
542
- height: item.height,
543
- spec: item.spec,
544
- title: item.title
545
- }, item.key, false, undefined, this))
546
- }, undefined, false, undefined, this)
547
- ]
548
- }, undefined, true, undefined, this);
549
- }
550
-
551
- // src/ui/hooks/useAgentList.ts
552
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
553
- import { useCallback, useEffect, useMemo, useState } from "react";
554
- function useAgentList(options = {}) {
555
- const { handlers, projectId } = useTemplateRuntime();
556
- const { agent } = handlers;
557
- const [data, setData] = useState(null);
558
- const [loading, setLoading] = useState(true);
559
- const [error, setError] = useState(null);
560
- const [page, setPage] = useState(1);
561
- const fetchData = useCallback(async () => {
562
- setLoading(true);
563
- setError(null);
564
- try {
565
- const result = await agent.listAgents({
566
- projectId,
567
- search: options.search,
568
- status: options.status === "all" ? undefined : options.status,
569
- limit: options.limit ?? 20,
570
- offset: (page - 1) * (options.limit ?? 20)
571
- });
572
- setData(result);
573
- } catch (err) {
574
- setError(err instanceof Error ? err : new Error("Unknown error"));
575
- } finally {
576
- setLoading(false);
577
- }
578
- }, [agent, projectId, options.search, options.status, options.limit, page]);
579
- useEffect(() => {
580
- fetchData();
581
- }, [fetchData]);
582
- const stats = useMemo(() => {
583
- if (!data)
584
- return null;
585
- return {
586
- total: data.total,
587
- active: data.items.filter((a) => a.status === "ACTIVE").length,
588
- paused: data.items.filter((a) => a.status === "PAUSED").length,
589
- draft: data.items.filter((a) => a.status === "DRAFT").length
590
- };
591
- }, [data]);
592
- return {
593
- data,
594
- loading,
595
- error,
596
- stats,
597
- page,
598
- refetch: fetchData,
599
- nextPage: () => setPage((p) => p + 1),
600
- prevPage: () => page > 1 && setPage((p) => p - 1)
601
- };
602
- }
603
-
604
- // src/ui/hooks/useAgentMutations.ts
605
- import { useTemplateRuntime as useTemplateRuntime2 } from "@contractspec/lib.example-shared-ui";
606
- import { useCallback as useCallback2, useState as useState2 } from "react";
607
-
608
- // src/shared/demo-runtime-seed.ts
609
- var AGENT_CONSOLE_DEMO_ORGANIZATION_ID = "demo-org";
610
- var AGENT_CONSOLE_DEMO_PROJECT_ID = "agent-console-demo";
611
- function slugify(name) {
612
- return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
613
- }
614
- function cloneAgent(agent) {
615
- return { ...agent };
616
- }
617
- function cloneTool(tool) {
618
- return { ...tool };
619
- }
620
- function cloneRun(run) {
621
- return { ...run };
622
- }
623
- function createDefaultNow() {
624
- let tick = 0;
625
- const base = Date.parse("2026-03-20T09:00:00.000Z");
626
- return () => new Date(base + tick++ * 60000);
627
- }
628
- function normalizeProvider(provider) {
629
- return provider.toLowerCase();
630
- }
631
- function normalizeRunStatus(status) {
632
- return status === "IN_PROGRESS" ? "RUNNING" : status;
633
- }
634
- function createSeedState(projectId, organizationId) {
635
- const agents = MOCK_AGENTS.map((agent) => ({
636
- id: agent.id,
637
- projectId,
638
- organizationId,
639
- name: agent.name,
640
- slug: agent.slug,
641
- description: agent.description,
642
- modelProvider: normalizeProvider(agent.modelProvider),
643
- modelName: agent.modelName,
644
- systemPrompt: agent.systemPrompt,
645
- temperature: typeof agent.modelConfig?.temperature === "number" ? agent.modelConfig.temperature : 0.4,
646
- maxTokens: 8192,
647
- status: agent.status,
648
- createdAt: agent.createdAt,
649
- updatedAt: agent.updatedAt
650
- }));
651
- const tools = MOCK_TOOLS.map((tool) => ({
652
- id: tool.id,
653
- projectId,
654
- organizationId,
655
- name: tool.name,
656
- description: tool.description,
657
- version: tool.version,
658
- category: tool.category,
659
- status: tool.status,
660
- inputSchema: JSON.stringify(tool.parametersSchema),
661
- outputSchema: tool.outputSchema ? JSON.stringify(tool.outputSchema) : undefined,
662
- endpoint: typeof tool.implementationConfig?.url === "string" ? tool.implementationConfig.url : undefined,
663
- createdAt: tool.createdAt,
664
- updatedAt: tool.updatedAt
665
- }));
666
- const agentNames = new Map(agents.map((agent) => [agent.id, agent.name]));
667
- const runs = MOCK_RUNS.map((run) => ({
668
- id: run.id,
669
- projectId,
670
- agentId: run.agentId,
671
- agentName: agentNames.get(run.agentId) ?? run.agentName ?? "Unknown agent",
672
- status: normalizeRunStatus(run.status),
673
- input: JSON.stringify(run.input),
674
- output: run.output ? JSON.stringify(run.output) : undefined,
675
- totalTokens: run.totalTokens,
676
- promptTokens: run.promptTokens,
677
- completionTokens: run.completionTokens,
678
- estimatedCostUsd: run.estimatedCostUsd ?? 0,
679
- durationMs: run.durationMs,
680
- errorMessage: run.errorMessage,
681
- queuedAt: run.queuedAt,
682
- startedAt: run.startedAt,
683
- completedAt: run.completedAt
684
- }));
685
- return { agents, tools, runs };
686
- }
687
- function summarizeRunMetrics(runs) {
688
- const totalRuns = runs.length;
689
- const completedRuns = runs.filter((run) => run.status === "COMPLETED").length;
690
- const completedDurations = runs.map((run) => run.durationMs).filter((duration) => typeof duration === "number");
691
- return {
692
- totalRuns,
693
- successRate: totalRuns === 0 ? 0 : completedRuns / totalRuns,
694
- averageDurationMs: completedDurations.length === 0 ? 0 : Math.round(completedDurations.reduce((sum, duration) => sum + duration, 0) / completedDurations.length),
695
- totalTokens: runs.reduce((sum, run) => sum + run.totalTokens, 0),
696
- totalCostUsd: runs.reduce((sum, run) => sum + run.estimatedCostUsd, 0)
697
- };
698
- }
699
-
700
- // src/ui/hooks/useAgentMutations.ts
701
- function normalizeMutationError(error, fallbackMessage) {
702
- return error instanceof Error ? error : new Error(fallbackMessage);
703
- }
704
- function useAgentMutations(options = {}) {
705
- const { handlers, projectId } = useTemplateRuntime2();
706
- const { agent } = handlers;
707
- const [createState, setCreateState] = useState2({
708
- loading: false,
709
- error: null,
710
- data: null
711
- });
712
- const [updateState, setUpdateState] = useState2({
713
- loading: false,
714
- error: null,
715
- data: null
716
- });
717
- const [executeState, setExecuteState] = useState2({
718
- loading: false,
719
- error: null,
720
- data: null
721
- });
722
- const createAgent = useCallback2(async (input) => {
723
- setCreateState({ loading: true, error: null, data: null });
724
- try {
725
- const result = await agent.createAgent(input, {
726
- projectId,
727
- organizationId: AGENT_CONSOLE_DEMO_ORGANIZATION_ID
728
- });
729
- setCreateState({ loading: false, error: null, data: result });
730
- options.onSuccess?.();
731
- return result;
732
- } catch (err) {
733
- const error = normalizeMutationError(err, "Failed to create agent");
734
- setCreateState({ loading: false, error, data: null });
735
- options.onError?.(error);
736
- throw error;
737
- }
738
- }, [agent, projectId, options]);
739
- const updateAgent = useCallback2(async (input) => {
740
- setUpdateState({ loading: true, error: null, data: null });
741
- try {
742
- const result = await agent.updateAgent(input);
743
- setUpdateState({ loading: false, error: null, data: result });
744
- options.onSuccess?.();
745
- return result;
746
- } catch (err) {
747
- const error = normalizeMutationError(err, "Failed to update agent");
748
- setUpdateState({ loading: false, error, data: null });
749
- options.onError?.(error);
750
- throw error;
751
- }
752
- }, [agent, options]);
753
- const activateAgent = useCallback2(async (agentId) => {
754
- return updateAgent({ id: agentId, status: "ACTIVE" });
755
- }, [updateAgent]);
756
- const pauseAgent = useCallback2(async (agentId) => {
757
- return updateAgent({ id: agentId, status: "PAUSED" });
758
- }, [updateAgent]);
759
- const archiveAgent = useCallback2(async (agentId) => {
760
- return updateAgent({ id: agentId, status: "ARCHIVED" });
761
- }, [updateAgent]);
762
- const executeAgent = useCallback2(async (input) => {
763
- setExecuteState({ loading: true, error: null, data: null });
764
- try {
765
- const result = await agent.executeAgent({
766
- agentId: input.agentId,
767
- message: input.message,
768
- context: {
769
- projectId,
770
- organizationId: AGENT_CONSOLE_DEMO_ORGANIZATION_ID
771
- }
772
- });
773
- setExecuteState({ loading: false, error: null, data: result });
774
- options.onSuccess?.();
775
- return result;
776
- } catch (err) {
777
- const error = normalizeMutationError(err, "Failed to execute agent");
778
- setExecuteState({ loading: false, error, data: null });
779
- options.onError?.(error);
780
- throw error;
781
- }
782
- }, [agent, projectId, options]);
783
- return {
784
- createAgent,
785
- updateAgent,
786
- activateAgent,
787
- pauseAgent,
788
- archiveAgent,
789
- executeAgent,
790
- createState,
791
- updateState,
792
- executeState,
793
- isLoading: createState.loading || updateState.loading || executeState.loading
794
- };
795
- }
796
-
797
- // src/ui/hooks/useRunList.ts
798
- import { useTemplateRuntime as useTemplateRuntime3 } from "@contractspec/lib.example-shared-ui";
799
- import { useCallback as useCallback3, useEffect as useEffect2, useState as useState3 } from "react";
800
- function useRunList(options = {}) {
801
- const { handlers, projectId } = useTemplateRuntime3();
802
- const { agent } = handlers;
803
- const [data, setData] = useState3(null);
804
- const [metrics, setMetrics] = useState3(null);
805
- const [loading, setLoading] = useState3(true);
806
- const [error, setError] = useState3(null);
807
- const [internalPageIndex, setInternalPageIndex] = useState3(0);
808
- const pageSize = options.pageSize ?? options.limit ?? 20;
809
- const pageIndex = options.pageIndex ?? internalPageIndex;
810
- const [sort] = options.sorting ?? [];
811
- const fetchData = useCallback3(async () => {
812
- setLoading(true);
813
- setError(null);
814
- try {
815
- const [runsResult, metricsResult] = await Promise.all([
816
- agent.listRuns({
817
- projectId,
818
- agentId: options.agentId,
819
- status: options.status === "all" ? undefined : options.status,
820
- sortBy: sort?.id,
821
- sortDirection: sort ? sort.desc ? "desc" : "asc" : undefined,
822
- limit: pageSize,
823
- offset: pageIndex * pageSize
824
- }),
825
- agent.getRunMetrics({
826
- projectId,
827
- agentId: options.agentId
828
- })
829
- ]);
830
- setData(runsResult);
831
- setMetrics(metricsResult);
832
- } catch (err) {
833
- setError(err instanceof Error ? err : new Error("Unknown error"));
834
- } finally {
835
- setLoading(false);
836
- }
837
- }, [
838
- agent,
839
- pageIndex,
840
- pageSize,
841
- projectId,
842
- options.agentId,
843
- options.status,
844
- sort?.desc,
845
- sort?.id
846
- ]);
847
- useEffect2(() => {
848
- fetchData();
849
- }, [fetchData]);
850
- const hasControlledPagination = options.pageIndex !== undefined;
851
- return {
852
- data,
853
- metrics,
854
- loading,
855
- error,
856
- page: pageIndex + 1,
857
- pageIndex,
858
- pageSize,
859
- refetch: fetchData,
860
- nextPage: hasControlledPagination ? undefined : () => setInternalPageIndex((current) => current + 1),
861
- prevPage: hasControlledPagination ? undefined : () => setInternalPageIndex((current) => Math.max(0, current - 1))
862
- };
863
- }
864
-
865
- // src/ui/modals/AgentActionsModal.tsx
866
- import { Button } from "@contractspec/lib.design-system";
867
- import { useState as useState4 } from "react";
868
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
869
- "use client";
870
- function getStatusColor(status) {
871
- switch (status) {
872
- case "ACTIVE":
873
- return "text-green-600 bg-green-100 dark:text-green-400 dark:bg-green-900/30";
874
- case "DRAFT":
875
- return "text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30";
876
- case "PAUSED":
877
- return "text-yellow-600 bg-yellow-100 dark:text-yellow-400 dark:bg-yellow-900/30";
878
- case "ARCHIVED":
879
- return "text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700";
880
- default:
881
- return "text-gray-600 bg-gray-100";
882
- }
883
- }
884
- function AgentActionsModal({
885
- isOpen,
886
- agent,
887
- onClose,
888
- onActivate,
889
- onPause,
890
- onArchive,
891
- onExecute,
892
- isLoading = false
893
- }) {
894
- const [mode, setMode] = useState4("menu");
895
- const [message, setMessage] = useState4("");
896
- const [confirmAction, setConfirmAction] = useState4(null);
897
- const [error, setError] = useState4(null);
898
- const resetForm = () => {
899
- setMode("menu");
900
- setMessage("");
901
- setConfirmAction(null);
902
- setError(null);
903
- };
904
- const handleClose = () => {
905
- resetForm();
906
- onClose();
907
- };
908
- const handleExecute = async () => {
909
- if (!agent)
910
- return;
911
- setError(null);
912
- if (!message.trim()) {
913
- setError("Please enter a message");
914
- return;
915
- }
916
- try {
917
- await onExecute(agent.id, message.trim());
918
- handleClose();
919
- } catch (err) {
920
- setError(err instanceof Error ? err.message : "Failed to execute agent");
921
- }
922
- };
923
- const handleStatusChange = async (action) => {
924
- if (!agent)
925
- return;
926
- setError(null);
927
- try {
928
- switch (action) {
929
- case "activate":
930
- await onActivate(agent.id);
931
- break;
932
- case "pause":
933
- await onPause(agent.id);
934
- break;
935
- case "archive":
936
- await onArchive(agent.id);
937
- break;
938
- }
939
- handleClose();
940
- } catch (err) {
941
- setError(err instanceof Error ? err.message : `Failed to ${action} agent`);
942
- }
943
- };
944
- if (!isOpen || !agent)
945
- return null;
946
- return /* @__PURE__ */ jsxDEV2("div", {
947
- className: "fixed inset-0 z-50 flex items-center justify-center",
948
- children: [
949
- /* @__PURE__ */ jsxDEV2("div", {
950
- className: "absolute inset-0 bg-background/80 backdrop-blur-sm",
951
- onClick: handleClose,
952
- role: "button",
953
- tabIndex: 0,
954
- onKeyDown: (e) => {
955
- if (e.key === "Enter" || e.key === " ")
956
- handleClose();
957
- },
958
- "aria-label": "Close modal"
959
- }, undefined, false, undefined, this),
960
- /* @__PURE__ */ jsxDEV2("div", {
961
- className: "relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",
962
- children: [
963
- /* @__PURE__ */ jsxDEV2("div", {
964
- className: "mb-4 border-border border-b pb-4",
965
- children: [
966
- /* @__PURE__ */ jsxDEV2("h2", {
967
- className: "font-semibold text-xl",
968
- children: agent.name
969
- }, undefined, false, undefined, this),
970
- /* @__PURE__ */ jsxDEV2("div", {
971
- className: "mt-1 flex items-center gap-2",
972
- children: [
973
- /* @__PURE__ */ jsxDEV2("span", {
974
- className: "text-muted-foreground text-sm",
975
- children: [
976
- agent.modelProvider,
977
- " / ",
978
- agent.modelName
979
- ]
980
- }, undefined, true, undefined, this),
981
- /* @__PURE__ */ jsxDEV2("span", {
982
- className: `rounded-full px-2 py-0.5 font-medium text-xs ${getStatusColor(agent.status)}`,
983
- children: agent.status
984
- }, undefined, false, undefined, this)
985
- ]
986
- }, undefined, true, undefined, this),
987
- agent.description && /* @__PURE__ */ jsxDEV2("p", {
988
- className: "mt-2 text-muted-foreground text-sm",
989
- children: agent.description
990
- }, undefined, false, undefined, this)
991
- ]
992
- }, undefined, true, undefined, this),
993
- mode === "menu" && /* @__PURE__ */ jsxDEV2("div", {
994
- className: "space-y-3",
995
- children: [
996
- agent.status === "ACTIVE" && /* @__PURE__ */ jsxDEV2(Button, {
997
- className: "w-full justify-start",
998
- variant: "ghost",
999
- onPress: () => setMode("execute"),
1000
- children: [
1001
- /* @__PURE__ */ jsxDEV2("span", {
1002
- className: "mr-2",
1003
- children: "▶️"
1004
- }, undefined, false, undefined, this),
1005
- " Execute Agent"
1006
- ]
1007
- }, undefined, true, undefined, this),
1008
- (agent.status === "DRAFT" || agent.status === "PAUSED") && /* @__PURE__ */ jsxDEV2(Button, {
1009
- className: "w-full justify-start",
1010
- variant: "ghost",
1011
- onPress: () => handleStatusChange("activate"),
1012
- disabled: isLoading,
1013
- children: [
1014
- /* @__PURE__ */ jsxDEV2("span", {
1015
- className: "mr-2",
1016
- children: "\uD83D\uDFE2"
1017
- }, undefined, false, undefined, this),
1018
- " Activate Agent"
1019
- ]
1020
- }, undefined, true, undefined, this),
1021
- agent.status === "ACTIVE" && /* @__PURE__ */ jsxDEV2(Button, {
1022
- className: "w-full justify-start",
1023
- variant: "ghost",
1024
- onPress: () => handleStatusChange("pause"),
1025
- disabled: isLoading,
1026
- children: [
1027
- /* @__PURE__ */ jsxDEV2("span", {
1028
- className: "mr-2",
1029
- children: "⏸️"
1030
- }, undefined, false, undefined, this),
1031
- " Pause Agent"
1032
- ]
1033
- }, undefined, true, undefined, this),
1034
- agent.status !== "ARCHIVED" && /* @__PURE__ */ jsxDEV2(Button, {
1035
- className: "w-full justify-start text-yellow-600 hover:text-yellow-700",
1036
- variant: "ghost",
1037
- onPress: () => {
1038
- setConfirmAction("archive");
1039
- setMode("confirm");
1040
- },
1041
- children: [
1042
- /* @__PURE__ */ jsxDEV2("span", {
1043
- className: "mr-2",
1044
- children: "\uD83D\uDCE6"
1045
- }, undefined, false, undefined, this),
1046
- " Archive Agent"
1047
- ]
1048
- }, undefined, true, undefined, this),
1049
- agent.status === "ARCHIVED" && /* @__PURE__ */ jsxDEV2(Button, {
1050
- className: "w-full justify-start",
1051
- variant: "ghost",
1052
- onPress: () => handleStatusChange("activate"),
1053
- disabled: isLoading,
1054
- children: [
1055
- /* @__PURE__ */ jsxDEV2("span", {
1056
- className: "mr-2",
1057
- children: "\uD83D\uDD04"
1058
- }, undefined, false, undefined, this),
1059
- " Restore Agent"
1060
- ]
1061
- }, undefined, true, undefined, this),
1062
- error && /* @__PURE__ */ jsxDEV2("div", {
1063
- className: "rounded-md bg-destructive/10 p-3 text-destructive text-sm",
1064
- children: error
1065
- }, undefined, false, undefined, this),
1066
- /* @__PURE__ */ jsxDEV2("div", {
1067
- className: "border-border border-t pt-3",
1068
- children: /* @__PURE__ */ jsxDEV2(Button, {
1069
- className: "w-full",
1070
- variant: "outline",
1071
- onPress: handleClose,
1072
- children: "Close"
1073
- }, undefined, false, undefined, this)
1074
- }, undefined, false, undefined, this)
1075
- ]
1076
- }, undefined, true, undefined, this),
1077
- mode === "execute" && /* @__PURE__ */ jsxDEV2("div", {
1078
- className: "space-y-4",
1079
- children: [
1080
- /* @__PURE__ */ jsxDEV2("div", {
1081
- children: [
1082
- /* @__PURE__ */ jsxDEV2("label", {
1083
- htmlFor: "execute-message",
1084
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1085
- children: "Message *"
1086
- }, undefined, false, undefined, this),
1087
- /* @__PURE__ */ jsxDEV2("textarea", {
1088
- id: "execute-message",
1089
- value: message,
1090
- onChange: (e) => setMessage(e.target.value),
1091
- placeholder: "Enter your message to the agent...",
1092
- rows: 4,
1093
- disabled: isLoading,
1094
- className: "w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
1095
- }, undefined, false, undefined, this)
1096
- ]
1097
- }, undefined, true, undefined, this),
1098
- error && /* @__PURE__ */ jsxDEV2("div", {
1099
- className: "rounded-md bg-destructive/10 p-3 text-destructive text-sm",
1100
- children: error
1101
- }, undefined, false, undefined, this),
1102
- /* @__PURE__ */ jsxDEV2("div", {
1103
- className: "flex justify-end gap-3 pt-2",
1104
- children: [
1105
- /* @__PURE__ */ jsxDEV2(Button, {
1106
- variant: "ghost",
1107
- onPress: () => setMode("menu"),
1108
- disabled: isLoading,
1109
- children: "Back"
1110
- }, undefined, false, undefined, this),
1111
- /* @__PURE__ */ jsxDEV2(Button, {
1112
- onPress: handleExecute,
1113
- disabled: isLoading,
1114
- children: isLoading ? "Executing..." : "▶️ Execute"
1115
- }, undefined, false, undefined, this)
1116
- ]
1117
- }, undefined, true, undefined, this)
1118
- ]
1119
- }, undefined, true, undefined, this),
1120
- mode === "confirm" && confirmAction === "archive" && /* @__PURE__ */ jsxDEV2("div", {
1121
- className: "space-y-4",
1122
- children: [
1123
- /* @__PURE__ */ jsxDEV2("p", {
1124
- className: "text-muted-foreground",
1125
- children: [
1126
- "Are you sure you want to archive",
1127
- " ",
1128
- /* @__PURE__ */ jsxDEV2("span", {
1129
- className: "font-medium text-foreground",
1130
- children: agent.name
1131
- }, undefined, false, undefined, this),
1132
- "?"
1133
- ]
1134
- }, undefined, true, undefined, this),
1135
- /* @__PURE__ */ jsxDEV2("p", {
1136
- className: "text-muted-foreground text-sm",
1137
- children: "Archived agents cannot be executed but can be restored later."
1138
- }, undefined, false, undefined, this),
1139
- error && /* @__PURE__ */ jsxDEV2("div", {
1140
- className: "rounded-md bg-destructive/10 p-3 text-destructive text-sm",
1141
- children: error
1142
- }, undefined, false, undefined, this),
1143
- /* @__PURE__ */ jsxDEV2("div", {
1144
- className: "flex justify-end gap-3 pt-2",
1145
- children: [
1146
- /* @__PURE__ */ jsxDEV2(Button, {
1147
- variant: "ghost",
1148
- onPress: () => setMode("menu"),
1149
- disabled: isLoading,
1150
- children: "Cancel"
1151
- }, undefined, false, undefined, this),
1152
- /* @__PURE__ */ jsxDEV2(Button, {
1153
- onPress: () => handleStatusChange("archive"),
1154
- disabled: isLoading,
1155
- children: isLoading ? "Archiving..." : "\uD83D\uDCE6 Archive"
1156
- }, undefined, false, undefined, this)
1157
- ]
1158
- }, undefined, true, undefined, this)
1159
- ]
1160
- }, undefined, true, undefined, this)
1161
- ]
1162
- }, undefined, true, undefined, this)
1163
- ]
1164
- }, undefined, true, undefined, this);
1165
- }
1166
-
1167
- // src/ui/modals/CreateAgentModal.tsx
1168
- import { Button as Button2, Input } from "@contractspec/lib.design-system";
1169
- import { useState as useState5 } from "react";
1170
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1171
- "use client";
1172
- var MODEL_PROVIDERS = [
1173
- {
1174
- value: "openai",
1175
- label: "OpenAI",
1176
- models: ["gpt-5.4", "gpt-5-mini", "gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"]
1177
- },
1178
- {
1179
- value: "anthropic",
1180
- label: "Anthropic",
1181
- models: ["claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5"]
1182
- },
1183
- {
1184
- value: "google",
1185
- label: "Google",
1186
- models: [
1187
- "gemini-2.5-flash",
1188
- "gemini-2.5-pro",
1189
- "gemini-pro",
1190
- "gemini-ultra"
1191
- ]
1192
- },
1193
- {
1194
- value: "mistral",
1195
- label: "Mistral",
1196
- models: [
1197
- "mistral-large-2512",
1198
- "mistral-large-latest",
1199
- "mistral-medium-latest",
1200
- "mistral-small-latest"
1201
- ]
1202
- }
1203
- ];
1204
- function CreateAgentModal({
1205
- isOpen,
1206
- onClose,
1207
- onSubmit,
1208
- isLoading = false
1209
- }) {
1210
- const [name, setName] = useState5("");
1211
- const [description, setDescription] = useState5("");
1212
- const [modelProvider, setModelProvider] = useState5("openai");
1213
- const [modelName, setModelName] = useState5("gpt-5.4");
1214
- const [systemPrompt, setSystemPrompt] = useState5("");
1215
- const [error, setError] = useState5(null);
1216
- const selectedProvider = MODEL_PROVIDERS.find((p) => p.value === modelProvider);
1217
- const handleSubmit = async (e) => {
1218
- e.preventDefault();
1219
- setError(null);
1220
- if (!name.trim()) {
1221
- setError("Agent name is required");
1222
- return;
1223
- }
1224
- try {
1225
- await onSubmit({
1226
- name: name.trim(),
1227
- description: description.trim() || undefined,
1228
- modelProvider,
1229
- modelName,
1230
- systemPrompt: systemPrompt.trim() || undefined
1231
- });
1232
- setName("");
1233
- setDescription("");
1234
- setModelProvider("openai");
1235
- setModelName("gpt-5.4");
1236
- setSystemPrompt("");
1237
- onClose();
1238
- } catch (err) {
1239
- setError(err instanceof Error ? err.message : "Failed to create agent");
1240
- }
1241
- };
1242
- const handleProviderChange = (provider) => {
1243
- setModelProvider(provider);
1244
- const providerConfig = MODEL_PROVIDERS.find((p) => p.value === provider);
1245
- if (providerConfig) {
1246
- setModelName(providerConfig.models[0]);
1247
- }
1248
- };
1249
- if (!isOpen)
1250
- return null;
1251
- return /* @__PURE__ */ jsxDEV3("div", {
1252
- className: "fixed inset-0 z-50 flex items-center justify-center",
1253
- children: [
1254
- /* @__PURE__ */ jsxDEV3("div", {
1255
- className: "absolute inset-0 bg-background/80 backdrop-blur-sm",
1256
- onClick: onClose,
1257
- role: "button",
1258
- tabIndex: 0,
1259
- onKeyDown: (e) => {
1260
- if (e.key === "Enter" || e.key === " ")
1261
- onClose();
1262
- },
1263
- "aria-label": "Close modal"
1264
- }, undefined, false, undefined, this),
1265
- /* @__PURE__ */ jsxDEV3("div", {
1266
- className: "relative z-10 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl",
1267
- children: [
1268
- /* @__PURE__ */ jsxDEV3("h2", {
1269
- className: "mb-4 font-semibold text-xl",
1270
- children: "Create New Agent"
1271
- }, undefined, false, undefined, this),
1272
- /* @__PURE__ */ jsxDEV3("form", {
1273
- onSubmit: handleSubmit,
1274
- className: "space-y-4",
1275
- children: [
1276
- /* @__PURE__ */ jsxDEV3("div", {
1277
- children: [
1278
- /* @__PURE__ */ jsxDEV3("label", {
1279
- htmlFor: "agent-name",
1280
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1281
- children: "Agent Name *"
1282
- }, undefined, false, undefined, this),
1283
- /* @__PURE__ */ jsxDEV3(Input, {
1284
- id: "agent-name",
1285
- value: name,
1286
- onChange: (e) => setName(e.target.value),
1287
- placeholder: "e.g., Customer Support Bot",
1288
- disabled: isLoading
1289
- }, undefined, false, undefined, this)
1290
- ]
1291
- }, undefined, true, undefined, this),
1292
- /* @__PURE__ */ jsxDEV3("div", {
1293
- children: [
1294
- /* @__PURE__ */ jsxDEV3("label", {
1295
- htmlFor: "agent-description",
1296
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1297
- children: "Description"
1298
- }, undefined, false, undefined, this),
1299
- /* @__PURE__ */ jsxDEV3("textarea", {
1300
- id: "agent-description",
1301
- value: description,
1302
- onChange: (e) => setDescription(e.target.value),
1303
- placeholder: "Describe what this agent does...",
1304
- rows: 2,
1305
- disabled: isLoading,
1306
- className: "w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
1307
- }, undefined, false, undefined, this)
1308
- ]
1309
- }, undefined, true, undefined, this),
1310
- /* @__PURE__ */ jsxDEV3("div", {
1311
- className: "flex gap-3",
1312
- children: [
1313
- /* @__PURE__ */ jsxDEV3("div", {
1314
- className: "flex-1",
1315
- children: [
1316
- /* @__PURE__ */ jsxDEV3("label", {
1317
- htmlFor: "model-provider",
1318
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1319
- children: "Provider *"
1320
- }, undefined, false, undefined, this),
1321
- /* @__PURE__ */ jsxDEV3("select", {
1322
- id: "model-provider",
1323
- value: modelProvider,
1324
- onChange: (e) => handleProviderChange(e.target.value),
1325
- disabled: isLoading,
1326
- className: "h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",
1327
- children: MODEL_PROVIDERS.map((p) => /* @__PURE__ */ jsxDEV3("option", {
1328
- value: p.value,
1329
- children: p.label
1330
- }, p.value, false, undefined, this))
1331
- }, undefined, false, undefined, this)
1332
- ]
1333
- }, undefined, true, undefined, this),
1334
- /* @__PURE__ */ jsxDEV3("div", {
1335
- className: "flex-1",
1336
- children: [
1337
- /* @__PURE__ */ jsxDEV3("label", {
1338
- htmlFor: "model-name",
1339
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1340
- children: "Model *"
1341
- }, undefined, false, undefined, this),
1342
- /* @__PURE__ */ jsxDEV3("select", {
1343
- id: "model-name",
1344
- value: modelName,
1345
- onChange: (e) => setModelName(e.target.value),
1346
- disabled: isLoading,
1347
- className: "h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",
1348
- children: selectedProvider?.models.map((m) => /* @__PURE__ */ jsxDEV3("option", {
1349
- value: m,
1350
- children: m
1351
- }, m, false, undefined, this))
1352
- }, undefined, false, undefined, this)
1353
- ]
1354
- }, undefined, true, undefined, this)
1355
- ]
1356
- }, undefined, true, undefined, this),
1357
- /* @__PURE__ */ jsxDEV3("div", {
1358
- children: [
1359
- /* @__PURE__ */ jsxDEV3("label", {
1360
- htmlFor: "system-prompt",
1361
- className: "mb-1 block font-medium text-muted-foreground text-sm",
1362
- children: "System Prompt"
1363
- }, undefined, false, undefined, this),
1364
- /* @__PURE__ */ jsxDEV3("textarea", {
1365
- id: "system-prompt",
1366
- value: systemPrompt,
1367
- onChange: (e) => setSystemPrompt(e.target.value),
1368
- placeholder: "You are a helpful assistant that...",
1369
- rows: 4,
1370
- disabled: isLoading,
1371
- className: "w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
1372
- }, undefined, false, undefined, this),
1373
- /* @__PURE__ */ jsxDEV3("p", {
1374
- className: "mt-1 text-muted-foreground text-xs",
1375
- children: "Instructions that define the agent's behavior"
1376
- }, undefined, false, undefined, this)
1377
- ]
1378
- }, undefined, true, undefined, this),
1379
- error && /* @__PURE__ */ jsxDEV3("div", {
1380
- className: "rounded-md bg-destructive/10 p-3 text-destructive text-sm",
1381
- children: error
1382
- }, undefined, false, undefined, this),
1383
- /* @__PURE__ */ jsxDEV3("div", {
1384
- className: "flex justify-end gap-3 pt-2",
1385
- children: [
1386
- /* @__PURE__ */ jsxDEV3(Button2, {
1387
- type: "button",
1388
- variant: "ghost",
1389
- onPress: onClose,
1390
- disabled: isLoading,
1391
- children: "Cancel"
1392
- }, undefined, false, undefined, this),
1393
- /* @__PURE__ */ jsxDEV3(Button2, {
1394
- type: "submit",
1395
- disabled: isLoading,
1396
- children: isLoading ? "Creating..." : "Create Agent"
1397
- }, undefined, false, undefined, this)
1398
- ]
1399
- }, undefined, true, undefined, this)
1400
- ]
1401
- }, undefined, true, undefined, this)
1402
- ]
1403
- }, undefined, true, undefined, this)
1404
- ]
1405
- }, undefined, true, undefined, this);
1406
- }
1407
-
1408
- // src/ui/views/run-list.shared.tsx
1409
- import { Button as Button3, StatusChip } from "@contractspec/lib.design-system";
1410
- import { HStack, VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1411
- import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
1412
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1413
- "use client";
1414
- function getStatusTone(status) {
1415
- switch (status) {
1416
- case "COMPLETED":
1417
- return "success";
1418
- case "RUNNING":
1419
- return "warning";
1420
- case "QUEUED":
1421
- return "neutral";
1422
- case "FAILED":
1423
- case "CANCELLED":
1424
- return "danger";
1425
- default:
1426
- return "neutral";
1427
- }
1428
- }
1429
- function formatDuration(ms) {
1430
- if (!ms)
1431
- return "-";
1432
- if (ms < 1000)
1433
- return `${ms}ms`;
1434
- if (ms < 60000)
1435
- return `${(ms / 1000).toFixed(1)}s`;
1436
- return `${(ms / 60000).toFixed(1)}m`;
1437
- }
1438
- function formatTokens(tokens) {
1439
- if (tokens < 1000)
1440
- return tokens.toString();
1441
- if (tokens < 1e6)
1442
- return `${(tokens / 1000).toFixed(1)}K`;
1443
- return `${(tokens / 1e6).toFixed(2)}M`;
1444
- }
1445
- function formatCost(cost) {
1446
- if (!cost)
1447
- return "-";
1448
- return `$${cost.toFixed(4)}`;
1449
- }
1450
- function formatJson(value) {
1451
- return JSON.stringify(value ?? null, null, 2);
1452
- }
1453
- function RunExpandedContent({ run }) {
1454
- return /* @__PURE__ */ jsxDEV4(VStack, {
1455
- gap: "sm",
1456
- className: "py-2",
1457
- children: [
1458
- /* @__PURE__ */ jsxDEV4(HStack, {
1459
- justify: "between",
1460
- className: "flex-wrap",
1461
- children: [
1462
- /* @__PURE__ */ jsxDEV4(StatusChip, {
1463
- tone: getStatusTone(run.status),
1464
- label: run.status
1465
- }, undefined, false, undefined, this),
1466
- /* @__PURE__ */ jsxDEV4(Text, {
1467
- className: "text-muted-foreground text-sm",
1468
- children: [
1469
- "Queued ",
1470
- run.queuedAt.toLocaleString()
1471
- ]
1472
- }, undefined, true, undefined, this)
1473
- ]
1474
- }, undefined, true, undefined, this),
1475
- /* @__PURE__ */ jsxDEV4(HStack, {
1476
- gap: "lg",
1477
- className: "flex-wrap",
1478
- children: [
1479
- /* @__PURE__ */ jsxDEV4(Text, {
1480
- className: "text-muted-foreground text-sm",
1481
- children: [
1482
- "Prompt ",
1483
- formatTokens(run.promptTokens)
1484
- ]
1485
- }, undefined, true, undefined, this),
1486
- /* @__PURE__ */ jsxDEV4(Text, {
1487
- className: "text-muted-foreground text-sm",
1488
- children: [
1489
- "Completion ",
1490
- formatTokens(run.completionTokens)
1491
- ]
1492
- }, undefined, true, undefined, this),
1493
- /* @__PURE__ */ jsxDEV4(Text, {
1494
- className: "text-muted-foreground text-sm",
1495
- children: [
1496
- "Duration ",
1497
- formatDuration(run.durationMs)
1498
- ]
1499
- }, undefined, true, undefined, this)
1500
- ]
1501
- }, undefined, true, undefined, this),
1502
- /* @__PURE__ */ jsxDEV4(VStack, {
1503
- gap: "xs",
1504
- children: [
1505
- /* @__PURE__ */ jsxDEV4(Text, {
1506
- className: "font-medium text-sm",
1507
- children: "Input"
1508
- }, undefined, false, undefined, this),
1509
- /* @__PURE__ */ jsxDEV4("pre", {
1510
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1511
- children: formatJson(run.input)
1512
- }, undefined, false, undefined, this)
1513
- ]
1514
- }, undefined, true, undefined, this),
1515
- /* @__PURE__ */ jsxDEV4(VStack, {
1516
- gap: "xs",
1517
- children: [
1518
- /* @__PURE__ */ jsxDEV4(Text, {
1519
- className: "font-medium text-sm",
1520
- children: "Output"
1521
- }, undefined, false, undefined, this),
1522
- /* @__PURE__ */ jsxDEV4("pre", {
1523
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1524
- children: formatJson(run.output ?? run.errorMessage ?? "Pending")
1525
- }, undefined, false, undefined, this)
1526
- ]
1527
- }, undefined, true, undefined, this)
1528
- ]
1529
- }, undefined, true, undefined, this);
1530
- }
1531
- function RunTableToolbar({
1532
- controller,
1533
- totalRuns
1534
- }) {
1535
- const firstRow = controller.rows[0];
1536
- const queuedColumn = controller.columns.find((column) => column.id === "queuedAt");
1537
- const durationColumn = controller.columns.find((column) => column.id === "durationMs");
1538
- const costColumn = controller.columns.find((column) => column.id === "estimatedCostUsd");
1539
- return /* @__PURE__ */ jsxDEV4(HStack, {
1540
- gap: "sm",
1541
- className: "flex-wrap",
1542
- children: [
1543
- /* @__PURE__ */ jsxDEV4(Text, {
1544
- className: "text-muted-foreground text-sm",
1545
- children: [
1546
- totalRuns,
1547
- " runs"
1548
- ]
1549
- }, undefined, true, undefined, this),
1550
- /* @__PURE__ */ jsxDEV4(Button3, {
1551
- variant: "outline",
1552
- size: "sm",
1553
- onPress: () => firstRow?.toggleExpanded?.(!firstRow?.isExpanded),
1554
- children: "Expand Latest Run"
1555
- }, undefined, false, undefined, this),
1556
- /* @__PURE__ */ jsxDEV4(Button3, {
1557
- variant: "outline",
1558
- size: "sm",
1559
- onPress: () => queuedColumn?.toggleVisibility?.(!queuedColumn?.visible),
1560
- children: queuedColumn?.visible ? "Hide Time" : "Show Time"
1561
- }, undefined, false, undefined, this),
1562
- /* @__PURE__ */ jsxDEV4(Button3, {
1563
- variant: "outline",
1564
- size: "sm",
1565
- onPress: () => durationColumn?.toggleVisibility?.(!durationColumn?.visible),
1566
- children: durationColumn?.visible ? "Hide Duration" : "Show Duration"
1567
- }, undefined, false, undefined, this),
1568
- /* @__PURE__ */ jsxDEV4(Button3, {
1569
- variant: "outline",
1570
- size: "sm",
1571
- onPress: () => costColumn?.toggleVisibility?.(!costColumn?.visible),
1572
- children: costColumn?.visible ? "Hide Cost" : "Show Cost"
1573
- }, undefined, false, undefined, this)
1574
- ]
1575
- }, undefined, true, undefined, this);
1576
- }
1577
-
1578
- // src/ui/views/run-data-table.columns.tsx
1579
- import { StatusChip as StatusChip2 } from "@contractspec/lib.design-system";
1580
- import { VStack as VStack2 } from "@contractspec/lib.ui-kit-web/ui/stack";
1581
- import { Text as Text2 } from "@contractspec/lib.ui-kit-web/ui/text";
1582
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
1583
- "use client";
1584
- function createRunTableColumns() {
1585
- return [
1586
- {
1587
- id: "queuedAt",
1588
- header: "Run",
1589
- label: "Run",
1590
- accessor: (run) => run.queuedAt.getTime(),
1591
- cell: ({ item }) => /* @__PURE__ */ jsxDEV5(VStack2, {
1592
- gap: "xs",
1593
- children: [
1594
- /* @__PURE__ */ jsxDEV5(Text2, {
1595
- className: "font-mono text-sm",
1596
- children: item.id.slice(-8)
1597
- }, undefined, false, undefined, this),
1598
- /* @__PURE__ */ jsxDEV5(Text2, {
1599
- className: "text-muted-foreground text-xs",
1600
- children: item.queuedAt.toLocaleString()
1601
- }, undefined, false, undefined, this)
1602
- ]
1603
- }, undefined, true, undefined, this),
1604
- size: 220,
1605
- minSize: 180,
1606
- canSort: true,
1607
- canHide: true,
1608
- canResize: true
1609
- },
1610
- {
1611
- id: "agentName",
1612
- header: "Agent",
1613
- label: "Agent",
1614
- accessor: (run) => run.agentName ?? "Unknown Agent",
1615
- cell: ({ value }) => /* @__PURE__ */ jsxDEV5(Text2, {
1616
- className: "font-medium",
1617
- children: typeof value === "string" ? value : "Unknown Agent"
1618
- }, undefined, false, undefined, this),
1619
- size: 220,
1620
- canSort: true,
1621
- canResize: true
1622
- },
1623
- {
1624
- id: "status",
1625
- header: "Status",
1626
- label: "Status",
1627
- accessorKey: "status",
1628
- cell: ({ value }) => {
1629
- const status = typeof value === "string" ? value : "QUEUED";
1630
- return /* @__PURE__ */ jsxDEV5(StatusChip2, {
1631
- tone: getStatusTone(status),
1632
- label: status
1633
- }, undefined, false, undefined, this);
1634
- },
1635
- size: 150,
1636
- canSort: true,
1637
- canResize: true
1638
- },
1639
- {
1640
- id: "totalTokens",
1641
- header: "Tokens",
1642
- label: "Tokens",
1643
- accessorKey: "totalTokens",
1644
- cell: ({ value }) => formatTokens(Number(value ?? 0)),
1645
- align: "right",
1646
- size: 140,
1647
- canSort: true,
1648
- canResize: true
1649
- },
1650
- {
1651
- id: "durationMs",
1652
- header: "Duration",
1653
- label: "Duration",
1654
- accessorKey: "durationMs",
1655
- cell: ({ value }) => formatDuration(typeof value === "number" ? value : undefined),
1656
- align: "right",
1657
- size: 140,
1658
- canSort: true,
1659
- canHide: true,
1660
- canResize: true
1661
- },
1662
- {
1663
- id: "estimatedCostUsd",
1664
- header: "Cost",
1665
- label: "Cost",
1666
- accessorKey: "estimatedCostUsd",
1667
- cell: ({ value }) => formatCost(typeof value === "number" ? value : undefined),
1668
- align: "right",
1669
- size: 140,
1670
- canSort: true,
1671
- canHide: true,
1672
- canResize: true
1673
- }
1674
- ];
1675
- }
1676
-
1677
- // src/ui/views/RunDataTable.tsx
1678
- import { DataTable } from "@contractspec/lib.design-system";
1679
- import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
1680
- import * as React from "react";
1681
- import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
1682
- "use client";
1683
- function RunDataTable({
1684
- runs,
1685
- totalItems,
1686
- pageIndex,
1687
- pageSize,
1688
- sorting,
1689
- loading,
1690
- onSortingChange,
1691
- onPaginationChange,
1692
- onRunClick
1693
- }) {
1694
- const columns = React.useMemo(() => createRunTableColumns(), []);
1695
- const controller = useContractTable({
1696
- data: runs,
1697
- columns,
1698
- executionMode: "server",
1699
- totalItems,
1700
- state: {
1701
- sorting,
1702
- pagination: { pageIndex, pageSize }
1703
- },
1704
- onSortingChange,
1705
- onPaginationChange,
1706
- initialState: {
1707
- columnVisibility: { estimatedCostUsd: false }
1708
- },
1709
- getRowId: (run) => run.id,
1710
- renderExpandedContent: (run) => /* @__PURE__ */ jsxDEV6(RunExpandedContent, {
1711
- run
1712
- }, undefined, false, undefined, this),
1713
- getCanExpand: () => true
1714
- });
1715
- return /* @__PURE__ */ jsxDEV6(DataTable, {
1716
- controller,
1717
- title: "Run History",
1718
- description: "Server-mode ContractSpec table with shared pagination, sorting, visibility, and expansion.",
1719
- loading,
1720
- onRowPress: (row) => onRunClick?.(row.id),
1721
- toolbar: /* @__PURE__ */ jsxDEV6(RunTableToolbar, {
1722
- controller,
1723
- totalRuns: totalItems
1724
- }, undefined, false, undefined, this),
1725
- emptyState: /* @__PURE__ */ jsxDEV6("div", {
1726
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1727
- children: "No runs yet"
1728
- }, undefined, false, undefined, this)
1729
- }, undefined, false, undefined, this);
1730
- }
1731
-
1732
- // src/ui/views/RunListView.tsx
1733
- import {
1734
- EmptyState,
1735
- ErrorState,
1736
- LoaderBlock,
1737
- StatCard,
1738
- StatCardGroup
1739
- } from "@contractspec/lib.design-system";
1740
- import { useState as useState6 } from "react";
1741
- import { jsxDEV as jsxDEV7 } from "react/jsx-dev-runtime";
1742
- "use client";
1743
- function RunListView({ agentId, onRunClick }) {
1744
- const [sorting, setSorting] = useState6([
1745
- { id: "queuedAt", desc: true }
1746
- ]);
1747
- const [pagination, setPagination] = useState6({
1748
- pageIndex: 0,
1749
- pageSize: 3
1750
- });
1751
- const { data, metrics, loading, error, refetch } = useRunList({
1752
- agentId,
1753
- pageIndex: pagination.pageIndex,
1754
- pageSize: pagination.pageSize,
1755
- sorting
1756
- });
1757
- if (loading && !data) {
1758
- return /* @__PURE__ */ jsxDEV7(LoaderBlock, {
1759
- label: "Loading runs..."
1760
- }, undefined, false, undefined, this);
1761
- }
1762
- if (error) {
1763
- return /* @__PURE__ */ jsxDEV7(ErrorState, {
1764
- title: "Failed to load runs",
1765
- description: error.message,
1766
- onRetry: refetch,
1767
- retryLabel: "Retry"
1768
- }, undefined, false, undefined, this);
1769
- }
1770
- if (!data?.items.length) {
1771
- return /* @__PURE__ */ jsxDEV7(EmptyState, {
1772
- title: "No runs yet",
1773
- description: "Execute an agent to see run history here."
1774
- }, undefined, false, undefined, this);
1775
- }
1776
- return /* @__PURE__ */ jsxDEV7("div", {
1777
- className: "space-y-6",
1778
- children: [
1779
- metrics ? /* @__PURE__ */ jsxDEV7(StatCardGroup, {
1780
- children: [
1781
- /* @__PURE__ */ jsxDEV7(StatCard, {
1782
- label: "Total Runs",
1783
- value: metrics.totalRuns
1784
- }, undefined, false, undefined, this),
1785
- /* @__PURE__ */ jsxDEV7(StatCard, {
1786
- label: "Success Rate",
1787
- value: `${(metrics.successRate * 100).toFixed(1)}%`
1788
- }, undefined, false, undefined, this),
1789
- /* @__PURE__ */ jsxDEV7(StatCard, {
1790
- label: "Total Tokens",
1791
- value: formatTokens(metrics.totalTokens)
1792
- }, undefined, false, undefined, this),
1793
- /* @__PURE__ */ jsxDEV7(StatCard, {
1794
- label: "Total Cost",
1795
- value: `$${metrics.totalCostUsd.toFixed(2)}`
1796
- }, undefined, false, undefined, this)
1797
- ]
1798
- }, undefined, true, undefined, this) : null,
1799
- /* @__PURE__ */ jsxDEV7(RunDataTable, {
1800
- runs: data.items,
1801
- totalItems: data.total,
1802
- pageIndex: pagination.pageIndex,
1803
- pageSize: pagination.pageSize,
1804
- sorting,
1805
- loading,
1806
- onSortingChange: (nextSorting) => {
1807
- setSorting(nextSorting);
1808
- setPagination((current) => ({ ...current, pageIndex: 0 }));
1809
- },
1810
- onPaginationChange: setPagination,
1811
- onRunClick
1812
- }, undefined, false, undefined, this)
1813
- ]
1814
- }, undefined, true, undefined, this);
1815
- }
1816
-
1817
- // src/ui/hooks/useToolList.ts
1818
- import { useTemplateRuntime as useTemplateRuntime4 } from "@contractspec/lib.example-shared-ui";
1819
- import { useCallback as useCallback4, useEffect as useEffect3, useMemo as useMemo3, useState as useState7 } from "react";
1820
- function useToolList(options = {}) {
1821
- const { handlers, projectId } = useTemplateRuntime4();
1822
- const { agent } = handlers;
1823
- const [data, setData] = useState7(null);
1824
- const [loading, setLoading] = useState7(true);
1825
- const [error, setError] = useState7(null);
1826
- const [page, setPage] = useState7(1);
1827
- const fetchData = useCallback4(async () => {
1828
- setLoading(true);
1829
- setError(null);
1830
- try {
1831
- const result = await agent.listTools({
1832
- projectId,
1833
- search: options.search,
1834
- category: options.category,
1835
- status: options.status === "all" ? undefined : options.status,
1836
- limit: options.limit ?? 50,
1837
- offset: (page - 1) * (options.limit ?? 50)
1838
- });
1839
- setData(result);
1840
- } catch (err) {
1841
- setError(err instanceof Error ? err : new Error("Unknown error"));
1842
- } finally {
1843
- setLoading(false);
1844
- }
1845
- }, [
1846
- agent,
1847
- projectId,
1848
- options.search,
1849
- options.category,
1850
- options.status,
1851
- options.limit,
1852
- page
1853
- ]);
1854
- useEffect3(() => {
1855
- fetchData();
1856
- }, [fetchData]);
1857
- const { stats, groupedByCategory, categoryStats } = useMemo3(() => {
1858
- if (!data)
1859
- return { stats: null, groupedByCategory: {}, categoryStats: [] };
1860
- const items = data.items;
1861
- const active = items.filter((t) => t.status === "ACTIVE").length;
1862
- const deprecated = items.filter((t) => t.status === "DEPRECATED").length;
1863
- const disabled = items.filter((t) => t.status === "DISABLED").length;
1864
- const grouped = {};
1865
- const byCategory = {};
1866
- items.forEach((t) => {
1867
- const cat = t.category;
1868
- if (!grouped[cat])
1869
- grouped[cat] = [];
1870
- grouped[cat].push(t);
1871
- byCategory[cat] = (byCategory[cat] || 0) + 1;
1872
- });
1873
- const catStats = Object.entries(byCategory).map(([category, count]) => ({ category, count })).sort((a, b) => b.count - a.count);
1874
- return {
1875
- stats: {
1876
- total: data.total,
1877
- active,
1878
- deprecated,
1879
- disabled,
1880
- topCategories: catStats.slice(0, 5)
1881
- },
1882
- groupedByCategory: grouped,
1883
- categoryStats: catStats
1884
- };
1885
- }, [data]);
1886
- return {
1887
- data,
1888
- loading,
1889
- error,
1890
- stats,
1891
- groupedByCategory,
1892
- categoryStats,
1893
- page,
1894
- refetch: fetchData,
1895
- nextPage: () => setPage((p) => p + 1),
1896
- prevPage: () => page > 1 && setPage((p) => p - 1)
1897
- };
1898
- }
1899
-
1900
- // src/ui/views/ToolRegistryView.tsx
1901
- import {
1902
- Button as Button4,
1903
- EmptyState as EmptyState2,
1904
- EntityCard,
1905
- ErrorState as ErrorState2,
1906
- LoaderBlock as LoaderBlock2,
1907
- StatCard as StatCard2,
1908
- StatCardGroup as StatCardGroup2,
1909
- StatusChip as StatusChip3
1910
- } from "@contractspec/lib.design-system";
1911
- import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
1912
- "use client";
1913
- var categoryIcons = {
1914
- RETRIEVAL: "\uD83D\uDD0D",
1915
- COMPUTATION: "\uD83E\uDDEE",
1916
- COMMUNICATION: "\uD83D\uDCE7",
1917
- INTEGRATION: "\uD83D\uDD17",
1918
- UTILITY: "\uD83D\uDEE0️",
1919
- CUSTOM: "⚙️"
1920
- };
1921
- function getStatusTone2(status) {
1922
- switch (status) {
1923
- case "ACTIVE":
1924
- return "success";
1925
- case "DRAFT":
1926
- return "neutral";
1927
- case "DEPRECATED":
1928
- return "warning";
1929
- case "DISABLED":
1930
- return "danger";
1931
- default:
1932
- return "neutral";
1933
- }
1934
- }
1935
- function ToolRegistryView({
1936
- onToolClick,
1937
- onCreateTool
1938
- }) {
1939
- const { data, loading, error, groupedByCategory, categoryStats, refetch } = useToolList();
1940
- if (loading && !data) {
1941
- return /* @__PURE__ */ jsxDEV8(LoaderBlock2, {
1942
- label: "Loading tools..."
1943
- }, undefined, false, undefined, this);
1944
- }
1945
- if (error) {
1946
- return /* @__PURE__ */ jsxDEV8(ErrorState2, {
1947
- title: "Failed to load tools",
1948
- description: error.message,
1949
- onRetry: refetch,
1950
- retryLabel: "Retry"
1951
- }, undefined, false, undefined, this);
1952
- }
1953
- if (!data?.items.length) {
1954
- return /* @__PURE__ */ jsxDEV8(EmptyState2, {
1955
- title: "No tools registered",
1956
- description: "Create your first tool to extend agent capabilities.",
1957
- primaryAction: onCreateTool ? /* @__PURE__ */ jsxDEV8(Button4, {
1958
- onPress: onCreateTool,
1959
- children: "Create Tool"
1960
- }, undefined, false, undefined, this) : undefined
1961
- }, undefined, false, undefined, this);
1962
- }
1963
- return /* @__PURE__ */ jsxDEV8("div", {
1964
- className: "space-y-8",
1965
- children: [
1966
- /* @__PURE__ */ jsxDEV8(StatCardGroup2, {
1967
- children: [
1968
- /* @__PURE__ */ jsxDEV8(StatCard2, {
1969
- label: "Total Tools",
1970
- value: data.total
1971
- }, undefined, false, undefined, this),
1972
- categoryStats.slice(0, 3).map(({ category, count }) => /* @__PURE__ */ jsxDEV8(StatCard2, {
1973
- label: `${categoryIcons[category] ?? ""} ${category}`,
1974
- value: count
1975
- }, category, false, undefined, this))
1976
- ]
1977
- }, undefined, true, undefined, this),
1978
- Object.entries(groupedByCategory).map(([category, tools]) => /* @__PURE__ */ jsxDEV8("section", {
1979
- className: "space-y-4",
1980
- children: [
1981
- /* @__PURE__ */ jsxDEV8("div", {
1982
- className: "flex items-center gap-2",
1983
- children: [
1984
- /* @__PURE__ */ jsxDEV8("span", {
1985
- className: "text-2xl",
1986
- children: categoryIcons[category]
1987
- }, undefined, false, undefined, this),
1988
- /* @__PURE__ */ jsxDEV8("h3", {
1989
- className: "font-semibold text-lg",
1990
- children: category
1991
- }, undefined, false, undefined, this),
1992
- /* @__PURE__ */ jsxDEV8("span", {
1993
- className: "rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs",
1994
- children: tools.length
1995
- }, undefined, false, undefined, this)
1996
- ]
1997
- }, undefined, true, undefined, this),
1998
- /* @__PURE__ */ jsxDEV8("div", {
1999
- className: "grid gap-4 md:grid-cols-2 lg:grid-cols-3",
2000
- children: tools.map((tool) => /* @__PURE__ */ jsxDEV8(EntityCard, {
2001
- cardTitle: tool.name,
2002
- cardSubtitle: `v${tool.version}`,
2003
- meta: /* @__PURE__ */ jsxDEV8("p", {
2004
- className: "text-muted-foreground text-sm",
2005
- children: tool.description
2006
- }, undefined, false, undefined, this),
2007
- chips: /* @__PURE__ */ jsxDEV8(StatusChip3, {
2008
- tone: getStatusTone2(tool.status),
2009
- label: tool.status
2010
- }, undefined, false, undefined, this),
2011
- footer: /* @__PURE__ */ jsxDEV8("code", {
2012
- className: "text-muted-foreground text-xs",
2013
- children: tool.name
2014
- }, undefined, false, undefined, this),
2015
- onClick: onToolClick ? () => onToolClick(tool.id) : undefined
2016
- }, tool.id, false, undefined, this))
2017
- }, undefined, false, undefined, this)
2018
- ]
2019
- }, category, true, undefined, this))
2020
- ]
2021
- }, undefined, true, undefined, this);
2022
- }
2023
-
2024
- // src/ui/AgentDashboard.tsx
2025
- import {
2026
- Button as Button5,
2027
- StatCard as StatCard3,
2028
- StatCardGroup as StatCardGroup3
2029
- } from "@contractspec/lib.design-system";
2030
- import { useCallback as useCallback5, useMemo as useMemo4, useState as useState8 } from "react";
2031
- import { jsxDEV as jsxDEV9 } from "react/jsx-dev-runtime";
2032
- "use client";
2033
- function AgentDashboard() {
2034
- const [activeTab, setActiveTab] = useState8("runs");
2035
- const [isCreateModalOpen, setIsCreateModalOpen] = useState8(false);
2036
- const [selectedAgent, setSelectedAgent] = useState8(null);
2037
- const [isAgentActionsOpen, setIsAgentActionsOpen] = useState8(false);
2038
- const [refreshVersion, setRefreshVersion] = useState8(0);
2039
- const { data: runData, metrics, refetch: refetchRuns } = useRunList();
2040
- const { refetch: refetchAgents } = useAgentList();
2041
- const mutations = useAgentMutations({
2042
- onSuccess: () => {
2043
- refetchAgents();
2044
- refetchRuns();
2045
- setRefreshVersion((current) => current + 1);
2046
- }
2047
- });
2048
- const handleAgentClick = useCallback5((agent) => {
2049
- setSelectedAgent(agent);
2050
- setIsAgentActionsOpen(true);
2051
- }, []);
2052
- const tabs = [
2053
- { id: "runs", label: "Runs", icon: "▶" },
2054
- { id: "agents", label: "Agents", icon: "\uD83E\uDD16" },
2055
- { id: "tools", label: "Tools", icon: "\uD83D\uDD27" },
2056
- { id: "metrics", label: "Metrics", icon: "\uD83D\uDCCA" }
2057
- ];
2058
- const summaryStats = useMemo4(() => {
2059
- if (!metrics) {
2060
- return [
2061
- { label: "Total Runs", value: "-", hint: "Loading..." },
2062
- { label: "Success Rate", value: "-", hint: "" },
2063
- { label: "Total Tokens", value: "-", hint: "" },
2064
- { label: "Total Cost", value: "-", hint: "" }
2065
- ];
2066
- }
2067
- return [
2068
- {
2069
- label: "Total Runs",
2070
- value: metrics.totalRuns.toLocaleString(),
2071
- hint: `${(metrics.successRate * 100).toFixed(0)}% success`
2072
- },
2073
- {
2074
- label: "Success Rate",
2075
- value: `${(metrics.successRate * 100).toFixed(0)}%`,
2076
- hint: "of all runs"
2077
- },
2078
- {
2079
- label: "Total Tokens",
2080
- value: metrics.totalTokens >= 1e6 ? `${(metrics.totalTokens / 1e6).toFixed(1)}M` : `${(metrics.totalTokens / 1000).toFixed(0)}K`,
2081
- hint: "This period"
2082
- },
2083
- {
2084
- label: "Total Cost",
2085
- value: `$${metrics.totalCostUsd.toFixed(2)}`,
2086
- hint: "This period"
2087
- }
2088
- ];
2089
- }, [metrics]);
2090
- return /* @__PURE__ */ jsxDEV9("div", {
2091
- className: "space-y-6",
2092
- children: [
2093
- /* @__PURE__ */ jsxDEV9("div", {
2094
- className: "flex items-center justify-between",
2095
- children: [
2096
- /* @__PURE__ */ jsxDEV9("h2", {
2097
- className: "font-bold text-2xl",
2098
- children: "AI Agent Console"
2099
- }, undefined, false, undefined, this),
2100
- /* @__PURE__ */ jsxDEV9(Button5, {
2101
- onPress: () => setIsCreateModalOpen(true),
2102
- children: [
2103
- /* @__PURE__ */ jsxDEV9("span", {
2104
- className: "mr-2",
2105
- children: "+"
2106
- }, undefined, false, undefined, this),
2107
- " New Agent"
2108
- ]
2109
- }, undefined, true, undefined, this)
2110
- ]
2111
- }, undefined, true, undefined, this),
2112
- /* @__PURE__ */ jsxDEV9(StatCardGroup3, {
2113
- children: summaryStats.map((stat, i) => /* @__PURE__ */ jsxDEV9(StatCard3, {
2114
- label: stat.label,
2115
- value: stat.value,
2116
- hint: stat.hint
2117
- }, i, false, undefined, this))
2118
- }, undefined, false, undefined, this),
2119
- /* @__PURE__ */ jsxDEV9(AgentVisualizationOverview, {
2120
- runs: runData?.items ?? []
2121
- }, undefined, false, undefined, this),
2122
- /* @__PURE__ */ jsxDEV9("nav", {
2123
- className: "flex gap-1 rounded-lg bg-muted p-1",
2124
- role: "tablist",
2125
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV9("button", {
2126
- type: "button",
2127
- role: "tab",
2128
- "aria-selected": activeTab === tab.id,
2129
- onClick: () => setActiveTab(tab.id),
2130
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
2131
- children: [
2132
- /* @__PURE__ */ jsxDEV9("span", {
2133
- children: tab.icon
2134
- }, undefined, false, undefined, this),
2135
- tab.label
2136
- ]
2137
- }, tab.id, true, undefined, this))
2138
- }, undefined, false, undefined, this),
2139
- /* @__PURE__ */ jsxDEV9("div", {
2140
- className: "min-h-[400px]",
2141
- role: "tabpanel",
2142
- children: [
2143
- activeTab === "runs" && /* @__PURE__ */ jsxDEV9(RunListView, {}, refreshVersion, false, undefined, this),
2144
- activeTab === "agents" && /* @__PURE__ */ jsxDEV9(AgentListViewWithActions, {
2145
- onAgentClick: handleAgentClick
2146
- }, refreshVersion, false, undefined, this),
2147
- activeTab === "tools" && /* @__PURE__ */ jsxDEV9(ToolRegistryView, {}, undefined, false, undefined, this),
2148
- activeTab === "metrics" && /* @__PURE__ */ jsxDEV9(MetricsView, {
2149
- metrics
2150
- }, undefined, false, undefined, this)
2151
- ]
2152
- }, undefined, true, undefined, this),
2153
- /* @__PURE__ */ jsxDEV9(CreateAgentModal, {
2154
- isOpen: isCreateModalOpen,
2155
- onClose: () => setIsCreateModalOpen(false),
2156
- onSubmit: async (input) => {
2157
- await mutations.createAgent(input);
2158
- },
2159
- isLoading: mutations.createState.loading
2160
- }, undefined, false, undefined, this),
2161
- /* @__PURE__ */ jsxDEV9(AgentActionsModal, {
2162
- isOpen: isAgentActionsOpen,
2163
- agent: selectedAgent,
2164
- onClose: () => {
2165
- setIsAgentActionsOpen(false);
2166
- setSelectedAgent(null);
2167
- },
2168
- onActivate: async (agentId) => {
2169
- await mutations.activateAgent(agentId);
2170
- },
2171
- onPause: async (agentId) => {
2172
- await mutations.pauseAgent(agentId);
2173
- },
2174
- onArchive: async (agentId) => {
2175
- await mutations.archiveAgent(agentId);
2176
- },
2177
- onExecute: async (agentId, message) => {
2178
- await mutations.executeAgent({ agentId, message });
2179
- },
2180
- isLoading: mutations.isLoading
2181
- }, undefined, false, undefined, this)
2182
- ]
2183
- }, undefined, true, undefined, this);
2184
- }
2185
- function AgentListViewWithActions({
2186
- onAgentClick
2187
- }) {
2188
- const { data, loading, error, stats, refetch } = useAgentList();
2189
- if (loading && !data) {
2190
- return /* @__PURE__ */ jsxDEV9("div", {
2191
- className: "flex h-64 items-center justify-center text-muted-foreground",
2192
- children: "Loading agents..."
2193
- }, undefined, false, undefined, this);
2194
- }
2195
- if (error) {
2196
- return /* @__PURE__ */ jsxDEV9("div", {
2197
- className: "flex h-64 flex-col items-center justify-center text-destructive",
2198
- children: [
2199
- /* @__PURE__ */ jsxDEV9("p", {
2200
- children: [
2201
- "Failed to load agents: ",
2202
- error.message
2203
- ]
2204
- }, undefined, true, undefined, this),
2205
- /* @__PURE__ */ jsxDEV9(Button5, {
2206
- variant: "outline",
2207
- onPress: refetch,
2208
- className: "mt-2",
2209
- children: "Retry"
2210
- }, undefined, false, undefined, this)
2211
- ]
2212
- }, undefined, true, undefined, this);
2213
- }
2214
- if (!data?.items.length) {
2215
- return /* @__PURE__ */ jsxDEV9("div", {
2216
- className: "flex h-64 flex-col items-center justify-center text-muted-foreground",
2217
- children: [
2218
- /* @__PURE__ */ jsxDEV9("p", {
2219
- className: "font-medium text-lg",
2220
- children: "No agents yet"
2221
- }, undefined, false, undefined, this),
2222
- /* @__PURE__ */ jsxDEV9("p", {
2223
- className: "text-sm",
2224
- children: "Create your first AI agent to get started."
2225
- }, undefined, false, undefined, this)
2226
- ]
2227
- }, undefined, true, undefined, this);
2228
- }
2229
- return /* @__PURE__ */ jsxDEV9("div", {
2230
- className: "space-y-4",
2231
- children: [
2232
- stats && /* @__PURE__ */ jsxDEV9("div", {
2233
- className: "flex gap-4 text-sm",
2234
- children: [
2235
- /* @__PURE__ */ jsxDEV9("span", {
2236
- children: [
2237
- "Total: ",
2238
- stats.total
2239
- ]
2240
- }, undefined, true, undefined, this),
2241
- /* @__PURE__ */ jsxDEV9("span", {
2242
- className: "text-green-600",
2243
- children: [
2244
- "Active: ",
2245
- stats.active
2246
- ]
2247
- }, undefined, true, undefined, this),
2248
- /* @__PURE__ */ jsxDEV9("span", {
2249
- className: "text-yellow-600",
2250
- children: [
2251
- "Paused: ",
2252
- stats.paused
2253
- ]
2254
- }, undefined, true, undefined, this),
2255
- /* @__PURE__ */ jsxDEV9("span", {
2256
- className: "text-blue-600",
2257
- children: [
2258
- "Draft: ",
2259
- stats.draft
2260
- ]
2261
- }, undefined, true, undefined, this)
2262
- ]
2263
- }, undefined, true, undefined, this),
2264
- /* @__PURE__ */ jsxDEV9("div", {
2265
- className: "grid gap-4 md:grid-cols-2 lg:grid-cols-3",
2266
- children: data.items.map((agent) => /* @__PURE__ */ jsxDEV9(AgentCard, {
2267
- agent,
2268
- onClick: () => onAgentClick(agent)
2269
- }, agent.id, false, undefined, this))
2270
- }, undefined, false, undefined, this)
2271
- ]
2272
- }, undefined, true, undefined, this);
2273
- }
2274
- function AgentCard({ agent, onClick }) {
2275
- const statusColors = {
2276
- ACTIVE: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
2277
- DRAFT: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
2278
- PAUSED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
2279
- ARCHIVED: "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"
2280
- };
2281
- return /* @__PURE__ */ jsxDEV9("div", {
2282
- onClick,
2283
- className: "cursor-pointer rounded-xl border border-border bg-card p-4 transition-all hover:shadow-md",
2284
- role: "button",
2285
- tabIndex: 0,
2286
- onKeyDown: (e) => {
2287
- if (e.key === "Enter" || e.key === " ")
2288
- onClick();
2289
- },
2290
- children: [
2291
- /* @__PURE__ */ jsxDEV9("div", {
2292
- className: "flex items-start justify-between",
2293
- children: [
2294
- /* @__PURE__ */ jsxDEV9("div", {
2295
- className: "min-w-0 flex-1",
2296
- children: [
2297
- /* @__PURE__ */ jsxDEV9("h3", {
2298
- className: "truncate font-semibold",
2299
- children: agent.name
2300
- }, undefined, false, undefined, this),
2301
- /* @__PURE__ */ jsxDEV9("p", {
2302
- className: "text-muted-foreground text-sm",
2303
- children: [
2304
- agent.modelProvider,
2305
- " / ",
2306
- agent.modelName
2307
- ]
2308
- }, undefined, true, undefined, this)
2309
- ]
2310
- }, undefined, true, undefined, this),
2311
- /* @__PURE__ */ jsxDEV9("span", {
2312
- className: `rounded-full px-2 py-0.5 font-medium text-xs ${statusColors[agent.status]}`,
2313
- children: agent.status
2314
- }, undefined, false, undefined, this)
2315
- ]
2316
- }, undefined, true, undefined, this),
2317
- agent.description && /* @__PURE__ */ jsxDEV9("p", {
2318
- className: "mt-2 line-clamp-2 text-muted-foreground text-sm",
2319
- children: agent.description
2320
- }, undefined, false, undefined, this),
2321
- /* @__PURE__ */ jsxDEV9("div", {
2322
- className: "mt-3 flex items-center justify-between",
2323
- children: [
2324
- /* @__PURE__ */ jsxDEV9("span", {
2325
- className: "text-muted-foreground text-xs",
2326
- children: agent.modelName
2327
- }, undefined, false, undefined, this),
2328
- /* @__PURE__ */ jsxDEV9(Button5, {
2329
- variant: "ghost",
2330
- size: "sm",
2331
- onPress: onClick,
2332
- children: "Actions"
2333
- }, undefined, false, undefined, this)
2334
- ]
2335
- }, undefined, true, undefined, this)
2336
- ]
2337
- }, undefined, true, undefined, this);
2338
- }
2339
- function MetricsView({ metrics }) {
2340
- if (!metrics) {
2341
- return /* @__PURE__ */ jsxDEV9("div", {
2342
- className: "flex h-64 items-center justify-center text-muted-foreground",
2343
- children: "Loading metrics..."
2344
- }, undefined, false, undefined, this);
2345
- }
2346
- const completedRuns = Math.round(metrics.totalRuns * metrics.successRate);
2347
- const failedRuns = metrics.totalRuns - completedRuns;
2348
- return /* @__PURE__ */ jsxDEV9("div", {
2349
- className: "space-y-6",
2350
- children: [
2351
- /* @__PURE__ */ jsxDEV9("h3", {
2352
- className: "font-semibold text-lg",
2353
- children: "Usage Analytics"
2354
- }, undefined, false, undefined, this),
2355
- /* @__PURE__ */ jsxDEV9("div", {
2356
- className: "grid gap-6 md:grid-cols-2",
2357
- children: [
2358
- /* @__PURE__ */ jsxDEV9("div", {
2359
- className: "rounded-xl border border-border bg-card p-4",
2360
- children: [
2361
- /* @__PURE__ */ jsxDEV9("h4", {
2362
- className: "font-medium",
2363
- children: "Run Outcomes"
2364
- }, undefined, false, undefined, this),
2365
- /* @__PURE__ */ jsxDEV9("div", {
2366
- className: "mt-4 space-y-3",
2367
- children: [
2368
- /* @__PURE__ */ jsxDEV9(ProgressBar, {
2369
- label: "Completed",
2370
- value: completedRuns,
2371
- total: metrics.totalRuns,
2372
- color: "bg-green-500"
2373
- }, undefined, false, undefined, this),
2374
- /* @__PURE__ */ jsxDEV9(ProgressBar, {
2375
- label: "Failed",
2376
- value: failedRuns,
2377
- total: metrics.totalRuns,
2378
- color: "bg-red-500"
2379
- }, undefined, false, undefined, this)
2380
- ]
2381
- }, undefined, true, undefined, this)
2382
- ]
2383
- }, undefined, true, undefined, this),
2384
- /* @__PURE__ */ jsxDEV9("div", {
2385
- className: "rounded-xl border border-border bg-card p-4",
2386
- children: [
2387
- /* @__PURE__ */ jsxDEV9("h4", {
2388
- className: "font-medium",
2389
- children: "Performance"
2390
- }, undefined, false, undefined, this),
2391
- /* @__PURE__ */ jsxDEV9("dl", {
2392
- className: "mt-4 grid grid-cols-2 gap-4",
2393
- children: [
2394
- /* @__PURE__ */ jsxDEV9("div", {
2395
- children: [
2396
- /* @__PURE__ */ jsxDEV9("dt", {
2397
- className: "text-muted-foreground text-sm",
2398
- children: "Avg Duration"
2399
- }, undefined, false, undefined, this),
2400
- /* @__PURE__ */ jsxDEV9("dd", {
2401
- className: "font-semibold text-xl",
2402
- children: [
2403
- (metrics.averageDurationMs / 1000).toFixed(1),
2404
- "s"
2405
- ]
2406
- }, undefined, true, undefined, this)
2407
- ]
2408
- }, undefined, true, undefined, this),
2409
- /* @__PURE__ */ jsxDEV9("div", {
2410
- children: [
2411
- /* @__PURE__ */ jsxDEV9("dt", {
2412
- className: "text-muted-foreground text-sm",
2413
- children: "Success Rate"
2414
- }, undefined, false, undefined, this),
2415
- /* @__PURE__ */ jsxDEV9("dd", {
2416
- className: "font-semibold text-xl",
2417
- children: [
2418
- (metrics.successRate * 100).toFixed(0),
2419
- "%"
2420
- ]
2421
- }, undefined, true, undefined, this)
2422
- ]
2423
- }, undefined, true, undefined, this)
2424
- ]
2425
- }, undefined, true, undefined, this)
2426
- ]
2427
- }, undefined, true, undefined, this)
2428
- ]
2429
- }, undefined, true, undefined, this),
2430
- /* @__PURE__ */ jsxDEV9("div", {
2431
- className: "rounded-xl border border-border bg-card p-4",
2432
- children: [
2433
- /* @__PURE__ */ jsxDEV9("h4", {
2434
- className: "font-medium",
2435
- children: "Key Metrics"
2436
- }, undefined, false, undefined, this),
2437
- /* @__PURE__ */ jsxDEV9("dl", {
2438
- className: "mt-4 grid gap-4 sm:grid-cols-3",
2439
- children: [
2440
- /* @__PURE__ */ jsxDEV9("div", {
2441
- children: [
2442
- /* @__PURE__ */ jsxDEV9("dt", {
2443
- className: "text-muted-foreground text-sm",
2444
- children: "Total Runs"
2445
- }, undefined, false, undefined, this),
2446
- /* @__PURE__ */ jsxDEV9("dd", {
2447
- className: "font-semibold text-2xl",
2448
- children: metrics.totalRuns.toLocaleString()
2449
- }, undefined, false, undefined, this)
2450
- ]
2451
- }, undefined, true, undefined, this),
2452
- /* @__PURE__ */ jsxDEV9("div", {
2453
- children: [
2454
- /* @__PURE__ */ jsxDEV9("dt", {
2455
- className: "text-muted-foreground text-sm",
2456
- children: "Total Tokens"
2457
- }, undefined, false, undefined, this),
2458
- /* @__PURE__ */ jsxDEV9("dd", {
2459
- className: "font-semibold text-2xl",
2460
- children: [
2461
- (metrics.totalTokens / 1000).toFixed(0),
2462
- "K"
2463
- ]
2464
- }, undefined, true, undefined, this)
2465
- ]
2466
- }, undefined, true, undefined, this),
2467
- /* @__PURE__ */ jsxDEV9("div", {
2468
- children: [
2469
- /* @__PURE__ */ jsxDEV9("dt", {
2470
- className: "text-muted-foreground text-sm",
2471
- children: "Cost per Run"
2472
- }, undefined, false, undefined, this),
2473
- /* @__PURE__ */ jsxDEV9("dd", {
2474
- className: "font-semibold text-2xl",
2475
- children: [
2476
- "$",
2477
- metrics.totalRuns > 0 ? (metrics.totalCostUsd / metrics.totalRuns).toFixed(4) : "0"
2478
- ]
2479
- }, undefined, true, undefined, this)
2480
- ]
2481
- }, undefined, true, undefined, this)
2482
- ]
2483
- }, undefined, true, undefined, this)
2484
- ]
2485
- }, undefined, true, undefined, this)
2486
- ]
2487
- }, undefined, true, undefined, this);
2488
- }
2489
- function ProgressBar({
2490
- label,
2491
- value,
2492
- total,
2493
- color
2494
- }) {
2495
- const pct = total > 0 ? value / total * 100 : 0;
2496
- return /* @__PURE__ */ jsxDEV9("div", {
2497
- children: [
2498
- /* @__PURE__ */ jsxDEV9("div", {
2499
- className: "flex justify-between text-sm",
2500
- children: [
2501
- /* @__PURE__ */ jsxDEV9("span", {
2502
- children: label
2503
- }, undefined, false, undefined, this),
2504
- /* @__PURE__ */ jsxDEV9("span", {
2505
- className: "text-muted-foreground",
2506
- children: [
2507
- value,
2508
- " (",
2509
- pct.toFixed(0),
2510
- "%)"
2511
- ]
2512
- }, undefined, true, undefined, this)
2513
- ]
2514
- }, undefined, true, undefined, this),
2515
- /* @__PURE__ */ jsxDEV9("div", {
2516
- className: "mt-1 h-2 overflow-hidden rounded-full bg-muted",
2517
- children: /* @__PURE__ */ jsxDEV9("div", {
2518
- className: `h-full ${color}`,
2519
- style: { width: `${pct}%` }
2520
- }, undefined, false, undefined, this)
2521
- }, undefined, false, undefined, this)
2522
- ]
2523
- }, undefined, true, undefined, this);
2524
- }
2525
- export {
2526
- AgentDashboard
2527
- };
1
+ import{defineVisualization as j,VisualizationRegistry as r0}from"@contractspec/lib.contracts-spec/visualizations";var x={key:"agent.run.list",version:"1.0.0"},s={version:"1.0.0",domain:"ai-ops",stability:"experimental",owners:["@example.agent-console"],tags:["agent-console","visualization","operations"]},m0=j({meta:{...s,key:"agent-console.visualization.run-status",title:"Run Status Breakdown",description:"Distribution of run outcomes across the current sample.",goal:"Make operational success and failure mix visible at a glance.",context:"Agent operations overview."},source:{primary:x,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"runs",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number"}],table:{caption:"Run counts by status."}}}),d0=j({meta:{...s,key:"agent-console.visualization.run-activity",title:"Recent Run Activity",description:"Daily run volume across the current sample.",goal:"Show whether agent activity is rising or slowing down.",context:"Operations trend monitoring."},source:{primary:x,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["runs"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number",color:"#0f766e"}],table:{caption:"Daily run counts."}}}),p0=j({meta:{...s,key:"agent-console.visualization.run-efficiency",title:"Duration vs Tokens",description:"Scatter chart comparing token consumption and runtime.",goal:"Reveal outlier runs that are slow relative to their token usage.",context:"Operational performance diagnostics."},source:{primary:x,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"totalTokens",yMeasures:["durationMs"],dimensions:[{key:"totalTokens",label:"Total Tokens",dataPath:"totalTokens",type:"number"}],measures:[{key:"durationMs",label:"Duration",dataPath:"durationMs",format:"duration",color:"#7c3aed"},{key:"estimatedCostUsd",label:"Cost",dataPath:"estimatedCostUsd",format:"currency"}],series:[{key:"runs",label:"Runs",measure:"durationMs",type:"scatter",color:"#7c3aed"}],table:{caption:"Run duration versus token usage."}}}),z0=[m0,d0,p0],k2=new r0([...z0]),E2=z0.map((m)=>({key:m.meta.key,version:m.meta.version}));function G0(m){if(!m)return"unknown";return m.toISOString().slice(0,10)}function U0(m){let p=new Map,y=new Map;for(let T of m)p.set(T.status,(p.get(T.status)??0)+1),y.set(G0(T.startedAt??T.queuedAt),(y.get(G0(T.startedAt??T.queuedAt))??0)+1);return[{key:"run-status",spec:m0,data:{data:Array.from(p.entries()).map(([T,f])=>({status:T,runs:f}))},title:"Run Status Breakdown",description:"Completed, failed, running, and cancelled runs in the sample.",height:260},{key:"run-activity",spec:d0,data:{data:Array.from(y.entries()).sort(([T],[f])=>T.localeCompare(f)).map(([T,f])=>({day:T,runs:f}))},title:"Recent Run Activity",description:"Daily run volume derived from run start times."},{key:"run-efficiency",spec:p0,data:{data:m.filter((T)=>typeof T.durationMs==="number").map((T)=>({totalTokens:T.totalTokens,durationMs:T.durationMs??0,estimatedCostUsd:T.estimatedCostUsd}))},title:"Duration vs Tokens",description:"Operational scatter plot for spotting inefficient runs."}]}var Q0=[{id:"agent-1",organizationId:"demo-org",name:"Customer Support Bot",slug:"customer-support-bot",description:"Handles tier-1 customer inquiries and routes complex issues.",status:"ACTIVE",modelProvider:"OPENAI",modelName:"gpt-4o-mini",modelConfig:{temperature:0.7},systemPrompt:"You are a helpful customer support assistant.",toolChoice:"auto",maxIterations:10,timeoutMs:120000,version:"1.0.0",tags:["support","tier-1"],createdAt:new Date("2024-01-15T10:00:00Z"),updatedAt:new Date("2024-03-20T14:30:00Z")},{id:"agent-2",organizationId:"demo-org",name:"Code Review Assistant",slug:"code-review-assistant",description:"Reviews pull requests and provides actionable feedback.",status:"ACTIVE",modelProvider:"ANTHROPIC",modelName:"claude-sonnet-4-20250514",modelConfig:{temperature:0.3},systemPrompt:"You are a code review expert.",toolChoice:"auto",maxIterations:15,timeoutMs:180000,version:"2.1.0",tags:["code","review","dev"],createdAt:new Date("2024-02-10T09:00:00Z"),updatedAt:new Date("2024-04-05T11:15:00Z")},{id:"agent-3",organizationId:"demo-org",name:"Data Analyst",slug:"data-analyst",description:"Queries databases and generates insights from data.",status:"PAUSED",modelProvider:"OPENAI",modelName:"gpt-4o",modelConfig:{temperature:0.5},systemPrompt:"You are a data analyst expert in SQL and analytics.",toolChoice:"required",maxIterations:20,timeoutMs:300000,version:"1.2.0",tags:["data","analytics","sql"],createdAt:new Date("2024-03-01T08:00:00Z"),updatedAt:new Date("2024-04-10T16:45:00Z")},{id:"agent-4",organizationId:"demo-org",name:"Meeting Scheduler",slug:"meeting-scheduler",description:"Schedules meetings and manages calendar conflicts.",status:"DRAFT",modelProvider:"GOOGLE",modelName:"gemini-2.0-flash",modelConfig:{temperature:0.2},systemPrompt:"You help schedule and organize meetings efficiently.",toolChoice:"auto",maxIterations:5,timeoutMs:60000,version:"0.1.0",tags:["calendar","scheduling"],createdAt:new Date("2024-04-01T12:00:00Z"),updatedAt:new Date("2024-04-01T12:00:00Z")}];var R0=[{id:"tool-1",organizationId:"demo-org",name:"Web Search",slug:"web-search",description:"Search the web for real-time information using Brave API.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},numResults:{type:"number",default:10}},required:["query"]},outputSchema:{type:"array",items:{type:"object"}},implementationType:"http",implementationConfig:{url:"https://api.brave.com/search",method:"GET"},maxInvocationsPerMinute:60,timeoutMs:30000,version:"1.0.0",tags:["search","web"],createdAt:new Date("2024-01-01T00:00:00Z"),updatedAt:new Date("2024-02-15T10:00:00Z")},{id:"tool-2",organizationId:"demo-org",name:"SQL Query",slug:"sql-query",description:"Execute read-only SQL queries against the data warehouse.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"SQL query"},maxRows:{type:"number",default:100}},required:["query"]},outputSchema:{type:"object"},implementationType:"function",implementationConfig:{handler:"executeSqlQuery"},maxInvocationsPerMinute:30,timeoutMs:60000,version:"1.1.0",tags:["sql","database"],createdAt:new Date("2024-01-05T00:00:00Z"),updatedAt:new Date("2024-03-10T14:00:00Z")},{id:"tool-3",organizationId:"demo-org",name:"Email Sender",slug:"email-sender",description:"Send emails via SMTP or API.",category:"COMMUNICATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{to:{type:"string"},subject:{type:"string"},body:{type:"string"}},required:["to","subject","body"]},implementationType:"http",implementationConfig:{url:"/api/send-email",method:"POST"},maxInvocationsPerMinute:10,timeoutMs:30000,version:"1.0.0",tags:["email","communication"],createdAt:new Date("2024-02-01T00:00:00Z"),updatedAt:new Date("2024-02-01T00:00:00Z")},{id:"tool-4",organizationId:"demo-org",name:"GitHub Integration",slug:"github-integration",description:"Interact with GitHub repositories, PRs, and issues.",category:"INTEGRATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{action:{type:"string",enum:["list_prs","get_pr","create_comment"]},repo:{type:"string"},params:{type:"object"}},required:["action","repo"]},implementationType:"http",implementationConfig:{url:"https://api.github.com",auth:"token"},maxInvocationsPerMinute:100,timeoutMs:15000,version:"2.0.0",tags:["github","integration","code"],createdAt:new Date("2024-02-20T00:00:00Z"),updatedAt:new Date("2024-04-01T09:00:00Z")},{id:"tool-5",organizationId:"demo-org",name:"Calculator",slug:"calculator",description:"Perform mathematical calculations.",category:"COMPUTATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{expression:{type:"string",description:"Math expression to evaluate"}},required:["expression"]},outputSchema:{type:"object",properties:{result:{type:"number"}}},implementationType:"function",implementationConfig:{handler:"evaluateMath"},timeoutMs:5000,version:"1.0.0",tags:["math","utility"],createdAt:new Date("2024-01-10T00:00:00Z"),updatedAt:new Date("2024-01-10T00:00:00Z")}];var K0=[{id:"run-1",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",sessionId:"session-1",input:{message:"How do I reset my password?",context:{}},output:{response:"You can reset your password by clicking..."},status:"COMPLETED",totalTokens:1250,promptTokens:800,completionTokens:450,totalIterations:3,durationMs:4500,estimatedCostUsd:0.0025,queuedAt:new Date("2024-04-15T10:00:00Z"),startedAt:new Date("2024-04-15T10:00:01Z"),completedAt:new Date("2024-04-15T10:00:05Z"),steps:[],logs:[]},{id:"run-2",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #123",context:{prNumber:123}},status:"IN_PROGRESS",totalTokens:3500,promptTokens:3000,completionTokens:500,totalIterations:5,queuedAt:new Date("2024-04-15T10:30:00Z"),startedAt:new Date("2024-04-15T10:30:02Z"),steps:[],logs:[]},{id:"run-3",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",input:{message:"What are your business hours?"},output:{response:"Our business hours are 9 AM to 5 PM EST..."},status:"COMPLETED",totalTokens:800,promptTokens:500,completionTokens:300,totalIterations:2,durationMs:2100,estimatedCostUsd:0.0012,queuedAt:new Date("2024-04-15T09:00:00Z"),startedAt:new Date("2024-04-15T09:00:01Z"),completedAt:new Date("2024-04-15T09:00:03Z"),steps:[],logs:[]},{id:"run-4",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-3",agentName:"Data Analyst",userId:"user-3",input:{message:"Generate sales report for Q1"},status:"FAILED",errorMessage:"Database connection timeout",errorCode:"DB_TIMEOUT",totalTokens:2000,promptTokens:1500,completionTokens:500,totalIterations:8,durationMs:45000,queuedAt:new Date("2024-04-14T15:00:00Z"),startedAt:new Date("2024-04-14T15:00:05Z"),completedAt:new Date("2024-04-14T15:00:50Z"),steps:[],logs:[]},{id:"run-5",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #120"},output:{response:"Code review complete. 3 suggestions..."},status:"COMPLETED",totalTokens:5200,promptTokens:4000,completionTokens:1200,totalIterations:7,durationMs:15000,estimatedCostUsd:0.0156,queuedAt:new Date("2024-04-14T11:00:00Z"),startedAt:new Date("2024-04-14T11:00:03Z"),completedAt:new Date("2024-04-14T11:00:18Z"),steps:[],logs:[]}];import{VisualizationCard as S0,VisualizationGrid as l0}from"@contractspec/lib.design-system";import{jsx as L,jsxs as P0}from"react/jsx-runtime";function Y0({runs:m}){let p=U0(m);return P0("section",{className:"space-y-3",children:[P0("div",{children:[L("h3",{className:"font-semibold text-lg",children:"Operational Visualizations"}),L("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),L(l0,{children:p.map((y)=>L(S0,{data:y.data,description:y.description,height:y.height,spec:y.spec,title:y.title},y.key))})]})}import{useTemplateRuntime as e0}from"@contractspec/lib.example-shared-ui";import{useCallback as n0,useEffect as o0,useMemo as g0,useState as r}from"react";function T0(m={}){let{handlers:p,projectId:y}=e0(),{agent:T}=p,[f,I]=r(null),[d,O]=r(!0),[U,G]=r(null),[z,Z]=r(1),Y=n0(async()=>{O(!0),G(null);try{let D=await T.listAgents({projectId:y,search:m.search,status:m.status==="all"?void 0:m.status,limit:m.limit??20,offset:(z-1)*(m.limit??20)});I(D)}catch(D){G(D instanceof Error?D:Error("Unknown error"))}finally{O(!1)}},[T,y,m.search,m.status,m.limit,z]);o0(()=>{Y()},[Y]);let h=g0(()=>{if(!f)return null;return{total:f.total,active:f.items.filter((D)=>D.status==="ACTIVE").length,paused:f.items.filter((D)=>D.status==="PAUSED").length,draft:f.items.filter((D)=>D.status==="DRAFT").length}},[f]);return{data:f,loading:d,error:U,stats:h,page:z,refetch:Y,nextPage:()=>Z((D)=>D+1),prevPage:()=>z>1&&Z((D)=>D-1)}}import{useTemplateRuntime as j0}from"@contractspec/lib.example-shared-ui";import{useCallback as b,useState as y0}from"react";var f0="demo-org",m1="agent-console-demo";function d1(m){return m.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function p1(m){return{...m}}function T1(m){return{...m}}function f1(m){return{...m}}function y1(){let m=0,p=Date.parse("2026-03-20T09:00:00.000Z");return()=>new Date(p+m++*60000)}function a0(m){return m.toLowerCase()}function t0(m){return m==="IN_PROGRESS"?"RUNNING":m}function w1(m,p){let y=Q0.map((d)=>({id:d.id,projectId:m,organizationId:p,name:d.name,slug:d.slug,description:d.description,modelProvider:a0(d.modelProvider),modelName:d.modelName,systemPrompt:d.systemPrompt,temperature:typeof d.modelConfig?.temperature==="number"?d.modelConfig.temperature:0.4,maxTokens:8192,status:d.status,createdAt:d.createdAt,updatedAt:d.updatedAt})),T=R0.map((d)=>({id:d.id,projectId:m,organizationId:p,name:d.name,description:d.description,version:d.version,category:d.category,status:d.status,inputSchema:JSON.stringify(d.parametersSchema),outputSchema:d.outputSchema?JSON.stringify(d.outputSchema):void 0,endpoint:typeof d.implementationConfig?.url==="string"?d.implementationConfig.url:void 0,createdAt:d.createdAt,updatedAt:d.updatedAt})),f=new Map(y.map((d)=>[d.id,d.name])),I=K0.map((d)=>({id:d.id,projectId:m,agentId:d.agentId,agentName:f.get(d.agentId)??d.agentName??"Unknown agent",status:t0(d.status),input:JSON.stringify(d.input),output:d.output?JSON.stringify(d.output):void 0,totalTokens:d.totalTokens,promptTokens:d.promptTokens,completionTokens:d.completionTokens,estimatedCostUsd:d.estimatedCostUsd??0,durationMs:d.durationMs,errorMessage:d.errorMessage,queuedAt:d.queuedAt,startedAt:d.startedAt,completedAt:d.completedAt}));return{agents:y,tools:T,runs:I}}function A1(m){let p=m.length,y=m.filter((f)=>f.status==="COMPLETED").length,T=m.map((f)=>f.durationMs).filter((f)=>typeof f==="number");return{totalRuns:p,successRate:p===0?0:y/p,averageDurationMs:T.length===0?0:Math.round(T.reduce((f,I)=>f+I,0)/T.length),totalTokens:m.reduce((f,I)=>f+I.totalTokens,0),totalCostUsd:m.reduce((f,I)=>f+I.estimatedCostUsd,0)}}function w0(m,p){return m instanceof Error?m:Error(p)}function u0(m={}){let{handlers:p,projectId:y}=j0(),{agent:T}=p,[f,I]=y0({loading:!1,error:null,data:null}),[d,O]=y0({loading:!1,error:null,data:null}),[U,G]=y0({loading:!1,error:null,data:null}),z=b(async(M)=>{I({loading:!0,error:null,data:null});try{let Q=await T.createAgent(M,{projectId:y,organizationId:f0});return I({loading:!1,error:null,data:Q}),m.onSuccess?.(),Q}catch(Q){let A=w0(Q,"Failed to create agent");throw I({loading:!1,error:A,data:null}),m.onError?.(A),A}},[T,y,m]),Z=b(async(M)=>{O({loading:!0,error:null,data:null});try{let Q=await T.updateAgent(M);return O({loading:!1,error:null,data:Q}),m.onSuccess?.(),Q}catch(Q){let A=w0(Q,"Failed to update agent");throw O({loading:!1,error:A,data:null}),m.onError?.(A),A}},[T,m]),Y=b(async(M)=>{return Z({id:M,status:"ACTIVE"})},[Z]),h=b(async(M)=>{return Z({id:M,status:"PAUSED"})},[Z]),D=b(async(M)=>{return Z({id:M,status:"ARCHIVED"})},[Z]),P=b(async(M)=>{G({loading:!0,error:null,data:null});try{let Q=await T.executeAgent({agentId:M.agentId,message:M.message,context:{projectId:y,organizationId:f0}});return G({loading:!1,error:null,data:Q}),m.onSuccess?.(),Q}catch(Q){let A=w0(Q,"Failed to execute agent");throw G({loading:!1,error:A,data:null}),m.onError?.(A),A}},[T,y,m]);return{createAgent:z,updateAgent:Z,activateAgent:Y,pauseAgent:h,archiveAgent:D,executeAgent:P,createState:f,updateState:d,executeState:U,isLoading:f.loading||d.loading||U.loading}}import{useTemplateRuntime as x0}from"@contractspec/lib.example-shared-ui";import{useCallback as s0,useEffect as m2,useState as c}from"react";function S(m={}){let{handlers:p,projectId:y}=x0(),{agent:T}=p,[f,I]=c(null),[d,O]=c(null),[U,G]=c(!0),[z,Z]=c(null),[Y,h]=c(0),D=m.pageSize??m.limit??20,P=m.pageIndex??Y,[M]=m.sorting??[],Q=s0(async()=>{G(!0),Z(null);try{let[w,R]=await Promise.all([T.listRuns({projectId:y,agentId:m.agentId,status:m.status==="all"?void 0:m.status,sortBy:M?.id,sortDirection:M?M.desc?"desc":"asc":void 0,limit:D,offset:P*D}),T.getRunMetrics({projectId:y,agentId:m.agentId})]);I(w),O(R)}catch(w){Z(w instanceof Error?w:Error("Unknown error"))}finally{G(!1)}},[T,P,D,y,m.agentId,m.status,M?.desc,M?.id]);m2(()=>{Q()},[Q]);let A=m.pageIndex!==void 0;return{data:f,metrics:d,loading:U,error:z,page:P+1,pageIndex:P,pageSize:D,refetch:Q,nextPage:A?void 0:()=>h((w)=>w+1),prevPage:A?void 0:()=>h((w)=>Math.max(0,w-1))}}import{Button as $}from"@contractspec/lib.design-system";import{useState as l}from"react";import{jsx as K,jsxs as _}from"react/jsx-runtime";function d2(m){switch(m){case"ACTIVE":return"text-green-600 bg-green-100 dark:text-green-400 dark:bg-green-900/30";case"DRAFT":return"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30";case"PAUSED":return"text-yellow-600 bg-yellow-100 dark:text-yellow-400 dark:bg-yellow-900/30";case"ARCHIVED":return"text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700";default:return"text-gray-600 bg-gray-100"}}function _0({isOpen:m,agent:p,onClose:y,onActivate:T,onPause:f,onArchive:I,onExecute:d,isLoading:O=!1}){let[U,G]=l("menu"),[z,Z]=l(""),[Y,h]=l(null),[D,P]=l(null),M=()=>{G("menu"),Z(""),h(null),P(null)},Q=()=>{M(),y()},A=async()=>{if(!p)return;if(P(null),!z.trim()){P("Please enter a message");return}try{await d(p.id,z.trim()),Q()}catch(R){P(R instanceof Error?R.message:"Failed to execute agent")}},w=async(R)=>{if(!p)return;P(null);try{switch(R){case"activate":await T(p.id);break;case"pause":await f(p.id);break;case"archive":await I(p.id);break}Q()}catch(k){P(k instanceof Error?k.message:`Failed to ${R} agent`)}};if(!m||!p)return null;return _("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[K("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:Q,role:"button",tabIndex:0,onKeyDown:(R)=>{if(R.key==="Enter"||R.key===" ")Q()},"aria-label":"Close modal"}),_("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[_("div",{className:"mb-4 border-border border-b pb-4",children:[K("h2",{className:"font-semibold text-xl",children:p.name}),_("div",{className:"mt-1 flex items-center gap-2",children:[_("span",{className:"text-muted-foreground text-sm",children:[p.modelProvider," / ",p.modelName]}),K("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${d2(p.status)}`,children:p.status})]}),p.description&&K("p",{className:"mt-2 text-muted-foreground text-sm",children:p.description})]}),U==="menu"&&_("div",{className:"space-y-3",children:[p.status==="ACTIVE"&&_($,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("execute"),children:[K("span",{className:"mr-2",children:"▶️"})," Execute Agent"]}),(p.status==="DRAFT"||p.status==="PAUSED")&&_($,{className:"w-full justify-start",variant:"ghost",onPress:()=>w("activate"),disabled:O,children:[K("span",{className:"mr-2",children:"\uD83D\uDFE2"})," Activate Agent"]}),p.status==="ACTIVE"&&_($,{className:"w-full justify-start",variant:"ghost",onPress:()=>w("pause"),disabled:O,children:[K("span",{className:"mr-2",children:"⏸️"})," Pause Agent"]}),p.status!=="ARCHIVED"&&_($,{className:"w-full justify-start text-yellow-600 hover:text-yellow-700",variant:"ghost",onPress:()=>{h("archive"),G("confirm")},children:[K("span",{className:"mr-2",children:"\uD83D\uDCE6"})," Archive Agent"]}),p.status==="ARCHIVED"&&_($,{className:"w-full justify-start",variant:"ghost",onPress:()=>w("activate"),disabled:O,children:[K("span",{className:"mr-2",children:"\uD83D\uDD04"})," Restore Agent"]}),D&&K("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:D}),K("div",{className:"border-border border-t pt-3",children:K($,{className:"w-full",variant:"outline",onPress:Q,children:"Close"})})]}),U==="execute"&&_("div",{className:"space-y-4",children:[_("div",{children:[K("label",{htmlFor:"execute-message",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Message *"}),K("textarea",{id:"execute-message",value:z,onChange:(R)=>Z(R.target.value),placeholder:"Enter your message to the agent...",rows:4,disabled:O,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),D&&K("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:D}),_("div",{className:"flex justify-end gap-3 pt-2",children:[K($,{variant:"ghost",onPress:()=>G("menu"),disabled:O,children:"Back"}),K($,{onPress:A,disabled:O,children:O?"Executing...":"▶️ Execute"})]})]}),U==="confirm"&&Y==="archive"&&_("div",{className:"space-y-4",children:[_("p",{className:"text-muted-foreground",children:["Are you sure you want to archive"," ",K("span",{className:"font-medium text-foreground",children:p.name}),"?"]}),K("p",{className:"text-muted-foreground text-sm",children:"Archived agents cannot be executed but can be restored later."}),D&&K("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:D}),_("div",{className:"flex justify-end gap-3 pt-2",children:[K($,{variant:"ghost",onPress:()=>G("menu"),disabled:O,children:"Cancel"}),K($,{onPress:()=>w("archive"),disabled:O,children:O?"Archiving...":"\uD83D\uDCE6 Archive"})]})]})]})]})}import{Button as h0,Input as p2}from"@contractspec/lib.design-system";import{useState as B}from"react";import{jsx as u,jsxs as X}from"react/jsx-runtime";var A0=[{value:"openai",label:"OpenAI",models:["gpt-5.4","gpt-5-mini","gpt-4o","gpt-4-turbo","gpt-3.5-turbo"]},{value:"anthropic",label:"Anthropic",models:["claude-sonnet-4-6","claude-opus-4-6","claude-haiku-4-5"]},{value:"google",label:"Google",models:["gemini-2.5-flash","gemini-2.5-pro","gemini-pro","gemini-ultra"]},{value:"mistral",label:"Mistral",models:["mistral-large-2512","mistral-large-latest","mistral-medium-latest","mistral-small-latest"]}];function J0({isOpen:m,onClose:p,onSubmit:y,isLoading:T=!1}){let[f,I]=B(""),[d,O]=B(""),[U,G]=B("openai"),[z,Z]=B("gpt-5.4"),[Y,h]=B(""),[D,P]=B(null),M=A0.find((w)=>w.value===U),Q=async(w)=>{if(w.preventDefault(),P(null),!f.trim()){P("Agent name is required");return}try{await y({name:f.trim(),description:d.trim()||void 0,modelProvider:U,modelName:z,systemPrompt:Y.trim()||void 0}),I(""),O(""),G("openai"),Z("gpt-5.4"),h(""),p()}catch(R){P(R instanceof Error?R.message:"Failed to create agent")}},A=(w)=>{G(w);let R=A0.find((k)=>k.value===w);if(R)Z(R.models[0])};if(!m)return null;return X("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[u("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:p,role:"button",tabIndex:0,onKeyDown:(w)=>{if(w.key==="Enter"||w.key===" ")p()},"aria-label":"Close modal"}),X("div",{className:"relative z-10 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl",children:[u("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Agent"}),X("form",{onSubmit:Q,className:"space-y-4",children:[X("div",{children:[u("label",{htmlFor:"agent-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Agent Name *"}),u(p2,{id:"agent-name",value:f,onChange:(w)=>I(w.target.value),placeholder:"e.g., Customer Support Bot",disabled:T})]}),X("div",{children:[u("label",{htmlFor:"agent-description",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Description"}),u("textarea",{id:"agent-description",value:d,onChange:(w)=>O(w.target.value),placeholder:"Describe what this agent does...",rows:2,disabled:T,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),X("div",{className:"flex gap-3",children:[X("div",{className:"flex-1",children:[u("label",{htmlFor:"model-provider",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Provider *"}),u("select",{id:"model-provider",value:U,onChange:(w)=>A(w.target.value),disabled:T,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:A0.map((w)=>u("option",{value:w.value,children:w.label},w.value))})]}),X("div",{className:"flex-1",children:[u("label",{htmlFor:"model-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Model *"}),u("select",{id:"model-name",value:z,onChange:(w)=>Z(w.target.value),disabled:T,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:M?.models.map((w)=>u("option",{value:w,children:w},w))})]})]}),X("div",{children:[u("label",{htmlFor:"system-prompt",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"System Prompt"}),u("textarea",{id:"system-prompt",value:Y,onChange:(w)=>h(w.target.value),placeholder:"You are a helpful assistant that...",rows:4,disabled:T,className:"w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"}),u("p",{className:"mt-1 text-muted-foreground text-xs",children:"Instructions that define the agent's behavior"})]}),D&&u("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:D}),X("div",{className:"flex justify-end gap-3 pt-2",children:[u(h0,{type:"button",variant:"ghost",onPress:p,disabled:T,children:"Cancel"}),u(h0,{type:"submit",disabled:T,children:T?"Creating...":"Create Agent"})]})]})]})]})}import{Button as e,StatusChip as T2}from"@contractspec/lib.design-system";import{HStack as D0,VStack as Z0}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as v}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as V,jsxs as W}from"react/jsx-runtime";function N0(m){switch(m){case"COMPLETED":return"success";case"RUNNING":return"warning";case"QUEUED":return"neutral";case"FAILED":case"CANCELLED":return"danger";default:return"neutral"}}function q0(m){if(!m)return"-";if(m<1000)return`${m}ms`;if(m<60000)return`${(m/1000).toFixed(1)}s`;return`${(m/60000).toFixed(1)}m`}function i(m){if(m<1000)return m.toString();if(m<1e6)return`${(m/1000).toFixed(1)}K`;return`${(m/1e6).toFixed(2)}M`}function W0(m){if(!m)return"-";return`$${m.toFixed(4)}`}function H0(m){return JSON.stringify(m??null,null,2)}function $0({run:m}){return W(Z0,{gap:"sm",className:"py-2",children:[W(D0,{justify:"between",className:"flex-wrap",children:[V(T2,{tone:N0(m.status),label:m.status}),W(v,{className:"text-muted-foreground text-sm",children:["Queued ",m.queuedAt.toLocaleString()]})]}),W(D0,{gap:"lg",className:"flex-wrap",children:[W(v,{className:"text-muted-foreground text-sm",children:["Prompt ",i(m.promptTokens)]}),W(v,{className:"text-muted-foreground text-sm",children:["Completion ",i(m.completionTokens)]}),W(v,{className:"text-muted-foreground text-sm",children:["Duration ",q0(m.durationMs)]})]}),W(Z0,{gap:"xs",children:[V(v,{className:"font-medium text-sm",children:"Input"}),V("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:H0(m.input)})]}),W(Z0,{gap:"xs",children:[V(v,{className:"font-medium text-sm",children:"Output"}),V("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:H0(m.output??m.errorMessage??"Pending")})]})]})}function X0({controller:m,totalRuns:p}){let y=m.rows[0],T=m.columns.find((d)=>d.id==="queuedAt"),f=m.columns.find((d)=>d.id==="durationMs"),I=m.columns.find((d)=>d.id==="estimatedCostUsd");return W(D0,{gap:"sm",className:"flex-wrap",children:[W(v,{className:"text-muted-foreground text-sm",children:[p," runs"]}),V(e,{variant:"outline",size:"sm",onPress:()=>y?.toggleExpanded?.(!y?.isExpanded),children:"Expand Latest Run"}),V(e,{variant:"outline",size:"sm",onPress:()=>T?.toggleVisibility?.(!T?.visible),children:T?.visible?"Hide Time":"Show Time"}),V(e,{variant:"outline",size:"sm",onPress:()=>f?.toggleVisibility?.(!f?.visible),children:f?.visible?"Hide Duration":"Show Duration"}),V(e,{variant:"outline",size:"sm",onPress:()=>I?.toggleVisibility?.(!I?.visible),children:I?.visible?"Hide Cost":"Show Cost"})]})}import{StatusChip as f2}from"@contractspec/lib.design-system";import{VStack as y2}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as I0}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as n,jsxs as w2}from"react/jsx-runtime";function F0(){return[{id:"queuedAt",header:"Run",label:"Run",accessor:(m)=>m.queuedAt.getTime(),cell:({item:m})=>w2(y2,{gap:"xs",children:[n(I0,{className:"font-mono text-sm",children:m.id.slice(-8)}),n(I0,{className:"text-muted-foreground text-xs",children:m.queuedAt.toLocaleString()})]}),size:220,minSize:180,canSort:!0,canHide:!0,canResize:!0},{id:"agentName",header:"Agent",label:"Agent",accessor:(m)=>m.agentName??"Unknown Agent",cell:({value:m})=>n(I0,{className:"font-medium",children:typeof m==="string"?m:"Unknown Agent"}),size:220,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:m})=>{let p=typeof m==="string"?m:"QUEUED";return n(f2,{tone:N0(p),label:p})},size:150,canSort:!0,canResize:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:m})=>i(Number(m??0)),align:"right",size:140,canSort:!0,canResize:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:m})=>q0(typeof m==="number"?m:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0},{id:"estimatedCostUsd",header:"Cost",label:"Cost",accessorKey:"estimatedCostUsd",cell:({value:m})=>W0(typeof m==="number"?m:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0}]}import{DataTable as A2}from"@contractspec/lib.design-system";import{useContractTable as Z2}from"@contractspec/lib.presentation-runtime-react";import*as V0 from"react";import{jsx as o}from"react/jsx-runtime";function k0({runs:m,totalItems:p,pageIndex:y,pageSize:T,sorting:f,loading:I,onSortingChange:d,onPaginationChange:O,onRunClick:U}){let G=V0.useMemo(()=>F0(),[]),z=Z2({data:m,columns:G,executionMode:"server",totalItems:p,state:{sorting:f,pagination:{pageIndex:y,pageSize:T}},onSortingChange:d,onPaginationChange:O,initialState:{columnVisibility:{estimatedCostUsd:!1}},getRowId:(Z)=>Z.id,renderExpandedContent:(Z)=>o($0,{run:Z}),getCanExpand:()=>!0});return o(A2,{controller:z,title:"Run History",description:"Server-mode ContractSpec table with shared pagination, sorting, visibility, and expansion.",loading:I,onRowPress:(Z)=>U?.(Z.id),toolbar:o(X0,{controller:z,totalRuns:p}),emptyState:o("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No runs yet"})})}import{EmptyState as D2,ErrorState as N2,LoaderBlock as q2,StatCard as g,StatCardGroup as I2}from"@contractspec/lib.design-system";import{useState as E0}from"react";import{jsx as E,jsxs as v0}from"react/jsx-runtime";function b0({agentId:m,onRunClick:p}){let[y,T]=E0([{id:"queuedAt",desc:!0}]),[f,I]=E0({pageIndex:0,pageSize:3}),{data:d,metrics:O,loading:U,error:G,refetch:z}=S({agentId:m,pageIndex:f.pageIndex,pageSize:f.pageSize,sorting:y});if(U&&!d)return E(q2,{label:"Loading runs..."});if(G)return E(N2,{title:"Failed to load runs",description:G.message,onRetry:z,retryLabel:"Retry"});if(!d?.items.length)return E(D2,{title:"No runs yet",description:"Execute an agent to see run history here."});return v0("div",{className:"space-y-6",children:[O?v0(I2,{children:[E(g,{label:"Total Runs",value:O.totalRuns}),E(g,{label:"Success Rate",value:`${(O.successRate*100).toFixed(1)}%`}),E(g,{label:"Total Tokens",value:i(O.totalTokens)}),E(g,{label:"Total Cost",value:`$${O.totalCostUsd.toFixed(2)}`})]}):null,E(k0,{runs:d.items,totalItems:d.total,pageIndex:f.pageIndex,pageSize:f.pageSize,sorting:y,loading:U,onSortingChange:(Z)=>{T(Z),I((Y)=>({...Y,pageIndex:0}))},onPaginationChange:I,onRunClick:p})]})}import{useTemplateRuntime as O2}from"@contractspec/lib.example-shared-ui";import{useCallback as M2,useEffect as z2,useMemo as G2,useState as a}from"react";function B0(m={}){let{handlers:p,projectId:y}=O2(),{agent:T}=p,[f,I]=a(null),[d,O]=a(!0),[U,G]=a(null),[z,Z]=a(1),Y=M2(async()=>{O(!0),G(null);try{let M=await T.listTools({projectId:y,search:m.search,category:m.category,status:m.status==="all"?void 0:m.status,limit:m.limit??50,offset:(z-1)*(m.limit??50)});I(M)}catch(M){G(M instanceof Error?M:Error("Unknown error"))}finally{O(!1)}},[T,y,m.search,m.category,m.status,m.limit,z]);z2(()=>{Y()},[Y]);let{stats:h,groupedByCategory:D,categoryStats:P}=G2(()=>{if(!f)return{stats:null,groupedByCategory:{},categoryStats:[]};let M=f.items,Q=M.filter((H)=>H.status==="ACTIVE").length,A=M.filter((H)=>H.status==="DEPRECATED").length,w=M.filter((H)=>H.status==="DISABLED").length,R={},k={};M.forEach((H)=>{let F=H.category;if(!R[F])R[F]=[];R[F].push(H),k[F]=(k[F]||0)+1});let M0=Object.entries(k).map(([H,F])=>({category:H,count:F})).sort((H,F)=>F.count-H.count);return{stats:{total:f.total,active:Q,deprecated:A,disabled:w,topCategories:M0.slice(0,5)},groupedByCategory:R,categoryStats:M0}},[f]);return{data:f,loading:d,error:U,stats:h,groupedByCategory:D,categoryStats:P,page:z,refetch:Y,nextPage:()=>Z((M)=>M+1),prevPage:()=>z>1&&Z((M)=>M-1)}}import{Button as U2,EmptyState as Q2,EntityCard as R2,ErrorState as K2,LoaderBlock as P2,StatCard as i0,StatCardGroup as Y2,StatusChip as u2}from"@contractspec/lib.design-system";import{jsx as J,jsxs as t}from"react/jsx-runtime";var c0={RETRIEVAL:"\uD83D\uDD0D",COMPUTATION:"\uD83E\uDDEE",COMMUNICATION:"\uD83D\uDCE7",INTEGRATION:"\uD83D\uDD17",UTILITY:"\uD83D\uDEE0️",CUSTOM:"⚙️"};function _2(m){switch(m){case"ACTIVE":return"success";case"DRAFT":return"neutral";case"DEPRECATED":return"warning";case"DISABLED":return"danger";default:return"neutral"}}function C0({onToolClick:m,onCreateTool:p}){let{data:y,loading:T,error:f,groupedByCategory:I,categoryStats:d,refetch:O}=B0();if(T&&!y)return J(P2,{label:"Loading tools..."});if(f)return J(K2,{title:"Failed to load tools",description:f.message,onRetry:O,retryLabel:"Retry"});if(!y?.items.length)return J(Q2,{title:"No tools registered",description:"Create your first tool to extend agent capabilities.",primaryAction:p?J(U2,{onPress:p,children:"Create Tool"}):void 0});return t("div",{className:"space-y-8",children:[t(Y2,{children:[J(i0,{label:"Total Tools",value:y.total}),d.slice(0,3).map(({category:U,count:G})=>J(i0,{label:`${c0[U]??""} ${U}`,value:G},U))]}),Object.entries(I).map(([U,G])=>t("section",{className:"space-y-4",children:[t("div",{className:"flex items-center gap-2",children:[J("span",{className:"text-2xl",children:c0[U]}),J("h3",{className:"font-semibold text-lg",children:U}),J("span",{className:"rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs",children:G.length})]}),J("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:G.map((z)=>J(R2,{cardTitle:z.name,cardSubtitle:`v${z.version}`,meta:J("p",{className:"text-muted-foreground text-sm",children:z.description}),chips:J(u2,{tone:_2(z.status),label:z.status}),footer:J("code",{className:"text-muted-foreground text-xs",children:z.name}),onClick:m?()=>m(z.id):void 0},z.id))})]},U))]})}import{Button as O0,StatCard as h2,StatCardGroup as J2}from"@contractspec/lib.design-system";import{useCallback as H2,useMemo as W2,useState as C}from"react";import{jsx as N,jsxs as q}from"react/jsx-runtime";function qm(){let[m,p]=C("runs"),[y,T]=C(!1),[f,I]=C(null),[d,O]=C(!1),[U,G]=C(0),{data:z,metrics:Z,refetch:Y}=S(),{refetch:h}=T0(),D=u0({onSuccess:()=>{h(),Y(),G((A)=>A+1)}}),P=H2((A)=>{I(A),O(!0)},[]),M=[{id:"runs",label:"Runs",icon:"▶"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}],Q=W2(()=>{if(!Z)return[{label:"Total Runs",value:"-",hint:"Loading..."},{label:"Success Rate",value:"-",hint:""},{label:"Total Tokens",value:"-",hint:""},{label:"Total Cost",value:"-",hint:""}];return[{label:"Total Runs",value:Z.totalRuns.toLocaleString(),hint:`${(Z.successRate*100).toFixed(0)}% success`},{label:"Success Rate",value:`${(Z.successRate*100).toFixed(0)}%`,hint:"of all runs"},{label:"Total Tokens",value:Z.totalTokens>=1e6?`${(Z.totalTokens/1e6).toFixed(1)}M`:`${(Z.totalTokens/1000).toFixed(0)}K`,hint:"This period"},{label:"Total Cost",value:`$${Z.totalCostUsd.toFixed(2)}`,hint:"This period"}]},[Z]);return q("div",{className:"space-y-6",children:[q("div",{className:"flex items-center justify-between",children:[N("h2",{className:"font-bold text-2xl",children:"AI Agent Console"}),q(O0,{onPress:()=>T(!0),children:[N("span",{className:"mr-2",children:"+"})," New Agent"]})]}),N(J2,{children:Q.map((A,w)=>N(h2,{label:A.label,value:A.value,hint:A.hint},w))}),N(Y0,{runs:z?.items??[]}),N("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:M.map((A)=>q("button",{type:"button",role:"tab","aria-selected":m===A.id,onClick:()=>p(A.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${m===A.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[N("span",{children:A.icon}),A.label]},A.id))}),q("div",{className:"min-h-[400px]",role:"tabpanel",children:[m==="runs"&&N(b0,{},U),m==="agents"&&N($2,{onAgentClick:P},U),m==="tools"&&N(C0,{}),m==="metrics"&&N(F2,{metrics:Z})]}),N(J0,{isOpen:y,onClose:()=>T(!1),onSubmit:async(A)=>{await D.createAgent(A)},isLoading:D.createState.loading}),N(_0,{isOpen:d,agent:f,onClose:()=>{O(!1),I(null)},onActivate:async(A)=>{await D.activateAgent(A)},onPause:async(A)=>{await D.pauseAgent(A)},onArchive:async(A)=>{await D.archiveAgent(A)},onExecute:async(A,w)=>{await D.executeAgent({agentId:A,message:w})},isLoading:D.isLoading})]})}function $2({onAgentClick:m}){let{data:p,loading:y,error:T,stats:f,refetch:I}=T0();if(y&&!p)return N("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading agents..."});if(T)return q("div",{className:"flex h-64 flex-col items-center justify-center text-destructive",children:[q("p",{children:["Failed to load agents: ",T.message]}),N(O0,{variant:"outline",onPress:I,className:"mt-2",children:"Retry"})]});if(!p?.items.length)return q("div",{className:"flex h-64 flex-col items-center justify-center text-muted-foreground",children:[N("p",{className:"font-medium text-lg",children:"No agents yet"}),N("p",{className:"text-sm",children:"Create your first AI agent to get started."})]});return q("div",{className:"space-y-4",children:[f&&q("div",{className:"flex gap-4 text-sm",children:[q("span",{children:["Total: ",f.total]}),q("span",{className:"text-green-600",children:["Active: ",f.active]}),q("span",{className:"text-yellow-600",children:["Paused: ",f.paused]}),q("span",{className:"text-blue-600",children:["Draft: ",f.draft]})]}),N("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:p.items.map((d)=>N(X2,{agent:d,onClick:()=>m(d)},d.id))})]})}function X2({agent:m,onClick:p}){let y={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",PAUSED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",ARCHIVED:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"};return q("div",{onClick:p,className:"cursor-pointer rounded-xl border border-border bg-card p-4 transition-all hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(T)=>{if(T.key==="Enter"||T.key===" ")p()},children:[q("div",{className:"flex items-start justify-between",children:[q("div",{className:"min-w-0 flex-1",children:[N("h3",{className:"truncate font-semibold",children:m.name}),q("p",{className:"text-muted-foreground text-sm",children:[m.modelProvider," / ",m.modelName]})]}),N("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${y[m.status]}`,children:m.status})]}),m.description&&N("p",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:m.description}),q("div",{className:"mt-3 flex items-center justify-between",children:[N("span",{className:"text-muted-foreground text-xs",children:m.modelName}),N(O0,{variant:"ghost",size:"sm",onPress:p,children:"Actions"})]})]})}function F2({metrics:m}){if(!m)return N("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading metrics..."});let p=Math.round(m.totalRuns*m.successRate),y=m.totalRuns-p;return q("div",{className:"space-y-6",children:[N("h3",{className:"font-semibold text-lg",children:"Usage Analytics"}),q("div",{className:"grid gap-6 md:grid-cols-2",children:[q("div",{className:"rounded-xl border border-border bg-card p-4",children:[N("h4",{className:"font-medium",children:"Run Outcomes"}),q("div",{className:"mt-4 space-y-3",children:[N(L0,{label:"Completed",value:p,total:m.totalRuns,color:"bg-green-500"}),N(L0,{label:"Failed",value:y,total:m.totalRuns,color:"bg-red-500"})]})]}),q("div",{className:"rounded-xl border border-border bg-card p-4",children:[N("h4",{className:"font-medium",children:"Performance"}),q("dl",{className:"mt-4 grid grid-cols-2 gap-4",children:[q("div",{children:[N("dt",{className:"text-muted-foreground text-sm",children:"Avg Duration"}),q("dd",{className:"font-semibold text-xl",children:[(m.averageDurationMs/1000).toFixed(1),"s"]})]}),q("div",{children:[N("dt",{className:"text-muted-foreground text-sm",children:"Success Rate"}),q("dd",{className:"font-semibold text-xl",children:[(m.successRate*100).toFixed(0),"%"]})]})]})]})]}),q("div",{className:"rounded-xl border border-border bg-card p-4",children:[N("h4",{className:"font-medium",children:"Key Metrics"}),q("dl",{className:"mt-4 grid gap-4 sm:grid-cols-3",children:[q("div",{children:[N("dt",{className:"text-muted-foreground text-sm",children:"Total Runs"}),N("dd",{className:"font-semibold text-2xl",children:m.totalRuns.toLocaleString()})]}),q("div",{children:[N("dt",{className:"text-muted-foreground text-sm",children:"Total Tokens"}),q("dd",{className:"font-semibold text-2xl",children:[(m.totalTokens/1000).toFixed(0),"K"]})]}),q("div",{children:[N("dt",{className:"text-muted-foreground text-sm",children:"Cost per Run"}),q("dd",{className:"font-semibold text-2xl",children:["$",m.totalRuns>0?(m.totalCostUsd/m.totalRuns).toFixed(4):"0"]})]})]})]})]})}function L0({label:m,value:p,total:y,color:T}){let f=y>0?p/y*100:0;return q("div",{children:[q("div",{className:"flex justify-between text-sm",children:[N("span",{children:m}),q("span",{className:"text-muted-foreground",children:[p," (",f.toFixed(0),"%)"]})]}),N("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-muted",children:N("div",{className:`h-full ${T}`,style:{width:`${f}%`}})})]})}export{qm as AgentDashboard};