@sixb/server 0.0.1

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 (216) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -0
  3. package/dist/auth/access-token-boundary.d.ts +23 -0
  4. package/dist/auth/access-token-boundary.d.ts.map +1 -0
  5. package/dist/auth/application-access.d.ts +4 -0
  6. package/dist/auth/application-access.d.ts.map +1 -0
  7. package/dist/auth/browser-origin.d.ts +62 -0
  8. package/dist/auth/browser-origin.d.ts.map +1 -0
  9. package/dist/auth/csrf.d.ts +2 -0
  10. package/dist/auth/csrf.d.ts.map +1 -0
  11. package/dist/auth/guard.d.ts +35 -0
  12. package/dist/auth/guard.d.ts.map +1 -0
  13. package/dist/auth/public-routes.d.ts +8 -0
  14. package/dist/auth/public-routes.d.ts.map +1 -0
  15. package/dist/auth/responses.d.ts +11 -0
  16. package/dist/auth/responses.d.ts.map +1 -0
  17. package/dist/auth/return-to.d.ts +3 -0
  18. package/dist/auth/return-to.d.ts.map +1 -0
  19. package/dist/auth/scope.d.ts +43 -0
  20. package/dist/auth/scope.d.ts.map +1 -0
  21. package/dist/auth/session-activity.d.ts +4 -0
  22. package/dist/auth/session-activity.d.ts.map +1 -0
  23. package/dist/auth/session-cookies.d.ts +12 -0
  24. package/dist/auth/session-cookies.d.ts.map +1 -0
  25. package/dist/files/content.d.ts +141 -0
  26. package/dist/files/content.d.ts.map +1 -0
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +11522 -0
  30. package/dist/index.js.map +78 -0
  31. package/dist/openapi/security.d.ts +26 -0
  32. package/dist/openapi/security.d.ts.map +1 -0
  33. package/dist/openapi/tags.d.ts +151 -0
  34. package/dist/openapi/tags.d.ts.map +1 -0
  35. package/dist/registerRoutes.d.ts +31 -0
  36. package/dist/registerRoutes.d.ts.map +1 -0
  37. package/dist/routes/action-runs.d.ts +244 -0
  38. package/dist/routes/action-runs.d.ts.map +1 -0
  39. package/dist/routes/actions.d.ts +183 -0
  40. package/dist/routes/actions.d.ts.map +1 -0
  41. package/dist/routes/agent-api-gateway.d.ts +4 -0
  42. package/dist/routes/agent-api-gateway.d.ts.map +1 -0
  43. package/dist/routes/agents.d.ts +1061 -0
  44. package/dist/routes/agents.d.ts.map +1 -0
  45. package/dist/routes/auth.d.ts +1366 -0
  46. package/dist/routes/auth.d.ts.map +1 -0
  47. package/dist/routes/connectors.d.ts +108 -0
  48. package/dist/routes/connectors.d.ts.map +1 -0
  49. package/dist/routes/datasets.d.ts +339 -0
  50. package/dist/routes/datasets.d.ts.map +1 -0
  51. package/dist/routes/events.d.ts +116 -0
  52. package/dist/routes/events.d.ts.map +1 -0
  53. package/dist/routes/files.d.ts +340 -0
  54. package/dist/routes/files.d.ts.map +1 -0
  55. package/dist/routes/links.d.ts +175 -0
  56. package/dist/routes/links.d.ts.map +1 -0
  57. package/dist/routes/logs.d.ts +88 -0
  58. package/dist/routes/logs.d.ts.map +1 -0
  59. package/dist/routes/objects.d.ts +450 -0
  60. package/dist/routes/objects.d.ts.map +1 -0
  61. package/dist/routes/ontology.d.ts +240 -0
  62. package/dist/routes/ontology.d.ts.map +1 -0
  63. package/dist/routes/pipelines.d.ts +399 -0
  64. package/dist/routes/pipelines.d.ts.map +1 -0
  65. package/dist/routes/project.d.ts +56 -0
  66. package/dist/routes/project.d.ts.map +1 -0
  67. package/dist/routes/projections.d.ts +916 -0
  68. package/dist/routes/projections.d.ts.map +1 -0
  69. package/dist/routes/rules.d.ts +165 -0
  70. package/dist/routes/rules.d.ts.map +1 -0
  71. package/dist/routes/status.d.ts +81 -0
  72. package/dist/routes/status.d.ts.map +1 -0
  73. package/dist/routes/syncs.d.ts +294 -0
  74. package/dist/routes/syncs.d.ts.map +1 -0
  75. package/dist/routes/telemetry.d.ts +241 -0
  76. package/dist/routes/telemetry.d.ts.map +1 -0
  77. package/dist/routes/webhook-runs.d.ts +89 -0
  78. package/dist/routes/webhook-runs.d.ts.map +1 -0
  79. package/dist/routes/webhooks.d.ts +60 -0
  80. package/dist/routes/webhooks.d.ts.map +1 -0
  81. package/dist/routes/workflows.d.ts +973 -0
  82. package/dist/routes/workflows.d.ts.map +1 -0
  83. package/dist/routes/ws/agents.d.ts +99 -0
  84. package/dist/routes/ws/agents.d.ts.map +1 -0
  85. package/dist/routes/ws/events.d.ts +89 -0
  86. package/dist/routes/ws/events.d.ts.map +1 -0
  87. package/dist/routes/ws/index.d.ts +31 -0
  88. package/dist/routes/ws/index.d.ts.map +1 -0
  89. package/dist/routes/ws/log-subscription-hub.d.ts +47 -0
  90. package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -0
  91. package/dist/routes/ws/logs.d.ts +110 -0
  92. package/dist/routes/ws/logs.d.ts.map +1 -0
  93. package/dist/schemas/actions.d.ts +644 -0
  94. package/dist/schemas/actions.d.ts.map +1 -0
  95. package/dist/schemas/agents.d.ts +3157 -0
  96. package/dist/schemas/agents.d.ts.map +1 -0
  97. package/dist/schemas/auth.d.ts +2023 -0
  98. package/dist/schemas/auth.d.ts.map +1 -0
  99. package/dist/schemas/common.d.ts +30 -0
  100. package/dist/schemas/common.d.ts.map +1 -0
  101. package/dist/schemas/connectors.d.ts +82 -0
  102. package/dist/schemas/connectors.d.ts.map +1 -0
  103. package/dist/schemas/datasets.d.ts +744 -0
  104. package/dist/schemas/datasets.d.ts.map +1 -0
  105. package/dist/schemas/event-payloads.d.ts +477 -0
  106. package/dist/schemas/event-payloads.d.ts.map +1 -0
  107. package/dist/schemas/events.d.ts +665 -0
  108. package/dist/schemas/events.d.ts.map +1 -0
  109. package/dist/schemas/files.d.ts +241 -0
  110. package/dist/schemas/files.d.ts.map +1 -0
  111. package/dist/schemas/links.d.ts +90 -0
  112. package/dist/schemas/links.d.ts.map +1 -0
  113. package/dist/schemas/logs.d.ts +231 -0
  114. package/dist/schemas/logs.d.ts.map +1 -0
  115. package/dist/schemas/objects.d.ts +288 -0
  116. package/dist/schemas/objects.d.ts.map +1 -0
  117. package/dist/schemas/ontology.d.ts +778 -0
  118. package/dist/schemas/ontology.d.ts.map +1 -0
  119. package/dist/schemas/pipelines.d.ts +1373 -0
  120. package/dist/schemas/pipelines.d.ts.map +1 -0
  121. package/dist/schemas/project.d.ts +9 -0
  122. package/dist/schemas/project.d.ts.map +1 -0
  123. package/dist/schemas/projections.d.ts +6992 -0
  124. package/dist/schemas/projections.d.ts.map +1 -0
  125. package/dist/schemas/rules.d.ts +204 -0
  126. package/dist/schemas/rules.d.ts.map +1 -0
  127. package/dist/schemas/status.d.ts +189 -0
  128. package/dist/schemas/status.d.ts.map +1 -0
  129. package/dist/schemas/syncs.d.ts +538 -0
  130. package/dist/schemas/syncs.d.ts.map +1 -0
  131. package/dist/schemas/telemetry.d.ts +265 -0
  132. package/dist/schemas/telemetry.d.ts.map +1 -0
  133. package/dist/schemas/webhook-runs.d.ts +169 -0
  134. package/dist/schemas/webhook-runs.d.ts.map +1 -0
  135. package/dist/schemas/workflows.d.ts +1720 -0
  136. package/dist/schemas/workflows.d.ts.map +1 -0
  137. package/dist/server.d.ts +64 -0
  138. package/dist/server.d.ts.map +1 -0
  139. package/dist/tsconfig.json +5 -0
  140. package/dist/utils/http.d.ts +23 -0
  141. package/dist/utils/http.d.ts.map +1 -0
  142. package/dist/utils/request-body.d.ts +15 -0
  143. package/dist/utils/request-body.d.ts.map +1 -0
  144. package/dist/utils/ws.d.ts +10 -0
  145. package/dist/utils/ws.d.ts.map +1 -0
  146. package/package.json +68 -0
  147. package/src/auth/access-token-boundary.ts +68 -0
  148. package/src/auth/application-access.ts +16 -0
  149. package/src/auth/browser-origin.ts +367 -0
  150. package/src/auth/csrf.ts +1 -0
  151. package/src/auth/guard.ts +169 -0
  152. package/src/auth/public-routes.ts +87 -0
  153. package/src/auth/responses.ts +54 -0
  154. package/src/auth/return-to.ts +21 -0
  155. package/src/auth/scope.ts +64 -0
  156. package/src/auth/session-activity.ts +19 -0
  157. package/src/auth/session-cookies.ts +43 -0
  158. package/src/files/content.ts +419 -0
  159. package/src/index.ts +2 -0
  160. package/src/openapi/security.ts +37 -0
  161. package/src/openapi/tags.ts +151 -0
  162. package/src/registerRoutes.ts +49 -0
  163. package/src/routes/action-runs.ts +238 -0
  164. package/src/routes/actions.ts +126 -0
  165. package/src/routes/agent-api-gateway.ts +260 -0
  166. package/src/routes/agents.ts +943 -0
  167. package/src/routes/auth.ts +2233 -0
  168. package/src/routes/connectors.ts +69 -0
  169. package/src/routes/datasets.ts +402 -0
  170. package/src/routes/events.ts +55 -0
  171. package/src/routes/files.ts +675 -0
  172. package/src/routes/links.ts +143 -0
  173. package/src/routes/logs.ts +65 -0
  174. package/src/routes/objects.ts +838 -0
  175. package/src/routes/ontology.ts +138 -0
  176. package/src/routes/pipelines.ts +332 -0
  177. package/src/routes/project.ts +16 -0
  178. package/src/routes/projections.ts +251 -0
  179. package/src/routes/rules.ts +124 -0
  180. package/src/routes/status.ts +53 -0
  181. package/src/routes/syncs.ts +243 -0
  182. package/src/routes/telemetry.ts +207 -0
  183. package/src/routes/webhook-runs.ts +81 -0
  184. package/src/routes/webhooks.ts +508 -0
  185. package/src/routes/workflows.ts +1333 -0
  186. package/src/routes/ws/agents.ts +301 -0
  187. package/src/routes/ws/events.ts +278 -0
  188. package/src/routes/ws/index.ts +12 -0
  189. package/src/routes/ws/log-subscription-hub.ts +375 -0
  190. package/src/routes/ws/logs.ts +117 -0
  191. package/src/schemas/actions.ts +123 -0
  192. package/src/schemas/agents.ts +293 -0
  193. package/src/schemas/auth.ts +317 -0
  194. package/src/schemas/common.ts +60 -0
  195. package/src/schemas/connectors.ts +21 -0
  196. package/src/schemas/datasets.ts +107 -0
  197. package/src/schemas/event-payloads.ts +79 -0
  198. package/src/schemas/events.ts +117 -0
  199. package/src/schemas/files.ts +82 -0
  200. package/src/schemas/links.ts +38 -0
  201. package/src/schemas/logs.ts +76 -0
  202. package/src/schemas/objects.ts +759 -0
  203. package/src/schemas/ontology.ts +77 -0
  204. package/src/schemas/pipelines.ts +150 -0
  205. package/src/schemas/project.ts +5 -0
  206. package/src/schemas/projections.ts +144 -0
  207. package/src/schemas/rules.ts +98 -0
  208. package/src/schemas/status.ts +51 -0
  209. package/src/schemas/syncs.ts +83 -0
  210. package/src/schemas/telemetry.ts +59 -0
  211. package/src/schemas/webhook-runs.ts +40 -0
  212. package/src/schemas/workflows.ts +229 -0
  213. package/src/server.ts +383 -0
  214. package/src/utils/http.ts +108 -0
  215. package/src/utils/request-body.ts +62 -0
  216. package/src/utils/ws.ts +59 -0
@@ -0,0 +1,1333 @@
1
+ import {
2
+ type OntologySource,
3
+ type Principal,
4
+ type ScopedSixb,
5
+ type Sixb,
6
+ SYSTEM_PRINCIPAL,
7
+ type WorkflowDefinition,
8
+ } from "@sixb/core"
9
+ import { publishAgentRunCancel } from "@sixb/core/internal/agents"
10
+ import { canViewWorkflowIntervention, canViewWorkflowRun } from "@sixb/core/internal/authorization"
11
+ import {
12
+ snapshotWorkflowInterventionResponse,
13
+ type WorkflowInterventionNodeDefinition,
14
+ } from "@sixb/core/internal/workflows"
15
+ import type {
16
+ WorkflowAgentNodeRunRecord,
17
+ WorkflowInterventionRecord,
18
+ WorkflowNodeRunRecord,
19
+ WorkflowRunRecord,
20
+ WorkflowRunStorage,
21
+ } from "@sixb/core/storage"
22
+ import type { Elysia } from "elysia"
23
+ import { z } from "zod"
24
+ import { bearerSecurityRequirement } from "../auth/access-token-boundary"
25
+ import { requestAuthState } from "../auth/scope"
26
+ import {
27
+ createContextualFileContentResponse,
28
+ fileContentGetResponses,
29
+ fileContentHeadResponses,
30
+ } from "../files/content"
31
+ import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
32
+ import { OPENAPI_TAGS } from "../openapi/tags"
33
+ import { ErrorResponseSchema } from "../schemas/common"
34
+ import { FileContentQuerySchema } from "../schemas/files"
35
+ import {
36
+ CancelWorkflowInterventionBodySchema,
37
+ CancelWorkflowInterventionResponseSchema,
38
+ CancelWorkflowRunBodySchema,
39
+ CancelWorkflowRunResponseSchema,
40
+ RequestWorkflowRunBodySchema,
41
+ RequestWorkflowRunResponseSchema,
42
+ SubmitWorkflowInterventionBodySchema,
43
+ SubmitWorkflowInterventionResponseSchema,
44
+ WorkflowAgentNodeExecutionSchema,
45
+ WorkflowInterventionListResponseSchema,
46
+ WorkflowInterventionParamsSchema,
47
+ WorkflowInterventionSchema,
48
+ WorkflowInterventionsQuerySchema,
49
+ WorkflowParamsSchema,
50
+ WorkflowRunDetailResponseSchema,
51
+ WorkflowRunListResponseSchema,
52
+ WorkflowRunParamsSchema,
53
+ WorkflowRunsQuerySchema,
54
+ WorkflowSchema,
55
+ } from "../schemas/workflows"
56
+ import {
57
+ handleRouteError,
58
+ parseDate,
59
+ parseOptionalInt,
60
+ toIsoString,
61
+ unconfiguredStorageResponse,
62
+ } from "../utils/http"
63
+
64
+ const WorkflowRunFileContentQuerySchema = FileContentQuerySchema.extend({
65
+ path: z
66
+ .string()
67
+ .min(1)
68
+ .regex(/^\/input(?:\/|$)/, "Workflow run file content paths must start with /input/"),
69
+ })
70
+
71
+ const WorkflowNodeFileContentQuerySchema = FileContentQuerySchema.extend({
72
+ path: z
73
+ .string()
74
+ .min(1)
75
+ .regex(
76
+ /^\/(?:input|output)(?:\/|$)/,
77
+ "Workflow node file content paths must start with /input/ or /output/"
78
+ ),
79
+ })
80
+
81
+ const WorkflowNodeFileContentParamsSchema = WorkflowRunParamsSchema.extend({
82
+ nodeKey: z.string().min(1),
83
+ })
84
+
85
+ function serializeWorkflowRun(run: WorkflowRunRecord) {
86
+ return {
87
+ id: run.id,
88
+ projectId: run.projectId,
89
+ workflowId: run.workflowId,
90
+ status: run.status,
91
+ input: run.input,
92
+ queuedAt: run.queuedAt ? toIsoString(run.queuedAt) : undefined,
93
+ startedAt: toIsoString(run.startedAt),
94
+ finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
95
+ error: run.error,
96
+ requestedBy: serializePrincipal(run.requestedByPrincipal),
97
+ }
98
+ }
99
+
100
+ type SerializedWorkflowRun = ReturnType<typeof serializeWorkflowRun>
101
+
102
+ function serializeWorkflowNodeRun(
103
+ node: WorkflowNodeRunRecord,
104
+ agentExecution?: WorkflowAgentNodeRunRecord | null
105
+ ) {
106
+ return {
107
+ id: node.id,
108
+ projectId: node.projectId,
109
+ workflowRunId: node.workflowRunId,
110
+ workflowId: node.workflowId,
111
+ nodeIndex: node.nodeIndex,
112
+ nodeType: node.nodeType,
113
+ nodeId: node.nodeId,
114
+ nodeKey: node.nodeKey,
115
+ status: node.status,
116
+ input: node.input,
117
+ startedAt: toIsoString(node.startedAt),
118
+ finishedAt: node.finishedAt ? toIsoString(node.finishedAt) : undefined,
119
+ output: node.output,
120
+ error: node.error,
121
+ ...(agentExecution
122
+ ? { agentExecution: serializeWorkflowAgentExecutionSummary(agentExecution) }
123
+ : {}),
124
+ }
125
+ }
126
+
127
+ function serializePrincipal(principal: Principal) {
128
+ return { principalType: principal.type, principalId: principal.id }
129
+ }
130
+
131
+ function serializeWorkflowAgentExecutionSummary(execution: WorkflowAgentNodeRunRecord) {
132
+ return {
133
+ agentId: execution.agentId,
134
+ status: execution.status,
135
+ attempt: execution.attempt,
136
+ modelId: execution.modelId,
137
+ finishReason: execution.finishReason,
138
+ usage: execution.usage,
139
+ startedAt: execution.startedAt ? toIsoString(execution.startedAt) : undefined,
140
+ completedAt: execution.completedAt ? toIsoString(execution.completedAt) : undefined,
141
+ }
142
+ }
143
+
144
+ function serializeWorkflowAgentExecution(execution: WorkflowAgentNodeRunRecord) {
145
+ return {
146
+ ...serializeWorkflowAgentExecutionSummary(execution),
147
+ nodeRunId: execution.nodeRunId,
148
+ prompt: execution.prompt,
149
+ executionPrincipal: execution.executionPrincipal
150
+ ? serializePrincipal(execution.executionPrincipal)
151
+ : undefined,
152
+ trace: execution.trace,
153
+ diagnostics: execution.diagnostics,
154
+ error: execution.error,
155
+ createdAt: toIsoString(execution.createdAt),
156
+ }
157
+ }
158
+
159
+ async function serializeWorkflowNodeWithExecution(
160
+ storage: WorkflowRunStorage,
161
+ node: WorkflowNodeRunRecord
162
+ ) {
163
+ const execution =
164
+ node.nodeType === "agent"
165
+ ? await storage.agentNodes.getByNodeRunId({
166
+ projectId: node.projectId,
167
+ nodeRunId: node.id,
168
+ })
169
+ : null
170
+ return serializeWorkflowNodeRun(node, execution)
171
+ }
172
+
173
+ function canAccessWorkflowRun(
174
+ authz: ReturnType<typeof requestAuthState>["authz"],
175
+ scoped: ScopedSixb<readonly OntologySource[]> | null,
176
+ run: WorkflowRunRecord
177
+ ): boolean {
178
+ return (
179
+ canViewWorkflowRun(authz, run) && (!scoped || scoped.getWorkflowById(run.workflowId) !== null)
180
+ )
181
+ }
182
+
183
+ function serializeWorkflowIntervention(intervention: WorkflowInterventionRecord) {
184
+ return {
185
+ id: intervention.id,
186
+ projectId: intervention.projectId,
187
+ workflowId: intervention.workflowId,
188
+ workflowRunId: intervention.workflowRunId,
189
+ nodeRunId: intervention.nodeRunId,
190
+ nodeIndex: intervention.nodeIndex,
191
+ nodeId: intervention.nodeId,
192
+ nodeKey: intervention.nodeKey,
193
+ interventionId: intervention.interventionId,
194
+ input: intervention.input,
195
+ defaultResponse: intervention.defaultResponse,
196
+ status: intervention.status,
197
+ requestedAt: toIsoString(intervention.requestedAt),
198
+ expiresAt: intervention.expiresAt ? toIsoString(intervention.expiresAt) : undefined,
199
+ submittedAt: intervention.submittedAt ? toIsoString(intervention.submittedAt) : undefined,
200
+ submittedBy: intervention.submittedBy,
201
+ response: intervention.response,
202
+ cancelledAt: intervention.cancelledAt ? toIsoString(intervention.cancelledAt) : undefined,
203
+ cancelledBy: intervention.cancelledBy,
204
+ expiredAt: intervention.expiredAt ? toIsoString(intervention.expiredAt) : undefined,
205
+ }
206
+ }
207
+
208
+ async function workflowRunFileContentResponse(
209
+ sixb: Sixb<readonly OntologySource[]>,
210
+ context: {
211
+ readonly params: { readonly runId: string }
212
+ readonly query: unknown
213
+ readonly request: Request
214
+ readonly set: { status?: number | string }
215
+ },
216
+ options: { readonly head?: boolean } = {}
217
+ ) {
218
+ const { authz, scoped } = requestAuthState(context)
219
+
220
+ const storage = sixb.storage.workflowRuns
221
+ if (!storage) {
222
+ return unconfiguredStorageResponse(context.set, "Workflow run storage")
223
+ }
224
+
225
+ return createContextualFileContentResponse({
226
+ blobStorage: sixb.blobStorage,
227
+ query: context.query,
228
+ querySchema: WorkflowRunFileContentQuerySchema,
229
+ request: context.request,
230
+ set: context.set,
231
+ head: options.head,
232
+ resolveRoot: async () => {
233
+ const run = await storage.getById({ projectId: sixb.id, id: context.params.runId })
234
+ if (!run || !canAccessWorkflowRun(authz, scoped, run)) {
235
+ return null
236
+ }
237
+
238
+ return serializeWorkflowRun(run)
239
+ },
240
+ })
241
+ }
242
+
243
+ async function workflowNodeFileContentResponse(
244
+ sixb: Sixb<readonly OntologySource[]>,
245
+ context: {
246
+ readonly params: { readonly runId: string; readonly nodeKey: string }
247
+ readonly query: unknown
248
+ readonly request: Request
249
+ readonly set: { status?: number | string }
250
+ },
251
+ options: { readonly head?: boolean } = {}
252
+ ) {
253
+ const { authz, scoped } = requestAuthState(context)
254
+
255
+ const storage = sixb.storage.workflowRuns
256
+ if (!storage) {
257
+ return unconfiguredStorageResponse(context.set, "Workflow run storage")
258
+ }
259
+
260
+ return createContextualFileContentResponse({
261
+ blobStorage: sixb.blobStorage,
262
+ query: context.query,
263
+ querySchema: WorkflowNodeFileContentQuerySchema,
264
+ request: context.request,
265
+ set: context.set,
266
+ head: options.head,
267
+ resolveRoot: async () => {
268
+ const run = await storage.getById({ projectId: sixb.id, id: context.params.runId })
269
+ if (!run || !canAccessWorkflowRun(authz, scoped, run)) {
270
+ return null
271
+ }
272
+
273
+ const result = await storage.nodes.list({
274
+ projectId: sixb.id,
275
+ workflowRunId: run.id,
276
+ nodeKey: context.params.nodeKey,
277
+ limit: 1,
278
+ order: "asc",
279
+ })
280
+ const [node] = result.nodes
281
+ if (!node) {
282
+ return null
283
+ }
284
+
285
+ return serializeWorkflowNodeRun(node)
286
+ },
287
+ })
288
+ }
289
+
290
+ async function getLatestWorkflowRun(
291
+ sixb: Sixb<readonly OntologySource[]>,
292
+ workflowId: string
293
+ ): Promise<SerializedWorkflowRun | null> {
294
+ if (!sixb.storage.workflowRuns) {
295
+ return null
296
+ }
297
+
298
+ const storage = sixb.storage.workflowRuns
299
+ const result = await storage.listLatestByWorkflowIds({
300
+ projectId: sixb.id,
301
+ workflowIds: [workflowId],
302
+ })
303
+
304
+ const [latest] = result.runs
305
+ return latest ? serializeWorkflowRun(latest) : null
306
+ }
307
+
308
+ async function getLatestWorkflowRuns(
309
+ sixb: Sixb<readonly OntologySource[]>,
310
+ workflowIds: readonly string[]
311
+ ): Promise<Map<string, SerializedWorkflowRun>> {
312
+ const storage = sixb.storage.workflowRuns
313
+ if (!storage || workflowIds.length === 0) {
314
+ return new Map()
315
+ }
316
+
317
+ const result = await storage.listLatestByWorkflowIds({
318
+ projectId: sixb.id,
319
+ workflowIds,
320
+ })
321
+
322
+ return new Map(result.runs.map((run) => [run.workflowId, serializeWorkflowRun(run)]))
323
+ }
324
+
325
+ function serializeWorkflow(
326
+ workflow: WorkflowDefinition,
327
+ latestRun: SerializedWorkflowRun | null
328
+ ): ReturnType<typeof WorkflowSchema.parse> {
329
+ return WorkflowSchema.parse({
330
+ id: workflow.id,
331
+ input: workflow.input,
332
+ triggers: workflow.triggers,
333
+ nodes: workflow.nodes.map((node) => {
334
+ if (node.type === "step") {
335
+ return {
336
+ type: "step" as const,
337
+ id: node.id,
338
+ key: node.key,
339
+ input: node.step.input,
340
+ output: node.step.output,
341
+ }
342
+ }
343
+
344
+ if (node.type === "action") {
345
+ return {
346
+ type: "action" as const,
347
+ id: node.id,
348
+ key: node.key,
349
+ ...(node.action.binding.kind === "object"
350
+ ? { objectTypeId: node.action.binding.objectType.id }
351
+ : {}),
352
+ params: node.action.params,
353
+ }
354
+ }
355
+
356
+ if (node.type === "agent") {
357
+ return {
358
+ type: "agent" as const,
359
+ id: node.id,
360
+ key: node.key,
361
+ agentId: node.agentStep.agent.id,
362
+ input: node.agentStep.input,
363
+ output: node.agentStep.output,
364
+ }
365
+ }
366
+
367
+ return {
368
+ type: "intervention" as const,
369
+ id: node.id,
370
+ key: node.key,
371
+ input: node.intervention.input,
372
+ response: node.intervention.response,
373
+ description: node.intervention.description,
374
+ }
375
+ }),
376
+ latestRun,
377
+ })
378
+ }
379
+
380
+ function requireRegisteredInterventionNode(
381
+ workflow: WorkflowDefinition,
382
+ intervention: WorkflowInterventionRecord
383
+ ): WorkflowInterventionNodeDefinition {
384
+ const node = workflow.nodes[intervention.nodeIndex]
385
+ if (
386
+ node?.type !== "intervention" ||
387
+ node.id !== intervention.nodeId ||
388
+ node.key !== intervention.nodeKey ||
389
+ node.intervention.id !== intervention.interventionId
390
+ ) {
391
+ throw new Error(
392
+ `[SixbServer] Workflow intervention '${intervention.id}' does not match a registered intervention node.`
393
+ )
394
+ }
395
+
396
+ return node
397
+ }
398
+
399
+ function assertPendingIntervention(intervention: WorkflowInterventionRecord): void {
400
+ if (intervention.status !== "pending") {
401
+ throw new Error(`[SixbServer] Workflow intervention '${intervention.id}' is not pending.`)
402
+ }
403
+ }
404
+
405
+ async function emitWorkflowInterventionSubmitted(
406
+ sixb: Sixb<readonly OntologySource[]>,
407
+ intervention: WorkflowInterventionRecord
408
+ ): Promise<void> {
409
+ if (!intervention.submittedAt) {
410
+ throw new Error(`[SixbServer] Submitted intervention '${intervention.id}' has no submittedAt.`)
411
+ }
412
+
413
+ await sixb.events.append({
414
+ events: [
415
+ {
416
+ type: "workflow.intervention.submitted",
417
+ payload: {
418
+ workflowId: intervention.workflowId,
419
+ runId: intervention.workflowRunId,
420
+ nodeRunId: intervention.nodeRunId,
421
+ interventionId: intervention.interventionId,
422
+ pendingInterventionId: intervention.id,
423
+ submittedAt: intervention.submittedAt.toISOString(),
424
+ },
425
+ },
426
+ ],
427
+ })
428
+ }
429
+
430
+ async function emitWorkflowInterventionCancelled(input: {
431
+ readonly sixb: Sixb<readonly OntologySource[]>
432
+ readonly workflow: WorkflowDefinition
433
+ readonly intervention: WorkflowInterventionRecord
434
+ readonly node: WorkflowNodeRunRecord
435
+ readonly run: WorkflowRunRecord
436
+ }): Promise<void> {
437
+ const { sixb, workflow, intervention, node, run } = input
438
+ if (!intervention.cancelledAt) {
439
+ throw new Error(`[SixbServer] Cancelled intervention '${intervention.id}' has no cancelledAt.`)
440
+ }
441
+ if (!node.finishedAt) {
442
+ throw new Error(`[SixbServer] Cancelled workflow node run '${node.id}' has no finishedAt.`)
443
+ }
444
+ if (!run.finishedAt) {
445
+ throw new Error(`[SixbServer] Cancelled workflow run '${run.id}' has no finishedAt.`)
446
+ }
447
+
448
+ await sixb.events.append({
449
+ events: [
450
+ {
451
+ type: "workflow.intervention.cancelled",
452
+ payload: {
453
+ workflowId: intervention.workflowId,
454
+ runId: intervention.workflowRunId,
455
+ nodeRunId: intervention.nodeRunId,
456
+ interventionId: intervention.interventionId,
457
+ pendingInterventionId: intervention.id,
458
+ cancelledAt: intervention.cancelledAt.toISOString(),
459
+ },
460
+ },
461
+ {
462
+ type: "workflow.run.node.finished",
463
+ payload: {
464
+ workflowId: node.workflowId,
465
+ runId: node.workflowRunId,
466
+ nodeRunId: node.id,
467
+ nodeIndex: node.nodeIndex,
468
+ totalNodes: workflow.nodes.length,
469
+ nodeType: node.nodeType,
470
+ nodeId: node.nodeId,
471
+ nodeKey: node.nodeKey,
472
+ status: "cancelled",
473
+ finishedAt: node.finishedAt.toISOString(),
474
+ ...(node.error ? { error: node.error } : {}),
475
+ },
476
+ },
477
+ {
478
+ type: "workflow.run.finished",
479
+ payload: {
480
+ workflowId: run.workflowId,
481
+ runId: run.id,
482
+ status: "cancelled",
483
+ finishedAt: run.finishedAt.toISOString(),
484
+ ...(run.error ? { error: run.error } : {}),
485
+ },
486
+ },
487
+ ],
488
+ })
489
+ }
490
+
491
+ async function emitWorkflowRunCancelled(input: {
492
+ readonly sixb: Sixb<readonly OntologySource[]>
493
+ readonly workflow: WorkflowDefinition
494
+ readonly run: WorkflowRunRecord
495
+ readonly node?: WorkflowNodeRunRecord
496
+ }): Promise<void> {
497
+ const { sixb, workflow, run, node } = input
498
+ if (!run.finishedAt) {
499
+ throw new Error(`[SixbServer] Cancelled workflow run '${run.id}' has no finishedAt.`)
500
+ }
501
+ await sixb.events.append({
502
+ events: [
503
+ ...(node?.finishedAt
504
+ ? [
505
+ {
506
+ type: "workflow.run.node.finished" as const,
507
+ payload: {
508
+ workflowId: node.workflowId,
509
+ runId: node.workflowRunId,
510
+ nodeRunId: node.id,
511
+ nodeIndex: node.nodeIndex,
512
+ totalNodes: workflow.nodes.length,
513
+ nodeType: node.nodeType,
514
+ nodeId: node.nodeId,
515
+ nodeKey: node.nodeKey,
516
+ status: "cancelled" as const,
517
+ finishedAt: node.finishedAt.toISOString(),
518
+ ...(node.error ? { error: node.error } : {}),
519
+ },
520
+ },
521
+ ]
522
+ : []),
523
+ {
524
+ type: "workflow.run.finished",
525
+ payload: {
526
+ workflowId: run.workflowId,
527
+ runId: run.id,
528
+ status: "cancelled",
529
+ finishedAt: run.finishedAt.toISOString(),
530
+ ...(run.error ? { error: run.error } : {}),
531
+ },
532
+ },
533
+ ],
534
+ })
535
+ }
536
+
537
+ export function registerWorkflowRoutes(app: Elysia, sixb: Sixb<readonly OntologySource[]>) {
538
+ return app
539
+ .get(
540
+ "/api/workflows",
541
+ async (context) => {
542
+ const { scoped } = requestAuthState(context)
543
+ const workflows = scoped ? scoped.listWorkflows() : sixb.workflows.list()
544
+ const latestRuns = await getLatestWorkflowRuns(
545
+ sixb,
546
+ workflows.map((workflow) => workflow.id)
547
+ )
548
+
549
+ return workflows.map((workflow) =>
550
+ serializeWorkflow(workflow, latestRuns.get(workflow.id) ?? null)
551
+ )
552
+ },
553
+ {
554
+ response: { 200: WorkflowSchema.array() },
555
+ detail: {
556
+ summary: "List registered workflows",
557
+ tags: [OPENAPI_TAGS.workflows.name],
558
+ operationId: "listWorkflows",
559
+ security: bearerSecurityRequirement("listWorkflows"),
560
+ },
561
+ }
562
+ )
563
+ .get(
564
+ "/api/workflows/:workflowId",
565
+ async (context) => {
566
+ const { params, set } = context
567
+ const { scoped } = requestAuthState(context)
568
+ // Non-runnable workflows are hidden as 404 (existence-hiding), matching
569
+ // the object/action read routes.
570
+ const workflow = scoped
571
+ ? scoped.getWorkflowById(params.workflowId)
572
+ : sixb.workflows.getById(params.workflowId)
573
+ if (!workflow) {
574
+ set.status = 404
575
+ return { error: "Workflow not found" }
576
+ }
577
+
578
+ return serializeWorkflow(workflow, await getLatestWorkflowRun(sixb, workflow.id))
579
+ },
580
+ {
581
+ params: WorkflowParamsSchema,
582
+ response: { 200: WorkflowSchema, 404: ErrorResponseSchema },
583
+ detail: {
584
+ summary: "Get workflow metadata",
585
+ tags: [OPENAPI_TAGS.workflows.name],
586
+ operationId: "getWorkflow",
587
+ security: bearerSecurityRequirement("getWorkflow"),
588
+ },
589
+ }
590
+ )
591
+ .get(
592
+ "/api/workflow-interventions",
593
+ async (context) => {
594
+ const { query, set } = context
595
+ const { authz, scoped } = requestAuthState(context)
596
+ try {
597
+ const parsed = WorkflowInterventionsQuerySchema.parse(query)
598
+ const limit = parseOptionalInt(parsed.limit)
599
+ const offset = parseOptionalInt(parsed.offset)
600
+ const storage = sixb.storage.workflowInterventions
601
+ if (!storage) {
602
+ return unconfiguredStorageResponse(set, "Workflow intervention storage")
603
+ }
604
+
605
+ const workflowIds = scoped
606
+ ? scoped.listWorkflows().map((workflow) => workflow.id)
607
+ : authz
608
+ ? [...authz.grants["run:workflow"]]
609
+ : undefined
610
+ const result = await storage.list({
611
+ projectId: sixb.id,
612
+ workflowId: parsed.workflowId,
613
+ workflowIds,
614
+ workflowRunId: parsed.workflowRunId,
615
+ nodeRunId: parsed.nodeRunId,
616
+ nodeId: parsed.nodeId,
617
+ nodeKey: parsed.nodeKey,
618
+ interventionId: parsed.interventionId,
619
+ statuses: parsed.status ? [parsed.status] : undefined,
620
+ requestedAfter: parseDate(parsed.requestedAfter),
621
+ requestedBefore: parseDate(parsed.requestedBefore),
622
+ limit,
623
+ offset,
624
+ order: parsed.order,
625
+ })
626
+
627
+ return WorkflowInterventionListResponseSchema.parse({
628
+ interventions: result.interventions.map(serializeWorkflowIntervention),
629
+ hasMore: result.hasMore,
630
+ total: result.total,
631
+ })
632
+ } catch (error) {
633
+ return handleRouteError(error, set)
634
+ }
635
+ },
636
+ {
637
+ query: WorkflowInterventionsQuerySchema,
638
+ response: {
639
+ 200: WorkflowInterventionListResponseSchema,
640
+ 400: ErrorResponseSchema,
641
+ 501: ErrorResponseSchema,
642
+ },
643
+ detail: {
644
+ summary: "List workflow interventions",
645
+ tags: [OPENAPI_TAGS.workflowInterventions.name],
646
+ operationId: "listWorkflowInterventions",
647
+ },
648
+ }
649
+ )
650
+ .get(
651
+ "/api/workflow-interventions/:interventionId",
652
+ async (context) => {
653
+ const { params, set } = context
654
+ const { authz, scoped } = requestAuthState(context)
655
+ try {
656
+ const storage = sixb.storage.workflowInterventions
657
+ if (!storage) {
658
+ return unconfiguredStorageResponse(set, "Workflow intervention storage")
659
+ }
660
+
661
+ const intervention = await storage.getById({
662
+ projectId: sixb.id,
663
+ id: params.interventionId,
664
+ })
665
+ if (
666
+ !intervention ||
667
+ !canViewWorkflowIntervention(authz, intervention) ||
668
+ (scoped && !scoped.getWorkflowById(intervention.workflowId))
669
+ ) {
670
+ set.status = 404
671
+ return { error: "Workflow intervention not found" }
672
+ }
673
+
674
+ return WorkflowInterventionSchema.parse(serializeWorkflowIntervention(intervention))
675
+ } catch (error) {
676
+ return handleRouteError(error, set)
677
+ }
678
+ },
679
+ {
680
+ params: WorkflowInterventionParamsSchema,
681
+ response: {
682
+ 200: WorkflowInterventionSchema,
683
+ 400: ErrorResponseSchema,
684
+ 404: ErrorResponseSchema,
685
+ 501: ErrorResponseSchema,
686
+ },
687
+ detail: {
688
+ summary: "Get workflow intervention detail",
689
+ tags: [OPENAPI_TAGS.workflowInterventions.name],
690
+ operationId: "getWorkflowIntervention",
691
+ },
692
+ }
693
+ )
694
+ .post(
695
+ "/api/workflow-interventions/:interventionId/submit",
696
+ async (context) => {
697
+ const { params, body, set } = context
698
+ const { authz, scoped } = requestAuthState(context)
699
+ try {
700
+ const storage = sixb.storage.workflowInterventions
701
+ if (!storage) {
702
+ return unconfiguredStorageResponse(set, "Workflow intervention storage")
703
+ }
704
+
705
+ const intervention = await storage.getById({
706
+ projectId: sixb.id,
707
+ id: params.interventionId,
708
+ })
709
+ if (
710
+ !intervention ||
711
+ !canViewWorkflowIntervention(authz, intervention) ||
712
+ (scoped && !scoped.getWorkflowById(intervention.workflowId))
713
+ ) {
714
+ set.status = 404
715
+ return { error: "Workflow intervention not found" }
716
+ }
717
+ assertPendingIntervention(intervention)
718
+
719
+ const workflow = sixb.workflows.getById(intervention.workflowId)
720
+ if (!workflow) {
721
+ set.status = 404
722
+ return { error: "Workflow not found" }
723
+ }
724
+
725
+ const node = requireRegisteredInterventionNode(workflow, intervention)
726
+ const parsedBody = SubmitWorkflowInterventionBodySchema.parse(body)
727
+ const response = snapshotWorkflowInterventionResponse({
728
+ workflowId: workflow.id,
729
+ intervention: node.intervention,
730
+ value: parsedBody.response,
731
+ valueTypesById: sixb.ontology.getValueTypesById(),
732
+ })
733
+
734
+ const submitted = await storage.submit({
735
+ projectId: sixb.id,
736
+ id: intervention.id,
737
+ response,
738
+ submittedBy: serializePrincipal(authz?.principal ?? SYSTEM_PRINCIPAL),
739
+ })
740
+
741
+ const [job] = await sixb.queues.workflows.enqueue({
742
+ projectId: sixb.id,
743
+ jobs: [
744
+ {
745
+ type: "workflow.run.resume.requested",
746
+ payload: {
747
+ workflowId: submitted.workflowId,
748
+ runId: submitted.workflowRunId,
749
+ resume: { kind: "intervention", interventionId: submitted.id },
750
+ },
751
+ },
752
+ ],
753
+ })
754
+
755
+ await emitWorkflowInterventionSubmitted(sixb, submitted)
756
+
757
+ set.status = 202
758
+ return SubmitWorkflowInterventionResponseSchema.parse({
759
+ intervention: serializeWorkflowIntervention(submitted),
760
+ jobId: job?.id ?? "",
761
+ })
762
+ } catch (error) {
763
+ return handleRouteError(error, set)
764
+ }
765
+ },
766
+ {
767
+ params: WorkflowInterventionParamsSchema,
768
+ body: SubmitWorkflowInterventionBodySchema,
769
+ response: {
770
+ 202: SubmitWorkflowInterventionResponseSchema,
771
+ 400: ErrorResponseSchema,
772
+ 404: ErrorResponseSchema,
773
+ 501: ErrorResponseSchema,
774
+ },
775
+ detail: {
776
+ summary: "Submit a workflow intervention response",
777
+ tags: [OPENAPI_TAGS.workflowInterventions.name],
778
+ operationId: "submitWorkflowIntervention",
779
+ security: SIXB_CSRF_SECURITY_REQUIREMENT,
780
+ },
781
+ }
782
+ )
783
+ .post(
784
+ "/api/workflow-interventions/:interventionId/cancel",
785
+ async (context) => {
786
+ const { params, body, set } = context
787
+ const { authz, scoped } = requestAuthState(context)
788
+ try {
789
+ const interventionStorage = sixb.storage.workflowInterventions
790
+ if (!interventionStorage) {
791
+ return unconfiguredStorageResponse(set, "Workflow intervention storage")
792
+ }
793
+
794
+ const runStorage = sixb.storage.workflowRuns
795
+ if (!runStorage) {
796
+ return unconfiguredStorageResponse(set, "Workflow run storage")
797
+ }
798
+
799
+ const intervention = await interventionStorage.getById({
800
+ projectId: sixb.id,
801
+ id: params.interventionId,
802
+ })
803
+ if (
804
+ !intervention ||
805
+ !canViewWorkflowIntervention(authz, intervention) ||
806
+ (scoped && !scoped.getWorkflowById(intervention.workflowId))
807
+ ) {
808
+ set.status = 404
809
+ return { error: "Workflow intervention not found" }
810
+ }
811
+ assertPendingIntervention(intervention)
812
+
813
+ const workflow = sixb.workflows.getById(intervention.workflowId)
814
+ if (!workflow) {
815
+ set.status = 404
816
+ return { error: "Workflow not found" }
817
+ }
818
+ requireRegisteredInterventionNode(workflow, intervention)
819
+
820
+ const run = await runStorage.getById({
821
+ projectId: sixb.id,
822
+ id: intervention.workflowRunId,
823
+ })
824
+ if (!run) {
825
+ set.status = 404
826
+ return { error: "Workflow run not found" }
827
+ }
828
+ if (run.status !== "waiting") {
829
+ set.status = 400
830
+ return { error: "Workflow run is not waiting" }
831
+ }
832
+
833
+ const nodeRun = await runStorage.nodes.getById({
834
+ projectId: sixb.id,
835
+ id: intervention.nodeRunId,
836
+ })
837
+ if (!nodeRun) {
838
+ set.status = 404
839
+ return { error: "Workflow node run not found" }
840
+ }
841
+ if (nodeRun.status !== "waiting") {
842
+ set.status = 400
843
+ return { error: "Workflow node run is not waiting" }
844
+ }
845
+
846
+ CancelWorkflowInterventionBodySchema.parse(body ?? {})
847
+ const cancelledAt = new Date()
848
+ const { cancelled, cancelledNode, cancelledRun } = await sixb.storage.transaction(
849
+ async (tx) => {
850
+ if (!tx.workflowInterventions || !tx.workflowRuns) {
851
+ throw new Error("[SixbServer] Workflow storage disappeared during cancellation.")
852
+ }
853
+ const cancelled = await tx.workflowInterventions.cancel({
854
+ projectId: sixb.id,
855
+ id: intervention.id,
856
+ cancelledAt,
857
+ cancelledBy: serializePrincipal(authz?.principal ?? SYSTEM_PRINCIPAL),
858
+ })
859
+ const cancelledNode = await tx.workflowRuns.nodes.finish({
860
+ projectId: sixb.id,
861
+ id: intervention.nodeRunId,
862
+ status: "cancelled",
863
+ finishedAt: cancelledAt,
864
+ error: "Workflow intervention cancelled.",
865
+ })
866
+ const cancelledRun = await tx.workflowRuns.finish({
867
+ projectId: sixb.id,
868
+ id: intervention.workflowRunId,
869
+ status: "cancelled",
870
+ finishedAt: cancelledAt,
871
+ error: "Workflow intervention cancelled.",
872
+ })
873
+ return { cancelled, cancelledNode, cancelledRun }
874
+ }
875
+ )
876
+
877
+ await emitWorkflowInterventionCancelled({
878
+ sixb,
879
+ workflow,
880
+ intervention: cancelled,
881
+ node: cancelledNode,
882
+ run: cancelledRun,
883
+ })
884
+
885
+ return CancelWorkflowInterventionResponseSchema.parse({
886
+ intervention: serializeWorkflowIntervention(cancelled),
887
+ })
888
+ } catch (error) {
889
+ return handleRouteError(error, set)
890
+ }
891
+ },
892
+ {
893
+ params: WorkflowInterventionParamsSchema,
894
+ body: CancelWorkflowInterventionBodySchema,
895
+ response: {
896
+ 200: CancelWorkflowInterventionResponseSchema,
897
+ 400: ErrorResponseSchema,
898
+ 404: ErrorResponseSchema,
899
+ 501: ErrorResponseSchema,
900
+ },
901
+ detail: {
902
+ summary: "Cancel a workflow intervention",
903
+ tags: [OPENAPI_TAGS.workflowInterventions.name],
904
+ operationId: "cancelWorkflowIntervention",
905
+ security: SIXB_CSRF_SECURITY_REQUIREMENT,
906
+ },
907
+ }
908
+ )
909
+ .get(
910
+ "/api/workflow-runs",
911
+ async (context) => {
912
+ const { query, set } = context
913
+ const { authz, scoped } = requestAuthState(context)
914
+ try {
915
+ const parsed = WorkflowRunsQuerySchema.parse(query)
916
+ const limit = parseOptionalInt(parsed.limit)
917
+ const offset = parseOptionalInt(parsed.offset)
918
+ const storage = sixb.storage.workflowRuns
919
+ if (!storage) {
920
+ return unconfiguredStorageResponse(set, "Workflow run storage")
921
+ }
922
+
923
+ const workflowIds = scoped
924
+ ? scoped.listWorkflows().map((workflow) => workflow.id)
925
+ : authz
926
+ ? [...authz.grants["run:workflow"]]
927
+ : undefined
928
+ const result = await storage.list({
929
+ projectId: sixb.id,
930
+ workflowId: parsed.workflowId,
931
+ workflowIds,
932
+ statuses: parsed.status ? [parsed.status] : undefined,
933
+ startedAfter: parseDate(parsed.startedAfter),
934
+ startedBefore: parseDate(parsed.startedBefore),
935
+ limit,
936
+ offset,
937
+ order: parsed.order,
938
+ })
939
+
940
+ return {
941
+ runs: result.runs.map(serializeWorkflowRun),
942
+ hasMore: result.hasMore,
943
+ total: result.total,
944
+ }
945
+ } catch (error) {
946
+ return handleRouteError(error, set)
947
+ }
948
+ },
949
+ {
950
+ query: WorkflowRunsQuerySchema,
951
+ response: {
952
+ 200: WorkflowRunListResponseSchema,
953
+ 400: ErrorResponseSchema,
954
+ 501: ErrorResponseSchema,
955
+ },
956
+ detail: {
957
+ summary: "List workflow run history",
958
+ tags: [OPENAPI_TAGS.workflowRuns.name],
959
+ operationId: "listWorkflowRuns",
960
+ },
961
+ }
962
+ )
963
+ .get(
964
+ "/api/workflow-runs/:runId",
965
+ async (context) => {
966
+ const { params, set } = context
967
+ const { authz, scoped } = requestAuthState(context)
968
+ try {
969
+ const storage = sixb.storage.workflowRuns
970
+ if (!storage) {
971
+ return unconfiguredStorageResponse(set, "Workflow run storage")
972
+ }
973
+
974
+ const run = await storage.getById({ projectId: sixb.id, id: params.runId })
975
+ if (!run || !canAccessWorkflowRun(authz, scoped, run)) {
976
+ set.status = 404
977
+ return { error: "Workflow run not found" }
978
+ }
979
+
980
+ const nodes = await storage.nodes.list({
981
+ projectId: sixb.id,
982
+ workflowRunId: run.id,
983
+ order: "asc",
984
+ })
985
+
986
+ return WorkflowRunDetailResponseSchema.parse({
987
+ run: serializeWorkflowRun(run),
988
+ nodes: await Promise.all(
989
+ nodes.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node))
990
+ ),
991
+ })
992
+ } catch (error) {
993
+ return handleRouteError(error, set)
994
+ }
995
+ },
996
+ {
997
+ params: WorkflowRunParamsSchema,
998
+ response: {
999
+ 200: WorkflowRunDetailResponseSchema,
1000
+ 400: ErrorResponseSchema,
1001
+ 404: ErrorResponseSchema,
1002
+ 501: ErrorResponseSchema,
1003
+ },
1004
+ detail: {
1005
+ summary: "Get workflow run detail",
1006
+ tags: [OPENAPI_TAGS.workflowRuns.name],
1007
+ operationId: "getWorkflowRun",
1008
+ },
1009
+ }
1010
+ )
1011
+ .get(
1012
+ "/api/workflow-runs/:runId/nodes/:nodeKey/agent-execution",
1013
+ async (context) => {
1014
+ const { params, set } = context
1015
+ const { authz, scoped } = requestAuthState(context)
1016
+ try {
1017
+ const storage = sixb.storage.workflowRuns
1018
+ if (!storage) {
1019
+ return unconfiguredStorageResponse(set, "Workflow run storage")
1020
+ }
1021
+ const run = await storage.getById({ projectId: sixb.id, id: params.runId })
1022
+ if (!run || !canAccessWorkflowRun(authz, scoped, run)) {
1023
+ set.status = 404
1024
+ return { error: "Workflow agent execution not found" }
1025
+ }
1026
+ const listed = await storage.nodes.list({
1027
+ projectId: sixb.id,
1028
+ workflowRunId: run.id,
1029
+ nodeKey: params.nodeKey,
1030
+ limit: 1,
1031
+ order: "asc",
1032
+ })
1033
+ const node = listed.nodes[0]
1034
+ if (!node || node.nodeType !== "agent") {
1035
+ set.status = 404
1036
+ return { error: "Workflow agent execution not found" }
1037
+ }
1038
+ const execution = await storage.agentNodes.getByNodeRunId({
1039
+ projectId: sixb.id,
1040
+ nodeRunId: node.id,
1041
+ })
1042
+ if (!execution) {
1043
+ set.status = 404
1044
+ return { error: "Workflow agent execution not found" }
1045
+ }
1046
+ return WorkflowAgentNodeExecutionSchema.parse(serializeWorkflowAgentExecution(execution))
1047
+ } catch (error) {
1048
+ return handleRouteError(error, set)
1049
+ }
1050
+ },
1051
+ {
1052
+ params: WorkflowNodeFileContentParamsSchema,
1053
+ response: {
1054
+ 200: WorkflowAgentNodeExecutionSchema,
1055
+ 400: ErrorResponseSchema,
1056
+ 404: ErrorResponseSchema,
1057
+ 501: ErrorResponseSchema,
1058
+ },
1059
+ detail: {
1060
+ summary: "Get workflow agent node execution detail",
1061
+ tags: [OPENAPI_TAGS.workflowRuns.name],
1062
+ operationId: "getWorkflowAgentNodeExecution",
1063
+ security: bearerSecurityRequirement("getWorkflowAgentNodeExecution"),
1064
+ },
1065
+ }
1066
+ )
1067
+ .post(
1068
+ "/api/workflow-runs/:runId/cancel",
1069
+ async (context) => {
1070
+ const { params, body, set } = context
1071
+ const { authz, scoped } = requestAuthState(context)
1072
+ try {
1073
+ CancelWorkflowRunBodySchema.parse(body ?? {})
1074
+ const storage = sixb.storage.workflowRuns
1075
+ if (!storage) {
1076
+ return unconfiguredStorageResponse(set, "Workflow run storage")
1077
+ }
1078
+ const existing = await storage.getById({ projectId: sixb.id, id: params.runId })
1079
+ if (!existing || !canAccessWorkflowRun(authz, scoped, existing)) {
1080
+ set.status = 404
1081
+ return { error: "Workflow run not found" }
1082
+ }
1083
+ const workflow = sixb.workflows.getById(existing.workflowId)
1084
+ if (!workflow) {
1085
+ set.status = 404
1086
+ return { error: "Workflow not found" }
1087
+ }
1088
+ const listed = await storage.nodes.list({
1089
+ projectId: sixb.id,
1090
+ workflowRunId: existing.id,
1091
+ order: "asc",
1092
+ })
1093
+ if (existing.status === "cancelled") {
1094
+ return CancelWorkflowRunResponseSchema.parse({
1095
+ run: serializeWorkflowRun(existing),
1096
+ nodes: await Promise.all(
1097
+ listed.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node))
1098
+ ),
1099
+ })
1100
+ }
1101
+ if (existing.status === "succeeded" || existing.status === "failed") {
1102
+ set.status = 400
1103
+ return { error: `Workflow run is already ${existing.status}` }
1104
+ }
1105
+
1106
+ const cancelledAt = new Date()
1107
+ const cancellationError = "Workflow run cancelled."
1108
+ const result = await sixb.storage.transaction(async (tx) => {
1109
+ const runs = tx.workflowRuns
1110
+ if (!runs) {
1111
+ throw new Error("[SixbServer] Workflow storage disappeared during cancellation.")
1112
+ }
1113
+ const run = await runs.getById({ projectId: sixb.id, id: existing.id })
1114
+ if (!run || !["queued", "running", "waiting"].includes(run.status)) {
1115
+ throw new Error(`[SixbServer] Workflow run '${existing.id}' is no longer active.`)
1116
+ }
1117
+ const active = [...listed.nodes]
1118
+ .reverse()
1119
+ .find((node) => node.status === "running" || node.status === "waiting")
1120
+ let cancelledNode: WorkflowNodeRunRecord | undefined
1121
+ if (active?.nodeType === "agent") {
1122
+ const execution = await runs.agentNodes.getByNodeRunId({
1123
+ projectId: sixb.id,
1124
+ nodeRunId: active.id,
1125
+ })
1126
+ if (execution?.status === "queued" || execution?.status === "running") {
1127
+ await runs.agentNodes.cancel({
1128
+ projectId: sixb.id,
1129
+ nodeRunId: active.id,
1130
+ completedAt: cancelledAt,
1131
+ error: cancellationError,
1132
+ })
1133
+ }
1134
+ }
1135
+ if (active?.nodeType === "intervention" && tx.workflowInterventions) {
1136
+ const pending = await tx.workflowInterventions.list({
1137
+ projectId: sixb.id,
1138
+ workflowRunId: run.id,
1139
+ nodeRunId: active.id,
1140
+ statuses: ["pending"],
1141
+ limit: 1,
1142
+ })
1143
+ const intervention = pending.interventions[0]
1144
+ if (intervention) {
1145
+ await tx.workflowInterventions.cancel({
1146
+ projectId: sixb.id,
1147
+ id: intervention.id,
1148
+ cancelledAt,
1149
+ cancelledBy: serializePrincipal(authz?.principal ?? SYSTEM_PRINCIPAL),
1150
+ })
1151
+ }
1152
+ }
1153
+ if (active) {
1154
+ cancelledNode = await runs.nodes.finish({
1155
+ projectId: sixb.id,
1156
+ id: active.id,
1157
+ status: "cancelled",
1158
+ finishedAt: cancelledAt,
1159
+ error: cancellationError,
1160
+ executionToken: run.execution?.token,
1161
+ })
1162
+ }
1163
+ const cancelledRun = await runs.finish({
1164
+ projectId: sixb.id,
1165
+ id: run.id,
1166
+ status: "cancelled",
1167
+ finishedAt: cancelledAt,
1168
+ error: cancellationError,
1169
+ executionToken: run.execution?.token,
1170
+ })
1171
+ return { run: cancelledRun, node: cancelledNode }
1172
+ })
1173
+
1174
+ await emitWorkflowRunCancelled({ sixb, workflow, ...result })
1175
+ if (result.node?.nodeType === "agent") {
1176
+ await publishAgentRunCancel(sixb.broker, {
1177
+ projectId: sixb.id,
1178
+ runId: result.node.id,
1179
+ }).catch((error) => {
1180
+ console.error(
1181
+ `[SixbServer] Could not signal cancellation for workflow agent node '${result.node?.id}'.`,
1182
+ error
1183
+ )
1184
+ })
1185
+ }
1186
+ const nodes = await storage.nodes.list({
1187
+ projectId: sixb.id,
1188
+ workflowRunId: existing.id,
1189
+ order: "asc",
1190
+ })
1191
+ return CancelWorkflowRunResponseSchema.parse({
1192
+ run: serializeWorkflowRun(result.run),
1193
+ nodes: await Promise.all(
1194
+ nodes.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node))
1195
+ ),
1196
+ })
1197
+ } catch (error) {
1198
+ return handleRouteError(error, set)
1199
+ }
1200
+ },
1201
+ {
1202
+ params: WorkflowRunParamsSchema,
1203
+ body: CancelWorkflowRunBodySchema,
1204
+ response: {
1205
+ 200: CancelWorkflowRunResponseSchema,
1206
+ 400: ErrorResponseSchema,
1207
+ 404: ErrorResponseSchema,
1208
+ 501: ErrorResponseSchema,
1209
+ },
1210
+ detail: {
1211
+ summary: "Cancel a workflow run",
1212
+ tags: [OPENAPI_TAGS.workflowRuns.name],
1213
+ operationId: "cancelWorkflowRun",
1214
+ security: bearerSecurityRequirement("cancelWorkflowRun"),
1215
+ },
1216
+ }
1217
+ )
1218
+ .get(
1219
+ "/api/workflow-runs/:runId/files/content",
1220
+ (context) => workflowRunFileContentResponse(sixb, context),
1221
+ {
1222
+ params: WorkflowRunParamsSchema,
1223
+ query: FileContentQuerySchema,
1224
+ detail: {
1225
+ summary: "Get workflow run file content",
1226
+ tags: ["Workflows"],
1227
+ operationId: "getWorkflowRunFileContent",
1228
+ security: bearerSecurityRequirement("getWorkflowRunFileContent"),
1229
+ responses: fileContentGetResponses({ optionalStorage: true }),
1230
+ },
1231
+ }
1232
+ )
1233
+ .head(
1234
+ "/api/workflow-runs/:runId/files/content",
1235
+ (context) => workflowRunFileContentResponse(sixb, context, { head: true }),
1236
+ {
1237
+ params: WorkflowRunParamsSchema,
1238
+ query: FileContentQuerySchema,
1239
+ detail: {
1240
+ summary: "Head workflow run file content",
1241
+ tags: ["Workflows"],
1242
+ operationId: "headWorkflowRunFileContent",
1243
+ security: bearerSecurityRequirement("headWorkflowRunFileContent"),
1244
+ responses: fileContentHeadResponses({ optionalStorage: true }),
1245
+ },
1246
+ }
1247
+ )
1248
+ .get(
1249
+ "/api/workflow-runs/:runId/nodes/:nodeKey/files/content",
1250
+ (context) => workflowNodeFileContentResponse(sixb, context),
1251
+ {
1252
+ params: WorkflowNodeFileContentParamsSchema,
1253
+ query: FileContentQuerySchema,
1254
+ detail: {
1255
+ summary: "Get workflow node run file content",
1256
+ tags: ["Workflows"],
1257
+ operationId: "getWorkflowNodeRunFileContent",
1258
+ security: bearerSecurityRequirement("getWorkflowNodeRunFileContent"),
1259
+ responses: fileContentGetResponses({ optionalStorage: true }),
1260
+ },
1261
+ }
1262
+ )
1263
+ .head(
1264
+ "/api/workflow-runs/:runId/nodes/:nodeKey/files/content",
1265
+ (context) => workflowNodeFileContentResponse(sixb, context, { head: true }),
1266
+ {
1267
+ params: WorkflowNodeFileContentParamsSchema,
1268
+ query: FileContentQuerySchema,
1269
+ detail: {
1270
+ summary: "Head workflow node run file content",
1271
+ tags: ["Workflows"],
1272
+ operationId: "headWorkflowNodeRunFileContent",
1273
+ security: bearerSecurityRequirement("headWorkflowNodeRunFileContent"),
1274
+ responses: fileContentHeadResponses({ optionalStorage: true }),
1275
+ },
1276
+ }
1277
+ )
1278
+ .post(
1279
+ "/api/workflows/:workflowId/runs",
1280
+ async (context) => {
1281
+ const { params, body, set } = context
1282
+ const { scoped } = requestAuthState(context)
1283
+ try {
1284
+ const workflow = sixb.workflows.getById(params.workflowId)
1285
+ if (!workflow) {
1286
+ set.status = 404
1287
+ return { error: "Workflow not found" }
1288
+ }
1289
+
1290
+ if (!sixb.storage.workflowRuns) {
1291
+ return unconfiguredStorageResponse(set, "Workflow run storage")
1292
+ }
1293
+
1294
+ const parsedBody = RequestWorkflowRunBodySchema.parse(body)
1295
+ const input = {
1296
+ workflowId: workflow.id,
1297
+ input: parsedBody.input ?? {},
1298
+ source: { type: "manual" } as const,
1299
+ }
1300
+ const result = scoped
1301
+ ? await scoped.requestWorkflowRun(input)
1302
+ : await sixb.requestWorkflowRun(input)
1303
+
1304
+ set.status = 202
1305
+ return RequestWorkflowRunResponseSchema.parse({
1306
+ runId: result.runId,
1307
+ jobId: result.jobId ?? "",
1308
+ workflowId: result.workflowId,
1309
+ queuedAt: result.queuedAt,
1310
+ })
1311
+ } catch (error) {
1312
+ return handleRouteError(error, set)
1313
+ }
1314
+ },
1315
+ {
1316
+ params: WorkflowParamsSchema,
1317
+ body: RequestWorkflowRunBodySchema,
1318
+ response: {
1319
+ 202: RequestWorkflowRunResponseSchema,
1320
+ 400: ErrorResponseSchema,
1321
+ 403: ErrorResponseSchema,
1322
+ 404: ErrorResponseSchema,
1323
+ 501: ErrorResponseSchema,
1324
+ },
1325
+ detail: {
1326
+ summary: "Request a workflow run",
1327
+ tags: [OPENAPI_TAGS.workflowRuns.name],
1328
+ operationId: "requestWorkflowRun",
1329
+ security: bearerSecurityRequirement("requestWorkflowRun"),
1330
+ },
1331
+ }
1332
+ )
1333
+ }