@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,2150 +1,13 @@
1
- // src/agent/agent.enum.ts
2
- import { defineEnum } from "@contractspec/lib.schema";
3
- var AgentStatusEnum = defineEnum("AgentStatus", [
4
- "DRAFT",
5
- "ACTIVE",
6
- "PAUSED",
7
- "ARCHIVED"
8
- ]);
9
- var ModelProviderEnum = defineEnum("ModelProvider", [
10
- "OPENAI",
11
- "ANTHROPIC",
12
- "GOOGLE",
13
- "MISTRAL",
14
- "CUSTOM"
15
- ]);
16
- var ToolChoiceEnum = defineEnum("ToolChoice", [
17
- "auto",
18
- "required",
19
- "none"
20
- ]);
21
-
22
- // src/agent/agent.event.ts
23
- import { defineEvent } from "@contractspec/lib.contracts-spec";
24
- import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
25
- var OWNERS = ["@agent-console-team"];
26
- var AgentCreatedPayload = defineSchemaModel({
27
- name: "AgentCreatedPayload",
28
- description: "Payload for agent created event",
29
- fields: {
30
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
31
- organizationId: {
32
- type: ScalarTypeEnum.String_unsecure(),
33
- isOptional: false
34
- },
35
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
36
- slug: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
37
- modelProvider: {
38
- type: ScalarTypeEnum.String_unsecure(),
39
- isOptional: false
40
- },
41
- modelName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
42
- toolCount: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
43
- createdById: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
44
- createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
45
- }
46
- });
47
- var AgentCreatedEvent = defineEvent({
48
- meta: {
49
- key: "agent-console.agent.created",
50
- version: "1.0.0",
51
- description: "A new AI agent was configured.",
52
- stability: "stable",
53
- owners: [...OWNERS],
54
- tags: ["agent", "created"]
55
- },
56
- payload: AgentCreatedPayload
57
- });
58
- var AgentUpdatedPayload = defineSchemaModel({
59
- name: "AgentUpdatedPayload",
60
- description: "Payload for agent updated event",
61
- fields: {
62
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
63
- organizationId: {
64
- type: ScalarTypeEnum.String_unsecure(),
65
- isOptional: false
66
- },
67
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
68
- status: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
69
- updatedFields: {
70
- type: ScalarTypeEnum.String_unsecure(),
71
- isArray: true,
72
- isOptional: false
73
- },
74
- updatedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
75
- }
76
- });
77
- var AgentUpdatedEvent = defineEvent({
78
- meta: {
79
- key: "agent-console.agent.updated",
80
- version: "1.0.0",
81
- description: "An AI agent configuration was updated.",
82
- stability: "stable",
83
- owners: [...OWNERS],
84
- tags: ["agent", "updated"]
85
- },
86
- payload: AgentUpdatedPayload
87
- });
88
- var AgentToolAssignedPayload = defineSchemaModel({
89
- name: "AgentToolAssignedPayload",
90
- description: "Payload for agent tool assigned event",
91
- fields: {
92
- agentId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
93
- toolId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
94
- agentName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
95
- toolName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
96
- assignedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
97
- }
98
- });
99
- var AgentToolAssignedEvent = defineEvent({
100
- meta: {
101
- key: "agent-console.agent.toolAssigned",
102
- version: "1.0.0",
103
- description: "A tool was assigned to an agent.",
104
- stability: "stable",
105
- owners: [...OWNERS],
106
- tags: ["agent", "tool", "assigned"]
107
- },
108
- payload: AgentToolAssignedPayload
109
- });
110
- var AgentToolRemovedPayload = defineSchemaModel({
111
- name: "AgentToolRemovedPayload",
112
- description: "Payload for agent tool removed event",
113
- fields: {
114
- agentId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
115
- toolId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
116
- agentName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
117
- toolName: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
118
- removedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
119
- }
120
- });
121
- var AgentToolRemovedEvent = defineEvent({
122
- meta: {
123
- key: "agent-console.agent.toolRemoved",
124
- version: "1.0.0",
125
- description: "A tool was removed from an agent.",
126
- stability: "stable",
127
- owners: [...OWNERS],
128
- tags: ["agent", "tool", "removed"]
129
- },
130
- payload: AgentToolRemovedPayload
131
- });
132
-
133
- // src/agent/agent.schema.ts
134
- import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
135
- var AgentModel = defineSchemaModel2({
136
- name: "Agent",
137
- description: "AI agent configuration",
138
- fields: {
139
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
140
- organizationId: {
141
- type: ScalarTypeEnum2.String_unsecure(),
142
- isOptional: false
143
- },
144
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
145
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
146
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
147
- status: { type: AgentStatusEnum, isOptional: false },
148
- modelProvider: { type: ModelProviderEnum, isOptional: false },
149
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
150
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
151
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
152
- userPromptTemplate: {
153
- type: ScalarTypeEnum2.String_unsecure(),
154
- isOptional: true
155
- },
156
- toolIds: {
157
- type: ScalarTypeEnum2.String_unsecure(),
158
- isArray: true,
159
- isOptional: true
160
- },
161
- toolChoice: {
162
- type: ToolChoiceEnum,
163
- isOptional: false,
164
- defaultValue: "auto"
165
- },
166
- maxIterations: {
167
- type: ScalarTypeEnum2.Int_unsecure(),
168
- isOptional: false,
169
- defaultValue: 10
170
- },
171
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
172
- timeoutMs: {
173
- type: ScalarTypeEnum2.Int_unsecure(),
174
- isOptional: false,
175
- defaultValue: 120000
176
- },
177
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
178
- tags: {
179
- type: ScalarTypeEnum2.String_unsecure(),
180
- isArray: true,
181
- isOptional: true
182
- },
183
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
184
- updatedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
185
- }
186
- });
187
- var AgentSummaryModel = defineSchemaModel2({
188
- name: "AgentSummary",
189
- description: "Summary of an agent for list views",
190
- fields: {
191
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
192
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
193
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
194
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
195
- status: { type: AgentStatusEnum, isOptional: false },
196
- modelProvider: { type: ModelProviderEnum, isOptional: false },
197
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
198
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
199
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
200
- }
201
- });
202
- var AgentToolRefModel = defineSchemaModel2({
203
- name: "AgentToolRef",
204
- description: "Tool reference in agent context",
205
- fields: {
206
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
207
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
208
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
209
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
210
- category: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false }
211
- }
212
- });
213
- var AgentWithToolsModel = defineSchemaModel2({
214
- name: "AgentWithTools",
215
- description: "Agent with associated tools",
216
- fields: {
217
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
218
- organizationId: {
219
- type: ScalarTypeEnum2.String_unsecure(),
220
- isOptional: false
221
- },
222
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
223
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
224
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
225
- status: { type: AgentStatusEnum, isOptional: false },
226
- modelProvider: { type: ModelProviderEnum, isOptional: false },
227
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
228
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
229
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
230
- userPromptTemplate: {
231
- type: ScalarTypeEnum2.String_unsecure(),
232
- isOptional: true
233
- },
234
- toolIds: {
235
- type: ScalarTypeEnum2.String_unsecure(),
236
- isArray: true,
237
- isOptional: true
238
- },
239
- toolChoice: { type: ToolChoiceEnum, isOptional: false },
240
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
241
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
242
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
243
- version: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
244
- tags: {
245
- type: ScalarTypeEnum2.String_unsecure(),
246
- isArray: true,
247
- isOptional: true
248
- },
249
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
250
- updatedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
251
- tools: { type: AgentToolRefModel, isArray: true, isOptional: true }
252
- }
253
- });
254
- var CreateAgentInputModel = defineSchemaModel2({
255
- name: "CreateAgentInput",
256
- description: "Input for creating an agent",
257
- fields: {
258
- organizationId: {
259
- type: ScalarTypeEnum2.String_unsecure(),
260
- isOptional: false
261
- },
262
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
263
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
264
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
265
- modelProvider: { type: ModelProviderEnum, isOptional: false },
266
- modelName: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
267
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
268
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
269
- userPromptTemplate: {
270
- type: ScalarTypeEnum2.String_unsecure(),
271
- isOptional: true
272
- },
273
- toolIds: {
274
- type: ScalarTypeEnum2.String_unsecure(),
275
- isArray: true,
276
- isOptional: true
277
- },
278
- toolChoice: { type: ToolChoiceEnum, isOptional: true },
279
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
280
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
281
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
282
- tags: {
283
- type: ScalarTypeEnum2.String_unsecure(),
284
- isArray: true,
285
- isOptional: true
286
- }
287
- }
288
- });
289
- var UpdateAgentInputModel = defineSchemaModel2({
290
- name: "UpdateAgentInput",
291
- description: "Input for updating an agent",
292
- fields: {
293
- agentId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
294
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: true },
295
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
296
- status: { type: AgentStatusEnum, isOptional: true },
297
- modelConfig: { type: ScalarTypeEnum2.JSONObject(), isOptional: true },
298
- systemPrompt: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
299
- userPromptTemplate: {
300
- type: ScalarTypeEnum2.String_unsecure(),
301
- isOptional: true
302
- },
303
- toolIds: {
304
- type: ScalarTypeEnum2.String_unsecure(),
305
- isArray: true,
306
- isOptional: true
307
- },
308
- toolChoice: { type: ToolChoiceEnum, isOptional: true },
309
- maxIterations: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
310
- maxTokensPerRun: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
311
- timeoutMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: true },
312
- tags: {
313
- type: ScalarTypeEnum2.String_unsecure(),
314
- isArray: true,
315
- isOptional: true
316
- }
317
- }
318
- });
319
-
320
- // src/agent/agent.operation.ts
321
- import {
322
- defineCommand,
323
- defineQuery
324
- } from "@contractspec/lib.contracts-spec/operations";
325
- import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
326
- var OWNERS2 = ["@agent-console-team"];
327
- var CreateAgentCommand = defineCommand({
328
- meta: {
329
- key: "agent-console.agent.create",
330
- version: "1.0.0",
331
- stability: "stable",
332
- owners: [...OWNERS2],
333
- tags: ["agent", "create"],
334
- description: "Creates a new AI agent configuration.",
335
- goal: "Allow users to define new AI agents with specific models and tools.",
336
- context: "Called from the agent builder UI when creating a new agent."
337
- },
338
- io: {
339
- input: CreateAgentInputModel,
340
- output: defineSchemaModel3({
341
- name: "CreateAgentOutput",
342
- fields: {
343
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
344
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
345
- slug: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
346
- status: { type: AgentStatusEnum, isOptional: false }
347
- }
348
- }),
349
- errors: {
350
- SLUG_EXISTS: {
351
- description: "An agent with this slug already exists in the organization",
352
- http: 409,
353
- gqlCode: "SLUG_EXISTS",
354
- when: "Slug is already taken"
355
- }
356
- }
357
- },
358
- policy: { auth: "user" },
359
- sideEffects: {
360
- emits: [
361
- {
362
- ref: AgentCreatedEvent.meta,
363
- when: "Agent is successfully created"
364
- }
365
- ],
366
- audit: ["agent-console.agent.created"]
367
- },
368
- acceptance: {
369
- scenarios: [
370
- {
371
- key: "create-agent-happy-path",
372
- given: ["User is authenticated", "Organization exists"],
373
- when: ["User submits valid agent configuration"],
374
- then: [
375
- "New agent is created with DRAFT status",
376
- "AgentCreated event is emitted"
377
- ]
378
- },
379
- {
380
- key: "create-agent-slug-conflict",
381
- given: ["User is authenticated", "Agent with same slug exists"],
382
- when: ["User submits agent with duplicate slug"],
383
- then: ["SLUG_EXISTS error is returned with 409 status"]
384
- }
385
- ],
386
- examples: [
387
- {
388
- key: "basic-create",
389
- input: {
390
- name: "Support Assistant",
391
- slug: "support-assistant",
392
- modelProvider: "openai",
393
- modelId: "gpt-4"
394
- },
395
- output: {
396
- id: "agent-123",
397
- name: "Support Assistant",
398
- slug: "support-assistant",
399
- status: "draft"
400
- }
401
- }
402
- ]
403
- }
404
- });
405
- var UpdateAgentCommand = defineCommand({
406
- meta: {
407
- key: "agent-console.agent.update",
408
- version: "1.0.0",
409
- stability: "stable",
410
- owners: [...OWNERS2],
411
- tags: ["agent", "update"],
412
- description: "Updates an existing AI agent configuration.",
413
- goal: "Allow users to modify agent settings and configuration.",
414
- context: "Called from the agent settings UI."
415
- },
416
- io: {
417
- input: UpdateAgentInputModel,
418
- output: defineSchemaModel3({
419
- name: "UpdateAgentOutput",
420
- fields: {
421
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
422
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
423
- status: { type: AgentStatusEnum, isOptional: false },
424
- updatedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: false }
425
- }
426
- }),
427
- errors: {
428
- AGENT_NOT_FOUND: {
429
- description: "The specified agent does not exist",
430
- http: 404,
431
- gqlCode: "AGENT_NOT_FOUND",
432
- when: "Agent ID is invalid"
433
- }
434
- }
435
- },
436
- policy: { auth: "user" },
437
- sideEffects: {
438
- emits: [
439
- {
440
- key: "agent.updated",
441
- version: "1.0.0",
442
- stability: "stable",
443
- owners: [...OWNERS2],
444
- tags: ["agent", "updated"],
445
- when: "Agent is updated",
446
- payload: AgentSummaryModel
447
- }
448
- ],
449
- audit: ["agent.updated"]
450
- },
451
- acceptance: {
452
- scenarios: [
453
- {
454
- key: "update-agent-happy-path",
455
- given: ["Agent exists", "User owns the agent"],
456
- when: ["User submits updated configuration"],
457
- then: ["Agent is updated", "AgentUpdated event is emitted"]
458
- },
459
- {
460
- key: "update-agent-not-found",
461
- given: ["Agent does not exist"],
462
- when: ["User attempts to update"],
463
- then: ["AGENT_NOT_FOUND error is returned"]
464
- }
465
- ],
466
- examples: [
467
- {
468
- key: "update-name",
469
- input: {
470
- agentId: "agent-123",
471
- name: "Updated Assistant",
472
- systemPrompt: "You are a helpful assistant."
473
- },
474
- output: {
475
- id: "agent-123",
476
- name: "Updated Assistant",
477
- status: "draft",
478
- updatedAt: "2025-01-01T00:00:00Z"
479
- }
480
- }
481
- ]
482
- }
483
- });
484
- var GetAgentQuery = defineQuery({
485
- meta: {
486
- key: "agent-console.agent.get",
487
- version: "1.0.0",
488
- stability: "stable",
489
- owners: [...OWNERS2],
490
- tags: ["agent", "get"],
491
- description: "Retrieves an agent by its ID.",
492
- goal: "View detailed agent configuration.",
493
- context: "Called when viewing agent details or editing."
494
- },
495
- io: {
496
- input: defineSchemaModel3({
497
- name: "GetAgentInput",
498
- fields: {
499
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
500
- includeTools: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
501
- }
502
- }),
503
- output: AgentWithToolsModel,
504
- errors: {
505
- AGENT_NOT_FOUND: {
506
- description: "The specified agent does not exist",
507
- http: 404,
508
- gqlCode: "AGENT_NOT_FOUND",
509
- when: "Agent ID is invalid"
510
- }
511
- }
512
- },
513
- policy: { auth: "user" },
514
- acceptance: {
515
- scenarios: [
516
- {
517
- key: "get-agent-happy-path",
518
- given: ["Agent exists"],
519
- when: ["User requests agent by ID"],
520
- then: ["Agent details are returned"]
521
- },
522
- {
523
- key: "get-agent-with-tools",
524
- given: ["Agent exists with assigned tools"],
525
- when: ["User requests agent with includeTools=true"],
526
- then: ["Agent details with tools list are returned"]
527
- }
528
- ],
529
- examples: [
530
- {
531
- key: "get-basic",
532
- input: { agentId: "agent-123", includeTools: false },
533
- output: {
534
- id: "agent-123",
535
- name: "Support Assistant",
536
- status: "active",
537
- tools: []
538
- }
539
- }
540
- ]
541
- }
542
- });
543
- var ListAgentsQuery = defineQuery({
544
- meta: {
545
- key: "agent-console.agent.list",
546
- version: "1.0.0",
547
- stability: "stable",
548
- owners: [...OWNERS2],
549
- tags: ["agent", "list"],
550
- description: "Lists agents for an organization with optional filtering.",
551
- goal: "Browse and search available agents.",
552
- context: "Agent list/dashboard view."
553
- },
554
- io: {
555
- input: defineSchemaModel3({
556
- name: "ListAgentsInput",
557
- fields: {
558
- organizationId: {
559
- type: ScalarTypeEnum3.String_unsecure(),
560
- isOptional: false
561
- },
562
- status: { type: AgentStatusEnum, isOptional: true },
563
- modelProvider: { type: ModelProviderEnum, isOptional: true },
564
- search: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
565
- limit: {
566
- type: ScalarTypeEnum3.Int_unsecure(),
567
- isOptional: true,
568
- defaultValue: 20
569
- },
570
- offset: {
571
- type: ScalarTypeEnum3.Int_unsecure(),
572
- isOptional: true,
573
- defaultValue: 0
574
- }
575
- }
576
- }),
577
- output: defineSchemaModel3({
578
- name: "ListAgentsOutput",
579
- fields: {
580
- items: { type: AgentSummaryModel, isArray: true, isOptional: false },
581
- total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
582
- hasMore: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
583
- }
584
- })
585
- },
586
- policy: { auth: "user" },
587
- acceptance: {
588
- scenarios: [
589
- {
590
- key: "list-agents-happy-path",
591
- given: ["Organization has agents"],
592
- when: ["User lists agents"],
593
- then: ["Paginated list of agents is returned"]
594
- },
595
- {
596
- key: "list-agents-filter-by-status",
597
- given: ["Organization has agents with mixed statuses"],
598
- when: ["User filters by status=active"],
599
- then: ["Only active agents are returned"]
600
- }
601
- ],
602
- examples: [
603
- {
604
- key: "list-basic",
605
- input: { organizationId: "org-123", limit: 10, offset: 0 },
606
- output: { items: [], total: 0, hasMore: false }
607
- }
608
- ]
609
- }
610
- });
611
- var AssignToolToAgentCommand = defineCommand({
612
- meta: {
613
- key: "agent-console.agent.assignTool",
614
- version: "1.0.0",
615
- stability: "stable",
616
- owners: [...OWNERS2],
617
- tags: ["agent", "tool", "assign"],
618
- description: "Assigns a tool to an agent with optional configuration.",
619
- goal: "Enable agents to use specific tools.",
620
- context: "Agent configuration UI - tool selection."
621
- },
622
- io: {
623
- input: defineSchemaModel3({
624
- name: "AssignToolToAgentInput",
625
- fields: {
626
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
627
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
628
- config: { type: ScalarTypeEnum3.JSONObject(), isOptional: true },
629
- order: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: true }
630
- }
631
- }),
632
- output: defineSchemaModel3({
633
- name: "AssignToolToAgentOutput",
634
- fields: {
635
- agentToolId: {
636
- type: ScalarTypeEnum3.String_unsecure(),
637
- isOptional: false
638
- },
639
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
640
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
641
- }
642
- }),
643
- errors: {
644
- TOOL_ALREADY_ASSIGNED: {
645
- description: "This tool is already assigned to the agent",
646
- http: 409,
647
- gqlCode: "TOOL_ALREADY_ASSIGNED",
648
- when: "Tool assignment already exists"
649
- }
650
- }
651
- },
652
- policy: { auth: "user" },
653
- sideEffects: { audit: ["agent.tool.assigned"] },
654
- acceptance: {
655
- scenarios: [
656
- {
657
- key: "assign-tool-happy-path",
658
- given: ["Agent exists", "Tool exists and is not assigned"],
659
- when: ["User assigns tool to agent"],
660
- then: ["Tool is assigned", "Assignment ID is returned"]
661
- },
662
- {
663
- key: "assign-tool-already-assigned",
664
- given: ["Tool is already assigned to agent"],
665
- when: ["User attempts to assign again"],
666
- then: ["TOOL_ALREADY_ASSIGNED error is returned"]
667
- }
668
- ],
669
- examples: [
670
- {
671
- key: "assign-basic",
672
- input: { agentId: "agent-123", toolId: "tool-456" },
673
- output: {
674
- agentToolId: "at-789",
675
- agentId: "agent-123",
676
- toolId: "tool-456"
677
- }
678
- }
679
- ]
680
- }
681
- });
682
- var RemoveToolFromAgentCommand = defineCommand({
683
- meta: {
684
- key: "agent-console.agent.removeTool",
685
- version: "1.0.0",
686
- stability: "stable",
687
- owners: [...OWNERS2],
688
- tags: ["agent", "tool", "remove"],
689
- description: "Removes a tool assignment from an agent.",
690
- goal: "Disable specific tools for an agent.",
691
- context: "Agent configuration UI - tool management."
692
- },
693
- io: {
694
- input: defineSchemaModel3({
695
- name: "RemoveToolFromAgentInput",
696
- fields: {
697
- agentId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
698
- toolId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
699
- }
700
- }),
701
- output: defineSchemaModel3({
702
- name: "RemoveToolFromAgentOutput",
703
- fields: {
704
- success: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
705
- }
706
- })
707
- },
708
- policy: { auth: "user" },
709
- sideEffects: { audit: ["agent.tool.removed"] },
710
- acceptance: {
711
- scenarios: [
712
- {
713
- key: "remove-tool-happy-path",
714
- given: ["Agent exists", "Tool is assigned to agent"],
715
- when: ["User removes tool from agent"],
716
- then: ["Tool is unassigned", "Success is returned"]
717
- }
718
- ],
719
- examples: [
720
- {
721
- key: "remove-basic",
722
- input: { agentId: "agent-123", toolId: "tool-456" },
723
- output: { success: true }
724
- }
725
- ]
726
- }
727
- });
728
-
729
- // src/run/run.enum.ts
730
- import { defineEnum as defineEnum2 } from "@contractspec/lib.schema";
731
- var RunStatusEnum = defineEnum2("RunStatus", [
732
- "QUEUED",
733
- "IN_PROGRESS",
734
- "COMPLETED",
735
- "FAILED",
736
- "CANCELLED",
737
- "EXPIRED"
738
- ]);
739
- var RunStepTypeEnum = defineEnum2("RunStepType", [
740
- "MESSAGE_CREATION",
741
- "TOOL_CALL",
742
- "TOOL_RESULT",
743
- "ERROR"
744
- ]);
745
- var LogLevelEnum = defineEnum2("LogLevel", [
746
- "DEBUG",
747
- "INFO",
748
- "WARN",
749
- "ERROR"
750
- ]);
751
- var GranularityEnum = defineEnum2("Granularity", [
752
- "hour",
753
- "day",
754
- "week",
755
- "month"
756
- ]);
757
-
758
- // src/run/run.schema.ts
759
- import { defineSchemaModel as defineSchemaModel4, ScalarTypeEnum as ScalarTypeEnum4 } from "@contractspec/lib.schema";
760
- var RunInputModel = defineSchemaModel4({
761
- name: "RunInput",
762
- description: "Input data for agent execution",
763
- fields: {
764
- message: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
765
- context: { type: ScalarTypeEnum4.JSONObject(), isOptional: true }
766
- }
767
- });
768
- var RunStepModel = defineSchemaModel4({
769
- name: "RunStep",
770
- description: "Individual step within a run",
771
- fields: {
772
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
773
- stepNumber: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
774
- type: { type: RunStepTypeEnum, isOptional: false },
775
- toolId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
776
- toolName: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
777
- input: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
778
- output: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
779
- status: { type: RunStatusEnum, isOptional: false },
780
- errorMessage: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
781
- tokensUsed: {
782
- type: ScalarTypeEnum4.Int_unsecure(),
783
- isOptional: false,
784
- defaultValue: 0
785
- },
786
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
787
- startedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
788
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true }
789
- }
790
- });
791
- var RunLogModel = defineSchemaModel4({
792
- name: "RunLog",
793
- description: "Execution log entry",
794
- fields: {
795
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
796
- stepId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
797
- level: { type: LogLevelEnum, isOptional: false },
798
- message: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
799
- data: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
800
- source: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
801
- traceId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
802
- spanId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
803
- timestamp: { type: ScalarTypeEnum4.DateTime(), isOptional: false }
804
- }
805
- });
806
- var RunAgentRefModel = defineSchemaModel4({
807
- name: "RunAgentRef",
808
- description: "Agent reference in a run",
809
- fields: {
810
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
811
- name: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
812
- modelProvider: {
813
- type: ScalarTypeEnum4.String_unsecure(),
814
- isOptional: false
815
- },
816
- modelName: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false }
817
- }
818
- });
819
- var RunModel = defineSchemaModel4({
820
- name: "Run",
821
- description: "Agent execution instance",
822
- fields: {
823
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
824
- organizationId: {
825
- type: ScalarTypeEnum4.String_unsecure(),
826
- isOptional: false
827
- },
828
- agentId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
829
- userId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
830
- sessionId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
831
- input: { type: ScalarTypeEnum4.JSONObject(), isOptional: false },
832
- output: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
833
- status: { type: RunStatusEnum, isOptional: false },
834
- errorMessage: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
835
- errorCode: { type: ScalarTypeEnum4.String_unsecure(), isOptional: true },
836
- totalTokens: {
837
- type: ScalarTypeEnum4.Int_unsecure(),
838
- isOptional: false,
839
- defaultValue: 0
840
- },
841
- promptTokens: {
842
- type: ScalarTypeEnum4.Int_unsecure(),
843
- isOptional: false,
844
- defaultValue: 0
845
- },
846
- completionTokens: {
847
- type: ScalarTypeEnum4.Int_unsecure(),
848
- isOptional: false,
849
- defaultValue: 0
850
- },
851
- totalIterations: {
852
- type: ScalarTypeEnum4.Int_unsecure(),
853
- isOptional: false,
854
- defaultValue: 0
855
- },
856
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
857
- estimatedCostUsd: {
858
- type: ScalarTypeEnum4.Float_unsecure(),
859
- isOptional: true
860
- },
861
- queuedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
862
- startedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true },
863
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true },
864
- metadata: { type: ScalarTypeEnum4.JSONObject(), isOptional: true },
865
- steps: { type: RunStepModel, isArray: true, isOptional: true },
866
- logs: { type: RunLogModel, isArray: true, isOptional: true },
867
- agent: { type: RunAgentRefModel, isOptional: true }
868
- }
869
- });
870
- var RunSummaryModel = defineSchemaModel4({
871
- name: "RunSummary",
872
- description: "Summary of a run for list views",
873
- fields: {
874
- id: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
875
- agentId: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
876
- agentName: { type: ScalarTypeEnum4.NonEmptyString(), isOptional: false },
877
- status: { type: RunStatusEnum, isOptional: false },
878
- totalTokens: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
879
- durationMs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: true },
880
- estimatedCostUsd: {
881
- type: ScalarTypeEnum4.Float_unsecure(),
882
- isOptional: true
883
- },
884
- queuedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: false },
885
- completedAt: { type: ScalarTypeEnum4.DateTime(), isOptional: true }
886
- }
887
- });
888
- var TimelineDataPointModel = defineSchemaModel4({
889
- name: "TimelineDataPoint",
890
- description: "Timeline data point for metrics",
891
- fields: {
892
- period: { type: ScalarTypeEnum4.String_unsecure(), isOptional: false },
893
- runs: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
894
- tokens: { type: ScalarTypeEnum4.Int_unsecure(), isOptional: false },
895
- costUsd: { type: ScalarTypeEnum4.Float_unsecure(), isOptional: false },
896
- avgDurationMs: { type: ScalarTypeEnum4.Float_unsecure(), isOptional: false }
897
- }
898
- });
899
-
900
- // src/run/run.operation.ts
901
- import {
902
- defineCommand as defineCommand2,
903
- defineQuery as defineQuery2
904
- } from "@contractspec/lib.contracts-spec/operations";
905
- import { defineSchemaModel as defineSchemaModel5, ScalarTypeEnum as ScalarTypeEnum5 } from "@contractspec/lib.schema";
906
- var OWNERS3 = ["@agent-console-team"];
907
- var ExecuteAgentCommand = defineCommand2({
908
- meta: {
909
- key: "agent.run.execute",
910
- version: "1.0.0",
911
- stability: "stable",
912
- owners: [...OWNERS3],
913
- tags: ["run", "execute"],
914
- description: "Starts a new agent run with the given input.",
915
- goal: "Execute an AI agent with user input.",
916
- context: "Called from chat interface or API."
917
- },
918
- io: {
919
- input: defineSchemaModel5({
920
- name: "ExecuteAgentInput",
921
- fields: {
922
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
923
- input: { type: RunInputModel, isOptional: false },
924
- sessionId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
925
- metadata: { type: ScalarTypeEnum5.JSONObject(), isOptional: true },
926
- stream: { type: ScalarTypeEnum5.Boolean(), isOptional: true },
927
- maxIterations: {
928
- type: ScalarTypeEnum5.Int_unsecure(),
929
- isOptional: true
930
- },
931
- timeoutMs: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: true }
932
- }
933
- }),
934
- output: defineSchemaModel5({
935
- name: "ExecuteAgentOutput",
936
- fields: {
937
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
938
- status: { type: RunStatusEnum, isOptional: false },
939
- estimatedWaitMs: {
940
- type: ScalarTypeEnum5.Int_unsecure(),
941
- isOptional: true
942
- }
943
- }
944
- }),
945
- errors: {
946
- AGENT_NOT_FOUND: {
947
- description: "The specified agent does not exist",
948
- http: 404,
949
- gqlCode: "AGENT_NOT_FOUND",
950
- when: "Agent ID is invalid"
951
- },
952
- AGENT_NOT_ACTIVE: {
953
- description: "The specified agent is not active",
954
- http: 400,
955
- gqlCode: "AGENT_NOT_ACTIVE",
956
- when: "Agent is in draft/paused/archived state"
957
- }
958
- }
959
- },
960
- policy: { auth: "user" },
961
- sideEffects: {
962
- emits: [
963
- {
964
- key: "run.started",
965
- version: "1.0.0",
966
- stability: "stable",
967
- owners: [...OWNERS3],
968
- tags: ["run", "started"],
969
- when: "Run is queued",
970
- payload: RunSummaryModel
971
- }
972
- ],
973
- audit: ["run.started"]
974
- },
975
- acceptance: {
976
- scenarios: [
977
- {
978
- key: "execute-agent-happy-path",
979
- given: ["Agent exists", "Agent is active"],
980
- when: ["User submits execution request"],
981
- then: ["Run is created", "RunStarted event is emitted"]
982
- },
983
- {
984
- key: "execute-agent-not-active",
985
- given: ["Agent exists but is not active"],
986
- when: ["User attempts to execute"],
987
- then: ["AGENT_NOT_ACTIVE error is returned"]
988
- }
989
- ],
990
- examples: [
991
- {
992
- key: "basic-execute",
993
- input: { agentId: "agent-123", input: { message: "Hello" } },
994
- output: { runId: "run-456", status: "pending", estimatedWaitMs: 5000 }
995
- }
996
- ]
997
- }
998
- });
999
- var CancelRunCommand = defineCommand2({
1000
- meta: {
1001
- key: "agent.run.cancel",
1002
- version: "1.0.0",
1003
- stability: "stable",
1004
- owners: [...OWNERS3],
1005
- tags: ["run", "cancel"],
1006
- description: "Cancels an in-progress agent run.",
1007
- goal: "Stop a running agent execution.",
1008
- context: "Called when user wants to abort a long-running task."
1009
- },
1010
- io: {
1011
- input: defineSchemaModel5({
1012
- name: "CancelRunInput",
1013
- fields: {
1014
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1015
- reason: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true }
1016
- }
1017
- }),
1018
- output: defineSchemaModel5({
1019
- name: "CancelRunOutput",
1020
- fields: {
1021
- success: { type: ScalarTypeEnum5.Boolean(), isOptional: false },
1022
- status: { type: RunStatusEnum, isOptional: false }
1023
- }
1024
- }),
1025
- errors: {
1026
- RUN_NOT_FOUND: {
1027
- description: "The specified run does not exist",
1028
- http: 404,
1029
- gqlCode: "RUN_NOT_FOUND",
1030
- when: "Run ID is invalid"
1031
- },
1032
- RUN_NOT_CANCELLABLE: {
1033
- description: "The run cannot be cancelled",
1034
- http: 400,
1035
- gqlCode: "RUN_NOT_CANCELLABLE",
1036
- when: "Run is already completed/failed/cancelled"
1037
- }
1038
- }
1039
- },
1040
- policy: { auth: "user" },
1041
- sideEffects: {
1042
- emits: [
1043
- {
1044
- key: "run.cancelled",
1045
- version: "1.0.0",
1046
- stability: "stable",
1047
- owners: [...OWNERS3],
1048
- tags: ["run", "cancelled"],
1049
- when: "Run is cancelled",
1050
- payload: RunSummaryModel
1051
- }
1052
- ],
1053
- audit: ["run.cancelled"]
1054
- },
1055
- acceptance: {
1056
- scenarios: [
1057
- {
1058
- key: "cancel-run-happy-path",
1059
- given: ["Run exists", "Run is in progress"],
1060
- when: ["User cancels run"],
1061
- then: ["Run is cancelled", "RunCancelled event is emitted"]
1062
- },
1063
- {
1064
- key: "cancel-run-already-completed",
1065
- given: ["Run exists but is already completed"],
1066
- when: ["User attempts to cancel"],
1067
- then: ["RUN_NOT_CANCELLABLE error is returned"]
1068
- }
1069
- ],
1070
- examples: [
1071
- {
1072
- key: "cancel-basic",
1073
- input: { runId: "run-456", reason: "User requested" },
1074
- output: { success: true, status: "cancelled" }
1075
- }
1076
- ]
1077
- }
1078
- });
1079
- var GetRunQuery = defineQuery2({
1080
- meta: {
1081
- key: "agent.run.get",
1082
- version: "1.0.0",
1083
- stability: "stable",
1084
- owners: [...OWNERS3],
1085
- tags: ["run", "get"],
1086
- description: "Retrieves a run by its ID with optional details.",
1087
- goal: "View detailed run information.",
1088
- context: "Run details page or monitoring."
1089
- },
1090
- io: {
1091
- input: defineSchemaModel5({
1092
- name: "GetRunInput",
1093
- fields: {
1094
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1095
- includeSteps: { type: ScalarTypeEnum5.Boolean(), isOptional: true },
1096
- includeLogs: { type: ScalarTypeEnum5.Boolean(), isOptional: true }
1097
- }
1098
- }),
1099
- output: RunModel,
1100
- errors: {
1101
- RUN_NOT_FOUND: {
1102
- description: "The specified run does not exist",
1103
- http: 404,
1104
- gqlCode: "RUN_NOT_FOUND",
1105
- when: "Run ID is invalid"
1106
- }
1107
- }
1108
- },
1109
- policy: { auth: "user" },
1110
- acceptance: {
1111
- scenarios: [
1112
- {
1113
- key: "get-run-happy-path",
1114
- given: ["Run exists"],
1115
- when: ["User requests run by ID"],
1116
- then: ["Run details are returned"]
1117
- }
1118
- ],
1119
- examples: [
1120
- {
1121
- key: "get-with-steps",
1122
- input: { runId: "run-456", includeSteps: true, includeLogs: false },
1123
- output: { id: "run-456", status: "completed", steps: [] }
1124
- }
1125
- ]
1126
- }
1127
- });
1128
- var ListRunsQuery = defineQuery2({
1129
- meta: {
1130
- key: "agent.run.list",
1131
- version: "1.0.0",
1132
- stability: "stable",
1133
- owners: [...OWNERS3],
1134
- tags: ["run", "list"],
1135
- description: "Lists runs with optional filtering.",
1136
- goal: "Browse and search run history.",
1137
- context: "Run history/dashboard view."
1138
- },
1139
- io: {
1140
- input: defineSchemaModel5({
1141
- name: "ListRunsInput",
1142
- fields: {
1143
- organizationId: {
1144
- type: ScalarTypeEnum5.String_unsecure(),
1145
- isOptional: true
1146
- },
1147
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1148
- userId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1149
- sessionId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1150
- status: { type: RunStatusEnum, isOptional: true },
1151
- startDate: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1152
- endDate: { type: ScalarTypeEnum5.DateTime(), isOptional: true },
1153
- limit: {
1154
- type: ScalarTypeEnum5.Int_unsecure(),
1155
- isOptional: true,
1156
- defaultValue: 20
1157
- },
1158
- offset: {
1159
- type: ScalarTypeEnum5.Int_unsecure(),
1160
- isOptional: true,
1161
- defaultValue: 0
1162
- }
1163
- }
1164
- }),
1165
- output: defineSchemaModel5({
1166
- name: "ListRunsOutput",
1167
- fields: {
1168
- items: { type: RunSummaryModel, isArray: true, isOptional: false },
1169
- total: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1170
- hasMore: { type: ScalarTypeEnum5.Boolean(), isOptional: false }
1171
- }
1172
- })
1173
- },
1174
- policy: { auth: "user" },
1175
- acceptance: {
1176
- scenarios: [
1177
- {
1178
- key: "list-runs-happy-path",
1179
- given: ["Organization has runs"],
1180
- when: ["User lists runs"],
1181
- then: ["Paginated list of runs is returned"]
1182
- }
1183
- ],
1184
- examples: [
1185
- {
1186
- key: "list-by-agent",
1187
- input: { agentId: "agent-123", limit: 20, offset: 0 },
1188
- output: { items: [], total: 0, hasMore: false }
1189
- }
1190
- ]
1191
- }
1192
- });
1193
- var GetRunStepsQuery = defineQuery2({
1194
- meta: {
1195
- key: "agent.run.getSteps",
1196
- version: "1.0.0",
1197
- stability: "stable",
1198
- owners: [...OWNERS3],
1199
- tags: ["run", "steps"],
1200
- description: "Retrieves all steps for a specific run.",
1201
- goal: "View step-by-step execution details.",
1202
- context: "Run details page - steps tab."
1203
- },
1204
- io: {
1205
- input: defineSchemaModel5({
1206
- name: "GetRunStepsInput",
1207
- fields: {
1208
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false }
1209
- }
1210
- }),
1211
- output: defineSchemaModel5({
1212
- name: "GetRunStepsOutput",
1213
- fields: {
1214
- steps: { type: RunStepModel, isArray: true, isOptional: false }
1215
- }
1216
- })
1217
- },
1218
- policy: { auth: "user" },
1219
- acceptance: {
1220
- scenarios: [
1221
- {
1222
- key: "get-run-steps-happy-path",
1223
- given: ["Run exists with steps"],
1224
- when: ["User requests steps"],
1225
- then: ["Steps list is returned"]
1226
- }
1227
- ],
1228
- examples: [
1229
- {
1230
- key: "get-steps-basic",
1231
- input: { runId: "run-456" },
1232
- output: { steps: [] }
1233
- }
1234
- ]
1235
- }
1236
- });
1237
- var GetRunLogsQuery = defineQuery2({
1238
- meta: {
1239
- key: "agent.run.getLogs",
1240
- version: "1.0.0",
1241
- stability: "stable",
1242
- owners: [...OWNERS3],
1243
- tags: ["run", "logs"],
1244
- description: "Retrieves all logs for a specific run.",
1245
- goal: "Debug and audit run execution.",
1246
- context: "Run details page - logs tab."
1247
- },
1248
- io: {
1249
- input: defineSchemaModel5({
1250
- name: "GetRunLogsInput",
1251
- fields: {
1252
- runId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: false },
1253
- level: { type: LogLevelEnum, isOptional: true },
1254
- stepId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1255
- limit: {
1256
- type: ScalarTypeEnum5.Int_unsecure(),
1257
- isOptional: true,
1258
- defaultValue: 100
1259
- },
1260
- offset: {
1261
- type: ScalarTypeEnum5.Int_unsecure(),
1262
- isOptional: true,
1263
- defaultValue: 0
1264
- }
1265
- }
1266
- }),
1267
- output: defineSchemaModel5({
1268
- name: "GetRunLogsOutput",
1269
- fields: {
1270
- items: { type: RunLogModel, isArray: true, isOptional: false },
1271
- total: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1272
- hasMore: { type: ScalarTypeEnum5.Boolean(), isOptional: false }
1273
- }
1274
- })
1275
- },
1276
- policy: { auth: "user" },
1277
- acceptance: {
1278
- scenarios: [
1279
- {
1280
- key: "get-run-logs-happy-path",
1281
- given: ["Run exists with logs"],
1282
- when: ["User requests logs"],
1283
- then: ["Paginated logs list is returned"]
1284
- }
1285
- ],
1286
- examples: [
1287
- {
1288
- key: "get-logs-filtered",
1289
- input: { runId: "run-456", level: "error", limit: 50 },
1290
- output: { items: [], total: 0, hasMore: false }
1291
- }
1292
- ]
1293
- }
1294
- });
1295
- var GetRunMetricsQuery = defineQuery2({
1296
- meta: {
1297
- key: "agent.run.getMetrics",
1298
- version: "1.0.0",
1299
- stability: "stable",
1300
- owners: [...OWNERS3],
1301
- tags: ["run", "metrics"],
1302
- description: "Retrieves aggregated metrics for runs within a time period.",
1303
- goal: "Monitor and analyze agent usage.",
1304
- context: "Analytics dashboard."
1305
- },
1306
- io: {
1307
- input: defineSchemaModel5({
1308
- name: "GetRunMetricsInput",
1309
- fields: {
1310
- organizationId: {
1311
- type: ScalarTypeEnum5.String_unsecure(),
1312
- isOptional: false
1313
- },
1314
- agentId: { type: ScalarTypeEnum5.String_unsecure(), isOptional: true },
1315
- startDate: { type: ScalarTypeEnum5.DateTime(), isOptional: false },
1316
- endDate: { type: ScalarTypeEnum5.DateTime(), isOptional: false },
1317
- granularity: {
1318
- type: GranularityEnum,
1319
- isOptional: true,
1320
- defaultValue: "day"
1321
- }
1322
- }
1323
- }),
1324
- output: defineSchemaModel5({
1325
- name: "GetRunMetricsOutput",
1326
- fields: {
1327
- totalRuns: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1328
- completedRuns: {
1329
- type: ScalarTypeEnum5.Int_unsecure(),
1330
- isOptional: false
1331
- },
1332
- failedRuns: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1333
- totalTokens: { type: ScalarTypeEnum5.Int_unsecure(), isOptional: false },
1334
- totalCostUsd: {
1335
- type: ScalarTypeEnum5.Float_unsecure(),
1336
- isOptional: false
1337
- },
1338
- averageDurationMs: {
1339
- type: ScalarTypeEnum5.Float_unsecure(),
1340
- isOptional: false
1341
- },
1342
- successRate: {
1343
- type: ScalarTypeEnum5.Float_unsecure(),
1344
- isOptional: false
1345
- },
1346
- timeline: {
1347
- type: TimelineDataPointModel,
1348
- isArray: true,
1349
- isOptional: false
1350
- }
1351
- }
1352
- })
1353
- },
1354
- policy: { auth: "user" },
1355
- acceptance: {
1356
- scenarios: [
1357
- {
1358
- key: "get-run-metrics-happy-path",
1359
- given: ["Organization has run history"],
1360
- when: ["User requests metrics for date range"],
1361
- then: ["Aggregated metrics are returned"]
1362
- }
1363
- ],
1364
- examples: [
1365
- {
1366
- key: "get-daily-metrics",
1367
- input: {
1368
- organizationId: "org-123",
1369
- startDate: "2025-01-01",
1370
- endDate: "2025-01-31",
1371
- granularity: "day"
1372
- },
1373
- output: {
1374
- totalRuns: 100,
1375
- completedRuns: 90,
1376
- failedRuns: 10,
1377
- totalTokens: 50000,
1378
- totalCostUsd: 5,
1379
- averageDurationMs: 2500,
1380
- successRate: 0.9,
1381
- timeline: []
1382
- }
1383
- }
1384
- ]
1385
- }
1386
- });
1387
-
1388
- // src/tool/tool.enum.ts
1389
- import { defineEnum as defineEnum3 } from "@contractspec/lib.schema";
1390
- var ToolCategoryEnum = defineEnum3("ToolCategory", [
1391
- "RETRIEVAL",
1392
- "COMPUTATION",
1393
- "COMMUNICATION",
1394
- "INTEGRATION",
1395
- "UTILITY",
1396
- "CUSTOM"
1397
- ]);
1398
- var ToolStatusEnum = defineEnum3("ToolStatus", [
1399
- "DRAFT",
1400
- "ACTIVE",
1401
- "DEPRECATED",
1402
- "DISABLED"
1403
- ]);
1404
- var ImplementationTypeEnum = defineEnum3("ImplementationType", [
1405
- "http",
1406
- "function",
1407
- "workflow"
1408
- ]);
1409
-
1410
- // src/tool/tool.schema.ts
1411
- import { defineSchemaModel as defineSchemaModel6, ScalarTypeEnum as ScalarTypeEnum6 } from "@contractspec/lib.schema";
1412
- var ToolModel = defineSchemaModel6({
1413
- name: "Tool",
1414
- description: "AI tool definition",
1415
- fields: {
1416
- id: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1417
- organizationId: {
1418
- type: ScalarTypeEnum6.String_unsecure(),
1419
- isOptional: false
1420
- },
1421
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1422
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1423
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1424
- category: { type: ToolCategoryEnum, isOptional: false },
1425
- status: { type: ToolStatusEnum, isOptional: false },
1426
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: false },
1427
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1428
- implementationType: { type: ImplementationTypeEnum, isOptional: false },
1429
- implementationConfig: {
1430
- type: ScalarTypeEnum6.JSONObject(),
1431
- isOptional: false
1432
- },
1433
- maxInvocationsPerMinute: {
1434
- type: ScalarTypeEnum6.Int_unsecure(),
1435
- isOptional: true
1436
- },
1437
- timeoutMs: {
1438
- type: ScalarTypeEnum6.Int_unsecure(),
1439
- isOptional: false,
1440
- defaultValue: 30000
1441
- },
1442
- version: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1443
- tags: {
1444
- type: ScalarTypeEnum6.String_unsecure(),
1445
- isArray: true,
1446
- isOptional: true
1447
- },
1448
- createdAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false },
1449
- updatedAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false }
1450
- }
1451
- });
1452
- var ToolSummaryModel = defineSchemaModel6({
1453
- name: "ToolSummary",
1454
- description: "Summary of a tool for list views",
1455
- fields: {
1456
- id: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1457
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1458
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1459
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1460
- category: { type: ToolCategoryEnum, isOptional: false },
1461
- status: { type: ToolStatusEnum, isOptional: false },
1462
- version: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1463
- createdAt: { type: ScalarTypeEnum6.DateTime(), isOptional: false }
1464
- }
1465
- });
1466
- var CreateToolInputModel = defineSchemaModel6({
1467
- name: "CreateToolInput",
1468
- description: "Input for creating a tool",
1469
- fields: {
1470
- organizationId: {
1471
- type: ScalarTypeEnum6.String_unsecure(),
1472
- isOptional: false
1473
- },
1474
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: false },
1475
- slug: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1476
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1477
- category: { type: ToolCategoryEnum, isOptional: true },
1478
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: false },
1479
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1480
- implementationType: { type: ImplementationTypeEnum, isOptional: false },
1481
- implementationConfig: {
1482
- type: ScalarTypeEnum6.JSONObject(),
1483
- isOptional: false
1484
- },
1485
- maxInvocationsPerMinute: {
1486
- type: ScalarTypeEnum6.Int_unsecure(),
1487
- isOptional: true
1488
- },
1489
- timeoutMs: { type: ScalarTypeEnum6.Int_unsecure(), isOptional: true },
1490
- tags: {
1491
- type: ScalarTypeEnum6.String_unsecure(),
1492
- isArray: true,
1493
- isOptional: true
1494
- }
1495
- }
1496
- });
1497
- var UpdateToolInputModel = defineSchemaModel6({
1498
- name: "UpdateToolInput",
1499
- description: "Input for updating a tool",
1500
- fields: {
1501
- toolId: { type: ScalarTypeEnum6.String_unsecure(), isOptional: false },
1502
- name: { type: ScalarTypeEnum6.NonEmptyString(), isOptional: true },
1503
- description: { type: ScalarTypeEnum6.String_unsecure(), isOptional: true },
1504
- status: { type: ToolStatusEnum, isOptional: true },
1505
- parametersSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1506
- outputSchema: { type: ScalarTypeEnum6.JSONObject(), isOptional: true },
1507
- implementationConfig: {
1508
- type: ScalarTypeEnum6.JSONObject(),
1509
- isOptional: true
1510
- },
1511
- maxInvocationsPerMinute: {
1512
- type: ScalarTypeEnum6.Int_unsecure(),
1513
- isOptional: true
1514
- },
1515
- timeoutMs: { type: ScalarTypeEnum6.Int_unsecure(), isOptional: true },
1516
- tags: {
1517
- type: ScalarTypeEnum6.String_unsecure(),
1518
- isArray: true,
1519
- isOptional: true
1520
- }
1521
- }
1522
- });
1523
-
1524
- // src/tool/tool.operation.ts
1525
- import {
1526
- defineCommand as defineCommand3,
1527
- defineQuery as defineQuery3
1528
- } from "@contractspec/lib.contracts-spec/operations";
1529
- import { defineSchemaModel as defineSchemaModel7, ScalarTypeEnum as ScalarTypeEnum7 } from "@contractspec/lib.schema";
1530
- var OWNERS4 = ["@agent-console-team"];
1531
- var CreateToolCommand = defineCommand3({
1532
- meta: {
1533
- key: "agent.tool.create",
1534
- version: "1.0.0",
1535
- stability: "stable",
1536
- owners: [...OWNERS4],
1537
- tags: ["tool", "create"],
1538
- description: "Creates a new AI tool definition.",
1539
- goal: "Allow users to define new tools that agents can use.",
1540
- context: "Called from the tool builder UI when creating a new tool."
1541
- },
1542
- io: {
1543
- input: CreateToolInputModel,
1544
- output: defineSchemaModel7({
1545
- name: "CreateToolOutput",
1546
- fields: {
1547
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1548
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1549
- slug: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1550
- status: { type: ToolStatusEnum, isOptional: false }
1551
- }
1552
- }),
1553
- errors: {
1554
- SLUG_EXISTS: {
1555
- description: "A tool with this slug already exists in the organization",
1556
- http: 409,
1557
- gqlCode: "SLUG_EXISTS",
1558
- when: "Slug is already taken"
1559
- }
1560
- }
1561
- },
1562
- policy: { auth: "user" },
1563
- sideEffects: {
1564
- emits: [
1565
- {
1566
- key: "tool.created",
1567
- version: "1.0.0",
1568
- stability: "stable",
1569
- owners: [...OWNERS4],
1570
- tags: ["tool", "created"],
1571
- when: "Tool is successfully created",
1572
- payload: ToolSummaryModel
1573
- }
1574
- ],
1575
- audit: ["tool.created"]
1576
- },
1577
- acceptance: {
1578
- scenarios: [
1579
- {
1580
- key: "create-tool-happy-path",
1581
- given: ["User is authenticated", "Organization exists"],
1582
- when: ["User submits valid tool configuration"],
1583
- then: ["New tool is created", "ToolCreated event is emitted"]
1584
- },
1585
- {
1586
- key: "create-tool-slug-conflict",
1587
- given: ["Tool with same slug exists"],
1588
- when: ["User submits tool with duplicate slug"],
1589
- then: ["SLUG_EXISTS error is returned"]
1590
- }
1591
- ],
1592
- examples: [
1593
- {
1594
- key: "create-api-tool",
1595
- input: {
1596
- name: "Weather API",
1597
- slug: "weather-api",
1598
- category: "api",
1599
- description: "Fetches weather data"
1600
- },
1601
- output: {
1602
- id: "tool-123",
1603
- name: "Weather API",
1604
- slug: "weather-api",
1605
- status: "draft"
1606
- }
1607
- }
1608
- ]
1609
- }
1610
- });
1611
- var UpdateToolCommand = defineCommand3({
1612
- meta: {
1613
- key: "agent.tool.update",
1614
- version: "1.0.0",
1615
- stability: "stable",
1616
- owners: [...OWNERS4],
1617
- tags: ["tool", "update"],
1618
- description: "Updates an existing AI tool definition.",
1619
- goal: "Allow users to modify tool settings and configuration.",
1620
- context: "Called from the tool settings UI."
1621
- },
1622
- io: {
1623
- input: UpdateToolInputModel,
1624
- output: defineSchemaModel7({
1625
- name: "UpdateToolOutput",
1626
- fields: {
1627
- id: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1628
- name: { type: ScalarTypeEnum7.NonEmptyString(), isOptional: false },
1629
- status: { type: ToolStatusEnum, isOptional: false },
1630
- updatedAt: { type: ScalarTypeEnum7.DateTime(), isOptional: false }
1631
- }
1632
- }),
1633
- errors: {
1634
- TOOL_NOT_FOUND: {
1635
- description: "The specified tool does not exist",
1636
- http: 404,
1637
- gqlCode: "TOOL_NOT_FOUND",
1638
- when: "Tool ID is invalid"
1639
- }
1640
- }
1641
- },
1642
- policy: { auth: "user" },
1643
- sideEffects: {
1644
- emits: [
1645
- {
1646
- key: "tool.updated",
1647
- version: "1.0.0",
1648
- stability: "stable",
1649
- owners: [...OWNERS4],
1650
- tags: ["tool", "updated"],
1651
- when: "Tool is updated",
1652
- payload: ToolSummaryModel
1653
- }
1654
- ],
1655
- audit: ["tool.updated"]
1656
- },
1657
- acceptance: {
1658
- scenarios: [
1659
- {
1660
- key: "update-tool-happy-path",
1661
- given: ["Tool exists", "User owns the tool"],
1662
- when: ["User submits updated configuration"],
1663
- then: ["Tool is updated", "ToolUpdated event is emitted"]
1664
- }
1665
- ],
1666
- examples: [
1667
- {
1668
- key: "update-description",
1669
- input: { toolId: "tool-123", description: "Updated weather API tool" },
1670
- output: {
1671
- id: "tool-123",
1672
- name: "Weather API",
1673
- status: "draft",
1674
- updatedAt: "2025-01-01T00:00:00Z"
1675
- }
1676
- }
1677
- ]
1678
- }
1679
- });
1680
- var GetToolQuery = defineQuery3({
1681
- meta: {
1682
- key: "agent.tool.get",
1683
- version: "1.0.0",
1684
- stability: "stable",
1685
- owners: [...OWNERS4],
1686
- tags: ["tool", "get"],
1687
- description: "Retrieves a tool by its ID.",
1688
- goal: "View detailed tool configuration.",
1689
- context: "Called when viewing tool details or editing."
1690
- },
1691
- io: {
1692
- input: defineSchemaModel7({
1693
- name: "GetToolInput",
1694
- fields: {
1695
- toolId: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false }
1696
- }
1697
- }),
1698
- output: ToolModel,
1699
- errors: {
1700
- TOOL_NOT_FOUND: {
1701
- description: "The specified tool does not exist",
1702
- http: 404,
1703
- gqlCode: "TOOL_NOT_FOUND",
1704
- when: "Tool ID is invalid"
1705
- }
1706
- }
1707
- },
1708
- policy: { auth: "user" },
1709
- acceptance: {
1710
- scenarios: [
1711
- {
1712
- key: "get-tool-happy-path",
1713
- given: ["Tool exists"],
1714
- when: ["User requests tool by ID"],
1715
- then: ["Tool details are returned"]
1716
- }
1717
- ],
1718
- examples: [
1719
- {
1720
- key: "get-basic",
1721
- input: { toolId: "tool-123" },
1722
- output: {
1723
- id: "tool-123",
1724
- name: "Weather API",
1725
- status: "active",
1726
- category: "api"
1727
- }
1728
- }
1729
- ]
1730
- }
1731
- });
1732
- var ListToolsQuery = defineQuery3({
1733
- meta: {
1734
- key: "agent.tool.list",
1735
- version: "1.0.0",
1736
- stability: "stable",
1737
- owners: [...OWNERS4],
1738
- tags: ["tool", "list"],
1739
- description: "Lists tools for an organization with optional filtering.",
1740
- goal: "Browse and search available tools.",
1741
- context: "Tool list/dashboard view."
1742
- },
1743
- io: {
1744
- input: defineSchemaModel7({
1745
- name: "ListToolsInput",
1746
- fields: {
1747
- organizationId: {
1748
- type: ScalarTypeEnum7.String_unsecure(),
1749
- isOptional: false
1750
- },
1751
- category: { type: ToolCategoryEnum, isOptional: true },
1752
- status: { type: ToolStatusEnum, isOptional: true },
1753
- search: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1754
- limit: {
1755
- type: ScalarTypeEnum7.Int_unsecure(),
1756
- isOptional: true,
1757
- defaultValue: 20
1758
- },
1759
- offset: {
1760
- type: ScalarTypeEnum7.Int_unsecure(),
1761
- isOptional: true,
1762
- defaultValue: 0
1763
- }
1764
- }
1765
- }),
1766
- output: defineSchemaModel7({
1767
- name: "ListToolsOutput",
1768
- fields: {
1769
- items: { type: ToolSummaryModel, isArray: true, isOptional: false },
1770
- total: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: false },
1771
- hasMore: { type: ScalarTypeEnum7.Boolean(), isOptional: false }
1772
- }
1773
- })
1774
- },
1775
- policy: { auth: "user" },
1776
- acceptance: {
1777
- scenarios: [
1778
- {
1779
- key: "list-tools-happy-path",
1780
- given: ["Organization has tools"],
1781
- when: ["User lists tools"],
1782
- then: ["Paginated list of tools is returned"]
1783
- }
1784
- ],
1785
- examples: [
1786
- {
1787
- key: "list-by-category",
1788
- input: { organizationId: "org-123", category: "api", limit: 10 },
1789
- output: { items: [], total: 0, hasMore: false }
1790
- }
1791
- ]
1792
- }
1793
- });
1794
- var TestToolCommand = defineCommand3({
1795
- meta: {
1796
- key: "agent.tool.test",
1797
- version: "1.0.0",
1798
- stability: "stable",
1799
- owners: [...OWNERS4],
1800
- tags: ["tool", "test"],
1801
- description: "Tests a tool with sample input to verify it works correctly.",
1802
- goal: "Validate tool configuration before deployment.",
1803
- context: "Tool builder UI - test panel."
1804
- },
1805
- io: {
1806
- input: defineSchemaModel7({
1807
- name: "TestToolInput",
1808
- fields: {
1809
- toolId: { type: ScalarTypeEnum7.String_unsecure(), isOptional: false },
1810
- testInput: { type: ScalarTypeEnum7.JSONObject(), isOptional: false }
1811
- }
1812
- }),
1813
- output: defineSchemaModel7({
1814
- name: "TestToolOutput",
1815
- fields: {
1816
- success: { type: ScalarTypeEnum7.Boolean(), isOptional: false },
1817
- output: { type: ScalarTypeEnum7.JSONObject(), isOptional: true },
1818
- error: { type: ScalarTypeEnum7.String_unsecure(), isOptional: true },
1819
- durationMs: { type: ScalarTypeEnum7.Int_unsecure(), isOptional: false }
1820
- }
1821
- }),
1822
- errors: {
1823
- TOOL_NOT_FOUND: {
1824
- description: "The specified tool does not exist",
1825
- http: 404,
1826
- gqlCode: "TOOL_NOT_FOUND",
1827
- when: "Tool ID is invalid"
1828
- },
1829
- TOOL_EXECUTION_ERROR: {
1830
- description: "Tool execution failed",
1831
- http: 500,
1832
- gqlCode: "TOOL_EXECUTION_ERROR",
1833
- when: "Tool returns an error"
1834
- }
1835
- }
1836
- },
1837
- policy: { auth: "user" },
1838
- sideEffects: { audit: ["tool.tested"] },
1839
- acceptance: {
1840
- scenarios: [
1841
- {
1842
- key: "test-tool-success",
1843
- given: ["Tool exists", "Tool is configured correctly"],
1844
- when: ["User runs test with valid input"],
1845
- then: ["Tool executes successfully", "Output is returned"]
1846
- },
1847
- {
1848
- key: "test-tool-failure",
1849
- given: ["Tool exists", "Tool has configuration error"],
1850
- when: ["User runs test"],
1851
- then: ["TOOL_EXECUTION_ERROR is returned"]
1852
- }
1853
- ],
1854
- examples: [
1855
- {
1856
- key: "test-weather-api",
1857
- input: { toolId: "tool-123", testInput: { city: "Paris" } },
1858
- output: { success: true, output: { temperature: 22 }, durationMs: 150 }
1859
- }
1860
- ]
1861
- }
1862
- });
1863
-
1864
- // src/handlers/agent.handlers.ts
1865
- import { web } from "@contractspec/lib.runtime-sandbox";
1866
- var { generateId } = web;
1867
- var RUN_SORT_COLUMNS = {
1868
- queuedAt: "r.queuedAt",
1869
- totalTokens: "r.totalTokens",
1870
- durationMs: "r.durationMs",
1871
- estimatedCostUsd: "r.estimatedCostUsd",
1872
- status: "r.status",
1873
- agentName: "a.name"
1874
- };
1875
- function rowToAgent(row) {
1876
- return {
1877
- id: row.id,
1878
- projectId: row.projectId,
1879
- organizationId: row.organizationId,
1880
- name: row.name,
1881
- description: row.description ?? undefined,
1882
- modelProvider: row.modelProvider,
1883
- modelName: row.modelName,
1884
- systemPrompt: row.systemPrompt ?? undefined,
1885
- temperature: row.temperature,
1886
- maxTokens: row.maxTokens,
1887
- status: row.status,
1888
- createdAt: new Date(row.createdAt),
1889
- updatedAt: new Date(row.updatedAt)
1890
- };
1891
- }
1892
- function rowToTool(row) {
1893
- return {
1894
- id: row.id,
1895
- projectId: row.projectId,
1896
- organizationId: row.organizationId,
1897
- name: row.name,
1898
- description: row.description ?? undefined,
1899
- version: row.version,
1900
- category: row.category,
1901
- status: row.status,
1902
- inputSchema: row.inputSchema ?? undefined,
1903
- outputSchema: row.outputSchema ?? undefined,
1904
- endpoint: row.endpoint ?? undefined,
1905
- createdAt: new Date(row.createdAt),
1906
- updatedAt: new Date(row.updatedAt)
1907
- };
1908
- }
1909
- function rowToRun(row, agentName) {
1910
- return {
1911
- id: row.id,
1912
- projectId: row.projectId,
1913
- agentId: row.agentId,
1914
- agentName,
1915
- status: row.status,
1916
- input: row.input ?? undefined,
1917
- output: row.output ?? undefined,
1918
- totalTokens: row.totalTokens,
1919
- promptTokens: row.promptTokens,
1920
- completionTokens: row.completionTokens,
1921
- estimatedCostUsd: row.estimatedCostUsd,
1922
- durationMs: row.durationMs ?? undefined,
1923
- errorMessage: row.errorMessage ?? undefined,
1924
- queuedAt: new Date(row.queuedAt),
1925
- startedAt: row.startedAt ? new Date(row.startedAt) : undefined,
1926
- completedAt: row.completedAt ? new Date(row.completedAt) : undefined
1927
- };
1928
- }
1929
- function createAgentHandlers(db) {
1930
- async function listAgents(input) {
1931
- const {
1932
- projectId,
1933
- organizationId,
1934
- status,
1935
- search,
1936
- limit = 20,
1937
- offset = 0
1938
- } = input;
1939
- let whereClause = "WHERE projectId = ?";
1940
- const params = [projectId];
1941
- if (organizationId) {
1942
- whereClause += " AND organizationId = ?";
1943
- params.push(organizationId);
1944
- }
1945
- if (status && status !== "all") {
1946
- whereClause += " AND status = ?";
1947
- params.push(status);
1948
- }
1949
- if (search) {
1950
- whereClause += " AND (name LIKE ? OR description LIKE ?)";
1951
- params.push(`%${search}%`, `%${search}%`);
1952
- }
1953
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_definition ${whereClause}`, params)).rows;
1954
- const total = countResult[0]?.count ?? 0;
1955
- const rows = (await db.query(`SELECT * FROM agent_definition ${whereClause} ORDER BY createdAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
1956
- return {
1957
- items: rows.map(rowToAgent),
1958
- total,
1959
- hasMore: offset + rows.length < total
1960
- };
1961
- }
1962
- async function getAgent(id) {
1963
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [id])).rows;
1964
- return rows[0] ? rowToAgent(rows[0]) : null;
1965
- }
1966
- async function createAgent(input, context) {
1967
- const id = generateId("agent");
1968
- const now = new Date().toISOString();
1969
- await db.execute(`INSERT INTO agent_definition (id, projectId, organizationId, name, description, modelProvider, modelName, systemPrompt, temperature, maxTokens, status, createdAt, updatedAt)
1970
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1971
- id,
1972
- context.projectId,
1973
- context.organizationId,
1974
- input.name,
1975
- input.description ?? null,
1976
- input.modelProvider ?? "openai",
1977
- input.modelName ?? "gpt-4",
1978
- input.systemPrompt ?? null,
1979
- input.temperature ?? 0.7,
1980
- input.maxTokens ?? 4096,
1981
- "DRAFT",
1982
- now,
1983
- now
1984
- ]);
1985
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [id])).rows;
1986
- const row = rows[0];
1987
- if (!row) {
1988
- throw new Error("Failed to retrieve created agent");
1989
- }
1990
- return rowToAgent(row);
1991
- }
1992
- async function updateAgent(input) {
1993
- const now = new Date().toISOString();
1994
- const updates = ["updatedAt = ?"];
1995
- const params = [now];
1996
- if (input.name !== undefined) {
1997
- updates.push("name = ?");
1998
- params.push(input.name);
1999
- }
2000
- if (input.description !== undefined) {
2001
- updates.push("description = ?");
2002
- params.push(input.description);
2003
- }
2004
- if (input.status !== undefined) {
2005
- updates.push("status = ?");
2006
- params.push(input.status);
2007
- }
2008
- params.push(input.id);
2009
- await db.execute(`UPDATE agent_definition SET ${updates.join(", ")} WHERE id = ?`, params);
2010
- const rows = (await db.query(`SELECT * FROM agent_definition WHERE id = ?`, [input.id])).rows;
2011
- if (!rows[0]) {
2012
- throw new Error("NOT_FOUND");
2013
- }
2014
- return rowToAgent(rows[0]);
2015
- }
2016
- async function listTools(input) {
2017
- const {
2018
- projectId,
2019
- organizationId,
2020
- category,
2021
- status,
2022
- search,
2023
- limit = 50,
2024
- offset = 0
2025
- } = input;
2026
- let whereClause = "WHERE projectId = ?";
2027
- const params = [projectId];
2028
- if (organizationId) {
2029
- whereClause += " AND organizationId = ?";
2030
- params.push(organizationId);
2031
- }
2032
- if (category && category !== "all") {
2033
- whereClause += " AND category = ?";
2034
- params.push(category);
2035
- }
2036
- if (status && status !== "all") {
2037
- whereClause += " AND status = ?";
2038
- params.push(status);
2039
- }
2040
- if (search) {
2041
- whereClause += " AND (name LIKE ? OR description LIKE ?)";
2042
- params.push(`%${search}%`, `%${search}%`);
2043
- }
2044
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_tool ${whereClause}`, params)).rows;
2045
- const total = countResult[0]?.count ?? 0;
2046
- const rows = (await db.query(`SELECT * FROM agent_tool ${whereClause} ORDER BY name ASC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
2047
- return {
2048
- items: rows.map(rowToTool),
2049
- total,
2050
- hasMore: offset + rows.length < total
2051
- };
2052
- }
2053
- async function listRuns(input) {
2054
- const {
2055
- projectId,
2056
- agentId,
2057
- status,
2058
- sortBy,
2059
- sortDirection = "desc",
2060
- limit = 20,
2061
- offset = 0
2062
- } = input;
2063
- let whereClause = "WHERE r.projectId = ?";
2064
- const params = [projectId];
2065
- if (agentId) {
2066
- whereClause += " AND r.agentId = ?";
2067
- params.push(agentId);
2068
- }
2069
- if (status && status !== "all") {
2070
- whereClause += " AND r.status = ?";
2071
- params.push(status);
2072
- }
2073
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM agent_run r ${whereClause}`, params)).rows;
2074
- const total = countResult[0]?.count ?? 0;
2075
- const sortColumn = sortBy ? RUN_SORT_COLUMNS[sortBy] : RUN_SORT_COLUMNS.queuedAt;
2076
- const direction = sortDirection === "asc" ? "ASC" : "DESC";
2077
- const rows = (await db.query(`SELECT r.*, a.name as agentName
1
+ import{defineEnum as l}from"@contractspec/lib.schema";var U=l("AgentStatus",["DRAFT","ACTIVE","PAUSED","ARCHIVED"]),O=l("ModelProvider",["OPENAI","ANTHROPIC","GOOGLE","MISTRAL","CUSTOM"]),M=l("ToolChoice",["auto","required","none"]);import{defineEvent as s}from"@contractspec/lib.contracts-spec";import{defineSchemaModel as i,ScalarTypeEnum as V}from"@contractspec/lib.schema";var d=["@agent-console-team"],bk=i({name:"AgentCreatedPayload",description:"Payload for agent created event",fields:{id:{type:V.String_unsecure(),isOptional:!1},organizationId:{type:V.String_unsecure(),isOptional:!1},name:{type:V.String_unsecure(),isOptional:!1},slug:{type:V.String_unsecure(),isOptional:!1},modelProvider:{type:V.String_unsecure(),isOptional:!1},modelName:{type:V.String_unsecure(),isOptional:!1},toolCount:{type:V.Int_unsecure(),isOptional:!1},createdById:{type:V.String_unsecure(),isOptional:!0},createdAt:{type:V.DateTime(),isOptional:!1}}}),Hk=s({meta:{key:"agent-console.agent.created",version:"1.0.0",description:"A new AI agent was configured.",stability:"stable",owners:[...d],tags:["agent","created"]},payload:bk}),Ck=i({name:"AgentUpdatedPayload",description:"Payload for agent updated event",fields:{id:{type:V.String_unsecure(),isOptional:!1},organizationId:{type:V.String_unsecure(),isOptional:!1},name:{type:V.String_unsecure(),isOptional:!1},status:{type:V.String_unsecure(),isOptional:!1},updatedFields:{type:V.String_unsecure(),isArray:!0,isOptional:!1},updatedAt:{type:V.DateTime(),isOptional:!1}}}),mk=s({meta:{key:"agent-console.agent.updated",version:"1.0.0",description:"An AI agent configuration was updated.",stability:"stable",owners:[...d],tags:["agent","updated"]},payload:Ck}),Rk=i({name:"AgentToolAssignedPayload",description:"Payload for agent tool assigned event",fields:{agentId:{type:V.String_unsecure(),isOptional:!1},toolId:{type:V.String_unsecure(),isOptional:!1},agentName:{type:V.String_unsecure(),isOptional:!1},toolName:{type:V.String_unsecure(),isOptional:!1},assignedAt:{type:V.DateTime(),isOptional:!1}}}),uk=s({meta:{key:"agent-console.agent.toolAssigned",version:"1.0.0",description:"A tool was assigned to an agent.",stability:"stable",owners:[...d],tags:["agent","tool","assigned"]},payload:Rk}),gk=i({name:"AgentToolRemovedPayload",description:"Payload for agent tool removed event",fields:{agentId:{type:V.String_unsecure(),isOptional:!1},toolId:{type:V.String_unsecure(),isOptional:!1},agentName:{type:V.String_unsecure(),isOptional:!1},toolName:{type:V.String_unsecure(),isOptional:!1},removedAt:{type:V.DateTime(),isOptional:!1}}}),rk=s({meta:{key:"agent-console.agent.toolRemoved",version:"1.0.0",description:"A tool was removed from an agent.",stability:"stable",owners:[...d],tags:["agent","tool","removed"]},payload:gk});import{defineSchemaModel as R,ScalarTypeEnum as k}from"@contractspec/lib.schema";var kq=R({name:"Agent",description:"AI agent configuration",fields:{id:{type:k.String_unsecure(),isOptional:!1},organizationId:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!1},slug:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!0},status:{type:U,isOptional:!1},modelProvider:{type:O,isOptional:!1},modelName:{type:k.NonEmptyString(),isOptional:!1},modelConfig:{type:k.JSONObject(),isOptional:!0},systemPrompt:{type:k.String_unsecure(),isOptional:!1},userPromptTemplate:{type:k.String_unsecure(),isOptional:!0},toolIds:{type:k.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:M,isOptional:!1,defaultValue:"auto"},maxIterations:{type:k.Int_unsecure(),isOptional:!1,defaultValue:10},maxTokensPerRun:{type:k.Int_unsecure(),isOptional:!0},timeoutMs:{type:k.Int_unsecure(),isOptional:!1,defaultValue:120000},version:{type:k.NonEmptyString(),isOptional:!1},tags:{type:k.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:k.DateTime(),isOptional:!1},updatedAt:{type:k.DateTime(),isOptional:!1}}}),m=R({name:"AgentSummary",description:"Summary of an agent for list views",fields:{id:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!1},slug:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!0},status:{type:U,isOptional:!1},modelProvider:{type:O,isOptional:!1},modelName:{type:k.NonEmptyString(),isOptional:!1},version:{type:k.NonEmptyString(),isOptional:!1},createdAt:{type:k.DateTime(),isOptional:!1}}}),Mk=R({name:"AgentToolRef",description:"Tool reference in agent context",fields:{id:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!1},slug:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!1},category:{type:k.String_unsecure(),isOptional:!1}}}),Jk=R({name:"AgentWithTools",description:"Agent with associated tools",fields:{id:{type:k.String_unsecure(),isOptional:!1},organizationId:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!1},slug:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!0},status:{type:U,isOptional:!1},modelProvider:{type:O,isOptional:!1},modelName:{type:k.NonEmptyString(),isOptional:!1},modelConfig:{type:k.JSONObject(),isOptional:!0},systemPrompt:{type:k.String_unsecure(),isOptional:!1},userPromptTemplate:{type:k.String_unsecure(),isOptional:!0},toolIds:{type:k.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:M,isOptional:!1},maxIterations:{type:k.Int_unsecure(),isOptional:!1},maxTokensPerRun:{type:k.Int_unsecure(),isOptional:!0},timeoutMs:{type:k.Int_unsecure(),isOptional:!1},version:{type:k.NonEmptyString(),isOptional:!1},tags:{type:k.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:k.DateTime(),isOptional:!1},updatedAt:{type:k.DateTime(),isOptional:!1},tools:{type:Mk,isArray:!0,isOptional:!0}}}),Kk=R({name:"CreateAgentInput",description:"Input for creating an agent",fields:{organizationId:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!1},slug:{type:k.String_unsecure(),isOptional:!1},description:{type:k.String_unsecure(),isOptional:!0},modelProvider:{type:O,isOptional:!1},modelName:{type:k.NonEmptyString(),isOptional:!1},modelConfig:{type:k.JSONObject(),isOptional:!0},systemPrompt:{type:k.String_unsecure(),isOptional:!1},userPromptTemplate:{type:k.String_unsecure(),isOptional:!0},toolIds:{type:k.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:M,isOptional:!0},maxIterations:{type:k.Int_unsecure(),isOptional:!0},maxTokensPerRun:{type:k.Int_unsecure(),isOptional:!0},timeoutMs:{type:k.Int_unsecure(),isOptional:!0},tags:{type:k.String_unsecure(),isArray:!0,isOptional:!0}}}),Vk=R({name:"UpdateAgentInput",description:"Input for updating an agent",fields:{agentId:{type:k.String_unsecure(),isOptional:!1},name:{type:k.NonEmptyString(),isOptional:!0},description:{type:k.String_unsecure(),isOptional:!0},status:{type:U,isOptional:!0},modelConfig:{type:k.JSONObject(),isOptional:!0},systemPrompt:{type:k.String_unsecure(),isOptional:!0},userPromptTemplate:{type:k.String_unsecure(),isOptional:!0},toolIds:{type:k.String_unsecure(),isArray:!0,isOptional:!0},toolChoice:{type:M,isOptional:!0},maxIterations:{type:k.Int_unsecure(),isOptional:!0},maxTokensPerRun:{type:k.Int_unsecure(),isOptional:!0},timeoutMs:{type:k.Int_unsecure(),isOptional:!0},tags:{type:k.String_unsecure(),isArray:!0,isOptional:!0}}});import{defineCommand as y,defineQuery as Xk}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as P,ScalarTypeEnum as Y}from"@contractspec/lib.schema";var N=["@agent-console-team"],hk=y({meta:{key:"agent-console.agent.create",version:"1.0.0",stability:"stable",owners:[...N],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:Kk,output:P({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:U,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:Hk.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"}}]}}),fk=y({meta:{key:"agent-console.agent.update",version:"1.0.0",stability:"stable",owners:[...N],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:Vk,output:P({name:"UpdateAgentOutput",fields:{id:{type:Y.String_unsecure(),isOptional:!1},name:{type:Y.NonEmptyString(),isOptional:!1},status:{type:U,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:[...N],tags:["agent","updated"],when:"Agent is updated",payload:m}],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"}}]}}),wk=Xk({meta:{key:"agent-console.agent.get",version:"1.0.0",stability:"stable",owners:[...N],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:P({name:"GetAgentInput",fields:{agentId:{type:Y.String_unsecure(),isOptional:!1},includeTools:{type:Y.Boolean(),isOptional:!0}}}),output:Jk,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:[]}}]}}),sk=Xk({meta:{key:"agent-console.agent.list",version:"1.0.0",stability:"stable",owners:[...N],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:P({name:"ListAgentsInput",fields:{organizationId:{type:Y.String_unsecure(),isOptional:!1},status:{type:U,isOptional:!0},modelProvider:{type:O,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:P({name:"ListAgentsOutput",fields:{items:{type:m,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}}]}}),Xq=y({meta:{key:"agent-console.agent.assignTool",version:"1.0.0",stability:"stable",owners:[...N],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:P({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:P({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"}}]}}),Yq=y({meta:{key:"agent-console.agent.removeTool",version:"1.0.0",stability:"stable",owners:[...N],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:P({name:"RemoveToolFromAgentInput",fields:{agentId:{type:Y.String_unsecure(),isOptional:!1},toolId:{type:Y.String_unsecure(),isOptional:!1}}}),output:P({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}}]}});import{defineEnum as T}from"@contractspec/lib.schema";var I=T("RunStatus",["QUEUED","IN_PROGRESS","COMPLETED","FAILED","CANCELLED","EXPIRED"]),Yk=T("RunStepType",["MESSAGE_CREATION","TOOL_CALL","TOOL_RESULT","ERROR"]),t=T("LogLevel",["DEBUG","INFO","WARN","ERROR"]),Zk=T("Granularity",["hour","day","week","month"]);import{defineSchemaModel as A,ScalarTypeEnum as F}from"@contractspec/lib.schema";var $k=A({name:"RunInput",description:"Input data for agent execution",fields:{message:{type:F.NonEmptyString(),isOptional:!1},context:{type:F.JSONObject(),isOptional:!0}}}),u=A({name:"RunStep",description:"Individual step within a run",fields:{id:{type:F.String_unsecure(),isOptional:!1},stepNumber:{type:F.Int_unsecure(),isOptional:!1},type:{type:Yk,isOptional:!1},toolId:{type:F.String_unsecure(),isOptional:!0},toolName:{type:F.String_unsecure(),isOptional:!0},input:{type:F.JSONObject(),isOptional:!0},output:{type:F.JSONObject(),isOptional:!0},status:{type:I,isOptional:!1},errorMessage:{type:F.String_unsecure(),isOptional:!0},tokensUsed:{type:F.Int_unsecure(),isOptional:!1,defaultValue:0},durationMs:{type:F.Int_unsecure(),isOptional:!0},startedAt:{type:F.DateTime(),isOptional:!1},completedAt:{type:F.DateTime(),isOptional:!0}}}),r=A({name:"RunLog",description:"Execution log entry",fields:{id:{type:F.String_unsecure(),isOptional:!1},stepId:{type:F.String_unsecure(),isOptional:!0},level:{type:t,isOptional:!1},message:{type:F.String_unsecure(),isOptional:!1},data:{type:F.JSONObject(),isOptional:!0},source:{type:F.String_unsecure(),isOptional:!0},traceId:{type:F.String_unsecure(),isOptional:!0},spanId:{type:F.String_unsecure(),isOptional:!0},timestamp:{type:F.DateTime(),isOptional:!1}}}),ik=A({name:"RunAgentRef",description:"Agent reference in a run",fields:{id:{type:F.String_unsecure(),isOptional:!1},name:{type:F.NonEmptyString(),isOptional:!1},modelProvider:{type:F.String_unsecure(),isOptional:!1},modelName:{type:F.String_unsecure(),isOptional:!1}}}),Bk=A({name:"Run",description:"Agent execution instance",fields:{id:{type:F.String_unsecure(),isOptional:!1},organizationId:{type:F.String_unsecure(),isOptional:!1},agentId:{type:F.String_unsecure(),isOptional:!1},userId:{type:F.String_unsecure(),isOptional:!0},sessionId:{type:F.String_unsecure(),isOptional:!0},input:{type:F.JSONObject(),isOptional:!1},output:{type:F.JSONObject(),isOptional:!0},status:{type:I,isOptional:!1},errorMessage:{type:F.String_unsecure(),isOptional:!0},errorCode:{type:F.String_unsecure(),isOptional:!0},totalTokens:{type:F.Int_unsecure(),isOptional:!1,defaultValue:0},promptTokens:{type:F.Int_unsecure(),isOptional:!1,defaultValue:0},completionTokens:{type:F.Int_unsecure(),isOptional:!1,defaultValue:0},totalIterations:{type:F.Int_unsecure(),isOptional:!1,defaultValue:0},durationMs:{type:F.Int_unsecure(),isOptional:!0},estimatedCostUsd:{type:F.Float_unsecure(),isOptional:!0},queuedAt:{type:F.DateTime(),isOptional:!1},startedAt:{type:F.DateTime(),isOptional:!0},completedAt:{type:F.DateTime(),isOptional:!0},metadata:{type:F.JSONObject(),isOptional:!0},steps:{type:u,isArray:!0,isOptional:!0},logs:{type:r,isArray:!0,isOptional:!0},agent:{type:ik,isOptional:!0}}}),E=A({name:"RunSummary",description:"Summary of a run for list views",fields:{id:{type:F.String_unsecure(),isOptional:!1},agentId:{type:F.String_unsecure(),isOptional:!1},agentName:{type:F.NonEmptyString(),isOptional:!1},status:{type:I,isOptional:!1},totalTokens:{type:F.Int_unsecure(),isOptional:!1},durationMs:{type:F.Int_unsecure(),isOptional:!0},estimatedCostUsd:{type:F.Float_unsecure(),isOptional:!0},queuedAt:{type:F.DateTime(),isOptional:!1},completedAt:{type:F.DateTime(),isOptional:!0}}}),Dk=A({name:"TimelineDataPoint",description:"Timeline data point for metrics",fields:{period:{type:F.String_unsecure(),isOptional:!1},runs:{type:F.Int_unsecure(),isOptional:!1},tokens:{type:F.Int_unsecure(),isOptional:!1},costUsd:{type:F.Float_unsecure(),isOptional:!1},avgDurationMs:{type:F.Float_unsecure(),isOptional:!1}}});import{defineCommand as jk,defineQuery as h}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as G,ScalarTypeEnum as H}from"@contractspec/lib.schema";var L=["@agent-console-team"],dk=jk({meta:{key:"agent.run.execute",version:"1.0.0",stability:"stable",owners:[...L],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:G({name:"ExecuteAgentInput",fields:{agentId:{type:H.String_unsecure(),isOptional:!1},input:{type:$k,isOptional:!1},sessionId:{type:H.String_unsecure(),isOptional:!0},metadata:{type:H.JSONObject(),isOptional:!0},stream:{type:H.Boolean(),isOptional:!0},maxIterations:{type:H.Int_unsecure(),isOptional:!0},timeoutMs:{type:H.Int_unsecure(),isOptional:!0}}}),output:G({name:"ExecuteAgentOutput",fields:{runId:{type:H.String_unsecure(),isOptional:!1},status:{type:I,isOptional:!1},estimatedWaitMs:{type:H.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:[...L],tags:["run","started"],when:"Run is queued",payload:E}],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}}]}}),Pq=jk({meta:{key:"agent.run.cancel",version:"1.0.0",stability:"stable",owners:[...L],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:G({name:"CancelRunInput",fields:{runId:{type:H.String_unsecure(),isOptional:!1},reason:{type:H.String_unsecure(),isOptional:!0}}}),output:G({name:"CancelRunOutput",fields:{success:{type:H.Boolean(),isOptional:!1},status:{type:I,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:[...L],tags:["run","cancelled"],when:"Run is cancelled",payload:E}],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"}}]}}),Lq=h({meta:{key:"agent.run.get",version:"1.0.0",stability:"stable",owners:[...L],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:G({name:"GetRunInput",fields:{runId:{type:H.String_unsecure(),isOptional:!1},includeSteps:{type:H.Boolean(),isOptional:!0},includeLogs:{type:H.Boolean(),isOptional:!0}}}),output:Bk,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:[]}}]}}),yk=h({meta:{key:"agent.run.list",version:"1.0.0",stability:"stable",owners:[...L],tags:["run","list"],description:"Lists runs with optional filtering.",goal:"Browse and search run history.",context:"Run history/dashboard view."},io:{input:G({name:"ListRunsInput",fields:{organizationId:{type:H.String_unsecure(),isOptional:!0},agentId:{type:H.String_unsecure(),isOptional:!0},userId:{type:H.String_unsecure(),isOptional:!0},sessionId:{type:H.String_unsecure(),isOptional:!0},status:{type:I,isOptional:!0},startDate:{type:H.DateTime(),isOptional:!0},endDate:{type:H.DateTime(),isOptional:!0},limit:{type:H.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:H.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:G({name:"ListRunsOutput",fields:{items:{type:E,isArray:!0,isOptional:!1},total:{type:H.Int_unsecure(),isOptional:!1},hasMore:{type:H.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}}]}}),vq=h({meta:{key:"agent.run.getSteps",version:"1.0.0",stability:"stable",owners:[...L],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:G({name:"GetRunStepsInput",fields:{runId:{type:H.String_unsecure(),isOptional:!1}}}),output:G({name:"GetRunStepsOutput",fields:{steps:{type:u,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:[]}}]}}),Qq=h({meta:{key:"agent.run.getLogs",version:"1.0.0",stability:"stable",owners:[...L],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:G({name:"GetRunLogsInput",fields:{runId:{type:H.String_unsecure(),isOptional:!1},level:{type:t,isOptional:!0},stepId:{type:H.String_unsecure(),isOptional:!0},limit:{type:H.Int_unsecure(),isOptional:!0,defaultValue:100},offset:{type:H.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:G({name:"GetRunLogsOutput",fields:{items:{type:r,isArray:!0,isOptional:!1},total:{type:H.Int_unsecure(),isOptional:!1},hasMore:{type:H.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}}]}}),Tk=h({meta:{key:"agent.run.getMetrics",version:"1.0.0",stability:"stable",owners:[...L],tags:["run","metrics"],description:"Retrieves aggregated metrics for runs within a time period.",goal:"Monitor and analyze agent usage.",context:"Analytics dashboard."},io:{input:G({name:"GetRunMetricsInput",fields:{organizationId:{type:H.String_unsecure(),isOptional:!1},agentId:{type:H.String_unsecure(),isOptional:!0},startDate:{type:H.DateTime(),isOptional:!1},endDate:{type:H.DateTime(),isOptional:!1},granularity:{type:Zk,isOptional:!0,defaultValue:"day"}}}),output:G({name:"GetRunMetricsOutput",fields:{totalRuns:{type:H.Int_unsecure(),isOptional:!1},completedRuns:{type:H.Int_unsecure(),isOptional:!1},failedRuns:{type:H.Int_unsecure(),isOptional:!1},totalTokens:{type:H.Int_unsecure(),isOptional:!1},totalCostUsd:{type:H.Float_unsecure(),isOptional:!1},averageDurationMs:{type:H.Float_unsecure(),isOptional:!1},successRate:{type:H.Float_unsecure(),isOptional:!1},timeline:{type:Dk,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 n}from"@contractspec/lib.schema";var g=n("ToolCategory",["RETRIEVAL","COMPUTATION","COMMUNICATION","INTEGRATION","UTILITY","CUSTOM"]),W=n("ToolStatus",["DRAFT","ACTIVE","DEPRECATED","DISABLED"]),a=n("ImplementationType",["http","function","workflow"]);import{defineSchemaModel as o,ScalarTypeEnum as J}from"@contractspec/lib.schema";var zk=o({name:"Tool",description:"AI tool definition",fields:{id:{type:J.String_unsecure(),isOptional:!1},organizationId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!1},slug:{type:J.String_unsecure(),isOptional:!1},description:{type:J.String_unsecure(),isOptional:!1},category:{type:g,isOptional:!1},status:{type:W,isOptional:!1},parametersSchema:{type:J.JSONObject(),isOptional:!1},outputSchema:{type:J.JSONObject(),isOptional:!0},implementationType:{type:a,isOptional:!1},implementationConfig:{type:J.JSONObject(),isOptional:!1},maxInvocationsPerMinute:{type:J.Int_unsecure(),isOptional:!0},timeoutMs:{type:J.Int_unsecure(),isOptional:!1,defaultValue:30000},version:{type:J.NonEmptyString(),isOptional:!1},tags:{type:J.String_unsecure(),isArray:!0,isOptional:!0},createdAt:{type:J.DateTime(),isOptional:!1},updatedAt:{type:J.DateTime(),isOptional:!1}}}),S=o({name:"ToolSummary",description:"Summary of a tool for list views",fields:{id:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!1},slug:{type:J.String_unsecure(),isOptional:!1},description:{type:J.String_unsecure(),isOptional:!1},category:{type:g,isOptional:!1},status:{type:W,isOptional:!1},version:{type:J.NonEmptyString(),isOptional:!1},createdAt:{type:J.DateTime(),isOptional:!1}}}),Gk=o({name:"CreateToolInput",description:"Input for creating a tool",fields:{organizationId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!1},slug:{type:J.String_unsecure(),isOptional:!1},description:{type:J.String_unsecure(),isOptional:!1},category:{type:g,isOptional:!0},parametersSchema:{type:J.JSONObject(),isOptional:!1},outputSchema:{type:J.JSONObject(),isOptional:!0},implementationType:{type:a,isOptional:!1},implementationConfig:{type:J.JSONObject(),isOptional:!1},maxInvocationsPerMinute:{type:J.Int_unsecure(),isOptional:!0},timeoutMs:{type:J.Int_unsecure(),isOptional:!0},tags:{type:J.String_unsecure(),isArray:!0,isOptional:!0}}}),_k=o({name:"UpdateToolInput",description:"Input for updating a tool",fields:{toolId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!0},description:{type:J.String_unsecure(),isOptional:!0},status:{type:W,isOptional:!0},parametersSchema:{type:J.JSONObject(),isOptional:!0},outputSchema:{type:J.JSONObject(),isOptional:!0},implementationConfig:{type:J.JSONObject(),isOptional:!0},maxInvocationsPerMinute:{type:J.Int_unsecure(),isOptional:!0},timeoutMs:{type:J.Int_unsecure(),isOptional:!0},tags:{type:J.String_unsecure(),isArray:!0,isOptional:!0}}});import{defineCommand as e,defineQuery as xk}from"@contractspec/lib.contracts-spec/operations";import{defineSchemaModel as b,ScalarTypeEnum as D}from"@contractspec/lib.schema";var C=["@agent-console-team"],hq=e({meta:{key:"agent.tool.create",version:"1.0.0",stability:"stable",owners:[...C],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:Gk,output:b({name:"CreateToolOutput",fields:{id:{type:D.String_unsecure(),isOptional:!1},name:{type:D.NonEmptyString(),isOptional:!1},slug:{type:D.String_unsecure(),isOptional:!1},status:{type:W,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:[...C],tags:["tool","created"],when:"Tool is successfully created",payload:S}],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"}}]}}),fq=e({meta:{key:"agent.tool.update",version:"1.0.0",stability:"stable",owners:[...C],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:_k,output:b({name:"UpdateToolOutput",fields:{id:{type:D.String_unsecure(),isOptional:!1},name:{type:D.NonEmptyString(),isOptional:!1},status:{type:W,isOptional:!1},updatedAt:{type:D.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:[...C],tags:["tool","updated"],when:"Tool is updated",payload:S}],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"}}]}}),wq=xk({meta:{key:"agent.tool.get",version:"1.0.0",stability:"stable",owners:[...C],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:b({name:"GetToolInput",fields:{toolId:{type:D.String_unsecure(),isOptional:!1}}}),output:zk,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"}}]}}),tk=xk({meta:{key:"agent.tool.list",version:"1.0.0",stability:"stable",owners:[...C],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:b({name:"ListToolsInput",fields:{organizationId:{type:D.String_unsecure(),isOptional:!1},category:{type:g,isOptional:!0},status:{type:W,isOptional:!0},search:{type:D.String_unsecure(),isOptional:!0},limit:{type:D.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:D.Int_unsecure(),isOptional:!0,defaultValue:0}}}),output:b({name:"ListToolsOutput",fields:{items:{type:S,isArray:!0,isOptional:!1},total:{type:D.Int_unsecure(),isOptional:!1},hasMore:{type:D.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}}]}}),sq=e({meta:{key:"agent.tool.test",version:"1.0.0",stability:"stable",owners:[...C],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:b({name:"TestToolInput",fields:{toolId:{type:D.String_unsecure(),isOptional:!1},testInput:{type:D.JSONObject(),isOptional:!1}}}),output:b({name:"TestToolOutput",fields:{success:{type:D.Boolean(),isOptional:!1},output:{type:D.JSONObject(),isOptional:!0},error:{type:D.String_unsecure(),isOptional:!0},durationMs:{type:D.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 Ek}from"@contractspec/lib.runtime-sandbox";var{generateId:Uk}=Ek;var Pk={queuedAt:"r.queuedAt",totalTokens:"r.totalTokens",durationMs:"r.durationMs",estimatedCostUsd:"r.estimatedCostUsd",status:"r.status",agentName:"a.name"};function p(q){return{id:q.id,projectId:q.projectId,organizationId:q.organizationId,name:q.name,description:q.description??void 0,modelProvider:q.modelProvider,modelName:q.modelName,systemPrompt:q.systemPrompt??void 0,temperature:q.temperature,maxTokens:q.maxTokens,status:q.status,createdAt:new Date(q.createdAt),updatedAt:new Date(q.updatedAt)}}function ok(q){return{id:q.id,projectId:q.projectId,organizationId:q.organizationId,name:q.name,description:q.description??void 0,version:q.version,category:q.category,status:q.status,inputSchema:q.inputSchema??void 0,outputSchema:q.outputSchema??void 0,endpoint:q.endpoint??void 0,createdAt:new Date(q.createdAt),updatedAt:new Date(q.updatedAt)}}function Lk(q,c){return{id:q.id,projectId:q.projectId,agentId:q.agentId,agentName:c,status:q.status,input:q.input??void 0,output:q.output??void 0,totalTokens:q.totalTokens,promptTokens:q.promptTokens,completionTokens:q.completionTokens,estimatedCostUsd:q.estimatedCostUsd,durationMs:q.durationMs??void 0,errorMessage:q.errorMessage??void 0,queuedAt:new Date(q.queuedAt),startedAt:q.startedAt?new Date(q.startedAt):void 0,completedAt:q.completedAt?new Date(q.completedAt):void 0}}function Eq(q){async function c(K){let{projectId:$,organizationId:X,status:Z,search:B,limit:j=20,offset:v=0}=K,x="WHERE projectId = ?",z=[$];if(X)x+=" AND organizationId = ?",z.push(X);if(Z&&Z!=="all")x+=" AND status = ?",z.push(Z);if(B)x+=" AND (name LIKE ? OR description LIKE ?)",z.push(`%${B}%`,`%${B}%`);let f=(await q.query(`SELECT COUNT(*) as count FROM agent_definition ${x}`,z)).rows[0]?.count??0,Q=(await q.query(`SELECT * FROM agent_definition ${x} ORDER BY createdAt DESC LIMIT ? OFFSET ?`,[...z,j,v])).rows;return{items:Q.map(p),total:f,hasMore:v+Q.length<f}}async function kk(K){let $=(await q.query("SELECT * FROM agent_definition WHERE id = ?",[K])).rows;return $[0]?p($[0]):null}async function vk(K,$){let X=Uk("agent"),Z=new Date().toISOString();await q.execute(`INSERT INTO agent_definition (id, projectId, organizationId, name, description, modelProvider, modelName, systemPrompt, temperature, maxTokens, status, createdAt, updatedAt)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[X,$.projectId,$.organizationId,K.name,K.description??null,K.modelProvider??"openai",K.modelName??"gpt-4",K.systemPrompt??null,K.temperature??0.7,K.maxTokens??4096,"DRAFT",Z,Z]);let j=(await q.query("SELECT * FROM agent_definition WHERE id = ?",[X])).rows[0];if(!j)throw Error("Failed to retrieve created agent");return p(j)}async function Qk(K){let $=new Date().toISOString(),X=["updatedAt = ?"],Z=[$];if(K.name!==void 0)X.push("name = ?"),Z.push(K.name);if(K.description!==void 0)X.push("description = ?"),Z.push(K.description);if(K.status!==void 0)X.push("status = ?"),Z.push(K.status);Z.push(K.id),await q.execute(`UPDATE agent_definition SET ${X.join(", ")} WHERE id = ?`,Z);let B=(await q.query("SELECT * FROM agent_definition WHERE id = ?",[K.id])).rows;if(!B[0])throw Error("NOT_FOUND");return p(B[0])}async function Ik(K){let{projectId:$,organizationId:X,category:Z,status:B,search:j,limit:v=50,offset:x=0}=K,z="WHERE projectId = ?",_=[$];if(X)z+=" AND organizationId = ?",_.push(X);if(Z&&Z!=="all")z+=" AND category = ?",_.push(Z);if(B&&B!=="all")z+=" AND status = ?",_.push(B);if(j)z+=" AND (name LIKE ? OR description LIKE ?)",_.push(`%${j}%`,`%${j}%`);let Q=(await q.query(`SELECT COUNT(*) as count FROM agent_tool ${z}`,_)).rows[0]?.count??0,w=(await q.query(`SELECT * FROM agent_tool ${z} ORDER BY name ASC LIMIT ? OFFSET ?`,[..._,v,x])).rows;return{items:w.map(ok),total:Q,hasMore:x+w.length<Q}}async function Wk(K){let{projectId:$,agentId:X,status:Z,sortBy:B,sortDirection:j="desc",limit:v=20,offset:x=0}=K,z="WHERE r.projectId = ?",_=[$];if(X)z+=" AND r.agentId = ?",_.push(X);if(Z&&Z!=="all")z+=" AND r.status = ?",_.push(Z);let Q=(await q.query(`SELECT COUNT(*) as count FROM agent_run r ${z}`,_)).rows[0]?.count??0,w=B?Pk[B]:Pk.queuedAt,Ak=j==="asc"?"ASC":"DESC",qk=(await q.query(`SELECT r.*, a.name as agentName
2078
3
  FROM agent_run r
2079
4
  LEFT JOIN agent_definition a ON r.agentId = a.id
2080
- ${whereClause}
2081
- ORDER BY ${sortColumn} ${direction}, r.queuedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
2082
- return {
2083
- items: rows.map((r) => rowToRun(r, r.agentName)),
2084
- total,
2085
- hasMore: offset + rows.length < total
2086
- };
2087
- }
2088
- async function getRunMetrics(input) {
2089
- let whereClause = "WHERE projectId = ?";
2090
- const params = [input.projectId];
2091
- if (input.agentId) {
2092
- whereClause += " AND agentId = ?";
2093
- params.push(input.agentId);
2094
- }
2095
- if (input.startDate) {
2096
- whereClause += " AND queuedAt >= ?";
2097
- params.push(input.startDate.toISOString());
2098
- }
2099
- if (input.endDate) {
2100
- whereClause += " AND queuedAt <= ?";
2101
- params.push(input.endDate.toISOString());
2102
- }
2103
- const result = (await db.query(`SELECT
5
+ ${z}
6
+ ORDER BY ${w} ${Ak}, r.queuedAt DESC LIMIT ? OFFSET ?`,[..._,v,x])).rows;return{items:qk.map((Fk)=>Lk(Fk,Fk.agentName)),total:Q,hasMore:x+qk.length<Q}}async function Ok(K){let $="WHERE projectId = ?",X=[K.projectId];if(K.agentId)$+=" AND agentId = ?",X.push(K.agentId);if(K.startDate)$+=" AND queuedAt >= ?",X.push(K.startDate.toISOString());if(K.endDate)$+=" AND queuedAt <= ?",X.push(K.endDate.toISOString());let B=(await q.query(`SELECT
2104
7
  COUNT(*) as totalRuns,
2105
8
  SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completedRuns,
2106
9
  AVG(CASE WHEN status = 'COMPLETED' THEN durationMs ELSE NULL END) as avgDuration,
2107
10
  COALESCE(SUM(totalTokens), 0) as totalTokens,
2108
11
  COALESCE(SUM(estimatedCostUsd), 0) as totalCost
2109
- FROM agent_run ${whereClause}`, params)).rows;
2110
- const data = result[0];
2111
- const totalRuns = data?.totalRuns ?? 0;
2112
- const completedRuns = data?.completedRuns ?? 0;
2113
- return {
2114
- totalRuns,
2115
- successRate: totalRuns > 0 ? completedRuns / totalRuns : 0,
2116
- averageDurationMs: data?.avgDuration ?? 0,
2117
- totalTokens: data?.totalTokens ?? 0,
2118
- totalCostUsd: data?.totalCost ?? 0
2119
- };
2120
- }
2121
- async function executeAgent(input) {
2122
- const agent = await getAgent(input.agentId);
2123
- if (!agent)
2124
- throw new Error("AGENT_NOT_FOUND");
2125
- if (agent.status !== "ACTIVE")
2126
- throw new Error("AGENT_NOT_ACTIVE");
2127
- const id = generateId("run");
2128
- const now = new Date().toISOString();
2129
- const pid = input.context?.projectId ?? agent.projectId;
2130
- await db.execute(`INSERT INTO agent_run (id, projectId, agentId, status, input, totalTokens, promptTokens, completionTokens, estimatedCostUsd, queuedAt)
2131
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [id, pid, input.agentId, "QUEUED", input.message, 0, 0, 0, 0, now]);
2132
- 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;
2133
- if (!rows[0])
2134
- throw new Error("Failed to retrieve created run");
2135
- return rowToRun(rows[0], rows[0].agentName);
2136
- }
2137
- return {
2138
- listAgents,
2139
- getAgent,
2140
- createAgent,
2141
- updateAgent,
2142
- executeAgent,
2143
- listTools,
2144
- listRuns,
2145
- getRunMetrics
2146
- };
2147
- }
2148
- export {
2149
- createAgentHandlers
2150
- };
12
+ FROM agent_run ${$}`,X)).rows[0],j=B?.totalRuns??0,v=B?.completedRuns??0;return{totalRuns:j,successRate:j>0?v/j:0,averageDurationMs:B?.avgDuration??0,totalTokens:B?.totalTokens??0,totalCostUsd:B?.totalCost??0}}async function Nk(K){let $=await kk(K.agentId);if(!$)throw Error("AGENT_NOT_FOUND");if($.status!=="ACTIVE")throw Error("AGENT_NOT_ACTIVE");let X=Uk("run"),Z=new Date().toISOString(),B=K.context?.projectId??$.projectId;await q.execute(`INSERT INTO agent_run (id, projectId, agentId, status, input, totalTokens, promptTokens, completionTokens, estimatedCostUsd, queuedAt)
13
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[X,B,K.agentId,"QUEUED",K.message,0,0,0,0,Z]);let j=(await q.query("SELECT r.*, a.name as agentName FROM agent_run r LEFT JOIN agent_definition a ON r.agentId = a.id WHERE r.id = ?",[X])).rows;if(!j[0])throw Error("Failed to retrieve created run");return Lk(j[0],j[0].agentName)}return{listAgents:c,getAgent:kk,createAgent:vk,updateAgent:Qk,executeAgent:Nk,listTools:Ik,listRuns:Wk,getRunMetrics:Ok}}export{Eq as createAgentHandlers};