@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,301 @@
1
+ import type { AuthorizationContext, OntologySource, Sixb } from "@sixb/core"
2
+ import { agentRunStreamDefinition, agentRunStreamId } from "@sixb/core/agents/streams"
3
+ import type { BrokerRecord } from "@sixb/core/broker"
4
+ import type { Elysia } from "elysia"
5
+ import { z } from "zod"
6
+ import type { SixbServer } from "../../server"
7
+ import { decodeWsMessage, safeSend, wsAuthz, wsStateKey } from "../../utils/ws"
8
+ import { serializeAgentRun } from "../agents"
9
+
10
+ interface AgentStreamSubscriptionState {
11
+ runId: string | null
12
+ unsubscribe: (() => void) | null
13
+ }
14
+
15
+ const SubscribeSchema = z.object({
16
+ type: z.literal("subscribe"),
17
+ runId: z.string().min(1),
18
+ afterCursor: z.string().min(1).optional(),
19
+ })
20
+
21
+ const ReplaySchema = z.object({
22
+ type: z.literal("replay"),
23
+ runId: z.string().min(1),
24
+ afterCursor: z.string().min(1).optional(),
25
+ limit: z.number().int().positive().max(500).optional(),
26
+ })
27
+
28
+ const UnsubscribeSchema = z.object({
29
+ type: z.literal("unsubscribe"),
30
+ runId: z.string().min(1).optional(),
31
+ })
32
+
33
+ const AgentStreamMessageSchema = z.union([SubscribeSchema, ReplaySchema, UnsubscribeSchema])
34
+
35
+ type SubscribeMessage = z.infer<typeof SubscribeSchema>
36
+ type ReplayMessage = z.infer<typeof ReplaySchema>
37
+ type UnsubscribeMessage = z.infer<typeof UnsubscribeSchema>
38
+
39
+ export function parseAgentStreamMessage(payload: unknown):
40
+ | {
41
+ ok: true
42
+ data: z.infer<typeof AgentStreamMessageSchema>
43
+ }
44
+ | {
45
+ ok: false
46
+ error: string
47
+ } {
48
+ if (!payload || typeof payload !== "object") {
49
+ return { ok: false, error: "Message must be a JSON object." }
50
+ }
51
+
52
+ const parsed = AgentStreamMessageSchema.safeParse(payload)
53
+ if (!parsed.success) {
54
+ return {
55
+ ok: false,
56
+ error: parsed.error.issues[0]?.message ?? "Invalid websocket message.",
57
+ }
58
+ }
59
+
60
+ return { ok: true, data: parsed.data }
61
+ }
62
+
63
+ export async function canAccessAgentRunStream(
64
+ sixb: Sixb<readonly OntologySource[]>,
65
+ input: {
66
+ readonly runId: string
67
+ readonly authz: AuthorizationContext | null
68
+ }
69
+ ): Promise<{ ok: true } | { ok: false; message: string }> {
70
+ const storage = sixb.storage.agents
71
+ if (!storage) {
72
+ return { ok: false, message: "Agent storage is not configured." }
73
+ }
74
+
75
+ const run = await storage.runs.getById({ projectId: sixb.id, id: input.runId })
76
+ if (!run) {
77
+ return { ok: false, message: "Agent run not found." }
78
+ }
79
+
80
+ // Auth-disabled development runtimes are privileged, matching the existing HTTP agent routes.
81
+ if (!input.authz) {
82
+ return { ok: true }
83
+ }
84
+
85
+ // Reuse the one owner + `run:agent` rule instead of re-implementing it here: the scoped surface
86
+ // returns null for a thread the caller may not read (absent, not owner, or ungranted).
87
+ const thread = await sixb.as(input.authz).getThread(run.threadId)
88
+ if (!thread) {
89
+ return { ok: false, message: "Agent run not found." }
90
+ }
91
+
92
+ return { ok: true }
93
+ }
94
+
95
+ export function registerAgentStreamRoutes(app: Elysia, server: SixbServer) {
96
+ const states = new WeakMap<object, AgentStreamSubscriptionState>()
97
+
98
+ return app.ws("/ws/agents", {
99
+ open(ws) {
100
+ states.set(wsStateKey(ws), { runId: null, unsubscribe: null })
101
+ safeSend(ws, { type: "connected", channel: "agents" })
102
+ },
103
+
104
+ async message(ws, message) {
105
+ const decoded = await decodeWsMessage(message)
106
+ const parsed = parseAgentStreamMessage(decoded)
107
+ if (!parsed.ok) {
108
+ safeSend(ws, { type: "error", message: parsed.error })
109
+ return
110
+ }
111
+
112
+ if (parsed.data.type === "unsubscribe") {
113
+ unsubscribeAgentStream(states, ws, parsed.data)
114
+ return
115
+ }
116
+
117
+ if (parsed.data.type === "replay") {
118
+ await replayAgentStream(server, ws, parsed.data)
119
+ return
120
+ }
121
+
122
+ await subscribeAgentStream(states, server, ws, parsed.data)
123
+ },
124
+
125
+ close(ws) {
126
+ stopSubscription(states.get(wsStateKey(ws)))
127
+ states.delete(wsStateKey(ws))
128
+ },
129
+ })
130
+ }
131
+
132
+ async function subscribeAgentStream(
133
+ states: WeakMap<object, AgentStreamSubscriptionState>,
134
+ server: SixbServer,
135
+ ws: { send: (message: string) => void },
136
+ message: SubscribeMessage
137
+ ): Promise<void> {
138
+ const sixb = server.getSixb()
139
+ const access = await canAccessAgentRunStream(sixb, {
140
+ runId: message.runId,
141
+ authz: wsAuthz(ws),
142
+ })
143
+ if (!access.ok) {
144
+ safeSend(ws, { type: "error", message: access.message })
145
+ return
146
+ }
147
+
148
+ const streamId = agentRunStreamId(message.runId)
149
+ try {
150
+ await sixb.broker.ensureStream({
151
+ projectId: sixb.id,
152
+ stream: agentRunStreamDefinition(message.runId),
153
+ })
154
+ } catch (error) {
155
+ safeSend(ws, { type: "error", message: errorMessage(error) })
156
+ return
157
+ }
158
+
159
+ const state = states.get(wsStateKey(ws)) ?? { runId: null, unsubscribe: null }
160
+ stopSubscription(state)
161
+ states.set(wsStateKey(ws), state)
162
+
163
+ const buffered: BrokerRecord[] = []
164
+ let live = false
165
+ try {
166
+ state.unsubscribe = await sixb.broker.subscribe(
167
+ {
168
+ projectId: sixb.id,
169
+ streamId,
170
+ ...(message.afterCursor === undefined
171
+ ? { from: "earliest" as const }
172
+ : { afterCursor: message.afterCursor }),
173
+ },
174
+ (records) => {
175
+ if (!live) {
176
+ buffered.push(...records)
177
+ return
178
+ }
179
+ sendRecords(ws, records)
180
+ }
181
+ )
182
+ state.runId = message.runId
183
+ } catch (error) {
184
+ state.unsubscribe = null
185
+ state.runId = null
186
+ safeSend(ws, { type: "error", message: errorMessage(error) })
187
+ return
188
+ }
189
+
190
+ safeSend(ws, {
191
+ type: "subscribed",
192
+ runId: message.runId,
193
+ afterCursor: message.afterCursor ?? null,
194
+ })
195
+ sendRecords(ws, buffered.splice(0))
196
+ if (!(await sendRunSnapshot(sixb, ws, message.runId))) {
197
+ stopSubscription(state)
198
+ return
199
+ }
200
+ live = true
201
+ sendRecords(ws, buffered.splice(0))
202
+ }
203
+
204
+ async function replayAgentStream(
205
+ server: SixbServer,
206
+ ws: { send: (message: string) => void },
207
+ message: ReplayMessage
208
+ ): Promise<void> {
209
+ const sixb = server.getSixb()
210
+ const access = await canAccessAgentRunStream(sixb, {
211
+ runId: message.runId,
212
+ authz: wsAuthz(ws),
213
+ })
214
+ if (!access.ok) {
215
+ safeSend(ws, { type: "error", message: access.message })
216
+ return
217
+ }
218
+
219
+ const streamId = agentRunStreamId(message.runId)
220
+ try {
221
+ await sixb.broker.ensureStream({
222
+ projectId: sixb.id,
223
+ stream: agentRunStreamDefinition(message.runId),
224
+ })
225
+ const page = await sixb.broker.read({
226
+ projectId: sixb.id,
227
+ streamId,
228
+ afterCursor: message.afterCursor,
229
+ limit: message.limit,
230
+ })
231
+ sendRecords(ws, page.records)
232
+ safeSend(ws, {
233
+ type: "replayed",
234
+ runId: message.runId,
235
+ afterCursor: page.cursor ?? message.afterCursor ?? null,
236
+ count: page.records.length,
237
+ })
238
+ await sendRunSnapshot(sixb, ws, message.runId)
239
+ } catch (error) {
240
+ safeSend(ws, { type: "error", message: errorMessage(error) })
241
+ }
242
+ }
243
+
244
+ function unsubscribeAgentStream(
245
+ states: WeakMap<object, AgentStreamSubscriptionState>,
246
+ ws: { send: (message: string) => void },
247
+ message: UnsubscribeMessage
248
+ ): void {
249
+ const state = states.get(wsStateKey(ws))
250
+ const previousRunId = state?.runId ?? null
251
+
252
+ if (!message.runId || previousRunId === null || message.runId === previousRunId) {
253
+ stopSubscription(state)
254
+ }
255
+
256
+ safeSend(ws, {
257
+ type: "unsubscribed",
258
+ runId: message.runId ?? previousRunId,
259
+ })
260
+ }
261
+
262
+ function stopSubscription(state: AgentStreamSubscriptionState | undefined): void {
263
+ if (!state) {
264
+ return
265
+ }
266
+ state.unsubscribe?.()
267
+ state.unsubscribe = null
268
+ state.runId = null
269
+ }
270
+
271
+ async function sendRunSnapshot(
272
+ sixb: Sixb<readonly OntologySource[]>,
273
+ ws: { send: (message: string) => void },
274
+ runId: string
275
+ ): Promise<boolean> {
276
+ try {
277
+ const run = await sixb.storage.agents?.runs.getById({ projectId: sixb.id, id: runId })
278
+ if (!run) {
279
+ safeSend(ws, { type: "error", message: "Agent run not found." })
280
+ return false
281
+ }
282
+ safeSend(ws, { type: "run.snapshot", run: serializeAgentRun(run) })
283
+ return true
284
+ } catch (error) {
285
+ safeSend(ws, { type: "error", message: errorMessage(error) })
286
+ return false
287
+ }
288
+ }
289
+
290
+ function sendRecords(
291
+ ws: { send: (message: string) => void },
292
+ records: readonly BrokerRecord[]
293
+ ): void {
294
+ for (const record of records) {
295
+ safeSend(ws, { type: "record", record })
296
+ }
297
+ }
298
+
299
+ function errorMessage(error: unknown): string {
300
+ return error instanceof Error ? error.message : String(error)
301
+ }
@@ -0,0 +1,278 @@
1
+ import type { DomainEvent } from "@sixb/core"
2
+ import { scopeKeysForEvent } from "@sixb/core/events/scope"
3
+ import { canViewEvent } from "@sixb/core/internal/authorization"
4
+ import type { Elysia } from "elysia"
5
+ import { z } from "zod"
6
+ import { EVENT_TOPICS, EVENT_TYPES } from "../../schemas/events"
7
+ import type { SixbServer } from "../../server"
8
+ import { decodeWsMessage, safeSend, wsAuthz, wsStateKey } from "../../utils/ws"
9
+
10
+ interface EventSubscriptionState {
11
+ topics?: DomainEvent["topic"][]
12
+ types?: DomainEvent["type"][]
13
+ objectTypeId?: string
14
+ primaryId?: string
15
+ actionId?: string
16
+ runId?: string
17
+ afterCursor?: string
18
+ limit: number
19
+ polling: boolean
20
+ timer: ReturnType<typeof setInterval> | null
21
+ initialized: Promise<void>
22
+ initializationFailureHandled: boolean
23
+ }
24
+
25
+ const SubscribeSchema = z.object({
26
+ type: z.literal("subscribe"),
27
+ topic: z.enum(EVENT_TOPICS).optional(),
28
+ types: z.array(z.enum(EVENT_TYPES)).optional(),
29
+ objectTypeId: z.string().optional(),
30
+ primaryId: z.string().optional(),
31
+ actionId: z.string().optional(),
32
+ runId: z.string().optional(),
33
+ afterCursor: z.string().optional(),
34
+ limit: z.number().int().positive().max(500).optional(),
35
+ })
36
+
37
+ const UnsubscribeSchema = z.object({
38
+ type: z.literal("unsubscribe"),
39
+ })
40
+
41
+ const SubscriptionMessageSchema = z.union([SubscribeSchema, UnsubscribeSchema])
42
+
43
+ export function parseSubscriptionMessage(payload: unknown):
44
+ | {
45
+ ok: true
46
+ data: z.infer<typeof SubscriptionMessageSchema>
47
+ }
48
+ | {
49
+ ok: false
50
+ error: string
51
+ } {
52
+ if (!payload || typeof payload !== "object") {
53
+ return { ok: false, error: "Message must be a JSON object." }
54
+ }
55
+
56
+ const parsed = SubscriptionMessageSchema.safeParse(payload)
57
+ if (!parsed.success) {
58
+ return {
59
+ ok: false,
60
+ error: parsed.error.issues[0]?.message ?? "Invalid websocket message.",
61
+ }
62
+ }
63
+
64
+ return { ok: true, data: parsed.data }
65
+ }
66
+
67
+ async function resolveLatestCursor(server: SixbServer): Promise<string | undefined> {
68
+ return server.getSixb().events.latestCursor()
69
+ }
70
+
71
+ function createDefaultState(): EventSubscriptionState {
72
+ return {
73
+ topics: undefined,
74
+ types: undefined,
75
+ objectTypeId: undefined,
76
+ primaryId: undefined,
77
+ actionId: undefined,
78
+ runId: undefined,
79
+ afterCursor: undefined,
80
+ limit: 200,
81
+ polling: false,
82
+ timer: null,
83
+ initialized: Promise.resolve(),
84
+ initializationFailureHandled: false,
85
+ }
86
+ }
87
+
88
+ export function registerEventStreamRoutes(app: Elysia, server: SixbServer) {
89
+ const states = new WeakMap<object, EventSubscriptionState>()
90
+
91
+ const awaitInitialization = async (
92
+ ws: { close: () => void; send: (message: string) => void },
93
+ state: EventSubscriptionState
94
+ ): Promise<boolean> => {
95
+ try {
96
+ await state.initialized
97
+ return true
98
+ } catch (error) {
99
+ if (state.initializationFailureHandled) return false
100
+ state.initializationFailureHandled = true
101
+ const message = error instanceof Error ? error.message : String(error)
102
+ safeSend(ws, {
103
+ type: "error",
104
+ message: `[SixbServer] Failed to initialize event websocket: ${message}`,
105
+ })
106
+ ws.close()
107
+ return false
108
+ }
109
+ }
110
+
111
+ const stopPolling = (ws: object) => {
112
+ const state = states.get(wsStateKey(ws))
113
+ if (!state) {
114
+ return
115
+ }
116
+
117
+ if (state.timer) {
118
+ clearInterval(state.timer)
119
+ state.timer = null
120
+ }
121
+ }
122
+
123
+ const startPolling = (ws: { send: (message: string) => void }) => {
124
+ const state = states.get(wsStateKey(ws))
125
+ if (!state || state.timer) {
126
+ return
127
+ }
128
+
129
+ const authz = wsAuthz(ws)
130
+
131
+ const tick = async () => {
132
+ if (state.polling) {
133
+ return
134
+ }
135
+
136
+ state.polling = true
137
+ try {
138
+ const p = server.getSixb()
139
+ const events = await p.events.read({
140
+ afterCursor: state.afterCursor,
141
+ limit: state.limit,
142
+ topics: state.topics,
143
+ types: state.types,
144
+ })
145
+
146
+ // Each event payload may carry object data, so visibility is derived
147
+ // per-event from the principal's grants (see `canViewEvent`), and the
148
+ // optional scope narrows the stream further. The cursor advances over
149
+ // every event read, not just the ones sent.
150
+ for (const event of events) {
151
+ if (!eventMatchesScope(event, state)) {
152
+ continue
153
+ }
154
+ if (canViewEvent(authz, event)) {
155
+ safeSend(ws, { type: "event", event })
156
+ }
157
+ }
158
+
159
+ const last = events[events.length - 1]
160
+ if (last) {
161
+ state.afterCursor = last.cursor
162
+ }
163
+ } catch (error) {
164
+ const message = error instanceof Error ? error.message : String(error)
165
+ safeSend(ws, { type: "error", message })
166
+ } finally {
167
+ state.polling = false
168
+ }
169
+ }
170
+
171
+ state.timer = setInterval(() => {
172
+ void tick()
173
+ }, 500)
174
+
175
+ void tick()
176
+ }
177
+
178
+ return app.ws("/ws/events", {
179
+ async open(ws) {
180
+ // Any authenticated principal may connect; events are filtered per-event
181
+ // by grants as they stream (see the poll loop in `startPolling`).
182
+ const state = createDefaultState()
183
+ states.set(wsStateKey(ws), state)
184
+ state.initialized = resolveLatestCursor(server).then((cursor) => {
185
+ state.afterCursor = cursor
186
+ })
187
+ if (!(await awaitInitialization(ws, state))) return
188
+ safeSend(ws, { type: "connected", channel: "events" })
189
+ },
190
+
191
+ async message(ws, message) {
192
+ const decoded = await decodeWsMessage(message)
193
+ const parsed = parseSubscriptionMessage(decoded)
194
+ if (!parsed.ok) {
195
+ safeSend(ws, { type: "error", message: parsed.error })
196
+ return
197
+ }
198
+
199
+ const state = states.get(wsStateKey(ws))
200
+ if (!state) {
201
+ safeSend(ws, { type: "error", message: "Subscription state not found." })
202
+ return
203
+ }
204
+
205
+ // Older clients may subscribe immediately on websocket open. Wait for the
206
+ // initial cursor instead of allowing that message to race connection setup.
207
+ if (!(await awaitInitialization(ws, state))) return
208
+
209
+ if (parsed.data.type === "unsubscribe") {
210
+ stopPolling(ws)
211
+ state.topics = undefined
212
+ state.types = undefined
213
+ state.objectTypeId = undefined
214
+ state.primaryId = undefined
215
+ state.actionId = undefined
216
+ state.runId = undefined
217
+ state.afterCursor = await resolveLatestCursor(server)
218
+ safeSend(ws, { type: "unsubscribed" })
219
+ return
220
+ }
221
+
222
+ state.topics = parsed.data.topic ? [parsed.data.topic] : undefined
223
+ state.types = parsed.data.types
224
+ state.objectTypeId = parsed.data.objectTypeId
225
+ state.primaryId = parsed.data.primaryId
226
+ state.actionId = parsed.data.actionId
227
+ state.runId = parsed.data.runId
228
+ state.limit = parsed.data.limit ?? state.limit
229
+ state.afterCursor = parsed.data.afterCursor ?? state.afterCursor
230
+
231
+ startPolling(ws)
232
+ safeSend(ws, {
233
+ type: "subscribed",
234
+ topic: state.topics?.[0] ?? null,
235
+ types: state.types ?? null,
236
+ afterCursor: state.afterCursor ?? null,
237
+ })
238
+ },
239
+
240
+ close(ws) {
241
+ stopPolling(ws)
242
+ states.delete(wsStateKey(ws))
243
+ },
244
+ })
245
+ }
246
+
247
+ /**
248
+ * Narrow an event to an optional subscription scope. Scope keys are resolved by core's
249
+ * `scopeKeysForEvent` (the same extraction the client predicate uses), so events
250
+ * without those keys (e.g. workflows) never match a scoped subscription.
251
+ */
252
+ function eventMatchesScope(event: DomainEvent, filter: EventSubscriptionState): boolean {
253
+ const { objectTypeId, primaryId, actionId, runId } = filter
254
+ if (
255
+ objectTypeId === undefined &&
256
+ primaryId === undefined &&
257
+ actionId === undefined &&
258
+ runId === undefined
259
+ ) {
260
+ return true
261
+ }
262
+
263
+ const scope = scopeKeysForEvent(event)
264
+ if (objectTypeId !== undefined && scope.objectTypeId !== objectTypeId) {
265
+ return false
266
+ }
267
+ if (primaryId !== undefined && scope.primaryId !== primaryId) {
268
+ return false
269
+ }
270
+ if (actionId !== undefined && scope.actionId !== actionId) {
271
+ return false
272
+ }
273
+ if (runId !== undefined && scope.runId !== runId) {
274
+ return false
275
+ }
276
+
277
+ return true
278
+ }
@@ -0,0 +1,12 @@
1
+ import type { Elysia } from "elysia"
2
+ import type { SixbServer } from "../../server"
3
+ import { registerAgentStreamRoutes } from "./agents"
4
+ import { registerEventStreamRoutes } from "./events"
5
+ import { registerLogStreamRoutes } from "./logs"
6
+
7
+ export function registerWebSocketRoutes(app: Elysia, server: SixbServer) {
8
+ registerEventStreamRoutes(app, server)
9
+ registerLogStreamRoutes(app, server)
10
+ registerAgentStreamRoutes(app, server)
11
+ return app
12
+ }