@contractspec/example.agent-console 3.8.9 → 3.8.11

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 +30 -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,2951 +1,14 @@
1
1
  // @bun
2
- // src/agent/agent.enum.ts
3
- import { defineEnum } from "@contractspec/lib.schema";
4
- var AgentStatusEnum = defineEnum("AgentStatus", [
5
- "DRAFT",
6
- "ACTIVE",
7
- "PAUSED",
8
- "ARCHIVED"
9
- ]);
10
- var ModelProviderEnum = defineEnum("ModelProvider", [
11
- "OPENAI",
12
- "ANTHROPIC",
13
- "GOOGLE",
14
- "MISTRAL",
15
- "CUSTOM"
16
- ]);
17
- var ToolChoiceEnum = defineEnum("ToolChoice", [
18
- "auto",
19
- "required",
20
- "none"
21
- ]);
22
-
23
- // src/agent/agent.event.ts
24
- import { defineEvent } from "@contractspec/lib.contracts-spec";
25
- import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
26
- var OWNERS = ["@agent-console-team"];
27
- var AgentCreatedPayload = defineSchemaModel({
28
- name: "AgentCreatedPayload",
29
- description: "Payload for agent created event",
30
- fields: {
31
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
32
- organizationId: {
33
- type: ScalarTypeEnum.String_unsecure(),
34
- isOptional: false
35
- },
36
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
37
- slug: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
38
- modelProvider: {
39
- type: ScalarTypeEnum.String_unsecure(),
40
- isOptional: false
41
- },
42
- modelName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
43
- toolCount: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
44
- createdById: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
45
- createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
46
- }
47
- });
48
- var AgentCreatedEvent = defineEvent({
49
- meta: {
50
- key: "agent-console.agent.created",
51
- version: "1.0.0",
52
- description: "A new AI agent was configured.",
53
- stability: "stable",
54
- owners: [...OWNERS],
55
- tags: ["agent", "created"]
56
- },
57
- payload: AgentCreatedPayload
58
- });
59
- var AgentUpdatedPayload = defineSchemaModel({
60
- name: "AgentUpdatedPayload",
61
- description: "Payload for agent updated event",
62
- fields: {
63
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
64
- organizationId: {
65
- type: ScalarTypeEnum.String_unsecure(),
66
- isOptional: false
67
- },
68
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
69
- status: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
70
- updatedFields: {
71
- type: ScalarTypeEnum.String_unsecure(),
72
- isArray: true,
73
- isOptional: false
74
- },
75
- updatedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
76
- }
77
- });
78
- var AgentUpdatedEvent = defineEvent({
79
- meta: {
80
- key: "agent-console.agent.updated",
81
- version: "1.0.0",
82
- description: "An AI agent configuration was updated.",
83
- stability: "stable",
84
- owners: [...OWNERS],
85
- tags: ["agent", "updated"]
86
- },
87
- payload: AgentUpdatedPayload
88
- });
89
- var AgentToolAssignedPayload = defineSchemaModel({
90
- name: "AgentToolAssignedPayload",
91
- description: "Payload for agent tool assigned event",
92
- fields: {
93
- agentId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
94
- toolId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
95
- agentName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
96
- toolName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
97
- assignedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
98
- }
99
- });
100
- var AgentToolAssignedEvent = defineEvent({
101
- meta: {
102
- key: "agent-console.agent.toolAssigned",
103
- version: "1.0.0",
104
- description: "A tool was assigned to an agent.",
105
- stability: "stable",
106
- owners: [...OWNERS],
107
- tags: ["agent", "tool", "assigned"]
108
- },
109
- payload: AgentToolAssignedPayload
110
- });
111
- var AgentToolRemovedPayload = defineSchemaModel({
112
- name: "AgentToolRemovedPayload",
113
- description: "Payload for agent tool removed event",
114
- fields: {
115
- agentId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
116
- toolId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
117
- agentName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
118
- toolName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
119
- removedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
120
- }
121
- });
122
- var AgentToolRemovedEvent = defineEvent({
123
- meta: {
124
- key: "agent-console.agent.toolRemoved",
125
- version: "1.0.0",
126
- description: "A tool was removed from an agent.",
127
- stability: "stable",
128
- owners: [...OWNERS],
129
- tags: ["agent", "tool", "removed"]
130
- },
131
- payload: AgentToolRemovedPayload
132
- });
133
-
134
- // src/shared/mock-agents.ts
135
- var MOCK_AGENTS = [
136
- {
137
- id: "agent-1",
138
- organizationId: "demo-org",
139
- name: "Customer Support Bot",
140
- slug: "customer-support-bot",
141
- description: "Handles tier-1 customer inquiries and routes complex issues.",
142
- status: "ACTIVE",
143
- modelProvider: "OPENAI",
144
- modelName: "gpt-4o-mini",
145
- modelConfig: { temperature: 0.7 },
146
- systemPrompt: "You are a helpful customer support assistant.",
147
- toolChoice: "auto",
148
- maxIterations: 10,
149
- timeoutMs: 120000,
150
- version: "1.0.0",
151
- tags: ["support", "tier-1"],
152
- createdAt: new Date("2024-01-15T10:00:00Z"),
153
- updatedAt: new Date("2024-03-20T14:30:00Z")
154
- },
155
- {
156
- id: "agent-2",
157
- organizationId: "demo-org",
158
- name: "Code Review Assistant",
159
- slug: "code-review-assistant",
160
- description: "Reviews pull requests and provides actionable feedback.",
161
- status: "ACTIVE",
162
- modelProvider: "ANTHROPIC",
163
- modelName: "claude-sonnet-4-20250514",
164
- modelConfig: { temperature: 0.3 },
165
- systemPrompt: "You are a code review expert.",
166
- toolChoice: "auto",
167
- maxIterations: 15,
168
- timeoutMs: 180000,
169
- version: "2.1.0",
170
- tags: ["code", "review", "dev"],
171
- createdAt: new Date("2024-02-10T09:00:00Z"),
172
- updatedAt: new Date("2024-04-05T11:15:00Z")
173
- },
174
- {
175
- id: "agent-3",
176
- organizationId: "demo-org",
177
- name: "Data Analyst",
178
- slug: "data-analyst",
179
- description: "Queries databases and generates insights from data.",
180
- status: "PAUSED",
181
- modelProvider: "OPENAI",
182
- modelName: "gpt-4o",
183
- modelConfig: { temperature: 0.5 },
184
- systemPrompt: "You are a data analyst expert in SQL and analytics.",
185
- toolChoice: "required",
186
- maxIterations: 20,
187
- timeoutMs: 300000,
188
- version: "1.2.0",
189
- tags: ["data", "analytics", "sql"],
190
- createdAt: new Date("2024-03-01T08:00:00Z"),
191
- updatedAt: new Date("2024-04-10T16:45:00Z")
192
- },
193
- {
194
- id: "agent-4",
195
- organizationId: "demo-org",
196
- name: "Meeting Scheduler",
197
- slug: "meeting-scheduler",
198
- description: "Schedules meetings and manages calendar conflicts.",
199
- status: "DRAFT",
200
- modelProvider: "GOOGLE",
201
- modelName: "gemini-2.0-flash",
202
- modelConfig: { temperature: 0.2 },
203
- systemPrompt: "You help schedule and organize meetings efficiently.",
204
- toolChoice: "auto",
205
- maxIterations: 5,
206
- timeoutMs: 60000,
207
- version: "0.1.0",
208
- tags: ["calendar", "scheduling"],
209
- createdAt: new Date("2024-04-01T12:00:00Z"),
210
- updatedAt: new Date("2024-04-01T12:00:00Z")
211
- }
212
- ];
213
-
214
- // src/shared/mock-tools.ts
215
- var MOCK_TOOLS = [
216
- {
217
- id: "tool-1",
218
- organizationId: "demo-org",
219
- name: "Web Search",
220
- slug: "web-search",
221
- description: "Search the web for real-time information using Brave API.",
222
- category: "RETRIEVAL",
223
- status: "ACTIVE",
224
- parametersSchema: {
225
- type: "object",
226
- properties: {
227
- query: { type: "string", description: "Search query" },
228
- numResults: { type: "number", default: 10 }
229
- },
230
- required: ["query"]
231
- },
232
- outputSchema: { type: "array", items: { type: "object" } },
233
- implementationType: "http",
234
- implementationConfig: {
235
- url: "https://api.brave.com/search",
236
- method: "GET"
237
- },
238
- maxInvocationsPerMinute: 60,
239
- timeoutMs: 30000,
240
- version: "1.0.0",
241
- tags: ["search", "web"],
242
- createdAt: new Date("2024-01-01T00:00:00Z"),
243
- updatedAt: new Date("2024-02-15T10:00:00Z")
244
- },
245
- {
246
- id: "tool-2",
247
- organizationId: "demo-org",
248
- name: "SQL Query",
249
- slug: "sql-query",
250
- description: "Execute read-only SQL queries against the data warehouse.",
251
- category: "RETRIEVAL",
252
- status: "ACTIVE",
253
- parametersSchema: {
254
- type: "object",
255
- properties: {
256
- query: { type: "string", description: "SQL query" },
257
- maxRows: { type: "number", default: 100 }
258
- },
259
- required: ["query"]
260
- },
261
- outputSchema: { type: "object" },
262
- implementationType: "function",
263
- implementationConfig: { handler: "executeSqlQuery" },
264
- maxInvocationsPerMinute: 30,
265
- timeoutMs: 60000,
266
- version: "1.1.0",
267
- tags: ["sql", "database"],
268
- createdAt: new Date("2024-01-05T00:00:00Z"),
269
- updatedAt: new Date("2024-03-10T14:00:00Z")
270
- },
271
- {
272
- id: "tool-3",
273
- organizationId: "demo-org",
274
- name: "Email Sender",
275
- slug: "email-sender",
276
- description: "Send emails via SMTP or API.",
277
- category: "COMMUNICATION",
278
- status: "ACTIVE",
279
- parametersSchema: {
280
- type: "object",
281
- properties: {
282
- to: { type: "string" },
283
- subject: { type: "string" },
284
- body: { type: "string" }
285
- },
286
- required: ["to", "subject", "body"]
287
- },
288
- implementationType: "http",
289
- implementationConfig: { url: "/api/send-email", method: "POST" },
290
- maxInvocationsPerMinute: 10,
291
- timeoutMs: 30000,
292
- version: "1.0.0",
293
- tags: ["email", "communication"],
294
- createdAt: new Date("2024-02-01T00:00:00Z"),
295
- updatedAt: new Date("2024-02-01T00:00:00Z")
296
- },
297
- {
298
- id: "tool-4",
299
- organizationId: "demo-org",
300
- name: "GitHub Integration",
301
- slug: "github-integration",
302
- description: "Interact with GitHub repositories, PRs, and issues.",
303
- category: "INTEGRATION",
304
- status: "ACTIVE",
305
- parametersSchema: {
306
- type: "object",
307
- properties: {
308
- action: {
309
- type: "string",
310
- enum: ["list_prs", "get_pr", "create_comment"]
311
- },
312
- repo: { type: "string" },
313
- params: { type: "object" }
314
- },
315
- required: ["action", "repo"]
316
- },
317
- implementationType: "http",
318
- implementationConfig: { url: "https://api.github.com", auth: "token" },
319
- maxInvocationsPerMinute: 100,
320
- timeoutMs: 15000,
321
- version: "2.0.0",
322
- tags: ["github", "integration", "code"],
323
- createdAt: new Date("2024-02-20T00:00:00Z"),
324
- updatedAt: new Date("2024-04-01T09:00:00Z")
325
- },
326
- {
327
- id: "tool-5",
328
- organizationId: "demo-org",
329
- name: "Calculator",
330
- slug: "calculator",
331
- description: "Perform mathematical calculations.",
332
- category: "COMPUTATION",
333
- status: "ACTIVE",
334
- parametersSchema: {
335
- type: "object",
336
- properties: {
337
- expression: {
338
- type: "string",
339
- description: "Math expression to evaluate"
340
- }
341
- },
342
- required: ["expression"]
343
- },
344
- outputSchema: {
345
- type: "object",
346
- properties: { result: { type: "number" } }
347
- },
348
- implementationType: "function",
349
- implementationConfig: { handler: "evaluateMath" },
350
- timeoutMs: 5000,
351
- version: "1.0.0",
352
- tags: ["math", "utility"],
353
- createdAt: new Date("2024-01-10T00:00:00Z"),
354
- updatedAt: new Date("2024-01-10T00:00:00Z")
355
- }
356
- ];
357
-
358
- // src/agent/agent.schema.ts
359
- import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
360
- var AgentModel = defineSchemaModel2({
361
- name: "Agent",
362
- description: "AI agent configuration",
363
- fields: {
364
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
365
- organizationId: {
366
- type: ScalarTypeEnum2.String_unsecure(),
367
- isOptional: false
368
- },
369
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
370
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
371
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
372
- status: { type: AgentStatusEnum, isOptional: false },
373
- modelProvider: { type: ModelProviderEnum, isOptional: false },
374
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
375
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
376
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
377
- userPromptTemplate: {
378
- type: ScalarTypeEnum2.String_unsecure(),
379
- isOptional: true
380
- },
381
- toolIds: {
382
- type: ScalarTypeEnum2.String_unsecure(),
383
- isArray: true,
384
- isOptional: true
385
- },
386
- toolChoice: {
387
- type: ToolChoiceEnum,
388
- isOptional: false,
389
- defaultValue: "auto"
390
- },
391
- maxIterations: {
392
- type: ScalarTypeEnum2.Int_unsecure(),
393
- isOptional: false,
394
- defaultValue: 10
395
- },
396
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
397
- timeoutMs: {
398
- type: ScalarTypeEnum2.Int_unsecure(),
399
- isOptional: false,
400
- defaultValue: 120000
401
- },
402
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
403
- tags: {
404
- type: ScalarTypeEnum2.String_unsecure(),
405
- isArray: true,
406
- isOptional: true
407
- },
408
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
409
- updatedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
410
- }
411
- });
412
- var AgentSummaryModel = defineSchemaModel2({
413
- name: "AgentSummary",
414
- description: "Summary of an agent for list views",
415
- fields: {
416
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
417
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
418
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
419
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
420
- status: { type: AgentStatusEnum, isOptional: false },
421
- modelProvider: { type: ModelProviderEnum, isOptional: false },
422
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
423
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
424
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
425
- }
426
- });
427
- var AgentToolRefModel = defineSchemaModel2({
428
- name: "AgentToolRef",
429
- description: "Tool reference in agent context",
430
- fields: {
431
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
432
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
433
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
434
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
435
- category: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false }
436
- }
437
- });
438
- var AgentWithToolsModel = defineSchemaModel2({
439
- name: "AgentWithTools",
440
- description: "Agent with associated tools",
441
- fields: {
442
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
443
- organizationId: {
444
- type: ScalarTypeEnum2.String_unsecure(),
445
- isOptional: false
446
- },
447
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
448
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
449
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
450
- status: { type: AgentStatusEnum, isOptional: false },
451
- modelProvider: { type: ModelProviderEnum, isOptional: false },
452
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
453
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
454
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
455
- userPromptTemplate: {
456
- type: ScalarTypeEnum2.String_unsecure(),
457
- isOptional: true
458
- },
459
- toolIds: {
460
- type: ScalarTypeEnum2.String_unsecure(),
461
- isArray: true,
462
- isOptional: true
463
- },
464
- toolChoice: { type: ToolChoiceEnum, isOptional: false },
465
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
466
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
467
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
468
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
469
- tags: {
470
- type: ScalarTypeEnum2.String_unsecure(),
471
- isArray: true,
472
- isOptional: true
473
- },
474
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
475
- updatedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
476
- tools: { type: AgentToolRefModel, isArray: true, isOptional: true }
477
- }
478
- });
479
- var CreateAgentInputModel = defineSchemaModel2({
480
- name: "CreateAgentInput",
481
- description: "Input for creating an agent",
482
- fields: {
483
- organizationId: {
484
- type: ScalarTypeEnum2.String_unsecure(),
485
- isOptional: false
486
- },
487
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
488
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
489
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
490
- modelProvider: { type: ModelProviderEnum, isOptional: false },
491
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
492
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
493
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
494
- userPromptTemplate: {
495
- type: ScalarTypeEnum2.String_unsecure(),
496
- isOptional: true
497
- },
498
- toolIds: {
499
- type: ScalarTypeEnum2.String_unsecure(),
500
- isArray: true,
501
- isOptional: true
502
- },
503
- toolChoice: { type: ToolChoiceEnum, isOptional: true },
504
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
505
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
506
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
507
- tags: {
508
- type: ScalarTypeEnum2.String_unsecure(),
509
- isArray: true,
510
- isOptional: true
511
- }
512
- }
513
- });
514
- var UpdateAgentInputModel = defineSchemaModel2({
515
- name: "UpdateAgentInput",
516
- description: "Input for updating an agent",
517
- fields: {
518
- agentId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
519
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: true },
520
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
521
- status: { type: AgentStatusEnum, isOptional: true },
522
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
523
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
524
- userPromptTemplate: {
525
- type: ScalarTypeEnum2.String_unsecure(),
526
- isOptional: true
527
- },
528
- toolIds: {
529
- type: ScalarTypeEnum2.String_unsecure(),
530
- isArray: true,
531
- isOptional: true
532
- },
533
- toolChoice: { type: ToolChoiceEnum, isOptional: true },
534
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
535
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
536
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
537
- tags: {
538
- type: ScalarTypeEnum2.String_unsecure(),
539
- isArray: true,
540
- isOptional: true
541
- }
542
- }
543
- });
544
-
545
- // src/agent/agent.operation.ts
546
- import {
547
- defineCommand,
548
- defineQuery
549
- } from "@contractspec/lib.contracts-spec/operations";
550
- import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
551
- var OWNERS2 = ["@agent-console-team"];
552
- var CreateAgentCommand = defineCommand({
553
- meta: {
554
- key: "agent-console.agent.create",
555
- version: "1.0.0",
556
- stability: "stable",
557
- owners: [...OWNERS2],
558
- tags: ["agent", "create"],
559
- description: "Creates a new AI agent configuration.",
560
- goal: "Allow users to define new AI agents with specific models and tools.",
561
- context: "Called from the agent builder UI when creating a new agent."
562
- },
563
- io: {
564
- input: CreateAgentInputModel,
565
- output: defineSchemaModel3({
566
- name: "CreateAgentOutput",
567
- fields: {
568
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
569
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
570
- slug: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
571
- status: { type: AgentStatusEnum, isOptional: false }
572
- }
573
- }),
574
- errors: {
575
- SLUG_EXISTS: {
576
- description: "An agent with this slug already exists in the organization",
577
- http: 409,
578
- gqlCode: "SLUG_EXISTS",
579
- when: "Slug is already taken"
580
- }
581
- }
582
- },
583
- policy: { auth: "user" },
584
- sideEffects: {
585
- emits: [
586
- {
587
- ref: AgentCreatedEvent.meta,
588
- when: "Agent is successfully created"
589
- }
590
- ],
591
- audit: ["agent-console.agent.created"]
592
- },
593
- acceptance: {
594
- scenarios: [
595
- {
596
- key: "create-agent-happy-path",
597
- given: ["User is authenticated", "Organization exists"],
598
- when: ["User submits valid agent configuration"],
599
- then: [
600
- "New agent is created with DRAFT status",
601
- "AgentCreated event is emitted"
602
- ]
603
- },
604
- {
605
- key: "create-agent-slug-conflict",
606
- given: ["User is authenticated", "Agent with same slug exists"],
607
- when: ["User submits agent with duplicate slug"],
608
- then: ["SLUG_EXISTS error is returned with 409 status"]
609
- }
610
- ],
611
- examples: [
612
- {
613
- key: "basic-create",
614
- input: {
615
- name: "Support Assistant",
616
- slug: "support-assistant",
617
- modelProvider: "openai",
618
- modelId: "gpt-4"
619
- },
620
- output: {
621
- id: "agent-123",
622
- name: "Support Assistant",
623
- slug: "support-assistant",
624
- status: "draft"
625
- }
626
- }
627
- ]
628
- }
629
- });
630
- var UpdateAgentCommand = defineCommand({
631
- meta: {
632
- key: "agent-console.agent.update",
633
- version: "1.0.0",
634
- stability: "stable",
635
- owners: [...OWNERS2],
636
- tags: ["agent", "update"],
637
- description: "Updates an existing AI agent configuration.",
638
- goal: "Allow users to modify agent settings and configuration.",
639
- context: "Called from the agent settings UI."
640
- },
641
- io: {
642
- input: UpdateAgentInputModel,
643
- output: defineSchemaModel3({
644
- name: "UpdateAgentOutput",
645
- fields: {
646
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
647
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
648
- status: { type: AgentStatusEnum, isOptional: false },
649
- updatedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: false }
650
- }
651
- }),
652
- errors: {
653
- AGENT_NOT_FOUND: {
654
- description: "The specified agent does not exist",
655
- http: 404,
656
- gqlCode: "AGENT_NOT_FOUND",
657
- when: "Agent ID is invalid"
658
- }
659
- }
660
- },
661
- policy: { auth: "user" },
662
- sideEffects: {
663
- emits: [
664
- {
665
- key: "agent.updated",
666
- version: "1.0.0",
667
- stability: "stable",
668
- owners: [...OWNERS2],
669
- tags: ["agent", "updated"],
670
- when: "Agent is updated",
671
- payload: AgentSummaryModel
672
- }
673
- ],
674
- audit: ["agent.updated"]
675
- },
676
- acceptance: {
677
- scenarios: [
678
- {
679
- key: "update-agent-happy-path",
680
- given: ["Agent exists", "User owns the agent"],
681
- when: ["User submits updated configuration"],
682
- then: ["Agent is updated", "AgentUpdated event is emitted"]
683
- },
684
- {
685
- key: "update-agent-not-found",
686
- given: ["Agent does not exist"],
687
- when: ["User attempts to update"],
688
- then: ["AGENT_NOT_FOUND error is returned"]
689
- }
690
- ],
691
- examples: [
692
- {
693
- key: "update-name",
694
- input: {
695
- agentId: "agent-123",
696
- name: "Updated Assistant",
697
- systemPrompt: "You are a helpful assistant."
698
- },
699
- output: {
700
- id: "agent-123",
701
- name: "Updated Assistant",
702
- status: "draft",
703
- updatedAt: "2025-01-01T00:00:00Z"
704
- }
705
- }
706
- ]
707
- }
708
- });
709
- var GetAgentQuery = defineQuery({
710
- meta: {
711
- key: "agent-console.agent.get",
712
- version: "1.0.0",
713
- stability: "stable",
714
- owners: [...OWNERS2],
715
- tags: ["agent", "get"],
716
- description: "Retrieves an agent by its ID.",
717
- goal: "View detailed agent configuration.",
718
- context: "Called when viewing agent details or editing."
719
- },
720
- io: {
721
- input: defineSchemaModel3({
722
- name: "GetAgentInput",
723
- fields: {
724
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
725
- includeTools: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
726
- }
727
- }),
728
- output: AgentWithToolsModel,
729
- errors: {
730
- AGENT_NOT_FOUND: {
731
- description: "The specified agent does not exist",
732
- http: 404,
733
- gqlCode: "AGENT_NOT_FOUND",
734
- when: "Agent ID is invalid"
735
- }
736
- }
737
- },
738
- policy: { auth: "user" },
739
- acceptance: {
740
- scenarios: [
741
- {
742
- key: "get-agent-happy-path",
743
- given: ["Agent exists"],
744
- when: ["User requests agent by ID"],
745
- then: ["Agent details are returned"]
746
- },
747
- {
748
- key: "get-agent-with-tools",
749
- given: ["Agent exists with assigned tools"],
750
- when: ["User requests agent with includeTools=true"],
751
- then: ["Agent details with tools list are returned"]
752
- }
753
- ],
754
- examples: [
755
- {
756
- key: "get-basic",
757
- input: { agentId: "agent-123", includeTools: false },
758
- output: {
759
- id: "agent-123",
760
- name: "Support Assistant",
761
- status: "active",
762
- tools: []
763
- }
764
- }
765
- ]
766
- }
767
- });
768
- var ListAgentsQuery = defineQuery({
769
- meta: {
770
- key: "agent-console.agent.list",
771
- version: "1.0.0",
772
- stability: "stable",
773
- owners: [...OWNERS2],
774
- tags: ["agent", "list"],
775
- description: "Lists agents for an organization with optional filtering.",
776
- goal: "Browse and search available agents.",
777
- context: "Agent list/dashboard view."
778
- },
779
- io: {
780
- input: defineSchemaModel3({
781
- name: "ListAgentsInput",
782
- fields: {
783
- organizationId: {
784
- type: ScalarTypeEnum3.String_unsecure(),
785
- isOptional: false
786
- },
787
- status: { type: AgentStatusEnum, isOptional: true },
788
- modelProvider: { type: ModelProviderEnum, isOptional: true },
789
- search: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
790
- limit: {
791
- type: ScalarTypeEnum3.Int_unsecure(),
792
- isOptional: true,
793
- defaultValue: 20
794
- },
795
- offset: {
796
- type: ScalarTypeEnum3.Int_unsecure(),
797
- isOptional: true,
798
- defaultValue: 0
799
- }
800
- }
801
- }),
802
- output: defineSchemaModel3({
803
- name: "ListAgentsOutput",
804
- fields: {
805
- items: { type: AgentSummaryModel, isArray: true, isOptional: false },
806
- total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
807
- hasMore: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
808
- }
809
- })
810
- },
811
- policy: { auth: "user" },
812
- acceptance: {
813
- scenarios: [
814
- {
815
- key: "list-agents-happy-path",
816
- given: ["Organization has agents"],
817
- when: ["User lists agents"],
818
- then: ["Paginated list of agents is returned"]
819
- },
820
- {
821
- key: "list-agents-filter-by-status",
822
- given: ["Organization has agents with mixed statuses"],
823
- when: ["User filters by status=active"],
824
- then: ["Only active agents are returned"]
825
- }
826
- ],
827
- examples: [
828
- {
829
- key: "list-basic",
830
- input: { organizationId: "org-123", limit: 10, offset: 0 },
831
- output: { items: [], total: 0, hasMore: false }
832
- }
833
- ]
834
- }
835
- });
836
- var AssignToolToAgentCommand = defineCommand({
837
- meta: {
838
- key: "agent-console.agent.assignTool",
839
- version: "1.0.0",
840
- stability: "stable",
841
- owners: [...OWNERS2],
842
- tags: ["agent", "tool", "assign"],
843
- description: "Assigns a tool to an agent with optional configuration.",
844
- goal: "Enable agents to use specific tools.",
845
- context: "Agent configuration UI - tool selection."
846
- },
847
- io: {
848
- input: defineSchemaModel3({
849
- name: "AssignToolToAgentInput",
850
- fields: {
851
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
852
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
853
- config: { type: ScalarTypeEnum3.JSONObject(), isOptional: true },
854
- order: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: true }
855
- }
856
- }),
857
- output: defineSchemaModel3({
858
- name: "AssignToolToAgentOutput",
859
- fields: {
860
- agentToolId: {
861
- type: ScalarTypeEnum3.String_unsecure(),
862
- isOptional: false
863
- },
864
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
865
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
866
- }
867
- }),
868
- errors: {
869
- TOOL_ALREADY_ASSIGNED: {
870
- description: "This tool is already assigned to the agent",
871
- http: 409,
872
- gqlCode: "TOOL_ALREADY_ASSIGNED",
873
- when: "Tool assignment already exists"
874
- }
875
- }
876
- },
877
- policy: { auth: "user" },
878
- sideEffects: { audit: ["agent.tool.assigned"] },
879
- acceptance: {
880
- scenarios: [
881
- {
882
- key: "assign-tool-happy-path",
883
- given: ["Agent exists", "Tool exists and is not assigned"],
884
- when: ["User assigns tool to agent"],
885
- then: ["Tool is assigned", "Assignment ID is returned"]
886
- },
887
- {
888
- key: "assign-tool-already-assigned",
889
- given: ["Tool is already assigned to agent"],
890
- when: ["User attempts to assign again"],
891
- then: ["TOOL_ALREADY_ASSIGNED error is returned"]
892
- }
893
- ],
894
- examples: [
895
- {
896
- key: "assign-basic",
897
- input: { agentId: "agent-123", toolId: "tool-456" },
898
- output: {
899
- agentToolId: "at-789",
900
- agentId: "agent-123",
901
- toolId: "tool-456"
902
- }
903
- }
904
- ]
905
- }
906
- });
907
- var RemoveToolFromAgentCommand = defineCommand({
908
- meta: {
909
- key: "agent-console.agent.removeTool",
910
- version: "1.0.0",
911
- stability: "stable",
912
- owners: [...OWNERS2],
913
- tags: ["agent", "tool", "remove"],
914
- description: "Removes a tool assignment from an agent.",
915
- goal: "Disable specific tools for an agent.",
916
- context: "Agent configuration UI - tool management."
917
- },
918
- io: {
919
- input: defineSchemaModel3({
920
- name: "RemoveToolFromAgentInput",
921
- fields: {
922
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
923
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
924
- }
925
- }),
926
- output: defineSchemaModel3({
927
- name: "RemoveToolFromAgentOutput",
928
- fields: {
929
- success: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
930
- }
931
- })
932
- },
933
- policy: { auth: "user" },
934
- sideEffects: { audit: ["agent.tool.removed"] },
935
- acceptance: {
936
- scenarios: [
937
- {
938
- key: "remove-tool-happy-path",
939
- given: ["Agent exists", "Tool is assigned to agent"],
940
- when: ["User removes tool from agent"],
941
- then: ["Tool is unassigned", "Success is returned"]
942
- }
943
- ],
944
- examples: [
945
- {
946
- key: "remove-basic",
947
- input: { agentId: "agent-123", toolId: "tool-456" },
948
- output: { success: true }
949
- }
950
- ]
951
- }
952
- });
953
-
954
- // src/agent/agent.handler.ts
955
- var nextMockAgentId = MOCK_AGENTS.length + 1;
956
- async function mockListAgentsHandler(input) {
957
- const {
958
- organizationId,
959
- status,
960
- modelProvider,
961
- search,
962
- limit = 20,
963
- offset = 0
964
- } = input;
965
- let filtered = MOCK_AGENTS.filter((a) => a.organizationId === organizationId);
966
- if (status)
967
- filtered = filtered.filter((a) => a.status === status);
968
- if (modelProvider)
969
- filtered = filtered.filter((a) => a.modelProvider === modelProvider);
970
- if (search) {
971
- const q = search.toLowerCase();
972
- filtered = filtered.filter((a) => a.name.toLowerCase().includes(q) || a.description?.toLowerCase().includes(q) || a.tags?.some((t) => t.toLowerCase().includes(q)));
973
- }
974
- const total = filtered.length;
975
- const items = filtered.slice(offset, offset + limit).map((a) => ({
976
- id: a.id,
977
- name: a.name,
978
- slug: a.slug,
979
- description: a.description,
980
- status: a.status,
981
- modelProvider: a.modelProvider,
982
- modelName: a.modelName,
983
- version: a.version,
984
- createdAt: a.createdAt
985
- }));
986
- return { items, total, hasMore: offset + limit < total };
987
- }
988
- async function mockGetAgentHandler(input) {
989
- const agent = MOCK_AGENTS.find((a) => a.id === input.agentId);
990
- if (!agent)
991
- throw new Error("AGENT_NOT_FOUND");
992
- const result = { ...agent, toolIds: ["tool-1", "tool-2"] };
993
- if (input.includeTools) {
994
- result.tools = MOCK_TOOLS.slice(0, 2).map((t) => ({
995
- id: t.id,
996
- name: t.name,
997
- slug: t.slug,
998
- description: t.description,
999
- category: t.category
1000
- }));
1001
- }
1002
- return result;
1003
- }
1004
- async function mockCreateAgentHandler(input) {
1005
- const exists = MOCK_AGENTS.some((a) => a.organizationId === input.organizationId && a.slug === input.slug);
1006
- if (exists)
1007
- throw new Error("SLUG_EXISTS");
1008
- return {
1009
- id: `agent-${nextMockAgentId++}`,
1010
- name: input.name,
1011
- slug: input.slug,
1012
- status: "DRAFT"
1013
- };
1014
- }
1015
- async function mockUpdateAgentHandler(input) {
1016
- const agent = MOCK_AGENTS.find((a) => a.id === input.agentId);
1017
- if (!agent)
1018
- throw new Error("AGENT_NOT_FOUND");
1019
- return {
1020
- id: agent.id,
1021
- name: input.name ?? agent.name,
1022
- status: input.status ?? agent.status,
1023
- updatedAt: new Date
1024
- };
1025
- }
1026
-
1027
- // src/run/run.enum.ts
1028
- import { defineEnum as defineEnum2 } from "@contractspec/lib.schema";
1029
- var RunStatusEnum = defineEnum2("RunStatus", [
1030
- "QUEUED",
1031
- "IN_PROGRESS",
1032
- "COMPLETED",
1033
- "FAILED",
1034
- "CANCELLED",
1035
- "EXPIRED"
1036
- ]);
1037
- var RunStepTypeEnum = defineEnum2("RunStepType", [
1038
- "MESSAGE_CREATION",
1039
- "TOOL_CALL",
1040
- "TOOL_RESULT",
1041
- "ERROR"
1042
- ]);
1043
- var LogLevelEnum = defineEnum2("LogLevel", [
1044
- "DEBUG",
1045
- "INFO",
1046
- "WARN",
1047
- "ERROR"
1048
- ]);
1049
- var GranularityEnum = defineEnum2("Granularity", [
1050
- "hour",
1051
- "day",
1052
- "week",
1053
- "month"
1054
- ]);
1055
-
1056
- // src/run/run.schema.ts
1057
- import { defineSchemaModel as defineSchemaModel4, ScalarTypeEnum as ScalarTypeEnum4 } from "@contractspec/lib.schema";
1058
- var RunInputModel = defineSchemaModel4({
1059
- name: "RunInput",
1060
- description: "Input data for agent execution",
1061
- fields: {
1062
- message: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
1063
- context: { type: ScalarTypeEnum4.JSONObject(), isOptional: true }
1064
- }
1065
- });
1066
- var RunStepModel = defineSchemaModel4({
1067
- name: "RunStep",
1068
- description: "Individual step within a run",
1069
- fields: {
1070
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1071
- stepNumber: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
1072
- type: { type: RunStepTypeEnum, isOptional: false },
1073
- toolId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1074
- toolName: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1075
- input: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
1076
- output: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
1077
- status: { type: RunStatusEnum, isOptional: false },
1078
- errorMessage: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1079
- tokensUsed: {
1080
- type: ScalarTypeEnum4.Int_unsecure(),
1081
- isOptional: false,
1082
- defaultValue: 0
1083
- },
1084
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
1085
- startedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
1086
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true }
1087
- }
1088
- });
1089
- var RunLogModel = defineSchemaModel4({
1090
- name: "RunLog",
1091
- description: "Execution log entry",
1092
- fields: {
1093
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1094
- stepId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1095
- level: { type: LogLevelEnum, isOptional: false },
1096
- message: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1097
- data: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
1098
- source: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1099
- traceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1100
- spanId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1101
- timestamp: { type: ScalarTypeEnum4.DateTime(), isOptional: false }
1102
- }
1103
- });
1104
- var RunAgentRefModel = defineSchemaModel4({
1105
- name: "RunAgentRef",
1106
- description: "Agent reference in a run",
1107
- fields: {
1108
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1109
- name: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
1110
- modelProvider: {
1111
- type: ScalarTypeEnum4.String_unsecure(),
1112
- isOptional: false
1113
- },
1114
- modelName: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false }
1115
- }
1116
- });
1117
- var RunModel = defineSchemaModel4({
1118
- name: "Run",
1119
- description: "Agent execution instance",
1120
- fields: {
1121
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1122
- organizationId: {
1123
- type: ScalarTypeEnum4.String_unsecure(),
1124
- isOptional: false
1125
- },
1126
- agentId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1127
- userId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1128
- sessionId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1129
- input: { type: ScalarTypeEnum4.JSONObject(), isOptional: false },
1130
- output: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
1131
- status: { type: RunStatusEnum, isOptional: false },
1132
- errorMessage: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1133
- errorCode: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
1134
- totalTokens: {
1135
- type: ScalarTypeEnum4.Int_unsecure(),
1136
- isOptional: false,
1137
- defaultValue: 0
1138
- },
1139
- promptTokens: {
1140
- type: ScalarTypeEnum4.Int_unsecure(),
1141
- isOptional: false,
1142
- defaultValue: 0
1143
- },
1144
- completionTokens: {
1145
- type: ScalarTypeEnum4.Int_unsecure(),
1146
- isOptional: false,
1147
- defaultValue: 0
1148
- },
1149
- totalIterations: {
1150
- type: ScalarTypeEnum4.Int_unsecure(),
1151
- isOptional: false,
1152
- defaultValue: 0
1153
- },
1154
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
1155
- estimatedCostUsd: {
1156
- type: ScalarTypeEnum4.Float_unsecure(),
1157
- isOptional: true
1158
- },
1159
- queuedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
1160
- startedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true },
1161
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true },
1162
- metadata: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
1163
- steps: { type: RunStepModel, isArray: true, isOptional: true },
1164
- logs: { type: RunLogModel, isArray: true, isOptional: true },
1165
- agent: { type: RunAgentRefModel, isOptional: true }
1166
- }
1167
- });
1168
- var RunSummaryModel = defineSchemaModel4({
1169
- name: "RunSummary",
1170
- description: "Summary of a run for list views",
1171
- fields: {
1172
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1173
- agentId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1174
- agentName: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
1175
- status: { type: RunStatusEnum, isOptional: false },
1176
- totalTokens: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
1177
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
1178
- estimatedCostUsd: {
1179
- type: ScalarTypeEnum4.Float_unsecure(),
1180
- isOptional: true
1181
- },
1182
- queuedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
1183
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true }
1184
- }
1185
- });
1186
- var TimelineDataPointModel = defineSchemaModel4({
1187
- name: "TimelineDataPoint",
1188
- description: "Timeline data point for metrics",
1189
- fields: {
1190
- period: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
1191
- runs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
1192
- tokens: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
1193
- costUsd: { type: ScalarTypeEnum4.Float_unsecure(), isOptional: false },
1194
- avgDurationMs: { type: ScalarTypeEnum4.Float_unsecure(), isOptional: false }
1195
- }
1196
- });
1197
-
1198
- // src/run/run.operation.ts
1199
- import {
1200
- defineCommand as defineCommand2,
1201
- defineQuery as defineQuery2
1202
- } from "@contractspec/lib.contracts-spec/operations";
1203
- import { defineSchemaModel as defineSchemaModel5, ScalarTypeEnum as ScalarTypeEnum5 } from "@contractspec/lib.schema";
1204
- var OWNERS3 = ["@agent-console-team"];
1205
- var ExecuteAgentCommand = defineCommand2({
1206
- meta: {
1207
- key: "agent.run.execute",
1208
- version: "1.0.0",
1209
- stability: "stable",
1210
- owners: [...OWNERS3],
1211
- tags: ["run", "execute"],
1212
- description: "Starts a new agent run with the given input.",
1213
- goal: "Execute an AI agent with user input.",
1214
- context: "Called from chat interface or API."
1215
- },
1216
- io: {
1217
- input: defineSchemaModel5({
1218
- name: "ExecuteAgentInput",
1219
- fields: {
1220
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1221
- input: { type: RunInputModel, isOptional: false },
1222
- sessionId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1223
- metadata: { type: ScalarTypeEnum5.JSONObject(), isOptional: true },
1224
- stream: { type: ScalarTypeEnum5.Boolean(), isOptional: true },
1225
- maxIterations: {
1226
- type: ScalarTypeEnum5.Int_unsecure(),
1227
- isOptional: true
1228
- },
1229
- timeoutMs: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: true }
1230
- }
1231
- }),
1232
- output: defineSchemaModel5({
1233
- name: "ExecuteAgentOutput",
1234
- fields: {
1235
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1236
- status: { type: RunStatusEnum, isOptional: false },
1237
- estimatedWaitMs: {
1238
- type: ScalarTypeEnum5.Int_unsecure(),
1239
- isOptional: true
1240
- }
1241
- }
1242
- }),
1243
- errors: {
1244
- AGENT_NOT_FOUND: {
1245
- description: "The specified agent does not exist",
1246
- http: 404,
1247
- gqlCode: "AGENT_NOT_FOUND",
1248
- when: "Agent ID is invalid"
1249
- },
1250
- AGENT_NOT_ACTIVE: {
1251
- description: "The specified agent is not active",
1252
- http: 400,
1253
- gqlCode: "AGENT_NOT_ACTIVE",
1254
- when: "Agent is in draft/paused/archived state"
1255
- }
1256
- }
1257
- },
1258
- policy: { auth: "user" },
1259
- sideEffects: {
1260
- emits: [
1261
- {
1262
- key: "run.started",
1263
- version: "1.0.0",
1264
- stability: "stable",
1265
- owners: [...OWNERS3],
1266
- tags: ["run", "started"],
1267
- when: "Run is queued",
1268
- payload: RunSummaryModel
1269
- }
1270
- ],
1271
- audit: ["run.started"]
1272
- },
1273
- acceptance: {
1274
- scenarios: [
1275
- {
1276
- key: "execute-agent-happy-path",
1277
- given: ["Agent exists", "Agent is active"],
1278
- when: ["User submits execution request"],
1279
- then: ["Run is created", "RunStarted event is emitted"]
1280
- },
1281
- {
1282
- key: "execute-agent-not-active",
1283
- given: ["Agent exists but is not active"],
1284
- when: ["User attempts to execute"],
1285
- then: ["AGENT_NOT_ACTIVE error is returned"]
1286
- }
1287
- ],
1288
- examples: [
1289
- {
1290
- key: "basic-execute",
1291
- input: { agentId: "agent-123", input: { message: "Hello" } },
1292
- output: { runId: "run-456", status: "pending", estimatedWaitMs: 5000 }
1293
- }
1294
- ]
1295
- }
1296
- });
1297
- var CancelRunCommand = defineCommand2({
1298
- meta: {
1299
- key: "agent.run.cancel",
1300
- version: "1.0.0",
1301
- stability: "stable",
1302
- owners: [...OWNERS3],
1303
- tags: ["run", "cancel"],
1304
- description: "Cancels an in-progress agent run.",
1305
- goal: "Stop a running agent execution.",
1306
- context: "Called when user wants to abort a long-running task."
1307
- },
1308
- io: {
1309
- input: defineSchemaModel5({
1310
- name: "CancelRunInput",
1311
- fields: {
1312
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1313
- reason: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true }
1314
- }
1315
- }),
1316
- output: defineSchemaModel5({
1317
- name: "CancelRunOutput",
1318
- fields: {
1319
- success: { type: ScalarTypeEnum5.Boolean(), isOptional: false },
1320
- status: { type: RunStatusEnum, isOptional: false }
1321
- }
1322
- }),
1323
- errors: {
1324
- RUN_NOT_FOUND: {
1325
- description: "The specified run does not exist",
1326
- http: 404,
1327
- gqlCode: "RUN_NOT_FOUND",
1328
- when: "Run ID is invalid"
1329
- },
1330
- RUN_NOT_CANCELLABLE: {
1331
- description: "The run cannot be cancelled",
1332
- http: 400,
1333
- gqlCode: "RUN_NOT_CANCELLABLE",
1334
- when: "Run is already completed/failed/cancelled"
1335
- }
1336
- }
1337
- },
1338
- policy: { auth: "user" },
1339
- sideEffects: {
1340
- emits: [
1341
- {
1342
- key: "run.cancelled",
1343
- version: "1.0.0",
1344
- stability: "stable",
1345
- owners: [...OWNERS3],
1346
- tags: ["run", "cancelled"],
1347
- when: "Run is cancelled",
1348
- payload: RunSummaryModel
1349
- }
1350
- ],
1351
- audit: ["run.cancelled"]
1352
- },
1353
- acceptance: {
1354
- scenarios: [
1355
- {
1356
- key: "cancel-run-happy-path",
1357
- given: ["Run exists", "Run is in progress"],
1358
- when: ["User cancels run"],
1359
- then: ["Run is cancelled", "RunCancelled event is emitted"]
1360
- },
1361
- {
1362
- key: "cancel-run-already-completed",
1363
- given: ["Run exists but is already completed"],
1364
- when: ["User attempts to cancel"],
1365
- then: ["RUN_NOT_CANCELLABLE error is returned"]
1366
- }
1367
- ],
1368
- examples: [
1369
- {
1370
- key: "cancel-basic",
1371
- input: { runId: "run-456", reason: "User requested" },
1372
- output: { success: true, status: "cancelled" }
1373
- }
1374
- ]
1375
- }
1376
- });
1377
- var GetRunQuery = defineQuery2({
1378
- meta: {
1379
- key: "agent.run.get",
1380
- version: "1.0.0",
1381
- stability: "stable",
1382
- owners: [...OWNERS3],
1383
- tags: ["run", "get"],
1384
- description: "Retrieves a run by its ID with optional details.",
1385
- goal: "View detailed run information.",
1386
- context: "Run details page or monitoring."
1387
- },
1388
- io: {
1389
- input: defineSchemaModel5({
1390
- name: "GetRunInput",
1391
- fields: {
1392
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1393
- includeSteps: { type: ScalarTypeEnum5.Boolean(), isOptional: true },
1394
- includeLogs: { type: ScalarTypeEnum5.Boolean(), isOptional: true }
1395
- }
1396
- }),
1397
- output: RunModel,
1398
- errors: {
1399
- RUN_NOT_FOUND: {
1400
- description: "The specified run does not exist",
1401
- http: 404,
1402
- gqlCode: "RUN_NOT_FOUND",
1403
- when: "Run ID is invalid"
1404
- }
1405
- }
1406
- },
1407
- policy: { auth: "user" },
1408
- acceptance: {
1409
- scenarios: [
1410
- {
1411
- key: "get-run-happy-path",
1412
- given: ["Run exists"],
1413
- when: ["User requests run by ID"],
1414
- then: ["Run details are returned"]
1415
- }
1416
- ],
1417
- examples: [
1418
- {
1419
- key: "get-with-steps",
1420
- input: { runId: "run-456", includeSteps: true, includeLogs: false },
1421
- output: { id: "run-456", status: "completed", steps: [] }
1422
- }
1423
- ]
1424
- }
1425
- });
1426
- var ListRunsQuery = defineQuery2({
1427
- meta: {
1428
- key: "agent.run.list",
1429
- version: "1.0.0",
1430
- stability: "stable",
1431
- owners: [...OWNERS3],
1432
- tags: ["run", "list"],
1433
- description: "Lists runs with optional filtering.",
1434
- goal: "Browse and search run history.",
1435
- context: "Run history/dashboard view."
1436
- },
1437
- io: {
1438
- input: defineSchemaModel5({
1439
- name: "ListRunsInput",
1440
- fields: {
1441
- organizationId: {
1442
- type: ScalarTypeEnum5.String_unsecure(),
1443
- isOptional: true
1444
- },
1445
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1446
- userId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1447
- sessionId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1448
- status: { type: RunStatusEnum, isOptional: true },
1449
- startDate: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1450
- endDate: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1451
- limit: {
1452
- type: ScalarTypeEnum5.Int_unsecure(),
1453
- isOptional: true,
1454
- defaultValue: 20
1455
- },
1456
- offset: {
1457
- type: ScalarTypeEnum5.Int_unsecure(),
1458
- isOptional: true,
1459
- defaultValue: 0
1460
- }
1461
- }
1462
- }),
1463
- output: defineSchemaModel5({
1464
- name: "ListRunsOutput",
1465
- fields: {
1466
- items: { type: RunSummaryModel, isArray: true, isOptional: false },
1467
- total: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1468
- hasMore: { type: ScalarTypeEnum5.Boolean(), isOptional: false }
1469
- }
1470
- })
1471
- },
1472
- policy: { auth: "user" },
1473
- acceptance: {
1474
- scenarios: [
1475
- {
1476
- key: "list-runs-happy-path",
1477
- given: ["Organization has runs"],
1478
- when: ["User lists runs"],
1479
- then: ["Paginated list of runs is returned"]
1480
- }
1481
- ],
1482
- examples: [
1483
- {
1484
- key: "list-by-agent",
1485
- input: { agentId: "agent-123", limit: 20, offset: 0 },
1486
- output: { items: [], total: 0, hasMore: false }
1487
- }
1488
- ]
1489
- }
1490
- });
1491
- var GetRunStepsQuery = defineQuery2({
1492
- meta: {
1493
- key: "agent.run.getSteps",
1494
- version: "1.0.0",
1495
- stability: "stable",
1496
- owners: [...OWNERS3],
1497
- tags: ["run", "steps"],
1498
- description: "Retrieves all steps for a specific run.",
1499
- goal: "View step-by-step execution details.",
1500
- context: "Run details page - steps tab."
1501
- },
1502
- io: {
1503
- input: defineSchemaModel5({
1504
- name: "GetRunStepsInput",
1505
- fields: {
1506
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false }
1507
- }
1508
- }),
1509
- output: defineSchemaModel5({
1510
- name: "GetRunStepsOutput",
1511
- fields: {
1512
- steps: { type: RunStepModel, isArray: true, isOptional: false }
1513
- }
1514
- })
1515
- },
1516
- policy: { auth: "user" },
1517
- acceptance: {
1518
- scenarios: [
1519
- {
1520
- key: "get-run-steps-happy-path",
1521
- given: ["Run exists with steps"],
1522
- when: ["User requests steps"],
1523
- then: ["Steps list is returned"]
1524
- }
1525
- ],
1526
- examples: [
1527
- {
1528
- key: "get-steps-basic",
1529
- input: { runId: "run-456" },
1530
- output: { steps: [] }
1531
- }
1532
- ]
1533
- }
1534
- });
1535
- var GetRunLogsQuery = defineQuery2({
1536
- meta: {
1537
- key: "agent.run.getLogs",
1538
- version: "1.0.0",
1539
- stability: "stable",
1540
- owners: [...OWNERS3],
1541
- tags: ["run", "logs"],
1542
- description: "Retrieves all logs for a specific run.",
1543
- goal: "Debug and audit run execution.",
1544
- context: "Run details page - logs tab."
1545
- },
1546
- io: {
1547
- input: defineSchemaModel5({
1548
- name: "GetRunLogsInput",
1549
- fields: {
1550
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1551
- level: { type: LogLevelEnum, isOptional: true },
1552
- stepId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1553
- limit: {
1554
- type: ScalarTypeEnum5.Int_unsecure(),
1555
- isOptional: true,
1556
- defaultValue: 100
1557
- },
1558
- offset: {
1559
- type: ScalarTypeEnum5.Int_unsecure(),
1560
- isOptional: true,
1561
- defaultValue: 0
1562
- }
1563
- }
1564
- }),
1565
- output: defineSchemaModel5({
1566
- name: "GetRunLogsOutput",
1567
- fields: {
1568
- items: { type: RunLogModel, isArray: true, isOptional: false },
1569
- total: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1570
- hasMore: { type: ScalarTypeEnum5.Boolean(), isOptional: false }
1571
- }
1572
- })
1573
- },
1574
- policy: { auth: "user" },
1575
- acceptance: {
1576
- scenarios: [
1577
- {
1578
- key: "get-run-logs-happy-path",
1579
- given: ["Run exists with logs"],
1580
- when: ["User requests logs"],
1581
- then: ["Paginated logs list is returned"]
1582
- }
1583
- ],
1584
- examples: [
1585
- {
1586
- key: "get-logs-filtered",
1587
- input: { runId: "run-456", level: "error", limit: 50 },
1588
- output: { items: [], total: 0, hasMore: false }
1589
- }
1590
- ]
1591
- }
1592
- });
1593
- var GetRunMetricsQuery = defineQuery2({
1594
- meta: {
1595
- key: "agent.run.getMetrics",
1596
- version: "1.0.0",
1597
- stability: "stable",
1598
- owners: [...OWNERS3],
1599
- tags: ["run", "metrics"],
1600
- description: "Retrieves aggregated metrics for runs within a time period.",
1601
- goal: "Monitor and analyze agent usage.",
1602
- context: "Analytics dashboard."
1603
- },
1604
- io: {
1605
- input: defineSchemaModel5({
1606
- name: "GetRunMetricsInput",
1607
- fields: {
1608
- organizationId: {
1609
- type: ScalarTypeEnum5.String_unsecure(),
1610
- isOptional: false
1611
- },
1612
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1613
- startDate: { type: ScalarTypeEnum5.DateTime(), isOptional: false },
1614
- endDate: { type: ScalarTypeEnum5.DateTime(), isOptional: false },
1615
- granularity: {
1616
- type: GranularityEnum,
1617
- isOptional: true,
1618
- defaultValue: "day"
1619
- }
1620
- }
1621
- }),
1622
- output: defineSchemaModel5({
1623
- name: "GetRunMetricsOutput",
1624
- fields: {
1625
- totalRuns: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1626
- completedRuns: {
1627
- type: ScalarTypeEnum5.Int_unsecure(),
1628
- isOptional: false
1629
- },
1630
- failedRuns: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1631
- totalTokens: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1632
- totalCostUsd: {
1633
- type: ScalarTypeEnum5.Float_unsecure(),
1634
- isOptional: false
1635
- },
1636
- averageDurationMs: {
1637
- type: ScalarTypeEnum5.Float_unsecure(),
1638
- isOptional: false
1639
- },
1640
- successRate: {
1641
- type: ScalarTypeEnum5.Float_unsecure(),
1642
- isOptional: false
1643
- },
1644
- timeline: {
1645
- type: TimelineDataPointModel,
1646
- isArray: true,
1647
- isOptional: false
1648
- }
1649
- }
1650
- })
1651
- },
1652
- policy: { auth: "user" },
1653
- acceptance: {
1654
- scenarios: [
1655
- {
1656
- key: "get-run-metrics-happy-path",
1657
- given: ["Organization has run history"],
1658
- when: ["User requests metrics for date range"],
1659
- then: ["Aggregated metrics are returned"]
1660
- }
1661
- ],
1662
- examples: [
1663
- {
1664
- key: "get-daily-metrics",
1665
- input: {
1666
- organizationId: "org-123",
1667
- startDate: "2025-01-01",
1668
- endDate: "2025-01-31",
1669
- granularity: "day"
1670
- },
1671
- output: {
1672
- totalRuns: 100,
1673
- completedRuns: 90,
1674
- failedRuns: 10,
1675
- totalTokens: 50000,
1676
- totalCostUsd: 5,
1677
- averageDurationMs: 2500,
1678
- successRate: 0.9,
1679
- timeline: []
1680
- }
1681
- }
1682
- ]
1683
- }
1684
- });
1685
-
1686
- // src/tool/tool.enum.ts
1687
- import { defineEnum as defineEnum3 } from "@contractspec/lib.schema";
1688
- var ToolCategoryEnum = defineEnum3("ToolCategory", [
1689
- "RETRIEVAL",
1690
- "COMPUTATION",
1691
- "COMMUNICATION",
1692
- "INTEGRATION",
1693
- "UTILITY",
1694
- "CUSTOM"
1695
- ]);
1696
- var ToolStatusEnum = defineEnum3("ToolStatus", [
1697
- "DRAFT",
1698
- "ACTIVE",
1699
- "DEPRECATED",
1700
- "DISABLED"
1701
- ]);
1702
- var ImplementationTypeEnum = defineEnum3("ImplementationType", [
1703
- "http",
1704
- "function",
1705
- "workflow"
1706
- ]);
1707
-
1708
- // src/tool/tool.schema.ts
1709
- import { defineSchemaModel as defineSchemaModel6, ScalarTypeEnum as ScalarTypeEnum6 } from "@contractspec/lib.schema";
1710
- var ToolModel = defineSchemaModel6({
1711
- name: "Tool",
1712
- description: "AI tool definition",
1713
- fields: {
1714
- id: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1715
- organizationId: {
1716
- type: ScalarTypeEnum6.String_unsecure(),
1717
- isOptional: false
1718
- },
1719
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1720
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1721
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1722
- category: { type: ToolCategoryEnum, isOptional: false },
1723
- status: { type: ToolStatusEnum, isOptional: false },
1724
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: false },
1725
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1726
- implementationType: { type: ImplementationTypeEnum, isOptional: false },
1727
- implementationConfig: {
1728
- type: ScalarTypeEnum6.JSONObject(),
1729
- isOptional: false
1730
- },
1731
- maxInvocationsPerMinute: {
1732
- type: ScalarTypeEnum6.Int_unsecure(),
1733
- isOptional: true
1734
- },
1735
- timeoutMs: {
1736
- type: ScalarTypeEnum6.Int_unsecure(),
1737
- isOptional: false,
1738
- defaultValue: 30000
1739
- },
1740
- version: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1741
- tags: {
1742
- type: ScalarTypeEnum6.String_unsecure(),
1743
- isArray: true,
1744
- isOptional: true
1745
- },
1746
- createdAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false },
1747
- updatedAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false }
1748
- }
1749
- });
1750
- var ToolSummaryModel = defineSchemaModel6({
1751
- name: "ToolSummary",
1752
- description: "Summary of a tool for list views",
1753
- fields: {
1754
- id: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1755
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1756
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1757
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1758
- category: { type: ToolCategoryEnum, isOptional: false },
1759
- status: { type: ToolStatusEnum, isOptional: false },
1760
- version: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1761
- createdAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false }
1762
- }
1763
- });
1764
- var CreateToolInputModel = defineSchemaModel6({
1765
- name: "CreateToolInput",
1766
- description: "Input for creating a tool",
1767
- fields: {
1768
- organizationId: {
1769
- type: ScalarTypeEnum6.String_unsecure(),
1770
- isOptional: false
1771
- },
1772
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1773
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1774
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1775
- category: { type: ToolCategoryEnum, isOptional: true },
1776
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: false },
1777
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1778
- implementationType: { type: ImplementationTypeEnum, isOptional: false },
1779
- implementationConfig: {
1780
- type: ScalarTypeEnum6.JSONObject(),
1781
- isOptional: false
1782
- },
1783
- maxInvocationsPerMinute: {
1784
- type: ScalarTypeEnum6.Int_unsecure(),
1785
- isOptional: true
1786
- },
1787
- timeoutMs: { type: ScalarTypeEnum6.Int_unsecure(), isOptional: true },
1788
- tags: {
1789
- type: ScalarTypeEnum6.String_unsecure(),
1790
- isArray: true,
1791
- isOptional: true
1792
- }
1793
- }
1794
- });
1795
- var UpdateToolInputModel = defineSchemaModel6({
1796
- name: "UpdateToolInput",
1797
- description: "Input for updating a tool",
1798
- fields: {
1799
- toolId: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1800
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: true },
1801
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: true },
1802
- status: { type: ToolStatusEnum, isOptional: true },
1803
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1804
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1805
- implementationConfig: {
1806
- type: ScalarTypeEnum6.JSONObject(),
1807
- isOptional: true
1808
- },
1809
- maxInvocationsPerMinute: {
1810
- type: ScalarTypeEnum6.Int_unsecure(),
1811
- isOptional: true
1812
- },
1813
- timeoutMs: { type: ScalarTypeEnum6.Int_unsecure(), isOptional: true },
1814
- tags: {
1815
- type: ScalarTypeEnum6.String_unsecure(),
1816
- isArray: true,
1817
- isOptional: true
1818
- }
1819
- }
1820
- });
1821
-
1822
- // src/tool/tool.operation.ts
1823
- import {
1824
- defineCommand as defineCommand3,
1825
- defineQuery as defineQuery3
1826
- } from "@contractspec/lib.contracts-spec/operations";
1827
- import { defineSchemaModel as defineSchemaModel7, ScalarTypeEnum as ScalarTypeEnum7 } from "@contractspec/lib.schema";
1828
- var OWNERS4 = ["@agent-console-team"];
1829
- var CreateToolCommand = defineCommand3({
1830
- meta: {
1831
- key: "agent.tool.create",
1832
- version: "1.0.0",
1833
- stability: "stable",
1834
- owners: [...OWNERS4],
1835
- tags: ["tool", "create"],
1836
- description: "Creates a new AI tool definition.",
1837
- goal: "Allow users to define new tools that agents can use.",
1838
- context: "Called from the tool builder UI when creating a new tool."
1839
- },
1840
- io: {
1841
- input: CreateToolInputModel,
1842
- output: defineSchemaModel7({
1843
- name: "CreateToolOutput",
1844
- fields: {
1845
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1846
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1847
- slug: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1848
- status: { type: ToolStatusEnum, isOptional: false }
1849
- }
1850
- }),
1851
- errors: {
1852
- SLUG_EXISTS: {
1853
- description: "A tool with this slug already exists in the organization",
1854
- http: 409,
1855
- gqlCode: "SLUG_EXISTS",
1856
- when: "Slug is already taken"
1857
- }
1858
- }
1859
- },
1860
- policy: { auth: "user" },
1861
- sideEffects: {
1862
- emits: [
1863
- {
1864
- key: "tool.created",
1865
- version: "1.0.0",
1866
- stability: "stable",
1867
- owners: [...OWNERS4],
1868
- tags: ["tool", "created"],
1869
- when: "Tool is successfully created",
1870
- payload: ToolSummaryModel
1871
- }
1872
- ],
1873
- audit: ["tool.created"]
1874
- },
1875
- acceptance: {
1876
- scenarios: [
1877
- {
1878
- key: "create-tool-happy-path",
1879
- given: ["User is authenticated", "Organization exists"],
1880
- when: ["User submits valid tool configuration"],
1881
- then: ["New tool is created", "ToolCreated event is emitted"]
1882
- },
1883
- {
1884
- key: "create-tool-slug-conflict",
1885
- given: ["Tool with same slug exists"],
1886
- when: ["User submits tool with duplicate slug"],
1887
- then: ["SLUG_EXISTS error is returned"]
1888
- }
1889
- ],
1890
- examples: [
1891
- {
1892
- key: "create-api-tool",
1893
- input: {
1894
- name: "Weather API",
1895
- slug: "weather-api",
1896
- category: "api",
1897
- description: "Fetches weather data"
1898
- },
1899
- output: {
1900
- id: "tool-123",
1901
- name: "Weather API",
1902
- slug: "weather-api",
1903
- status: "draft"
1904
- }
1905
- }
1906
- ]
1907
- }
1908
- });
1909
- var UpdateToolCommand = defineCommand3({
1910
- meta: {
1911
- key: "agent.tool.update",
1912
- version: "1.0.0",
1913
- stability: "stable",
1914
- owners: [...OWNERS4],
1915
- tags: ["tool", "update"],
1916
- description: "Updates an existing AI tool definition.",
1917
- goal: "Allow users to modify tool settings and configuration.",
1918
- context: "Called from the tool settings UI."
1919
- },
1920
- io: {
1921
- input: UpdateToolInputModel,
1922
- output: defineSchemaModel7({
1923
- name: "UpdateToolOutput",
1924
- fields: {
1925
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1926
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1927
- status: { type: ToolStatusEnum, isOptional: false },
1928
- updatedAt: { type: ScalarTypeEnum7.DateTime(), isOptional: false }
1929
- }
1930
- }),
1931
- errors: {
1932
- TOOL_NOT_FOUND: {
1933
- description: "The specified tool does not exist",
1934
- http: 404,
1935
- gqlCode: "TOOL_NOT_FOUND",
1936
- when: "Tool ID is invalid"
1937
- }
1938
- }
1939
- },
1940
- policy: { auth: "user" },
1941
- sideEffects: {
1942
- emits: [
1943
- {
1944
- key: "tool.updated",
1945
- version: "1.0.0",
1946
- stability: "stable",
1947
- owners: [...OWNERS4],
1948
- tags: ["tool", "updated"],
1949
- when: "Tool is updated",
1950
- payload: ToolSummaryModel
1951
- }
1952
- ],
1953
- audit: ["tool.updated"]
1954
- },
1955
- acceptance: {
1956
- scenarios: [
1957
- {
1958
- key: "update-tool-happy-path",
1959
- given: ["Tool exists", "User owns the tool"],
1960
- when: ["User submits updated configuration"],
1961
- then: ["Tool is updated", "ToolUpdated event is emitted"]
1962
- }
1963
- ],
1964
- examples: [
1965
- {
1966
- key: "update-description",
1967
- input: { toolId: "tool-123", description: "Updated weather API tool" },
1968
- output: {
1969
- id: "tool-123",
1970
- name: "Weather API",
1971
- status: "draft",
1972
- updatedAt: "2025-01-01T00:00:00Z"
1973
- }
1974
- }
1975
- ]
1976
- }
1977
- });
1978
- var GetToolQuery = defineQuery3({
1979
- meta: {
1980
- key: "agent.tool.get",
1981
- version: "1.0.0",
1982
- stability: "stable",
1983
- owners: [...OWNERS4],
1984
- tags: ["tool", "get"],
1985
- description: "Retrieves a tool by its ID.",
1986
- goal: "View detailed tool configuration.",
1987
- context: "Called when viewing tool details or editing."
1988
- },
1989
- io: {
1990
- input: defineSchemaModel7({
1991
- name: "GetToolInput",
1992
- fields: {
1993
- toolId: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false }
1994
- }
1995
- }),
1996
- output: ToolModel,
1997
- errors: {
1998
- TOOL_NOT_FOUND: {
1999
- description: "The specified tool does not exist",
2000
- http: 404,
2001
- gqlCode: "TOOL_NOT_FOUND",
2002
- when: "Tool ID is invalid"
2003
- }
2004
- }
2005
- },
2006
- policy: { auth: "user" },
2007
- acceptance: {
2008
- scenarios: [
2009
- {
2010
- key: "get-tool-happy-path",
2011
- given: ["Tool exists"],
2012
- when: ["User requests tool by ID"],
2013
- then: ["Tool details are returned"]
2014
- }
2015
- ],
2016
- examples: [
2017
- {
2018
- key: "get-basic",
2019
- input: { toolId: "tool-123" },
2020
- output: {
2021
- id: "tool-123",
2022
- name: "Weather API",
2023
- status: "active",
2024
- category: "api"
2025
- }
2026
- }
2027
- ]
2028
- }
2029
- });
2030
- var ListToolsQuery = defineQuery3({
2031
- meta: {
2032
- key: "agent.tool.list",
2033
- version: "1.0.0",
2034
- stability: "stable",
2035
- owners: [...OWNERS4],
2036
- tags: ["tool", "list"],
2037
- description: "Lists tools for an organization with optional filtering.",
2038
- goal: "Browse and search available tools.",
2039
- context: "Tool list/dashboard view."
2040
- },
2041
- io: {
2042
- input: defineSchemaModel7({
2043
- name: "ListToolsInput",
2044
- fields: {
2045
- organizationId: {
2046
- type: ScalarTypeEnum7.String_unsecure(),
2047
- isOptional: false
2048
- },
2049
- category: { type: ToolCategoryEnum, isOptional: true },
2050
- status: { type: ToolStatusEnum, isOptional: true },
2051
- search: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
2052
- limit: {
2053
- type: ScalarTypeEnum7.Int_unsecure(),
2054
- isOptional: true,
2055
- defaultValue: 20
2056
- },
2057
- offset: {
2058
- type: ScalarTypeEnum7.Int_unsecure(),
2059
- isOptional: true,
2060
- defaultValue: 0
2061
- }
2062
- }
2063
- }),
2064
- output: defineSchemaModel7({
2065
- name: "ListToolsOutput",
2066
- fields: {
2067
- items: { type: ToolSummaryModel, isArray: true, isOptional: false },
2068
- total: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: false },
2069
- hasMore: { type: ScalarTypeEnum7.Boolean(), isOptional: false }
2070
- }
2071
- })
2072
- },
2073
- policy: { auth: "user" },
2074
- acceptance: {
2075
- scenarios: [
2076
- {
2077
- key: "list-tools-happy-path",
2078
- given: ["Organization has tools"],
2079
- when: ["User lists tools"],
2080
- then: ["Paginated list of tools is returned"]
2081
- }
2082
- ],
2083
- examples: [
2084
- {
2085
- key: "list-by-category",
2086
- input: { organizationId: "org-123", category: "api", limit: 10 },
2087
- output: { items: [], total: 0, hasMore: false }
2088
- }
2089
- ]
2090
- }
2091
- });
2092
- var TestToolCommand = defineCommand3({
2093
- meta: {
2094
- key: "agent.tool.test",
2095
- version: "1.0.0",
2096
- stability: "stable",
2097
- owners: [...OWNERS4],
2098
- tags: ["tool", "test"],
2099
- description: "Tests a tool with sample input to verify it works correctly.",
2100
- goal: "Validate tool configuration before deployment.",
2101
- context: "Tool builder UI - test panel."
2102
- },
2103
- io: {
2104
- input: defineSchemaModel7({
2105
- name: "TestToolInput",
2106
- fields: {
2107
- toolId: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
2108
- testInput: { type: ScalarTypeEnum7.JSONObject(), isOptional: false }
2109
- }
2110
- }),
2111
- output: defineSchemaModel7({
2112
- name: "TestToolOutput",
2113
- fields: {
2114
- success: { type: ScalarTypeEnum7.Boolean(), isOptional: false },
2115
- output: { type: ScalarTypeEnum7.JSONObject(), isOptional: true },
2116
- error: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
2117
- durationMs: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: false }
2118
- }
2119
- }),
2120
- errors: {
2121
- TOOL_NOT_FOUND: {
2122
- description: "The specified tool does not exist",
2123
- http: 404,
2124
- gqlCode: "TOOL_NOT_FOUND",
2125
- when: "Tool ID is invalid"
2126
- },
2127
- TOOL_EXECUTION_ERROR: {
2128
- description: "Tool execution failed",
2129
- http: 500,
2130
- gqlCode: "TOOL_EXECUTION_ERROR",
2131
- when: "Tool returns an error"
2132
- }
2133
- }
2134
- },
2135
- policy: { auth: "user" },
2136
- sideEffects: { audit: ["tool.tested"] },
2137
- acceptance: {
2138
- scenarios: [
2139
- {
2140
- key: "test-tool-success",
2141
- given: ["Tool exists", "Tool is configured correctly"],
2142
- when: ["User runs test with valid input"],
2143
- then: ["Tool executes successfully", "Output is returned"]
2144
- },
2145
- {
2146
- key: "test-tool-failure",
2147
- given: ["Tool exists", "Tool has configuration error"],
2148
- when: ["User runs test"],
2149
- then: ["TOOL_EXECUTION_ERROR is returned"]
2150
- }
2151
- ],
2152
- examples: [
2153
- {
2154
- key: "test-weather-api",
2155
- input: { toolId: "tool-123", testInput: { city: "Paris" } },
2156
- output: { success: true, output: { temperature: 22 }, durationMs: 150 }
2157
- }
2158
- ]
2159
- }
2160
- });
2161
-
2162
- // src/handlers/agent.handlers.ts
2163
- import { web } from "@contractspec/lib.runtime-sandbox";
2164
- var { generateId } = web;
2165
- var RUN_SORT_COLUMNS = {
2166
- queuedAt: "r.queuedAt",
2167
- totalTokens: "r.totalTokens",
2168
- durationMs: "r.durationMs",
2169
- estimatedCostUsd: "r.estimatedCostUsd",
2170
- status: "r.status",
2171
- agentName: "a.name"
2172
- };
2173
- function rowToAgent(row) {
2174
- return {
2175
- id: row.id,
2176
- projectId: row.projectId,
2177
- organizationId: row.organizationId,
2178
- name: row.name,
2179
- description: row.description ?? undefined,
2180
- modelProvider: row.modelProvider,
2181
- modelName: row.modelName,
2182
- systemPrompt: row.systemPrompt ?? undefined,
2183
- temperature: row.temperature,
2184
- maxTokens: row.maxTokens,
2185
- status: row.status,
2186
- createdAt: new Date(row.createdAt),
2187
- updatedAt: new Date(row.updatedAt)
2188
- };
2189
- }
2190
- function rowToTool(row) {
2191
- return {
2192
- id: row.id,
2193
- projectId: row.projectId,
2194
- organizationId: row.organizationId,
2195
- name: row.name,
2196
- description: row.description ?? undefined,
2197
- version: row.version,
2198
- category: row.category,
2199
- status: row.status,
2200
- inputSchema: row.inputSchema ?? undefined,
2201
- outputSchema: row.outputSchema ?? undefined,
2202
- endpoint: row.endpoint ?? undefined,
2203
- createdAt: new Date(row.createdAt),
2204
- updatedAt: new Date(row.updatedAt)
2205
- };
2206
- }
2207
- function rowToRun(row, agentName) {
2208
- return {
2209
- id: row.id,
2210
- projectId: row.projectId,
2211
- agentId: row.agentId,
2212
- agentName,
2213
- status: row.status,
2214
- input: row.input ?? undefined,
2215
- output: row.output ?? undefined,
2216
- totalTokens: row.totalTokens,
2217
- promptTokens: row.promptTokens,
2218
- completionTokens: row.completionTokens,
2219
- estimatedCostUsd: row.estimatedCostUsd,
2220
- durationMs: row.durationMs ?? undefined,
2221
- errorMessage: row.errorMessage ?? undefined,
2222
- queuedAt: new Date(row.queuedAt),
2223
- startedAt: row.startedAt ? new Date(row.startedAt) : undefined,
2224
- completedAt: row.completedAt ? new Date(row.completedAt) : undefined
2225
- };
2226
- }
2227
- function createAgentHandlers(db) {
2228
- async function listAgents(input) {
2229
- const {
2230
- projectId,
2231
- organizationId,
2232
- status,
2233
- search,
2234
- limit = 20,
2235
- offset = 0
2236
- } = input;
2237
- let whereClause = "WHERE projectId = ?";
2238
- const params = [projectId];
2239
- if (organizationId) {
2240
- whereClause += " AND organizationId = ?";
2241
- params.push(organizationId);
2242
- }
2243
- if (status && status !== "all") {
2244
- whereClause += " AND status = ?";
2245
- params.push(status);
2246
- }
2247
- if (search) {
2248
- whereClause += " AND (name LIKE ? OR description LIKE ?)";
2249
- params.push(`%${search}%`, `%${search}%`);
2250
- }
2251
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_definition ${whereClause}`, params)).rows;
2252
- const total = countResult[0]?.count ?? 0;
2253
- const rows = (await db.query(`SELECT * FROM agent_definition ${whereClause} ORDER BY createdAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
2254
- return {
2255
- items: rows.map(rowToAgent),
2256
- total,
2257
- hasMore: offset + rows.length < total
2258
- };
2259
- }
2260
- async function getAgent(id) {
2261
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [id])).rows;
2262
- return rows[0] ? rowToAgent(rows[0]) : null;
2263
- }
2264
- async function createAgent(input, context) {
2265
- const id = generateId("agent");
2266
- const now = new Date().toISOString();
2267
- await db.execute(`INSERT INTO agent_definition (id, projectId, organizationId, name, description, modelProvider, modelName, systemPrompt, temperature, maxTokens, status, createdAt, updatedAt)
2268
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
2269
- id,
2270
- context.projectId,
2271
- context.organizationId,
2272
- input.name,
2273
- input.description ?? null,
2274
- input.modelProvider ?? "openai",
2275
- input.modelName ?? "gpt-4",
2276
- input.systemPrompt ?? null,
2277
- input.temperature ?? 0.7,
2278
- input.maxTokens ?? 4096,
2279
- "DRAFT",
2280
- now,
2281
- now
2282
- ]);
2283
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [id])).rows;
2284
- const row = rows[0];
2285
- if (!row) {
2286
- throw new Error("Failed to retrieve created agent");
2287
- }
2288
- return rowToAgent(row);
2289
- }
2290
- async function updateAgent(input) {
2291
- const now = new Date().toISOString();
2292
- const updates = ["updatedAt = ?"];
2293
- const params = [now];
2294
- if (input.name !== undefined) {
2295
- updates.push("name = ?");
2296
- params.push(input.name);
2297
- }
2298
- if (input.description !== undefined) {
2299
- updates.push("description = ?");
2300
- params.push(input.description);
2301
- }
2302
- if (input.status !== undefined) {
2303
- updates.push("status = ?");
2304
- params.push(input.status);
2305
- }
2306
- params.push(input.id);
2307
- await db.execute(`UPDATE agent_definition SET ${updates.join(", ")} WHERE id = ?`, params);
2308
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [input.id])).rows;
2309
- if (!rows[0]) {
2310
- throw new Error("NOT_FOUND");
2311
- }
2312
- return rowToAgent(rows[0]);
2313
- }
2314
- async function listTools(input) {
2315
- const {
2316
- projectId,
2317
- organizationId,
2318
- category,
2319
- status,
2320
- search,
2321
- limit = 50,
2322
- offset = 0
2323
- } = input;
2324
- let whereClause = "WHERE projectId = ?";
2325
- const params = [projectId];
2326
- if (organizationId) {
2327
- whereClause += " AND organizationId = ?";
2328
- params.push(organizationId);
2329
- }
2330
- if (category && category !== "all") {
2331
- whereClause += " AND category = ?";
2332
- params.push(category);
2333
- }
2334
- if (status && status !== "all") {
2335
- whereClause += " AND status = ?";
2336
- params.push(status);
2337
- }
2338
- if (search) {
2339
- whereClause += " AND (name LIKE ? OR description LIKE ?)";
2340
- params.push(`%${search}%`, `%${search}%`);
2341
- }
2342
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_tool ${whereClause}`, params)).rows;
2343
- const total = countResult[0]?.count ?? 0;
2344
- const rows = (await db.query(`SELECT * FROM agent_tool ${whereClause} ORDER BY name ASC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
2345
- return {
2346
- items: rows.map(rowToTool),
2347
- total,
2348
- hasMore: offset + rows.length < total
2349
- };
2350
- }
2351
- async function listRuns(input) {
2352
- const {
2353
- projectId,
2354
- agentId,
2355
- status,
2356
- sortBy,
2357
- sortDirection = "desc",
2358
- limit = 20,
2359
- offset = 0
2360
- } = input;
2361
- let whereClause = "WHERE r.projectId = ?";
2362
- const params = [projectId];
2363
- if (agentId) {
2364
- whereClause += " AND r.agentId = ?";
2365
- params.push(agentId);
2366
- }
2367
- if (status && status !== "all") {
2368
- whereClause += " AND r.status = ?";
2369
- params.push(status);
2370
- }
2371
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_run r ${whereClause}`, params)).rows;
2372
- const total = countResult[0]?.count ?? 0;
2373
- const sortColumn = sortBy ? RUN_SORT_COLUMNS[sortBy] : RUN_SORT_COLUMNS.queuedAt;
2374
- const direction = sortDirection === "asc" ? "ASC" : "DESC";
2375
- const rows = (await db.query(`SELECT r.*, a.name as agentName
2
+ import{defineEnum as P0}from"@contractspec/lib.schema";var C=P0("AgentStatus",["DRAFT","ACTIVE","PAUSED","ARCHIVED"]),t=P0("ModelProvider",["OPENAI","ANTHROPIC","GOOGLE","MISTRAL","CUSTOM"]),T=P0("ToolChoice",["auto","required","none"]);import{defineEvent as p}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as l,ScalarTypeEnum as B}from"@contractspec/lib.schema";var u=["@agent-console-team"],e0=l({name:"AgentCreatedPayload",description:"Payload for agent created event",fields:{id:{type:B.String_unsecure(),isOptional:!1},organizationId:{type:B.String_unsecure(),isOptional:!1},name:{type:B.String_unsecure(),isOptional:!1},slug:{type:B.String_unsecure(),isOptional:!1},modelProvider:{type:B.String_unsecure(),isOptional:!1},modelName:{type:B.String_unsecure(),isOptional:!1},toolCount:{type:B.Int_unsecure(),isOptional:!1},createdById:{type:B.String_unsecure(),isOptional:!0},createdAt:{type:B.DateTime(),isOptional:!1}}}),G0=p({meta:{key:"agent-console.agent.created",version:"1.0.0",description:"A new AI agent was configured.",stability:"stable",owners:[...u],tags:["agent","created"]},payload:e0}),E0=l({name:"AgentUpdatedPayload",description:"Payload for agent updated event",fields:{id:{type:B.String_unsecure(),isOptional:!1},organizationId:{type:B.String_unsecure(),isOptional:!1},name:{type:B.String_unsecure(),isOptional:!1},status:{type:B.String_unsecure(),isOptional:!1},updatedFields:{type:B.String_unsecure(),isArray:!0,isOptional:!1},updatedAt:{type:B.DateTime(),isOptional:!1}}}),bs=p({meta:{key:"agent-console.agent.updated",version:"1.0.0",description:"An AI agent configuration was updated.",stability:"stable",owners:[...u],tags:["agent","updated"]},payload:E0}),S0=l({name:"AgentToolAssignedPayload",description:"Payload for agent tool assigned event",fields:{agentId:{type:B.String_unsecure(),isOptional:!1},toolId:{type:B.String_unsecure(),isOptional:!1},agentName:{type:B.String_unsecure(),isOptional:!1},toolName:{type:B.String_unsecure(),isOptional:!1},assignedAt:{type:B.DateTime(),isOptional:!1}}}),Ns=p({meta:{key:"agent-console.agent.toolAssigned",version:"1.0.0",description:"A tool was assigned to an agent.",stability:"stable",owners:[...u],tags:["agent","tool","assigned"]},payload:S0}),p0=l({name:"AgentToolRemovedPayload",description:"Payload for agent tool removed event",fields:{agentId:{type:B.String_unsecure(),isOptional:!1},toolId:{type:B.String_unsecure(),isOptional:!1},agentName:{type:B.String_unsecure(),isOptional:!1},toolName:{type:B.String_unsecure(),isOptional:!1},removedAt:{type:B.DateTime(),isOptional:!1}}}),Qs=p({meta:{key:"agent-console.agent.toolRemoved",version:"1.0.0",description:"A tool was removed from an agent.",stability:"stable",owners:[...u],tags:["agent","tool","removed"]},payload:p0});var N=[{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 Q=[{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")}];import{defineSchemaModel as c,ScalarTypeEnum as Z}from"@contractspec/lib.schema";var ds=c({name:"Agent",description:"AI agent configuration",fields:{id:{type:Z.String_unsecure(),isOptional:!1},organizationId:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!1},slug:{type:Z.String_unsecure(),isOptional:!1},description:{type:Z.String_unsecure(),isOptional:!0},status:{type:C,isOptional:!1},modelProvider:{type:t,isOptional:!1},modelName:{type:Z.NonEmptyString(),isOptional:!1},modelConfig:{type:Z.JSONObject(),isOptional:!0},systemPrompt:{type:Z.String_unsecure(),isOptional:!1},userPromptTemplate:{type:Z.String_unsecure(),isOptional:!0},toolIds:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:T,isOptional:!1,defaultValue:"auto"},maxIterations:{type:Z.Int_unsecure(),isOptional:!1,defaultValue:10},maxTokensPerRun:{type:Z.Int_unsecure(),isOptional:!0},timeoutMs:{type:Z.Int_unsecure(),isOptional:!1,defaultValue:120000},version:{type:Z.NonEmptyString(),isOptional:!1},tags:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:Z.DateTime(),isOptional:!1},updatedAt:{type:Z.DateTime(),isOptional:!1}}}),o0=c({name:"AgentSummary",description:"Summary of an agent for list views",fields:{id:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!1},slug:{type:Z.String_unsecure(),isOptional:!1},description:{type:Z.String_unsecure(),isOptional:!0},status:{type:C,isOptional:!1},modelProvider:{type:t,isOptional:!1},modelName:{type:Z.NonEmptyString(),isOptional:!1},version:{type:Z.NonEmptyString(),isOptional:!1},createdAt:{type:Z.DateTime(),isOptional:!1}}}),l0=c({name:"AgentToolRef",description:"Tool reference in agent context",fields:{id:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!1},slug:{type:Z.String_unsecure(),isOptional:!1},description:{type:Z.String_unsecure(),isOptional:!1},category:{type:Z.String_unsecure(),isOptional:!1}}}),U0=c({name:"AgentWithTools",description:"Agent with associated tools",fields:{id:{type:Z.String_unsecure(),isOptional:!1},organizationId:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!1},slug:{type:Z.String_unsecure(),isOptional:!1},description:{type:Z.String_unsecure(),isOptional:!0},status:{type:C,isOptional:!1},modelProvider:{type:t,isOptional:!1},modelName:{type:Z.NonEmptyString(),isOptional:!1},modelConfig:{type:Z.JSONObject(),isOptional:!0},systemPrompt:{type:Z.String_unsecure(),isOptional:!1},userPromptTemplate:{type:Z.String_unsecure(),isOptional:!0},toolIds:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:T,isOptional:!1},maxIterations:{type:Z.Int_unsecure(),isOptional:!1},maxTokensPerRun:{type:Z.Int_unsecure(),isOptional:!0},timeoutMs:{type:Z.Int_unsecure(),isOptional:!1},version:{type:Z.NonEmptyString(),isOptional:!1},tags:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:Z.DateTime(),isOptional:!1},updatedAt:{type:Z.DateTime(),isOptional:!1},tools:{type:l0,isArray:!0,isOptional:!0}}}),$0=c({name:"CreateAgentInput",description:"Input for creating an agent",fields:{organizationId:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!1},slug:{type:Z.String_unsecure(),isOptional:!1},description:{type:Z.String_unsecure(),isOptional:!0},modelProvider:{type:t,isOptional:!1},modelName:{type:Z.NonEmptyString(),isOptional:!1},modelConfig:{type:Z.JSONObject(),isOptional:!0},systemPrompt:{type:Z.String_unsecure(),isOptional:!1},userPromptTemplate:{type:Z.String_unsecure(),isOptional:!0},toolIds:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:T,isOptional:!0},maxIterations:{type:Z.Int_unsecure(),isOptional:!0},maxTokensPerRun:{type:Z.Int_unsecure(),isOptional:!0},timeoutMs:{type:Z.Int_unsecure(),isOptional:!0},tags:{type:Z.String_unsecure(),isArray:!0,isOptional:!0}}}),X0=c({name:"UpdateAgentInput",description:"Input for updating an agent",fields:{agentId:{type:Z.String_unsecure(),isOptional:!1},name:{type:Z.NonEmptyString(),isOptional:!0},description:{type:Z.String_unsecure(),isOptional:!0},status:{type:C,isOptional:!0},modelConfig:{type:Z.JSONObject(),isOptional:!0},systemPrompt:{type:Z.String_unsecure(),isOptional:!0},userPromptTemplate:{type:Z.String_unsecure(),isOptional:!0},toolIds:{type:Z.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:T,isOptional:!0},maxIterations:{type:Z.Int_unsecure(),isOptional:!0},maxTokensPerRun:{type:Z.Int_unsecure(),isOptional:!0},timeoutMs:{type:Z.Int_unsecure(),isOptional:!0},tags:{type:Z.String_unsecure(),isArray:!0,isOptional:!0}}});import{defineCommand as n,defineQuery as _0}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as K,ScalarTypeEnum as Y}from"@contractspec/lib.schema";var h=["@agent-console-team"],v0=n({meta:{key:"agent-console.agent.create",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","create"],description:"Creates a new AI agent configuration.",goal:"Allow users to define new AI agents with specific models and tools.",context:"Called from the agent builder UI when creating a new agent."},io:{input:$0,output:K({name:"CreateAgentOutput",fields:{id:{type:Y.String_unsecure(),isOptional:!1},name:{type:Y.NonEmptyString(),isOptional:!1},slug:{type:Y.String_unsecure(),isOptional:!1},status:{type:C,isOptional:!1}}}),errors:{SLUG_EXISTS:{description:"An agent with this slug already exists in the organization",http:409,gqlCode:"SLUG_EXISTS",when:"Slug is already taken"}}},policy:{auth:"user"},sideEffects:{emits:[{ref:G0.meta,when:"Agent is successfully created"}],audit:["agent-console.agent.created"]},acceptance:{scenarios:[{key:"create-agent-happy-path",given:["User is authenticated","Organization exists"],when:["User submits valid agent configuration"],then:["New agent is created with DRAFT status","AgentCreated event is emitted"]},{key:"create-agent-slug-conflict",given:["User is authenticated","Agent with same slug exists"],when:["User submits agent with duplicate slug"],then:["SLUG_EXISTS error is returned with 409 status"]}],examples:[{key:"basic-create",input:{name:"Support Assistant",slug:"support-assistant",modelProvider:"openai",modelId:"gpt-4"},output:{id:"agent-123",name:"Support Assistant",slug:"support-assistant",status:"draft"}}]}}),k0=n({meta:{key:"agent-console.agent.update",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","update"],description:"Updates an existing AI agent configuration.",goal:"Allow users to modify agent settings and configuration.",context:"Called from the agent settings UI."},io:{input:X0,output:K({name:"UpdateAgentOutput",fields:{id:{type:Y.String_unsecure(),isOptional:!1},name:{type:Y.NonEmptyString(),isOptional:!1},status:{type:C,isOptional:!1},updatedAt:{type:Y.DateTime(),isOptional:!1}}}),errors:{AGENT_NOT_FOUND:{description:"The specified agent does not exist",http:404,gqlCode:"AGENT_NOT_FOUND",when:"Agent ID is invalid"}}},policy:{auth:"user"},sideEffects:{emits:[{key:"agent.updated",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","updated"],when:"Agent is updated",payload:o0}],audit:["agent.updated"]},acceptance:{scenarios:[{key:"update-agent-happy-path",given:["Agent exists","User owns the agent"],when:["User submits updated configuration"],then:["Agent is updated","AgentUpdated event is emitted"]},{key:"update-agent-not-found",given:["Agent does not exist"],when:["User attempts to update"],then:["AGENT_NOT_FOUND error is returned"]}],examples:[{key:"update-name",input:{agentId:"agent-123",name:"Updated Assistant",systemPrompt:"You are a helpful assistant."},output:{id:"agent-123",name:"Updated Assistant",status:"draft",updatedAt:"2025-01-01T00:00:00Z"}}]}}),b0=_0({meta:{key:"agent-console.agent.get",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","get"],description:"Retrieves an agent by its ID.",goal:"View detailed agent configuration.",context:"Called when viewing agent details or editing."},io:{input:K({name:"GetAgentInput",fields:{agentId:{type:Y.String_unsecure(),isOptional:!1},includeTools:{type:Y.Boolean(),isOptional:!0}}}),output:U0,errors:{AGENT_NOT_FOUND:{description:"The specified agent does not exist",http:404,gqlCode:"AGENT_NOT_FOUND",when:"Agent ID is invalid"}}},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-agent-happy-path",given:["Agent exists"],when:["User requests agent by ID"],then:["Agent details are returned"]},{key:"get-agent-with-tools",given:["Agent exists with assigned tools"],when:["User requests agent with includeTools=true"],then:["Agent details with tools list are returned"]}],examples:[{key:"get-basic",input:{agentId:"agent-123",includeTools:!1},output:{id:"agent-123",name:"Support Assistant",status:"active",tools:[]}}]}}),H0=_0({meta:{key:"agent-console.agent.list",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","list"],description:"Lists agents for an organization with optional filtering.",goal:"Browse and search available agents.",context:"Agent list/dashboard view."},io:{input:K({name:"ListAgentsInput",fields:{organizationId:{type:Y.String_unsecure(),isOptional:!1},status:{type:C,isOptional:!0},modelProvider:{type:t,isOptional:!0},search:{type:Y.String_unsecure(),isOptional:!0},limit:{type:Y.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:Y.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:K({name:"ListAgentsOutput",fields:{items:{type:o0,isArray:!0,isOptional:!1},total:{type:Y.Int_unsecure(),isOptional:!1},hasMore:{type:Y.Boolean(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-agents-happy-path",given:["Organization has agents"],when:["User lists agents"],then:["Paginated list of agents is returned"]},{key:"list-agents-filter-by-status",given:["Organization has agents with mixed statuses"],when:["User filters by status=active"],then:["Only active agents are returned"]}],examples:[{key:"list-basic",input:{organizationId:"org-123",limit:10,offset:0},output:{items:[],total:0,hasMore:!1}}]}}),cs=n({meta:{key:"agent-console.agent.assignTool",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","tool","assign"],description:"Assigns a tool to an agent with optional configuration.",goal:"Enable agents to use specific tools.",context:"Agent configuration UI - tool selection."},io:{input:K({name:"AssignToolToAgentInput",fields:{agentId:{type:Y.String_unsecure(),isOptional:!1},toolId:{type:Y.String_unsecure(),isOptional:!1},config:{type:Y.JSONObject(),isOptional:!0},order:{type:Y.Int_unsecure(),isOptional:!0}}}),output:K({name:"AssignToolToAgentOutput",fields:{agentToolId:{type:Y.String_unsecure(),isOptional:!1},agentId:{type:Y.String_unsecure(),isOptional:!1},toolId:{type:Y.String_unsecure(),isOptional:!1}}}),errors:{TOOL_ALREADY_ASSIGNED:{description:"This tool is already assigned to the agent",http:409,gqlCode:"TOOL_ALREADY_ASSIGNED",when:"Tool assignment already exists"}}},policy:{auth:"user"},sideEffects:{audit:["agent.tool.assigned"]},acceptance:{scenarios:[{key:"assign-tool-happy-path",given:["Agent exists","Tool exists and is not assigned"],when:["User assigns tool to agent"],then:["Tool is assigned","Assignment ID is returned"]},{key:"assign-tool-already-assigned",given:["Tool is already assigned to agent"],when:["User attempts to assign again"],then:["TOOL_ALREADY_ASSIGNED error is returned"]}],examples:[{key:"assign-basic",input:{agentId:"agent-123",toolId:"tool-456"},output:{agentToolId:"at-789",agentId:"agent-123",toolId:"tool-456"}}]}}),rs=n({meta:{key:"agent-console.agent.removeTool",version:"1.0.0",stability:"stable",owners:[...h],tags:["agent","tool","remove"],description:"Removes a tool assignment from an agent.",goal:"Disable specific tools for an agent.",context:"Agent configuration UI - tool management."},io:{input:K({name:"RemoveToolFromAgentInput",fields:{agentId:{type:Y.String_unsecure(),isOptional:!1},toolId:{type:Y.String_unsecure(),isOptional:!1}}}),output:K({name:"RemoveToolFromAgentOutput",fields:{success:{type:Y.Boolean(),isOptional:!1}}})},policy:{auth:"user"},sideEffects:{audit:["agent.tool.removed"]},acceptance:{scenarios:[{key:"remove-tool-happy-path",given:["Agent exists","Tool is assigned to agent"],when:["User removes tool from agent"],then:["Tool is unassigned","Success is returned"]}],examples:[{key:"remove-basic",input:{agentId:"agent-123",toolId:"tool-456"},output:{success:!0}}]}});var u0=N.length+1;async function n0(s){let{organizationId:k,status:g,modelProvider:L,search:z,limit:J=20,offset:P=0}=s,F=N.filter((A)=>A.organizationId===k);if(g)F=F.filter((A)=>A.status===g);if(L)F=F.filter((A)=>A.modelProvider===L);if(z){let A=z.toLowerCase();F=F.filter((H)=>H.name.toLowerCase().includes(A)||H.description?.toLowerCase().includes(A)||H.tags?.some((q)=>q.toLowerCase().includes(A)))}let D=F.length;return{items:F.slice(P,P+J).map((A)=>({id:A.id,name:A.name,slug:A.slug,description:A.description,status:A.status,modelProvider:A.modelProvider,modelName:A.modelName,version:A.version,createdAt:A.createdAt})),total:D,hasMore:P+J<D}}async function a0(s){let k=N.find((L)=>L.id===s.agentId);if(!k)throw Error("AGENT_NOT_FOUND");let g={...k,toolIds:["tool-1","tool-2"]};if(s.includeTools)g.tools=Q.slice(0,2).map((L)=>({id:L.id,name:L.name,slug:L.slug,description:L.description,category:L.category}));return g}async function ss(s){if(N.some((g)=>g.organizationId===s.organizationId&&g.slug===s.slug))throw Error("SLUG_EXISTS");return{id:`agent-${u0++}`,name:s.name,slug:s.slug,status:"DRAFT"}}async function Es(s){let k=N.find((g)=>g.id===s.agentId);if(!k)throw Error("AGENT_NOT_FOUND");return{id:k.id,name:s.name??k.name,status:s.status??k.status,updatedAt:new Date}}import{defineEnum as a}from"@contractspec/lib.schema";var W=a("RunStatus",["QUEUED","IN_PROGRESS","COMPLETED","FAILED","CANCELLED","EXPIRED"]),N0=a("RunStepType",["MESSAGE_CREATION","TOOL_CALL","TOOL_RESULT","ERROR"]),s0=a("LogLevel",["DEBUG","INFO","WARN","ERROR"]),Q0=a("Granularity",["hour","day","week","month"]);import{defineSchemaModel as M,ScalarTypeEnum as v}from"@contractspec/lib.schema";var C0=M({name:"RunInput",description:"Input data for agent execution",fields:{message:{type:v.NonEmptyString(),isOptional:!1},context:{type:v.JSONObject(),isOptional:!0}}}),g0=M({name:"RunStep",description:"Individual step within a run",fields:{id:{type:v.String_unsecure(),isOptional:!1},stepNumber:{type:v.Int_unsecure(),isOptional:!1},type:{type:N0,isOptional:!1},toolId:{type:v.String_unsecure(),isOptional:!0},toolName:{type:v.String_unsecure(),isOptional:!0},input:{type:v.JSONObject(),isOptional:!0},output:{type:v.JSONObject(),isOptional:!0},status:{type:W,isOptional:!1},errorMessage:{type:v.String_unsecure(),isOptional:!0},tokensUsed:{type:v.Int_unsecure(),isOptional:!1,defaultValue:0},durationMs:{type:v.Int_unsecure(),isOptional:!0},startedAt:{type:v.DateTime(),isOptional:!1},completedAt:{type:v.DateTime(),isOptional:!0}}}),q0=M({name:"RunLog",description:"Execution log entry",fields:{id:{type:v.String_unsecure(),isOptional:!1},stepId:{type:v.String_unsecure(),isOptional:!0},level:{type:s0,isOptional:!1},message:{type:v.String_unsecure(),isOptional:!1},data:{type:v.JSONObject(),isOptional:!0},source:{type:v.String_unsecure(),isOptional:!0},traceId:{type:v.String_unsecure(),isOptional:!0},spanId:{type:v.String_unsecure(),isOptional:!0},timestamp:{type:v.DateTime(),isOptional:!1}}}),Ds=M({name:"RunAgentRef",description:"Agent reference in a run",fields:{id:{type:v.String_unsecure(),isOptional:!1},name:{type:v.NonEmptyString(),isOptional:!1},modelProvider:{type:v.String_unsecure(),isOptional:!1},modelName:{type:v.String_unsecure(),isOptional:!1}}}),K0=M({name:"Run",description:"Agent execution instance",fields:{id:{type:v.String_unsecure(),isOptional:!1},organizationId:{type:v.String_unsecure(),isOptional:!1},agentId:{type:v.String_unsecure(),isOptional:!1},userId:{type:v.String_unsecure(),isOptional:!0},sessionId:{type:v.String_unsecure(),isOptional:!0},input:{type:v.JSONObject(),isOptional:!1},output:{type:v.JSONObject(),isOptional:!0},status:{type:W,isOptional:!1},errorMessage:{type:v.String_unsecure(),isOptional:!0},errorCode:{type:v.String_unsecure(),isOptional:!0},totalTokens:{type:v.Int_unsecure(),isOptional:!1,defaultValue:0},promptTokens:{type:v.Int_unsecure(),isOptional:!1,defaultValue:0},completionTokens:{type:v.Int_unsecure(),isOptional:!1,defaultValue:0},totalIterations:{type:v.Int_unsecure(),isOptional:!1,defaultValue:0},durationMs:{type:v.Int_unsecure(),isOptional:!0},estimatedCostUsd:{type:v.Float_unsecure(),isOptional:!0},queuedAt:{type:v.DateTime(),isOptional:!1},startedAt:{type:v.DateTime(),isOptional:!0},completedAt:{type:v.DateTime(),isOptional:!0},metadata:{type:v.JSONObject(),isOptional:!0},steps:{type:g0,isArray:!0,isOptional:!0},logs:{type:q0,isArray:!0,isOptional:!0},agent:{type:Ds,isOptional:!0}}}),D0=M({name:"RunSummary",description:"Summary of a run for list views",fields:{id:{type:v.String_unsecure(),isOptional:!1},agentId:{type:v.String_unsecure(),isOptional:!1},agentName:{type:v.NonEmptyString(),isOptional:!1},status:{type:W,isOptional:!1},totalTokens:{type:v.Int_unsecure(),isOptional:!1},durationMs:{type:v.Int_unsecure(),isOptional:!0},estimatedCostUsd:{type:v.Float_unsecure(),isOptional:!0},queuedAt:{type:v.DateTime(),isOptional:!1},completedAt:{type:v.DateTime(),isOptional:!0}}}),R0=M({name:"TimelineDataPoint",description:"Timeline data point for metrics",fields:{period:{type:v.String_unsecure(),isOptional:!1},runs:{type:v.Int_unsecure(),isOptional:!1},tokens:{type:v.Int_unsecure(),isOptional:!1},costUsd:{type:v.Float_unsecure(),isOptional:!1},avgDurationMs:{type:v.Float_unsecure(),isOptional:!1}}});import{defineCommand as O0,defineQuery as y}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as _,ScalarTypeEnum as j}from"@contractspec/lib.schema";var R=["@agent-console-team"],j0=O0({meta:{key:"agent.run.execute",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","execute"],description:"Starts a new agent run with the given input.",goal:"Execute an AI agent with user input.",context:"Called from chat interface or API."},io:{input:_({name:"ExecuteAgentInput",fields:{agentId:{type:j.String_unsecure(),isOptional:!1},input:{type:C0,isOptional:!1},sessionId:{type:j.String_unsecure(),isOptional:!0},metadata:{type:j.JSONObject(),isOptional:!0},stream:{type:j.Boolean(),isOptional:!0},maxIterations:{type:j.Int_unsecure(),isOptional:!0},timeoutMs:{type:j.Int_unsecure(),isOptional:!0}}}),output:_({name:"ExecuteAgentOutput",fields:{runId:{type:j.String_unsecure(),isOptional:!1},status:{type:W,isOptional:!1},estimatedWaitMs:{type:j.Int_unsecure(),isOptional:!0}}}),errors:{AGENT_NOT_FOUND:{description:"The specified agent does not exist",http:404,gqlCode:"AGENT_NOT_FOUND",when:"Agent ID is invalid"},AGENT_NOT_ACTIVE:{description:"The specified agent is not active",http:400,gqlCode:"AGENT_NOT_ACTIVE",when:"Agent is in draft/paused/archived state"}}},policy:{auth:"user"},sideEffects:{emits:[{key:"run.started",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","started"],when:"Run is queued",payload:D0}],audit:["run.started"]},acceptance:{scenarios:[{key:"execute-agent-happy-path",given:["Agent exists","Agent is active"],when:["User submits execution request"],then:["Run is created","RunStarted event is emitted"]},{key:"execute-agent-not-active",given:["Agent exists but is not active"],when:["User attempts to execute"],then:["AGENT_NOT_ACTIVE error is returned"]}],examples:[{key:"basic-execute",input:{agentId:"agent-123",input:{message:"Hello"}},output:{runId:"run-456",status:"pending",estimatedWaitMs:5000}}]}}),As=O0({meta:{key:"agent.run.cancel",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","cancel"],description:"Cancels an in-progress agent run.",goal:"Stop a running agent execution.",context:"Called when user wants to abort a long-running task."},io:{input:_({name:"CancelRunInput",fields:{runId:{type:j.String_unsecure(),isOptional:!1},reason:{type:j.String_unsecure(),isOptional:!0}}}),output:_({name:"CancelRunOutput",fields:{success:{type:j.Boolean(),isOptional:!1},status:{type:W,isOptional:!1}}}),errors:{RUN_NOT_FOUND:{description:"The specified run does not exist",http:404,gqlCode:"RUN_NOT_FOUND",when:"Run ID is invalid"},RUN_NOT_CANCELLABLE:{description:"The run cannot be cancelled",http:400,gqlCode:"RUN_NOT_CANCELLABLE",when:"Run is already completed/failed/cancelled"}}},policy:{auth:"user"},sideEffects:{emits:[{key:"run.cancelled",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","cancelled"],when:"Run is cancelled",payload:D0}],audit:["run.cancelled"]},acceptance:{scenarios:[{key:"cancel-run-happy-path",given:["Run exists","Run is in progress"],when:["User cancels run"],then:["Run is cancelled","RunCancelled event is emitted"]},{key:"cancel-run-already-completed",given:["Run exists but is already completed"],when:["User attempts to cancel"],then:["RUN_NOT_CANCELLABLE error is returned"]}],examples:[{key:"cancel-basic",input:{runId:"run-456",reason:"User requested"},output:{success:!0,status:"cancelled"}}]}}),Is=y({meta:{key:"agent.run.get",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","get"],description:"Retrieves a run by its ID with optional details.",goal:"View detailed run information.",context:"Run details page or monitoring."},io:{input:_({name:"GetRunInput",fields:{runId:{type:j.String_unsecure(),isOptional:!1},includeSteps:{type:j.Boolean(),isOptional:!0},includeLogs:{type:j.Boolean(),isOptional:!0}}}),output:K0,errors:{RUN_NOT_FOUND:{description:"The specified run does not exist",http:404,gqlCode:"RUN_NOT_FOUND",when:"Run ID is invalid"}}},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-run-happy-path",given:["Run exists"],when:["User requests run by ID"],then:["Run details are returned"]}],examples:[{key:"get-with-steps",input:{runId:"run-456",includeSteps:!0,includeLogs:!1},output:{id:"run-456",status:"completed",steps:[]}}]}}),z0=y({meta:{key:"agent.run.list",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","list"],description:"Lists runs with optional filtering.",goal:"Browse and search run history.",context:"Run history/dashboard view."},io:{input:_({name:"ListRunsInput",fields:{organizationId:{type:j.String_unsecure(),isOptional:!0},agentId:{type:j.String_unsecure(),isOptional:!0},userId:{type:j.String_unsecure(),isOptional:!0},sessionId:{type:j.String_unsecure(),isOptional:!0},status:{type:W,isOptional:!0},startDate:{type:j.DateTime(),isOptional:!0},endDate:{type:j.DateTime(),isOptional:!0},limit:{type:j.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:j.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:_({name:"ListRunsOutput",fields:{items:{type:D0,isArray:!0,isOptional:!1},total:{type:j.Int_unsecure(),isOptional:!1},hasMore:{type:j.Boolean(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-runs-happy-path",given:["Organization has runs"],when:["User lists runs"],then:["Paginated list of runs is returned"]}],examples:[{key:"list-by-agent",input:{agentId:"agent-123",limit:20,offset:0},output:{items:[],total:0,hasMore:!1}}]}}),Z2=y({meta:{key:"agent.run.getSteps",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","steps"],description:"Retrieves all steps for a specific run.",goal:"View step-by-step execution details.",context:"Run details page - steps tab."},io:{input:_({name:"GetRunStepsInput",fields:{runId:{type:j.String_unsecure(),isOptional:!1}}}),output:_({name:"GetRunStepsOutput",fields:{steps:{type:g0,isArray:!0,isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-run-steps-happy-path",given:["Run exists with steps"],when:["User requests steps"],then:["Steps list is returned"]}],examples:[{key:"get-steps-basic",input:{runId:"run-456"},output:{steps:[]}}]}}),P2=y({meta:{key:"agent.run.getLogs",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","logs"],description:"Retrieves all logs for a specific run.",goal:"Debug and audit run execution.",context:"Run details page - logs tab."},io:{input:_({name:"GetRunLogsInput",fields:{runId:{type:j.String_unsecure(),isOptional:!1},level:{type:s0,isOptional:!0},stepId:{type:j.String_unsecure(),isOptional:!0},limit:{type:j.Int_unsecure(),isOptional:!0,defaultValue:100},offset:{type:j.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:_({name:"GetRunLogsOutput",fields:{items:{type:q0,isArray:!0,isOptional:!1},total:{type:j.Int_unsecure(),isOptional:!1},hasMore:{type:j.Boolean(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-run-logs-happy-path",given:["Run exists with logs"],when:["User requests logs"],then:["Paginated logs list is returned"]}],examples:[{key:"get-logs-filtered",input:{runId:"run-456",level:"error",limit:50},output:{items:[],total:0,hasMore:!1}}]}}),Zs=y({meta:{key:"agent.run.getMetrics",version:"1.0.0",stability:"stable",owners:[...R],tags:["run","metrics"],description:"Retrieves aggregated metrics for runs within a time period.",goal:"Monitor and analyze agent usage.",context:"Analytics dashboard."},io:{input:_({name:"GetRunMetricsInput",fields:{organizationId:{type:j.String_unsecure(),isOptional:!1},agentId:{type:j.String_unsecure(),isOptional:!0},startDate:{type:j.DateTime(),isOptional:!1},endDate:{type:j.DateTime(),isOptional:!1},granularity:{type:Q0,isOptional:!0,defaultValue:"day"}}}),output:_({name:"GetRunMetricsOutput",fields:{totalRuns:{type:j.Int_unsecure(),isOptional:!1},completedRuns:{type:j.Int_unsecure(),isOptional:!1},failedRuns:{type:j.Int_unsecure(),isOptional:!1},totalTokens:{type:j.Int_unsecure(),isOptional:!1},totalCostUsd:{type:j.Float_unsecure(),isOptional:!1},averageDurationMs:{type:j.Float_unsecure(),isOptional:!1},successRate:{type:j.Float_unsecure(),isOptional:!1},timeline:{type:R0,isArray:!0,isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-run-metrics-happy-path",given:["Organization has run history"],when:["User requests metrics for date range"],then:["Aggregated metrics are returned"]}],examples:[{key:"get-daily-metrics",input:{organizationId:"org-123",startDate:"2025-01-01",endDate:"2025-01-31",granularity:"day"},output:{totalRuns:100,completedRuns:90,failedRuns:10,totalTokens:50000,totalCostUsd:5,averageDurationMs:2500,successRate:0.9,timeline:[]}}]}});import{defineEnum as V0}from"@contractspec/lib.schema";var r=V0("ToolCategory",["RETRIEVAL","COMPUTATION","COMMUNICATION","INTEGRATION","UTILITY","CUSTOM"]),d=V0("ToolStatus",["DRAFT","ACTIVE","DEPRECATED","DISABLED"]),x0=V0("ImplementationType",["http","function","workflow"]);import{defineSchemaModel as A0,ScalarTypeEnum as V}from"@contractspec/lib.schema";var W0=A0({name:"Tool",description:"AI tool definition",fields:{id:{type:V.String_unsecure(),isOptional:!1},organizationId:{type:V.String_unsecure(),isOptional:!1},name:{type:V.NonEmptyString(),isOptional:!1},slug:{type:V.String_unsecure(),isOptional:!1},description:{type:V.String_unsecure(),isOptional:!1},category:{type:r,isOptional:!1},status:{type:d,isOptional:!1},parametersSchema:{type:V.JSONObject(),isOptional:!1},outputSchema:{type:V.JSONObject(),isOptional:!0},implementationType:{type:x0,isOptional:!1},implementationConfig:{type:V.JSONObject(),isOptional:!1},maxInvocationsPerMinute:{type:V.Int_unsecure(),isOptional:!0},timeoutMs:{type:V.Int_unsecure(),isOptional:!1,defaultValue:30000},version:{type:V.NonEmptyString(),isOptional:!1},tags:{type:V.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:V.DateTime(),isOptional:!1},updatedAt:{type:V.DateTime(),isOptional:!1}}}),I0=A0({name:"ToolSummary",description:"Summary of a tool for list views",fields:{id:{type:V.String_unsecure(),isOptional:!1},name:{type:V.NonEmptyString(),isOptional:!1},slug:{type:V.String_unsecure(),isOptional:!1},description:{type:V.String_unsecure(),isOptional:!1},category:{type:r,isOptional:!1},status:{type:d,isOptional:!1},version:{type:V.NonEmptyString(),isOptional:!1},createdAt:{type:V.DateTime(),isOptional:!1}}}),d0=A0({name:"CreateToolInput",description:"Input for creating a tool",fields:{organizationId:{type:V.String_unsecure(),isOptional:!1},name:{type:V.NonEmptyString(),isOptional:!1},slug:{type:V.String_unsecure(),isOptional:!1},description:{type:V.String_unsecure(),isOptional:!1},category:{type:r,isOptional:!0},parametersSchema:{type:V.JSONObject(),isOptional:!1},outputSchema:{type:V.JSONObject(),isOptional:!0},implementationType:{type:x0,isOptional:!1},implementationConfig:{type:V.JSONObject(),isOptional:!1},maxInvocationsPerMinute:{type:V.Int_unsecure(),isOptional:!0},timeoutMs:{type:V.Int_unsecure(),isOptional:!0},tags:{type:V.String_unsecure(),isArray:!0,isOptional:!0}}}),t0=A0({name:"UpdateToolInput",description:"Input for updating a tool",fields:{toolId:{type:V.String_unsecure(),isOptional:!1},name:{type:V.NonEmptyString(),isOptional:!0},description:{type:V.String_unsecure(),isOptional:!0},status:{type:d,isOptional:!0},parametersSchema:{type:V.JSONObject(),isOptional:!0},outputSchema:{type:V.JSONObject(),isOptional:!0},implementationConfig:{type:V.JSONObject(),isOptional:!0},maxInvocationsPerMinute:{type:V.Int_unsecure(),isOptional:!0},timeoutMs:{type:V.Int_unsecure(),isOptional:!0},tags:{type:V.String_unsecure(),isArray:!0,isOptional:!0}}});import{defineCommand as L0,defineQuery as h0}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as w,ScalarTypeEnum as U}from"@contractspec/lib.schema";var f=["@agent-console-team"],Ps=L0({meta:{key:"agent.tool.create",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","create"],description:"Creates a new AI tool definition.",goal:"Allow users to define new tools that agents can use.",context:"Called from the tool builder UI when creating a new tool."},io:{input:d0,output:w({name:"CreateToolOutput",fields:{id:{type:U.String_unsecure(),isOptional:!1},name:{type:U.NonEmptyString(),isOptional:!1},slug:{type:U.String_unsecure(),isOptional:!1},status:{type:d,isOptional:!1}}}),errors:{SLUG_EXISTS:{description:"A tool with this slug already exists in the organization",http:409,gqlCode:"SLUG_EXISTS",when:"Slug is already taken"}}},policy:{auth:"user"},sideEffects:{emits:[{key:"tool.created",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","created"],when:"Tool is successfully created",payload:I0}],audit:["tool.created"]},acceptance:{scenarios:[{key:"create-tool-happy-path",given:["User is authenticated","Organization exists"],when:["User submits valid tool configuration"],then:["New tool is created","ToolCreated event is emitted"]},{key:"create-tool-slug-conflict",given:["Tool with same slug exists"],when:["User submits tool with duplicate slug"],then:["SLUG_EXISTS error is returned"]}],examples:[{key:"create-api-tool",input:{name:"Weather API",slug:"weather-api",category:"api",description:"Fetches weather data"},output:{id:"tool-123",name:"Weather API",slug:"weather-api",status:"draft"}}]}}),os=L0({meta:{key:"agent.tool.update",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","update"],description:"Updates an existing AI tool definition.",goal:"Allow users to modify tool settings and configuration.",context:"Called from the tool settings UI."},io:{input:t0,output:w({name:"UpdateToolOutput",fields:{id:{type:U.String_unsecure(),isOptional:!1},name:{type:U.NonEmptyString(),isOptional:!1},status:{type:d,isOptional:!1},updatedAt:{type:U.DateTime(),isOptional:!1}}}),errors:{TOOL_NOT_FOUND:{description:"The specified tool does not exist",http:404,gqlCode:"TOOL_NOT_FOUND",when:"Tool ID is invalid"}}},policy:{auth:"user"},sideEffects:{emits:[{key:"tool.updated",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","updated"],when:"Tool is updated",payload:I0}],audit:["tool.updated"]},acceptance:{scenarios:[{key:"update-tool-happy-path",given:["Tool exists","User owns the tool"],when:["User submits updated configuration"],then:["Tool is updated","ToolUpdated event is emitted"]}],examples:[{key:"update-description",input:{toolId:"tool-123",description:"Updated weather API tool"},output:{id:"tool-123",name:"Weather API",status:"draft",updatedAt:"2025-01-01T00:00:00Z"}}]}}),vs=h0({meta:{key:"agent.tool.get",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","get"],description:"Retrieves a tool by its ID.",goal:"View detailed tool configuration.",context:"Called when viewing tool details or editing."},io:{input:w({name:"GetToolInput",fields:{toolId:{type:U.String_unsecure(),isOptional:!1}}}),output:W0,errors:{TOOL_NOT_FOUND:{description:"The specified tool does not exist",http:404,gqlCode:"TOOL_NOT_FOUND",when:"Tool ID is invalid"}}},policy:{auth:"user"},acceptance:{scenarios:[{key:"get-tool-happy-path",given:["Tool exists"],when:["User requests tool by ID"],then:["Tool details are returned"]}],examples:[{key:"get-basic",input:{toolId:"tool-123"},output:{id:"tool-123",name:"Weather API",status:"active",category:"api"}}]}}),B0=h0({meta:{key:"agent.tool.list",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","list"],description:"Lists tools for an organization with optional filtering.",goal:"Browse and search available tools.",context:"Tool list/dashboard view."},io:{input:w({name:"ListToolsInput",fields:{organizationId:{type:U.String_unsecure(),isOptional:!1},category:{type:r,isOptional:!0},status:{type:d,isOptional:!0},search:{type:U.String_unsecure(),isOptional:!0},limit:{type:U.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:U.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:w({name:"ListToolsOutput",fields:{items:{type:I0,isArray:!0,isOptional:!1},total:{type:U.Int_unsecure(),isOptional:!1},hasMore:{type:U.Boolean(),isOptional:!1}}})},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-tools-happy-path",given:["Organization has tools"],when:["User lists tools"],then:["Paginated list of tools is returned"]}],examples:[{key:"list-by-category",input:{organizationId:"org-123",category:"api",limit:10},output:{items:[],total:0,hasMore:!1}}]}}),ks=L0({meta:{key:"agent.tool.test",version:"1.0.0",stability:"stable",owners:[...f],tags:["tool","test"],description:"Tests a tool with sample input to verify it works correctly.",goal:"Validate tool configuration before deployment.",context:"Tool builder UI - test panel."},io:{input:w({name:"TestToolInput",fields:{toolId:{type:U.String_unsecure(),isOptional:!1},testInput:{type:U.JSONObject(),isOptional:!1}}}),output:w({name:"TestToolOutput",fields:{success:{type:U.Boolean(),isOptional:!1},output:{type:U.JSONObject(),isOptional:!0},error:{type:U.String_unsecure(),isOptional:!0},durationMs:{type:U.Int_unsecure(),isOptional:!1}}}),errors:{TOOL_NOT_FOUND:{description:"The specified tool does not exist",http:404,gqlCode:"TOOL_NOT_FOUND",when:"Tool ID is invalid"},TOOL_EXECUTION_ERROR:{description:"Tool execution failed",http:500,gqlCode:"TOOL_EXECUTION_ERROR",when:"Tool returns an error"}}},policy:{auth:"user"},sideEffects:{audit:["tool.tested"]},acceptance:{scenarios:[{key:"test-tool-success",given:["Tool exists","Tool is configured correctly"],when:["User runs test with valid input"],then:["Tool executes successfully","Output is returned"]},{key:"test-tool-failure",given:["Tool exists","Tool has configuration error"],when:["User runs test"],then:["TOOL_EXECUTION_ERROR is returned"]}],examples:[{key:"test-weather-api",input:{toolId:"tool-123",testInput:{city:"Paris"}},output:{success:!0,output:{temperature:22},durationMs:150}}]}});import{web as Hs}from"@contractspec/lib.runtime-sandbox";var{generateId:M0}=Hs;var w0={queuedAt:"r.queuedAt",totalTokens:"r.totalTokens",durationMs:"r.durationMs",estimatedCostUsd:"r.estimatedCostUsd",status:"r.status",agentName:"a.name"};function Z0(s){return{id:s.id,projectId:s.projectId,organizationId:s.organizationId,name:s.name,description:s.description??void 0,modelProvider:s.modelProvider,modelName:s.modelName,systemPrompt:s.systemPrompt??void 0,temperature:s.temperature,maxTokens:s.maxTokens,status:s.status,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}function gs(s){return{id:s.id,projectId:s.projectId,organizationId:s.organizationId,name:s.name,description:s.description??void 0,version:s.version,category:s.category,status:s.status,inputSchema:s.inputSchema??void 0,outputSchema:s.outputSchema??void 0,endpoint:s.endpoint??void 0,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}function f0(s,k){return{id:s.id,projectId:s.projectId,agentId:s.agentId,agentName:k,status:s.status,input:s.input??void 0,output:s.output??void 0,totalTokens:s.totalTokens,promptTokens:s.promptTokens,completionTokens:s.completionTokens,estimatedCostUsd:s.estimatedCostUsd,durationMs:s.durationMs??void 0,errorMessage:s.errorMessage??void 0,queuedAt:new Date(s.queuedAt),startedAt:s.startedAt?new Date(s.startedAt):void 0,completedAt:s.completedAt?new Date(s.completedAt):void 0}}function G2(s){async function k(I){let{projectId:A,organizationId:H,status:q,search:o,limit:x=20,offset:$=0}=I,X="WHERE projectId = ?",G=[A];if(H)X+=" AND organizationId = ?",G.push(H);if(q&&q!=="all")X+=" AND status = ?",G.push(q);if(o)X+=" AND (name LIKE ? OR description LIKE ?)",G.push(`%${o}%`,`%${o}%`);let E=(await s.query(`SELECT COUNT(*) as count FROM agent_definition ${X}`,G)).rows[0]?.count??0,O=(await s.query(`SELECT * FROM agent_definition ${X} ORDER BY createdAt DESC LIMIT ? OFFSET ?`,[...G,x,$])).rows;return{items:O.map(Z0),total:E,hasMore:$+O.length<E}}async function g(I){let A=(await s.query("SELECT * FROM agent_definition WHERE id = ?",[I])).rows;return A[0]?Z0(A[0]):null}async function L(I,A){let H=M0("agent"),q=new Date().toISOString();await s.execute(`INSERT INTO agent_definition (id, projectId, organizationId, name, description, modelProvider, modelName, systemPrompt, temperature, maxTokens, status, createdAt, updatedAt)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[H,A.projectId,A.organizationId,I.name,I.description??null,I.modelProvider??"openai",I.modelName??"gpt-4",I.systemPrompt??null,I.temperature??0.7,I.maxTokens??4096,"DRAFT",q,q]);let x=(await s.query("SELECT * FROM agent_definition WHERE id = ?",[H])).rows[0];if(!x)throw Error("Failed to retrieve created agent");return Z0(x)}async function z(I){let A=new Date().toISOString(),H=["updatedAt = ?"],q=[A];if(I.name!==void 0)H.push("name = ?"),q.push(I.name);if(I.description!==void 0)H.push("description = ?"),q.push(I.description);if(I.status!==void 0)H.push("status = ?"),q.push(I.status);q.push(I.id),await s.execute(`UPDATE agent_definition SET ${H.join(", ")} WHERE id = ?`,q);let o=(await s.query("SELECT * FROM agent_definition WHERE id = ?",[I.id])).rows;if(!o[0])throw Error("NOT_FOUND");return Z0(o[0])}async function J(I){let{projectId:A,organizationId:H,category:q,status:o,search:x,limit:$=50,offset:X=0}=I,G="WHERE projectId = ?",b=[A];if(H)G+=" AND organizationId = ?",b.push(H);if(q&&q!=="all")G+=" AND category = ?",b.push(q);if(o&&o!=="all")G+=" AND status = ?",b.push(o);if(x)G+=" AND (name LIKE ? OR description LIKE ?)",b.push(`%${x}%`,`%${x}%`);let O=(await s.query(`SELECT COUNT(*) as count FROM agent_tool ${G}`,b)).rows[0]?.count??0,S=(await s.query(`SELECT * FROM agent_tool ${G} ORDER BY name ASC LIMIT ? OFFSET ?`,[...b,$,X])).rows;return{items:S.map(gs),total:O,hasMore:X+S.length<O}}async function P(I){let{projectId:A,agentId:H,status:q,sortBy:o,sortDirection:x="desc",limit:$=20,offset:X=0}=I,G="WHERE r.projectId = ?",b=[A];if(H)G+=" AND r.agentId = ?",b.push(H);if(q&&q!=="all")G+=" AND r.status = ?",b.push(q);let O=(await s.query(`SELECT COUNT(*) as count FROM agent_run r ${G}`,b)).rows[0]?.count??0,S=o?w0[o]:w0.queuedAt,m0=x==="asc"?"ASC":"DESC",Y0=(await s.query(`SELECT r.*, a.name as agentName
2376
4
  FROM agent_run r
2377
5
  LEFT JOIN agent_definition a ON r.agentId = a.id
2378
- ${whereClause}
2379
- ORDER BY ${sortColumn} ${direction}, r.queuedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
2380
- return {
2381
- items: rows.map((r) => rowToRun(r, r.agentName)),
2382
- total,
2383
- hasMore: offset + rows.length < total
2384
- };
2385
- }
2386
- async function getRunMetrics(input) {
2387
- let whereClause = "WHERE projectId = ?";
2388
- const params = [input.projectId];
2389
- if (input.agentId) {
2390
- whereClause += " AND agentId = ?";
2391
- params.push(input.agentId);
2392
- }
2393
- if (input.startDate) {
2394
- whereClause += " AND queuedAt >= ?";
2395
- params.push(input.startDate.toISOString());
2396
- }
2397
- if (input.endDate) {
2398
- whereClause += " AND queuedAt <= ?";
2399
- params.push(input.endDate.toISOString());
2400
- }
2401
- const result = (await db.query(`SELECT
6
+ ${G}
7
+ ORDER BY ${S} ${m0}, r.queuedAt DESC LIMIT ? OFFSET ?`,[...b,$,X])).rows;return{items:Y0.map((F0)=>f0(F0,F0.agentName)),total:O,hasMore:X+Y0.length<O}}async function F(I){let A="WHERE projectId = ?",H=[I.projectId];if(I.agentId)A+=" AND agentId = ?",H.push(I.agentId);if(I.startDate)A+=" AND queuedAt >= ?",H.push(I.startDate.toISOString());if(I.endDate)A+=" AND queuedAt <= ?",H.push(I.endDate.toISOString());let o=(await s.query(`SELECT
2402
8
  COUNT(*) as totalRuns,
2403
9
  SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completedRuns,
2404
10
  AVG(CASE WHEN status = 'COMPLETED' THEN durationMs ELSE NULL END) as avgDuration,
2405
11
  COALESCE(SUM(totalTokens), 0) as totalTokens,
2406
12
  COALESCE(SUM(estimatedCostUsd), 0) as totalCost
2407
- FROM agent_run ${whereClause}`, params)).rows;
2408
- const data = result[0];
2409
- const totalRuns = data?.totalRuns ?? 0;
2410
- const completedRuns = data?.completedRuns ?? 0;
2411
- return {
2412
- totalRuns,
2413
- successRate: totalRuns > 0 ? completedRuns / totalRuns : 0,
2414
- averageDurationMs: data?.avgDuration ?? 0,
2415
- totalTokens: data?.totalTokens ?? 0,
2416
- totalCostUsd: data?.totalCost ?? 0
2417
- };
2418
- }
2419
- async function executeAgent(input) {
2420
- const agent = await getAgent(input.agentId);
2421
- if (!agent)
2422
- throw new Error("AGENT_NOT_FOUND");
2423
- if (agent.status !== "ACTIVE")
2424
- throw new Error("AGENT_NOT_ACTIVE");
2425
- const id = generateId("run");
2426
- const now = new Date().toISOString();
2427
- const pid = input.context?.projectId ?? agent.projectId;
2428
- await db.execute(`INSERT INTO agent_run (id, projectId, agentId, status, input, totalTokens, promptTokens, completionTokens, estimatedCostUsd, queuedAt)
2429
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [id, pid, input.agentId, "QUEUED", input.message, 0, 0, 0, 0, now]);
2430
- const rows = (await db.query(`SELECT r.*, a.name as agentName FROM agent_run r LEFT JOIN agent_definition a ON r.agentId = a.id WHERE r.id = ?`, [id])).rows;
2431
- if (!rows[0])
2432
- throw new Error("Failed to retrieve created run");
2433
- return rowToRun(rows[0], rows[0].agentName);
2434
- }
2435
- return {
2436
- listAgents,
2437
- getAgent,
2438
- createAgent,
2439
- updateAgent,
2440
- executeAgent,
2441
- listTools,
2442
- listRuns,
2443
- getRunMetrics
2444
- };
2445
- }
2446
-
2447
- // src/shared/mock-runs.ts
2448
- var MOCK_RUNS = [
2449
- {
2450
- id: "run-1",
2451
- organizationId: "demo-org",
2452
- projectId: "demo-project",
2453
- agentId: "agent-1",
2454
- agentName: "Customer Support Bot",
2455
- userId: "user-1",
2456
- sessionId: "session-1",
2457
- input: { message: "How do I reset my password?", context: {} },
2458
- output: { response: "You can reset your password by clicking..." },
2459
- status: "COMPLETED",
2460
- totalTokens: 1250,
2461
- promptTokens: 800,
2462
- completionTokens: 450,
2463
- totalIterations: 3,
2464
- durationMs: 4500,
2465
- estimatedCostUsd: 0.0025,
2466
- queuedAt: new Date("2024-04-15T10:00:00Z"),
2467
- startedAt: new Date("2024-04-15T10:00:01Z"),
2468
- completedAt: new Date("2024-04-15T10:00:05Z"),
2469
- steps: [],
2470
- logs: []
2471
- },
2472
- {
2473
- id: "run-2",
2474
- organizationId: "demo-org",
2475
- projectId: "demo-project",
2476
- agentId: "agent-2",
2477
- agentName: "Code Review Assistant",
2478
- userId: "user-2",
2479
- input: { message: "Review PR #123", context: { prNumber: 123 } },
2480
- status: "IN_PROGRESS",
2481
- totalTokens: 3500,
2482
- promptTokens: 3000,
2483
- completionTokens: 500,
2484
- totalIterations: 5,
2485
- queuedAt: new Date("2024-04-15T10:30:00Z"),
2486
- startedAt: new Date("2024-04-15T10:30:02Z"),
2487
- steps: [],
2488
- logs: []
2489
- },
2490
- {
2491
- id: "run-3",
2492
- organizationId: "demo-org",
2493
- projectId: "demo-project",
2494
- agentId: "agent-1",
2495
- agentName: "Customer Support Bot",
2496
- userId: "user-1",
2497
- input: { message: "What are your business hours?" },
2498
- output: { response: "Our business hours are 9 AM to 5 PM EST..." },
2499
- status: "COMPLETED",
2500
- totalTokens: 800,
2501
- promptTokens: 500,
2502
- completionTokens: 300,
2503
- totalIterations: 2,
2504
- durationMs: 2100,
2505
- estimatedCostUsd: 0.0012,
2506
- queuedAt: new Date("2024-04-15T09:00:00Z"),
2507
- startedAt: new Date("2024-04-15T09:00:01Z"),
2508
- completedAt: new Date("2024-04-15T09:00:03Z"),
2509
- steps: [],
2510
- logs: []
2511
- },
2512
- {
2513
- id: "run-4",
2514
- organizationId: "demo-org",
2515
- projectId: "demo-project",
2516
- agentId: "agent-3",
2517
- agentName: "Data Analyst",
2518
- userId: "user-3",
2519
- input: { message: "Generate sales report for Q1" },
2520
- status: "FAILED",
2521
- errorMessage: "Database connection timeout",
2522
- errorCode: "DB_TIMEOUT",
2523
- totalTokens: 2000,
2524
- promptTokens: 1500,
2525
- completionTokens: 500,
2526
- totalIterations: 8,
2527
- durationMs: 45000,
2528
- queuedAt: new Date("2024-04-14T15:00:00Z"),
2529
- startedAt: new Date("2024-04-14T15:00:05Z"),
2530
- completedAt: new Date("2024-04-14T15:00:50Z"),
2531
- steps: [],
2532
- logs: []
2533
- },
2534
- {
2535
- id: "run-5",
2536
- organizationId: "demo-org",
2537
- projectId: "demo-project",
2538
- agentId: "agent-2",
2539
- agentName: "Code Review Assistant",
2540
- userId: "user-2",
2541
- input: { message: "Review PR #120" },
2542
- output: { response: "Code review complete. 3 suggestions..." },
2543
- status: "COMPLETED",
2544
- totalTokens: 5200,
2545
- promptTokens: 4000,
2546
- completionTokens: 1200,
2547
- totalIterations: 7,
2548
- durationMs: 15000,
2549
- estimatedCostUsd: 0.0156,
2550
- queuedAt: new Date("2024-04-14T11:00:00Z"),
2551
- startedAt: new Date("2024-04-14T11:00:03Z"),
2552
- completedAt: new Date("2024-04-14T11:00:18Z"),
2553
- steps: [],
2554
- logs: []
2555
- }
2556
- ];
2557
-
2558
- // src/run/run.handler.ts
2559
- var nextMockRunId = MOCK_RUNS.length + 1;
2560
- async function mockListRunsHandler(input) {
2561
- const { agentId, status, limit = 20, offset = 0 } = input;
2562
- let filtered = [...MOCK_RUNS];
2563
- if (agentId)
2564
- filtered = filtered.filter((r) => r.agentId === agentId);
2565
- if (status)
2566
- filtered = filtered.filter((r) => r.status === status);
2567
- const total = filtered.length;
2568
- const items = filtered.slice(offset, offset + limit).map((r) => {
2569
- const agent = MOCK_AGENTS.find((a) => a.id === r.agentId);
2570
- return {
2571
- id: r.id,
2572
- agentId: r.agentId,
2573
- agentName: agent?.name ?? "Unknown",
2574
- status: r.status,
2575
- totalTokens: r.totalTokens,
2576
- durationMs: r.durationMs,
2577
- estimatedCostUsd: r.estimatedCostUsd,
2578
- queuedAt: r.queuedAt,
2579
- completedAt: r.completedAt
2580
- };
2581
- });
2582
- return { items, total, hasMore: offset + limit < total };
2583
- }
2584
- async function mockGetRunHandler(input) {
2585
- const run = MOCK_RUNS.find((r) => r.id === input.runId);
2586
- if (!run)
2587
- throw new Error("RUN_NOT_FOUND");
2588
- const agent = MOCK_AGENTS.find((a) => a.id === run.agentId);
2589
- return {
2590
- ...run,
2591
- agent: agent ? {
2592
- id: agent.id,
2593
- name: agent.name,
2594
- modelProvider: agent.modelProvider,
2595
- modelName: agent.modelName
2596
- } : undefined,
2597
- steps: input.includeSteps ? run.steps : undefined,
2598
- logs: input.includeLogs ? run.logs : undefined
2599
- };
2600
- }
2601
- async function mockExecuteAgentHandler(input) {
2602
- const agent = MOCK_AGENTS.find((a) => a.id === input.agentId);
2603
- if (!agent)
2604
- throw new Error("AGENT_NOT_FOUND");
2605
- if (agent.status !== "ACTIVE")
2606
- throw new Error("AGENT_NOT_ACTIVE");
2607
- return {
2608
- runId: `run-${nextMockRunId++}`,
2609
- status: "QUEUED",
2610
- estimatedWaitMs: 500
2611
- };
2612
- }
2613
- async function mockCancelRunHandler(input) {
2614
- const run = MOCK_RUNS.find((r) => r.id === input.runId);
2615
- if (!run)
2616
- throw new Error("RUN_NOT_FOUND");
2617
- if (!["QUEUED", "IN_PROGRESS"].includes(run.status))
2618
- throw new Error("RUN_NOT_CANCELLABLE");
2619
- return { success: true, status: "CANCELLED" };
2620
- }
2621
-
2622
- // src/tool/tool.handler.ts
2623
- var nextMockToolId = MOCK_TOOLS.length + 1;
2624
- async function mockListToolsHandler(input) {
2625
- const {
2626
- organizationId,
2627
- category,
2628
- status,
2629
- search,
2630
- limit = 20,
2631
- offset = 0
2632
- } = input;
2633
- let filtered = MOCK_TOOLS.filter((t) => t.organizationId === organizationId);
2634
- if (category)
2635
- filtered = filtered.filter((t) => t.category === category);
2636
- if (status)
2637
- filtered = filtered.filter((t) => t.status === status);
2638
- if (search) {
2639
- const q = search.toLowerCase();
2640
- filtered = filtered.filter((t) => t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q));
2641
- }
2642
- const total = filtered.length;
2643
- const items = filtered.slice(offset, offset + limit).map((t) => ({
2644
- id: t.id,
2645
- name: t.name,
2646
- slug: t.slug,
2647
- description: t.description,
2648
- category: t.category,
2649
- status: t.status,
2650
- version: t.version,
2651
- createdAt: t.createdAt
2652
- }));
2653
- return { items, total, hasMore: offset + limit < total };
2654
- }
2655
- async function mockGetToolHandler(input) {
2656
- const tool = MOCK_TOOLS.find((t) => t.id === input.toolId);
2657
- if (!tool)
2658
- throw new Error("TOOL_NOT_FOUND");
2659
- return tool;
2660
- }
2661
- async function mockCreateToolHandler(input) {
2662
- const exists = MOCK_TOOLS.some((t) => t.organizationId === input.organizationId && t.slug === input.slug);
2663
- if (exists)
2664
- throw new Error("SLUG_EXISTS");
2665
- return {
2666
- id: `tool-${nextMockToolId++}`,
2667
- name: input.name,
2668
- slug: input.slug,
2669
- status: "DRAFT"
2670
- };
2671
- }
2672
- async function mockUpdateToolHandler(input) {
2673
- const tool = MOCK_TOOLS.find((t) => t.id === input.toolId);
2674
- if (!tool)
2675
- throw new Error("TOOL_NOT_FOUND");
2676
- return {
2677
- id: tool.id,
2678
- name: input.name ?? tool.name,
2679
- status: input.status ?? tool.status,
2680
- updatedAt: new Date
2681
- };
2682
- }
2683
- async function mockTestToolHandler(input) {
2684
- const tool = MOCK_TOOLS.find((t) => t.id === input.toolId);
2685
- if (!tool)
2686
- throw new Error("TOOL_NOT_FOUND");
2687
- await new Promise((resolve) => setTimeout(resolve, 100));
2688
- return {
2689
- success: true,
2690
- output: { result: "Test successful", input: input.testInput },
2691
- durationMs: 100
2692
- };
2693
- }
2694
- // src/shared/demo-runtime-seed.ts
2695
- var AGENT_CONSOLE_DEMO_ORGANIZATION_ID = "demo-org";
2696
- var AGENT_CONSOLE_DEMO_PROJECT_ID = "agent-console-demo";
2697
- function slugify(name) {
2698
- return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
2699
- }
2700
- function cloneAgent(agent) {
2701
- return { ...agent };
2702
- }
2703
- function cloneTool(tool) {
2704
- return { ...tool };
2705
- }
2706
- function cloneRun(run) {
2707
- return { ...run };
2708
- }
2709
- function createDefaultNow() {
2710
- let tick = 0;
2711
- const base = Date.parse("2026-03-20T09:00:00.000Z");
2712
- return () => new Date(base + tick++ * 60000);
2713
- }
2714
- function normalizeProvider(provider) {
2715
- return provider.toLowerCase();
2716
- }
2717
- function normalizeRunStatus(status) {
2718
- return status === "IN_PROGRESS" ? "RUNNING" : status;
2719
- }
2720
- function createSeedState(projectId, organizationId) {
2721
- const agents = MOCK_AGENTS.map((agent) => ({
2722
- id: agent.id,
2723
- projectId,
2724
- organizationId,
2725
- name: agent.name,
2726
- slug: agent.slug,
2727
- description: agent.description,
2728
- modelProvider: normalizeProvider(agent.modelProvider),
2729
- modelName: agent.modelName,
2730
- systemPrompt: agent.systemPrompt,
2731
- temperature: typeof agent.modelConfig?.temperature === "number" ? agent.modelConfig.temperature : 0.4,
2732
- maxTokens: 8192,
2733
- status: agent.status,
2734
- createdAt: agent.createdAt,
2735
- updatedAt: agent.updatedAt
2736
- }));
2737
- const tools = MOCK_TOOLS.map((tool) => ({
2738
- id: tool.id,
2739
- projectId,
2740
- organizationId,
2741
- name: tool.name,
2742
- description: tool.description,
2743
- version: tool.version,
2744
- category: tool.category,
2745
- status: tool.status,
2746
- inputSchema: JSON.stringify(tool.parametersSchema),
2747
- outputSchema: tool.outputSchema ? JSON.stringify(tool.outputSchema) : undefined,
2748
- endpoint: typeof tool.implementationConfig?.url === "string" ? tool.implementationConfig.url : undefined,
2749
- createdAt: tool.createdAt,
2750
- updatedAt: tool.updatedAt
2751
- }));
2752
- const agentNames = new Map(agents.map((agent) => [agent.id, agent.name]));
2753
- const runs = MOCK_RUNS.map((run) => ({
2754
- id: run.id,
2755
- projectId,
2756
- agentId: run.agentId,
2757
- agentName: agentNames.get(run.agentId) ?? run.agentName ?? "Unknown agent",
2758
- status: normalizeRunStatus(run.status),
2759
- input: JSON.stringify(run.input),
2760
- output: run.output ? JSON.stringify(run.output) : undefined,
2761
- totalTokens: run.totalTokens,
2762
- promptTokens: run.promptTokens,
2763
- completionTokens: run.completionTokens,
2764
- estimatedCostUsd: run.estimatedCostUsd ?? 0,
2765
- durationMs: run.durationMs,
2766
- errorMessage: run.errorMessage,
2767
- queuedAt: run.queuedAt,
2768
- startedAt: run.startedAt,
2769
- completedAt: run.completedAt
2770
- }));
2771
- return { agents, tools, runs };
2772
- }
2773
- function summarizeRunMetrics(runs) {
2774
- const totalRuns = runs.length;
2775
- const completedRuns = runs.filter((run) => run.status === "COMPLETED").length;
2776
- const completedDurations = runs.map((run) => run.durationMs).filter((duration) => typeof duration === "number");
2777
- return {
2778
- totalRuns,
2779
- successRate: totalRuns === 0 ? 0 : completedRuns / totalRuns,
2780
- averageDurationMs: completedDurations.length === 0 ? 0 : Math.round(completedDurations.reduce((sum, duration) => sum + duration, 0) / completedDurations.length),
2781
- totalTokens: runs.reduce((sum, run) => sum + run.totalTokens, 0),
2782
- totalCostUsd: runs.reduce((sum, run) => sum + run.estimatedCostUsd, 0)
2783
- };
2784
- }
2785
-
2786
- // src/shared/demo-runtime.ts
2787
- function createAgentConsoleDemoHandlers(options) {
2788
- const projectId = options.projectId;
2789
- const organizationId = options.organizationId ?? AGENT_CONSOLE_DEMO_ORGANIZATION_ID;
2790
- const now = options.now ?? createDefaultNow();
2791
- const state = createSeedState(projectId, organizationId);
2792
- let agentIndex = state.agents.length + 1;
2793
- let runIndex = state.runs.length + 1;
2794
- const nextId = (kind) => {
2795
- const nextIndex = kind === "agent" ? agentIndex++ : runIndex++;
2796
- return options.idFactory?.(kind, nextIndex) ?? `${kind}-demo-${nextIndex}`;
2797
- };
2798
- return {
2799
- async listAgents(input) {
2800
- const filtered = state.agents.filter((agent) => agent.projectId === input.projectId).filter((agent) => !input.organizationId || agent.organizationId === input.organizationId).filter((agent) => !input.status || input.status === "all" || agent.status === input.status).filter((agent) => {
2801
- if (!input.search)
2802
- return true;
2803
- const query = input.search.toLowerCase();
2804
- return agent.name.toLowerCase().includes(query) || (agent.description ?? "").toLowerCase().includes(query);
2805
- }).sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());
2806
- const limit = input.limit ?? 20;
2807
- const offset = input.offset ?? 0;
2808
- const items = filtered.slice(offset, offset + limit).map(cloneAgent);
2809
- return {
2810
- items,
2811
- total: filtered.length,
2812
- hasMore: offset + items.length < filtered.length
2813
- };
2814
- },
2815
- async getAgent(id) {
2816
- const agent = state.agents.find((item) => item.id === id);
2817
- return agent ? cloneAgent(agent) : null;
2818
- },
2819
- async createAgent(input, context) {
2820
- const name = input.name.trim();
2821
- const slug = slugify(name);
2822
- const duplicate = state.agents.find((agent2) => agent2.projectId === context.projectId && agent2.organizationId === context.organizationId && (agent2.slug === slug || agent2.name.toLowerCase() === name.toLowerCase()));
2823
- if (duplicate)
2824
- throw new Error("AGENT_NAME_OR_SLUG_EXISTS");
2825
- const timestamp = now();
2826
- const agent = {
2827
- id: nextId("agent"),
2828
- projectId: context.projectId,
2829
- organizationId: context.organizationId,
2830
- name,
2831
- slug,
2832
- description: input.description,
2833
- modelProvider: input.modelProvider ?? "openai",
2834
- modelName: input.modelName ?? "gpt-5.4",
2835
- systemPrompt: input.systemPrompt,
2836
- temperature: input.temperature ?? 0.4,
2837
- maxTokens: input.maxTokens ?? 8192,
2838
- status: "DRAFT",
2839
- createdAt: timestamp,
2840
- updatedAt: timestamp
2841
- };
2842
- state.agents.unshift(agent);
2843
- return cloneAgent(agent);
2844
- },
2845
- async updateAgent(input) {
2846
- const agent = state.agents.find((item) => item.id === input.id);
2847
- if (!agent)
2848
- throw new Error("AGENT_NOT_FOUND");
2849
- const nextName = input.name;
2850
- if (nextName && slugify(nextName) !== agent.slug) {
2851
- const duplicate = state.agents.find((item) => item.id !== agent.id && item.projectId === agent.projectId && item.organizationId === agent.organizationId && (item.slug === slugify(nextName) || item.name.toLowerCase() === nextName.toLowerCase()));
2852
- if (duplicate)
2853
- throw new Error("AGENT_NAME_OR_SLUG_EXISTS");
2854
- agent.slug = slugify(nextName);
2855
- agent.name = nextName;
2856
- }
2857
- if (input.description !== undefined)
2858
- agent.description = input.description;
2859
- if (input.status)
2860
- agent.status = input.status;
2861
- agent.updatedAt = now();
2862
- return cloneAgent(agent);
2863
- },
2864
- async executeAgent(input) {
2865
- const agent = state.agents.find((item) => item.id === input.agentId);
2866
- if (!agent)
2867
- throw new Error("AGENT_NOT_FOUND");
2868
- if (agent.status !== "ACTIVE")
2869
- throw new Error("AGENT_NOT_ACTIVE");
2870
- const queuedAt = now();
2871
- const startedAt = now();
2872
- const completedAt = now();
2873
- const durationMs = 2200 + input.message.length * 12;
2874
- const promptTokens = 600 + input.message.length * 3;
2875
- const completionTokens = 240 + agent.name.length * 4;
2876
- const run = {
2877
- id: nextId("run"),
2878
- projectId: input.context?.projectId ?? agent.projectId,
2879
- agentId: agent.id,
2880
- agentName: agent.name,
2881
- status: "COMPLETED",
2882
- input: input.message,
2883
- output: `Deterministic demo reply from ${agent.name}: ${input.message}`,
2884
- totalTokens: promptTokens + completionTokens,
2885
- promptTokens,
2886
- completionTokens,
2887
- estimatedCostUsd: Number(((promptTokens + completionTokens) / 1e6).toFixed(4)),
2888
- durationMs,
2889
- queuedAt,
2890
- startedAt,
2891
- completedAt
2892
- };
2893
- state.runs.unshift(run);
2894
- return cloneRun(run);
2895
- },
2896
- async listTools(input) {
2897
- const filtered = state.tools.filter((tool) => tool.projectId === input.projectId).filter((tool) => !input.organizationId || tool.organizationId === input.organizationId).filter((tool) => !input.category || input.category === "all" || tool.category === input.category).filter((tool) => !input.status || input.status === "all" || tool.status === input.status).filter((tool) => {
2898
- if (!input.search)
2899
- return true;
2900
- const query = input.search.toLowerCase();
2901
- return tool.name.toLowerCase().includes(query) || (tool.description ?? "").toLowerCase().includes(query);
2902
- }).sort((left, right) => left.name.localeCompare(right.name));
2903
- const limit = input.limit ?? 50;
2904
- const offset = input.offset ?? 0;
2905
- const items = filtered.slice(offset, offset + limit).map(cloneTool);
2906
- return {
2907
- items,
2908
- total: filtered.length,
2909
- hasMore: offset + items.length < filtered.length
2910
- };
2911
- },
2912
- async listRuns(input) {
2913
- const filtered = state.runs.filter((run) => run.projectId === input.projectId).filter((run) => !input.agentId || run.agentId === input.agentId).filter((run) => !input.status || input.status === "all" || run.status === input.status).sort((left, right) => right.queuedAt.getTime() - left.queuedAt.getTime());
2914
- const limit = input.limit ?? 20;
2915
- const offset = input.offset ?? 0;
2916
- const items = filtered.slice(offset, offset + limit).map(cloneRun);
2917
- return {
2918
- items,
2919
- total: filtered.length,
2920
- hasMore: offset + items.length < filtered.length
2921
- };
2922
- },
2923
- async getRunMetrics(input) {
2924
- const filtered = state.runs.filter((run) => {
2925
- if (run.projectId !== input.projectId)
2926
- return false;
2927
- if (input.agentId && run.agentId !== input.agentId)
2928
- return false;
2929
- if (input.startDate && run.queuedAt < input.startDate)
2930
- return false;
2931
- if (input.endDate && run.queuedAt > input.endDate)
2932
- return false;
2933
- return true;
2934
- });
2935
- return summarizeRunMetrics(filtered);
2936
- }
2937
- };
2938
- }
2939
- export {
2940
- mockListToolsHandler,
2941
- mockListRunsHandler,
2942
- mockListAgentsHandler,
2943
- mockGetToolHandler,
2944
- mockGetRunHandler,
2945
- mockGetAgentHandler,
2946
- mockExecuteAgentHandler,
2947
- mockCreateToolHandler,
2948
- mockCreateAgentHandler,
2949
- createAgentHandlers,
2950
- createAgentConsoleDemoHandlers
2951
- };
13
+ FROM agent_run ${A}`,H)).rows[0],x=o?.totalRuns??0,$=o?.completedRuns??0;return{totalRuns:x,successRate:x>0?$/x:0,averageDurationMs:o?.avgDuration??0,totalTokens:o?.totalTokens??0,totalCostUsd:o?.totalCost??0}}async function D(I){let A=await g(I.agentId);if(!A)throw Error("AGENT_NOT_FOUND");if(A.status!=="ACTIVE")throw Error("AGENT_NOT_ACTIVE");let H=M0("run"),q=new Date().toISOString(),o=I.context?.projectId??A.projectId;await s.execute(`INSERT INTO agent_run (id, projectId, agentId, status, input, totalTokens, promptTokens, completionTokens, estimatedCostUsd, queuedAt)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[H,o,I.agentId,"QUEUED",I.message,0,0,0,0,q]);let x=(await s.query("SELECT r.*, a.name as agentName FROM agent_run r LEFT JOIN agent_definition a ON r.agentId = a.id WHERE r.id = ?",[H])).rows;if(!x[0])throw Error("Failed to retrieve created run");return f0(x[0],x[0].agentName)}return{listAgents:k,getAgent:g,createAgent:L,updateAgent:z,executeAgent:D,listTools:J,listRuns:P,getRunMetrics:F}}var i=[{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:[]}];var qs=i.length+1;async function js(s){let{agentId:k,status:g,limit:L=20,offset:z=0}=s,J=[...i];if(k)J=J.filter((D)=>D.agentId===k);if(g)J=J.filter((D)=>D.status===g);let P=J.length;return{items:J.slice(z,z+L).map((D)=>{let I=N.find((A)=>A.id===D.agentId);return{id:D.id,agentId:D.agentId,agentName:I?.name??"Unknown",status:D.status,totalTokens:D.totalTokens,durationMs:D.durationMs,estimatedCostUsd:D.estimatedCostUsd,queuedAt:D.queuedAt,completedAt:D.completedAt}}),total:P,hasMore:z+L<P}}async function zs(s){let k=i.find((L)=>L.id===s.runId);if(!k)throw Error("RUN_NOT_FOUND");let g=N.find((L)=>L.id===k.agentId);return{...k,agent:g?{id:g.id,name:g.name,modelProvider:g.modelProvider,modelName:g.modelName}:void 0,steps:s.includeSteps?k.steps:void 0,logs:s.includeLogs?k.logs:void 0}}async function Vs(s){let k=N.find((g)=>g.id===s.agentId);if(!k)throw Error("AGENT_NOT_FOUND");if(k.status!=="ACTIVE")throw Error("AGENT_NOT_ACTIVE");return{runId:`run-${qs++}`,status:"QUEUED",estimatedWaitMs:500}}async function N2(s){let k=i.find((g)=>g.id===s.runId);if(!k)throw Error("RUN_NOT_FOUND");if(!["QUEUED","IN_PROGRESS"].includes(k.status))throw Error("RUN_NOT_CANCELLABLE");return{success:!0,status:"CANCELLED"}}var xs=Q.length+1;async function Ls(s){let{organizationId:k,category:g,status:L,search:z,limit:J=20,offset:P=0}=s,F=Q.filter((A)=>A.organizationId===k);if(g)F=F.filter((A)=>A.category===g);if(L)F=F.filter((A)=>A.status===L);if(z){let A=z.toLowerCase();F=F.filter((H)=>H.name.toLowerCase().includes(A)||H.description.toLowerCase().includes(A))}let D=F.length;return{items:F.slice(P,P+J).map((A)=>({id:A.id,name:A.name,slug:A.slug,description:A.description,category:A.category,status:A.status,version:A.version,createdAt:A.createdAt})),total:D,hasMore:P+J<D}}async function Bs(s){let k=Q.find((g)=>g.id===s.toolId);if(!k)throw Error("TOOL_NOT_FOUND");return k}async function Js(s){if(Q.some((g)=>g.organizationId===s.organizationId&&g.slug===s.slug))throw Error("SLUG_EXISTS");return{id:`tool-${xs++}`,name:s.name,slug:s.slug,status:"DRAFT"}}async function R2(s){let k=Q.find((g)=>g.id===s.toolId);if(!k)throw Error("TOOL_NOT_FOUND");return{id:k.id,name:s.name??k.name,status:s.status??k.status,updatedAt:new Date}}async function O2(s){if(!Q.find((g)=>g.id===s.toolId))throw Error("TOOL_NOT_FOUND");return await new Promise((g)=>setTimeout(g,100)),{success:!0,output:{result:"Test successful",input:s.testInput},durationMs:100}}var i0="demo-org",M2="agent-console-demo";function m(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function e(s){return{...s}}function c0(s){return{...s}}function J0(s){return{...s}}function r0(){let s=0,k=Date.parse("2026-03-20T09:00:00.000Z");return()=>new Date(k+s++*60000)}function Ys(s){return s.toLowerCase()}function Fs(s){return s==="IN_PROGRESS"?"RUNNING":s}function T0(s,k){let g=N.map((P)=>({id:P.id,projectId:s,organizationId:k,name:P.name,slug:P.slug,description:P.description,modelProvider:Ys(P.modelProvider),modelName:P.modelName,systemPrompt:P.systemPrompt,temperature:typeof P.modelConfig?.temperature==="number"?P.modelConfig.temperature:0.4,maxTokens:8192,status:P.status,createdAt:P.createdAt,updatedAt:P.updatedAt})),L=Q.map((P)=>({id:P.id,projectId:s,organizationId:k,name:P.name,description:P.description,version:P.version,category:P.category,status:P.status,inputSchema:JSON.stringify(P.parametersSchema),outputSchema:P.outputSchema?JSON.stringify(P.outputSchema):void 0,endpoint:typeof P.implementationConfig?.url==="string"?P.implementationConfig.url:void 0,createdAt:P.createdAt,updatedAt:P.updatedAt})),z=new Map(g.map((P)=>[P.id,P.name])),J=i.map((P)=>({id:P.id,projectId:s,agentId:P.agentId,agentName:z.get(P.agentId)??P.agentName??"Unknown agent",status:Fs(P.status),input:JSON.stringify(P.input),output:P.output?JSON.stringify(P.output):void 0,totalTokens:P.totalTokens,promptTokens:P.promptTokens,completionTokens:P.completionTokens,estimatedCostUsd:P.estimatedCostUsd??0,durationMs:P.durationMs,errorMessage:P.errorMessage,queuedAt:P.queuedAt,startedAt:P.startedAt,completedAt:P.completedAt}));return{agents:g,tools:L,runs:J}}function y0(s){let k=s.length,g=s.filter((z)=>z.status==="COMPLETED").length,L=s.map((z)=>z.durationMs).filter((z)=>typeof z==="number");return{totalRuns:k,successRate:k===0?0:g/k,averageDurationMs:L.length===0?0:Math.round(L.reduce((z,J)=>z+J,0)/L.length),totalTokens:s.reduce((z,J)=>z+J.totalTokens,0),totalCostUsd:s.reduce((z,J)=>z+J.estimatedCostUsd,0)}}function Gs(s){let k=s.projectId,g=s.organizationId??i0,L=s.now??r0(),z=T0(k,g),J=z.agents.length+1,P=z.runs.length+1,F=(D)=>{let I=D==="agent"?J++:P++;return s.idFactory?.(D,I)??`${D}-demo-${I}`};return{async listAgents(D){let I=z.agents.filter((o)=>o.projectId===D.projectId).filter((o)=>!D.organizationId||o.organizationId===D.organizationId).filter((o)=>!D.status||D.status==="all"||o.status===D.status).filter((o)=>{if(!D.search)return!0;let x=D.search.toLowerCase();return o.name.toLowerCase().includes(x)||(o.description??"").toLowerCase().includes(x)}).sort((o,x)=>x.updatedAt.getTime()-o.updatedAt.getTime()),A=D.limit??20,H=D.offset??0,q=I.slice(H,H+A).map(e);return{items:q,total:I.length,hasMore:H+q.length<I.length}},async getAgent(D){let I=z.agents.find((A)=>A.id===D);return I?e(I):null},async createAgent(D,I){let A=D.name.trim(),H=m(A);if(z.agents.find(($)=>$.projectId===I.projectId&&$.organizationId===I.organizationId&&($.slug===H||$.name.toLowerCase()===A.toLowerCase())))throw Error("AGENT_NAME_OR_SLUG_EXISTS");let o=L(),x={id:F("agent"),projectId:I.projectId,organizationId:I.organizationId,name:A,slug:H,description:D.description,modelProvider:D.modelProvider??"openai",modelName:D.modelName??"gpt-5.4",systemPrompt:D.systemPrompt,temperature:D.temperature??0.4,maxTokens:D.maxTokens??8192,status:"DRAFT",createdAt:o,updatedAt:o};return z.agents.unshift(x),e(x)},async updateAgent(D){let I=z.agents.find((H)=>H.id===D.id);if(!I)throw Error("AGENT_NOT_FOUND");let A=D.name;if(A&&m(A)!==I.slug){if(z.agents.find((q)=>q.id!==I.id&&q.projectId===I.projectId&&q.organizationId===I.organizationId&&(q.slug===m(A)||q.name.toLowerCase()===A.toLowerCase())))throw Error("AGENT_NAME_OR_SLUG_EXISTS");I.slug=m(A),I.name=A}if(D.description!==void 0)I.description=D.description;if(D.status)I.status=D.status;return I.updatedAt=L(),e(I)},async executeAgent(D){let I=z.agents.find((G)=>G.id===D.agentId);if(!I)throw Error("AGENT_NOT_FOUND");if(I.status!=="ACTIVE")throw Error("AGENT_NOT_ACTIVE");let A=L(),H=L(),q=L(),o=2200+D.message.length*12,x=600+D.message.length*3,$=240+I.name.length*4,X={id:F("run"),projectId:D.context?.projectId??I.projectId,agentId:I.id,agentName:I.name,status:"COMPLETED",input:D.message,output:`Deterministic demo reply from ${I.name}: ${D.message}`,totalTokens:x+$,promptTokens:x,completionTokens:$,estimatedCostUsd:Number(((x+$)/1e6).toFixed(4)),durationMs:o,queuedAt:A,startedAt:H,completedAt:q};return z.runs.unshift(X),J0(X)},async listTools(D){let I=z.tools.filter((o)=>o.projectId===D.projectId).filter((o)=>!D.organizationId||o.organizationId===D.organizationId).filter((o)=>!D.category||D.category==="all"||o.category===D.category).filter((o)=>!D.status||D.status==="all"||o.status===D.status).filter((o)=>{if(!D.search)return!0;let x=D.search.toLowerCase();return o.name.toLowerCase().includes(x)||(o.description??"").toLowerCase().includes(x)}).sort((o,x)=>o.name.localeCompare(x.name)),A=D.limit??50,H=D.offset??0,q=I.slice(H,H+A).map(c0);return{items:q,total:I.length,hasMore:H+q.length<I.length}},async listRuns(D){let I=z.runs.filter((o)=>o.projectId===D.projectId).filter((o)=>!D.agentId||o.agentId===D.agentId).filter((o)=>!D.status||D.status==="all"||o.status===D.status).sort((o,x)=>x.queuedAt.getTime()-o.queuedAt.getTime()),A=D.limit??20,H=D.offset??0,q=I.slice(H,H+A).map(J0);return{items:q,total:I.length,hasMore:H+q.length<I.length}},async getRunMetrics(D){let I=z.runs.filter((A)=>{if(A.projectId!==D.projectId)return!1;if(D.agentId&&A.agentId!==D.agentId)return!1;if(D.startDate&&A.queuedAt<D.startDate)return!1;if(D.endDate&&A.queuedAt>D.endDate)return!1;return!0});return y0(I)}}}export{Ls as mockListToolsHandler,js as mockListRunsHandler,n0 as mockListAgentsHandler,Bs as mockGetToolHandler,zs as mockGetRunHandler,a0 as mockGetAgentHandler,Vs as mockExecuteAgentHandler,Js as mockCreateToolHandler,ss as mockCreateAgentHandler,G2 as createAgentHandlers,Gs as createAgentConsoleDemoHandlers};