@sixb/server 0.1.20 → 0.1.22

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 (179) hide show
  1. package/dist/artifacts/frame.d.ts +18 -0
  2. package/dist/artifacts/frame.d.ts.map +1 -0
  3. package/dist/auth/browser-origin.d.ts +10 -1
  4. package/dist/auth/browser-origin.d.ts.map +1 -1
  5. package/dist/auth/experience.d.ts +1 -0
  6. package/dist/auth/experience.d.ts.map +1 -1
  7. package/dist/auth/public-routes.d.ts.map +1 -1
  8. package/dist/auth/responses.d.ts +1 -1
  9. package/dist/auth/responses.d.ts.map +1 -1
  10. package/dist/auth/scope.d.ts +19 -3
  11. package/dist/auth/scope.d.ts.map +1 -1
  12. package/dist/files/content.d.ts +2 -3
  13. package/dist/files/content.d.ts.map +1 -1
  14. package/dist/index.js +10636 -7071
  15. package/dist/index.js.map +56 -38
  16. package/dist/models/display.d.ts +27 -0
  17. package/dist/models/display.d.ts.map +1 -1
  18. package/dist/openapi/components.d.ts +14 -0
  19. package/dist/openapi/components.d.ts.map +1 -0
  20. package/dist/openapi/tags.d.ts +22 -2
  21. package/dist/openapi/tags.d.ts.map +1 -1
  22. package/dist/registerRoutes.d.ts +3 -0
  23. package/dist/registerRoutes.d.ts.map +1 -1
  24. package/dist/routes/actions.d.ts +5 -5
  25. package/dist/routes/activity.d.ts +35 -0
  26. package/dist/routes/activity.d.ts.map +1 -0
  27. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  28. package/dist/routes/agent-approval-gate.d.ts +27 -0
  29. package/dist/routes/agent-approval-gate.d.ts.map +1 -0
  30. package/dist/routes/agent-approvals.d.ts +599 -0
  31. package/dist/routes/agent-approvals.d.ts.map +1 -0
  32. package/dist/routes/agent-children.d.ts +318 -0
  33. package/dist/routes/agent-children.d.ts.map +1 -0
  34. package/dist/routes/agent-memory.d.ts +267 -0
  35. package/dist/routes/agent-memory.d.ts.map +1 -0
  36. package/dist/routes/agents.d.ts +1008 -98
  37. package/dist/routes/agents.d.ts.map +1 -1
  38. package/dist/routes/ai-accounting.d.ts.map +1 -1
  39. package/dist/routes/artifact-frames.d.ts +98 -0
  40. package/dist/routes/artifact-frames.d.ts.map +1 -0
  41. package/dist/routes/artifacts.d.ts +1508 -0
  42. package/dist/routes/artifacts.d.ts.map +1 -0
  43. package/dist/routes/auth.d.ts +117 -11
  44. package/dist/routes/auth.d.ts.map +1 -1
  45. package/dist/routes/connector-connection-runs.d.ts +84 -84
  46. package/dist/routes/connector-connections.d.ts +2 -2
  47. package/dist/routes/connectors.d.ts +2 -2
  48. package/dist/routes/datasets.d.ts +27 -27
  49. package/dist/routes/events.d.ts +5 -5
  50. package/dist/routes/files.d.ts +14 -14
  51. package/dist/routes/files.d.ts.map +1 -1
  52. package/dist/routes/links.d.ts +2 -2
  53. package/dist/routes/logs.d.ts +5 -5
  54. package/dist/routes/model-calls.d.ts +155 -0
  55. package/dist/routes/model-calls.d.ts.map +1 -0
  56. package/dist/routes/model-generations.d.ts +400 -0
  57. package/dist/routes/model-generations.d.ts.map +1 -0
  58. package/dist/routes/models.d.ts +434 -1
  59. package/dist/routes/models.d.ts.map +1 -1
  60. package/dist/routes/objects.d.ts +71 -40
  61. package/dist/routes/objects.d.ts.map +1 -1
  62. package/dist/routes/observed-agent-threads.d.ts +682 -0
  63. package/dist/routes/observed-agent-threads.d.ts.map +1 -0
  64. package/dist/routes/ontology.d.ts +66 -62
  65. package/dist/routes/ontology.d.ts.map +1 -1
  66. package/dist/routes/pipelines.d.ts +53 -53
  67. package/dist/routes/projections.d.ts +63 -63
  68. package/dist/routes/rules.d.ts +2 -2
  69. package/dist/routes/share-grants.d.ts +4 -4
  70. package/dist/routes/syncs.d.ts +18 -18
  71. package/dist/routes/users.d.ts +117 -0
  72. package/dist/routes/users.d.ts.map +1 -0
  73. package/dist/routes/webhook-runs.d.ts +1 -1
  74. package/dist/routes/workflows.d.ts +142 -76
  75. package/dist/routes/workflows.d.ts.map +1 -1
  76. package/dist/routes/ws/agents.d.ts +7 -2
  77. package/dist/routes/ws/agents.d.ts.map +1 -1
  78. package/dist/routes/ws/events.d.ts +6 -6
  79. package/dist/routes/ws/events.d.ts.map +1 -1
  80. package/dist/routes/ws/logs.d.ts +14 -14
  81. package/dist/routes/ws/subscription-hub.d.ts +8 -3
  82. package/dist/routes/ws/subscription-hub.d.ts.map +1 -1
  83. package/dist/schemas/actions.d.ts +15 -15
  84. package/dist/schemas/activity.d.ts +1298 -0
  85. package/dist/schemas/activity.d.ts.map +1 -0
  86. package/dist/schemas/agent-approvals.d.ts +1091 -0
  87. package/dist/schemas/agent-approvals.d.ts.map +1 -0
  88. package/dist/schemas/agent-memory.d.ts +250 -0
  89. package/dist/schemas/agent-memory.d.ts.map +1 -0
  90. package/dist/schemas/agents.d.ts +5485 -460
  91. package/dist/schemas/agents.d.ts.map +1 -1
  92. package/dist/schemas/ai-accounting.d.ts +1315 -436
  93. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  94. package/dist/schemas/ai-limits.d.ts +36 -36
  95. package/dist/schemas/ai-usage.d.ts +12 -0
  96. package/dist/schemas/ai-usage.d.ts.map +1 -1
  97. package/dist/schemas/artifacts.d.ts +1857 -0
  98. package/dist/schemas/artifacts.d.ts.map +1 -0
  99. package/dist/schemas/auth.d.ts +125 -52
  100. package/dist/schemas/auth.d.ts.map +1 -1
  101. package/dist/schemas/connectors.d.ts +42 -42
  102. package/dist/schemas/datasets.d.ts +108 -108
  103. package/dist/schemas/event-payloads.d.ts +6 -6
  104. package/dist/schemas/events.d.ts +32 -32
  105. package/dist/schemas/events.d.ts.map +1 -1
  106. package/dist/schemas/files.d.ts +24 -24
  107. package/dist/schemas/links.d.ts +2 -2
  108. package/dist/schemas/logs.d.ts +32 -32
  109. package/dist/schemas/models.d.ts +8889 -10
  110. package/dist/schemas/models.d.ts.map +1 -1
  111. package/dist/schemas/objects.d.ts +48 -12
  112. package/dist/schemas/objects.d.ts.map +1 -1
  113. package/dist/schemas/ontology.d.ts +127 -104
  114. package/dist/schemas/ontology.d.ts.map +1 -1
  115. package/dist/schemas/pipelines.d.ts +166 -166
  116. package/dist/schemas/projections.d.ts +346 -346
  117. package/dist/schemas/rules.d.ts +4 -4
  118. package/dist/schemas/share-grants.d.ts +14 -14
  119. package/dist/schemas/syncs.d.ts +40 -40
  120. package/dist/schemas/users.d.ts +72 -0
  121. package/dist/schemas/users.d.ts.map +1 -0
  122. package/dist/schemas/webhook-runs.d.ts +6 -6
  123. package/dist/schemas/workflows.d.ts +769 -254
  124. package/dist/schemas/workflows.d.ts.map +1 -1
  125. package/dist/server.d.ts +1 -0
  126. package/dist/server.d.ts.map +1 -1
  127. package/dist/utils/http.d.ts.map +1 -1
  128. package/package.json +7 -7
  129. package/src/artifacts/frame.ts +51 -0
  130. package/src/auth/browser-origin.ts +20 -5
  131. package/src/auth/experience.ts +1 -1
  132. package/src/auth/guard.ts +2 -2
  133. package/src/auth/public-routes.ts +16 -0
  134. package/src/auth/responses.ts +7 -6
  135. package/src/auth/scope.ts +32 -3
  136. package/src/files/content.ts +9 -13
  137. package/src/models/display.ts +61 -16
  138. package/src/openapi/components.ts +54 -0
  139. package/src/openapi/tags.ts +20 -0
  140. package/src/registerRoutes.ts +23 -0
  141. package/src/routes/activity.ts +327 -0
  142. package/src/routes/agent-api-gateway.ts +115 -91
  143. package/src/routes/agent-approval-gate.ts +213 -0
  144. package/src/routes/agent-approvals.ts +299 -0
  145. package/src/routes/agent-children.ts +209 -0
  146. package/src/routes/agent-memory.ts +210 -0
  147. package/src/routes/agents.ts +364 -143
  148. package/src/routes/ai-accounting.ts +4 -0
  149. package/src/routes/artifact-frames.ts +144 -0
  150. package/src/routes/artifacts.ts +717 -0
  151. package/src/routes/auth.ts +306 -13
  152. package/src/routes/file-downloads.ts +1 -3
  153. package/src/routes/files.ts +6 -7
  154. package/src/routes/model-calls.ts +120 -0
  155. package/src/routes/model-generations.ts +245 -0
  156. package/src/routes/models.ts +116 -9
  157. package/src/routes/objects.ts +55 -61
  158. package/src/routes/observed-agent-threads.ts +253 -0
  159. package/src/routes/ontology.ts +1 -0
  160. package/src/routes/users.ts +73 -0
  161. package/src/routes/workflows.ts +6 -9
  162. package/src/routes/ws/agents.ts +10 -5
  163. package/src/routes/ws/events.ts +3 -2
  164. package/src/routes/ws/subscription-hub.ts +53 -20
  165. package/src/schemas/activity.ts +287 -0
  166. package/src/schemas/agent-approvals.ts +129 -0
  167. package/src/schemas/agent-memory.ts +96 -0
  168. package/src/schemas/agents.ts +240 -2
  169. package/src/schemas/ai-accounting.ts +40 -4
  170. package/src/schemas/ai-usage.ts +10 -0
  171. package/src/schemas/artifacts.ts +246 -0
  172. package/src/schemas/auth.ts +25 -0
  173. package/src/schemas/models.ts +197 -1
  174. package/src/schemas/objects.ts +181 -0
  175. package/src/schemas/ontology.ts +1 -0
  176. package/src/schemas/users.ts +24 -0
  177. package/src/schemas/workflows.ts +2 -0
  178. package/src/server.ts +34 -19
  179. package/src/utils/http.ts +2 -0
@@ -0,0 +1,253 @@
1
+ import type { AgentThreadView, SixbHostView } from "@sixb/core"
2
+ import type { Elysia } from "elysia"
3
+ import { requireRequestSixb } from "../auth/scope"
4
+ import { fileContentGetResponses, handleFileContentQueryValidationError } from "../files/content"
5
+ import { OPENAPI_TAGS } from "../openapi/tags"
6
+ import {
7
+ AgentChildListQuerySchema,
8
+ AgentChildListResponseSchema,
9
+ AgentMessageFileContentParamsSchema,
10
+ AgentMessageListResponseSchema,
11
+ AgentMessagesQuerySchema,
12
+ AgentRunListQuerySchema,
13
+ AgentRunListResponseSchema,
14
+ AgentThreadParamsSchema,
15
+ AgentThreadSchema,
16
+ } from "../schemas/agents"
17
+ import { ErrorResponseSchema } from "../schemas/common"
18
+ import { FileContentQuerySchema } from "../schemas/files"
19
+ import { parseOptionalInt, unconfiguredStorageResponse } from "../utils/http"
20
+ import {
21
+ AgentChildFileContentQuerySchema,
22
+ agentChildFileContentResponse,
23
+ serializeAgentChild,
24
+ } from "./agent-children"
25
+ import {
26
+ agentMessageFileContentResponse,
27
+ handleAgentRouteError,
28
+ readThreadMessages,
29
+ serializeAgentRun,
30
+ serializeThread,
31
+ } from "./agents"
32
+
33
+ const errors = {
34
+ 400: ErrorResponseSchema,
35
+ 403: ErrorResponseSchema,
36
+ 404: ErrorResponseSchema,
37
+ 501: ErrorResponseSchema,
38
+ }
39
+
40
+ const OBSERVED =
41
+ "Read-only, whoever owns the thread. Takes can.observe(agent.threads); the response matches the owner's route."
42
+
43
+ /**
44
+ * Any user's conversation, read-only, with `can.observe(agent.threads)`. These routes are apart
45
+ * from `/api/agent-threads`, which stay the owner's: nothing here writes, and a reader without the
46
+ * grant gets 403 rather than the owner routes' 404.
47
+ */
48
+ export function registerObservedAgentThreadRoutes(app: Elysia, host: SixbHostView) {
49
+ return app
50
+ .get(
51
+ "/api/observed-agent-threads/:threadId",
52
+ async (context) => {
53
+ try {
54
+ const thread = await readObservedThread(context)
55
+ if (!host.storage.agents) {
56
+ return unconfiguredStorageResponse(context.set, "Agent storage")
57
+ }
58
+ if (!thread) {
59
+ return threadNotFound(context.set)
60
+ }
61
+
62
+ return await serializeThread(host, thread)
63
+ } catch (error) {
64
+ return handleAgentRouteError(error, context.set)
65
+ }
66
+ },
67
+ {
68
+ params: AgentThreadParamsSchema,
69
+ response: { 200: AgentThreadSchema, ...errors },
70
+ detail: {
71
+ summary: "Read another user's agent thread",
72
+ description: OBSERVED,
73
+ tags: [OPENAPI_TAGS.agentThreads.name],
74
+ operationId: "getObservedAgentThread",
75
+ },
76
+ }
77
+ )
78
+ .get(
79
+ "/api/observed-agent-threads/:threadId/messages",
80
+ async (context) => {
81
+ try {
82
+ const thread = await readObservedThread(context)
83
+ const storage = host.storage.agents
84
+ if (!storage) {
85
+ return unconfiguredStorageResponse(context.set, "Agent storage")
86
+ }
87
+ if (!thread) {
88
+ return threadNotFound(context.set)
89
+ }
90
+
91
+ const query = AgentMessagesQuerySchema.parse(context.query)
92
+ return AgentMessageListResponseSchema.parse(
93
+ await readThreadMessages(host, storage, thread, query)
94
+ )
95
+ } catch (error) {
96
+ return handleAgentRouteError(error, context.set)
97
+ }
98
+ },
99
+ {
100
+ params: AgentThreadParamsSchema,
101
+ query: AgentMessagesQuerySchema,
102
+ response: { 200: AgentMessageListResponseSchema, ...errors },
103
+ detail: {
104
+ summary: "List another user's agent thread messages",
105
+ description: `${OBSERVED} \`authors\` names who wrote the page's messages.`,
106
+ tags: [OPENAPI_TAGS.agentThreads.name],
107
+ operationId: "listObservedAgentThreadMessages",
108
+ },
109
+ }
110
+ )
111
+ .get(
112
+ "/api/observed-agent-threads/:threadId/messages/:messageId/files/content",
113
+ async (context) => {
114
+ try {
115
+ const thread = await readObservedThread(context)
116
+ return await agentMessageFileContentResponse(host, context, {
117
+ readThread: async () => thread,
118
+ })
119
+ } catch (error) {
120
+ return handleAgentRouteError(error, context.set)
121
+ }
122
+ },
123
+ {
124
+ params: AgentMessageFileContentParamsSchema,
125
+ query: FileContentQuerySchema,
126
+ detail: {
127
+ summary: "Get a file of another user's agent message",
128
+ description: OBSERVED,
129
+ tags: [OPENAPI_TAGS.agentThreads.name],
130
+ operationId: "getObservedAgentMessageFileContent",
131
+ responses: fileContentGetResponses({ optionalStorage: true }),
132
+ },
133
+ }
134
+ )
135
+ .get(
136
+ "/api/observed-agent-threads/:threadId/runs",
137
+ async (context) => {
138
+ try {
139
+ const thread = await readObservedThread(context)
140
+ if (!host.storage.agents) {
141
+ return unconfiguredStorageResponse(context.set, "Agent storage")
142
+ }
143
+ if (!thread) {
144
+ return threadNotFound(context.set)
145
+ }
146
+
147
+ const query = AgentRunListQuerySchema.parse(context.query)
148
+ const result = await requireRequestSixb(context).agent.observed.listRuns(
149
+ context.params.threadId,
150
+ {
151
+ statuses: query.status ? [query.status] : undefined,
152
+ limit: parseOptionalInt(query.limit),
153
+ offset: parseOptionalInt(query.offset),
154
+ order: query.order,
155
+ }
156
+ )
157
+ if (!result) {
158
+ return threadNotFound(context.set)
159
+ }
160
+
161
+ return AgentRunListResponseSchema.parse({
162
+ runs: result.runs.map(serializeAgentRun),
163
+ hasMore: result.hasMore,
164
+ total: result.total,
165
+ })
166
+ } catch (error) {
167
+ return handleAgentRouteError(error, context.set)
168
+ }
169
+ },
170
+ {
171
+ params: AgentThreadParamsSchema,
172
+ query: AgentRunListQuerySchema,
173
+ response: { 200: AgentRunListResponseSchema, ...errors },
174
+ detail: {
175
+ summary: "List another user's agent thread runs",
176
+ description: OBSERVED,
177
+ tags: [OPENAPI_TAGS.agentRuns.name],
178
+ operationId: "listObservedAgentThreadRuns",
179
+ },
180
+ }
181
+ )
182
+ .get(
183
+ "/api/observed-agent-threads/:threadId/children",
184
+ async (context) => {
185
+ try {
186
+ const query = AgentChildListQuerySchema.parse(context.query)
187
+ const result = await requireRequestSixb(context).agent.observed.listChildren(
188
+ context.params.threadId,
189
+ query.runId === undefined ? {} : { runId: query.runId }
190
+ )
191
+ if (!host.storage.agents) {
192
+ return unconfiguredStorageResponse(context.set, "Agent storage")
193
+ }
194
+ if (!result) {
195
+ return threadNotFound(context.set)
196
+ }
197
+
198
+ return AgentChildListResponseSchema.parse({
199
+ children: result.children.map(serializeAgentChild),
200
+ })
201
+ } catch (error) {
202
+ return handleAgentRouteError(error, context.set)
203
+ }
204
+ },
205
+ {
206
+ params: AgentThreadParamsSchema,
207
+ query: AgentChildListQuerySchema,
208
+ response: { 200: AgentChildListResponseSchema, ...errors },
209
+ detail: {
210
+ summary: "List the sub-agents of another user's agent conversation",
211
+ description: OBSERVED,
212
+ tags: [OPENAPI_TAGS.agentThreads.name],
213
+ operationId: "listObservedAgentThreadChildren",
214
+ },
215
+ }
216
+ )
217
+ .get(
218
+ "/api/observed-agent-threads/:threadId/child-files/content",
219
+ async (context) => {
220
+ try {
221
+ return await agentChildFileContentResponse(host, context, () =>
222
+ requireRequestSixb(context).agent.observed.getChild(context.params.threadId)
223
+ )
224
+ } catch (error) {
225
+ return handleAgentRouteError(error, context.set)
226
+ }
227
+ },
228
+ {
229
+ params: AgentThreadParamsSchema,
230
+ query: AgentChildFileContentQuerySchema,
231
+ error: handleFileContentQueryValidationError,
232
+ detail: {
233
+ summary: "Get a file of another user's sub-agent",
234
+ description: OBSERVED,
235
+ tags: [OPENAPI_TAGS.agentThreads.name],
236
+ operationId: "getObservedAgentChildFileContent",
237
+ responses: fileContentGetResponses({ optionalStorage: true }),
238
+ },
239
+ }
240
+ )
241
+ }
242
+
243
+ /** The thread, read as an observer: this authorizes, so a refusal comes before anything else. */
244
+ function readObservedThread(context: {
245
+ readonly params: { readonly threadId: string }
246
+ }): Promise<AgentThreadView | null> {
247
+ return requireRequestSixb(context).agent.observed.getById(context.params.threadId)
248
+ }
249
+
250
+ function threadNotFound(set: { status?: number | string }) {
251
+ set.status = 404
252
+ return { error: "Agent thread not found" }
253
+ }
@@ -21,6 +21,7 @@ function serializeProperty(
21
21
  required: property.required,
22
22
  nullable: property.nullable,
23
23
  primary: property.primary,
24
+ unique: property.unique,
24
25
  semanticType: property.semanticType,
25
26
  schema: property.schema,
26
27
  query: property.query ? { ...property.query } : undefined,
@@ -0,0 +1,73 @@
1
+ import { type SixbHostView, userRef } from "@sixb/core"
2
+ import type { Elysia } from "elysia"
3
+ import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
4
+ import { requireRequestSixb } from "../auth/scope"
5
+ import { OPENAPI_TAGS } from "../openapi/tags"
6
+ import { UserProfileSchema } from "../schemas/auth"
7
+ import { ErrorResponseSchema } from "../schemas/common"
8
+ import { ListUsersQuerySchema, ListUsersResponseSchema, UserParamsSchema } from "../schemas/users"
9
+ import { handleRouteError } from "../utils/http"
10
+
11
+ export function registerUserRoutes(app: Elysia, _host: SixbHostView) {
12
+ return app
13
+ .get(
14
+ "/api/users",
15
+ async (context) => {
16
+ const { query, set } = context
17
+ const sixb = requireRequestSixb(context)
18
+
19
+ try {
20
+ const page = await sixb.users.list(ListUsersQuerySchema.parse(query))
21
+ return { users: [...page.users], hasMore: page.hasMore, total: page.total }
22
+ } catch (error) {
23
+ return handleRouteError(error, set)
24
+ }
25
+ },
26
+ {
27
+ query: ListUsersQuerySchema,
28
+ response: {
29
+ 200: ListUsersResponseSchema,
30
+ 400: ErrorResponseSchema,
31
+ 403: ErrorResponseSchema,
32
+ },
33
+ detail: {
34
+ summary: "List project members",
35
+ tags: [OPENAPI_TAGS.users.name],
36
+ operationId: "listUsers",
37
+ security: accessTokenSecurityRequirement("listUsers"),
38
+ },
39
+ }
40
+ )
41
+ .get(
42
+ "/api/users/:userId",
43
+ async (context) => {
44
+ const { params, set } = context
45
+ const sixb = requireRequestSixb(context)
46
+
47
+ try {
48
+ const profile = await sixb.users.get(userRef(params.userId))
49
+ if (profile) return profile
50
+
51
+ set.status = 404
52
+ return { error: `[SixbServer] User '${params.userId}' not found.` }
53
+ } catch (error) {
54
+ return handleRouteError(error, set)
55
+ }
56
+ },
57
+ {
58
+ params: UserParamsSchema,
59
+ response: {
60
+ 200: UserProfileSchema,
61
+ 400: ErrorResponseSchema,
62
+ 403: ErrorResponseSchema,
63
+ 404: ErrorResponseSchema,
64
+ },
65
+ detail: {
66
+ summary: "Get a project member",
67
+ tags: [OPENAPI_TAGS.users.name],
68
+ operationId: "getUser",
69
+ security: accessTokenSecurityRequirement("getUser"),
70
+ },
71
+ }
72
+ )
73
+ }
@@ -9,7 +9,7 @@ import {
9
9
  import { publishAgentRunCancel } from "@sixb/core/internal/agents"
10
10
  import { createSixbError, toSixbFailure } from "@sixb/core/internal/errors"
11
11
  import { assertValidFileRefs } from "@sixb/core/internal/ontology"
12
- import type { Sixb, WorkflowRunView } from "@sixb/core/internal/request-execution"
12
+ import type { WorkflowRunView } from "@sixb/core/internal/request-execution"
13
13
  import {
14
14
  snapshotWorkflowInterventionResponse,
15
15
  type WorkflowInterventionNodeDefinition,
@@ -23,7 +23,7 @@ import { AGENT_RUN_FAILURE_CODES, WORKFLOW_RUN_FAILURE_CODES } from "@sixb/core/
23
23
  import type { Elysia } from "elysia"
24
24
  import { z } from "zod"
25
25
  import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
26
- import { requestAuthState, requireRequestSixb } from "../auth/scope"
26
+ import { requestActor, requestAuthState, requireRequestSixb } from "../auth/scope"
27
27
  import {
28
28
  createContextualFileContentResponse,
29
29
  fileContentGetResponses,
@@ -177,10 +177,6 @@ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
177
177
  return value !== null && typeof value === "object" && !Array.isArray(value)
178
178
  }
179
179
 
180
- function principalForExecution(sixb: Sixb): Principal {
181
- return sixb.execution.requestedBy ?? SYSTEM_PRINCIPAL
182
- }
183
-
184
180
  function toWorkflowCancellationFailure(input: {
185
181
  readonly message: string
186
182
  readonly at: Date
@@ -741,7 +737,7 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
741
737
  projectId: host.id,
742
738
  id: intervention.id,
743
739
  response,
744
- submittedBy: serializePrincipal(principalForExecution(sixb)),
740
+ submittedBy: serializePrincipal(requestActor(sixb)),
745
741
  })
746
742
 
747
743
  const [job] = await host.queues.workflows.enqueue({
@@ -850,7 +846,7 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
850
846
  projectId: host.id,
851
847
  id: intervention.id,
852
848
  cancelledAt,
853
- cancelledBy: serializePrincipal(principalForExecution(sixb)),
849
+ cancelledBy: serializePrincipal(requestActor(sixb)),
854
850
  })
855
851
  const cancelledNode = await tx.workflowRuns.nodes.finish({
856
852
  projectId: host.id,
@@ -1156,7 +1152,7 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
1156
1152
  projectId: host.id,
1157
1153
  id: intervention.id,
1158
1154
  cancelledAt,
1159
- cancelledBy: serializePrincipal(principalForExecution(sixb)),
1155
+ cancelledBy: serializePrincipal(requestActor(sixb)),
1160
1156
  })
1161
1157
  }
1162
1158
  }
@@ -1316,6 +1312,7 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
1316
1312
  const input = {
1317
1313
  workflowId: params.workflowId,
1318
1314
  input: parsedBody.input ?? {},
1315
+ ...(parsedBody.runId === undefined ? {} : { runId: parsedBody.runId }),
1319
1316
  source: { type: "manual" } as const,
1320
1317
  }
1321
1318
  const result = await sixb.workflows.requestById(input)
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  AGENT_ACTIVITY_STREAM_ID,
3
- type AgentRunActivityEvent,
4
- isAgentRunActivityEvent,
3
+ type AgentActivityEvent,
4
+ isAgentActivityEvent,
5
5
  } from "@sixb/core/agents/streams"
6
6
  import { BrokerCursorExpiredError, type BrokerRecord } from "@sixb/core/broker"
7
7
  import {
@@ -79,6 +79,10 @@ export function parseAgentStreamMessage(payload: unknown):
79
79
  return { ok: true, data: parsed.data }
80
80
  }
81
81
 
82
+ /**
83
+ * A run's stream reaches whoever reads its thread: a turn's conversation, or a sub-agent's, which
84
+ * is read through its conversation. Either starts with the run's snapshot.
85
+ */
82
86
  export async function canAccessAgentRunStream(
83
87
  sixb: Sixb,
84
88
  runId: string
@@ -90,9 +94,10 @@ export async function canAccessAgentRunStream(
90
94
  return { ok: true }
91
95
  }
92
96
 
97
+ /** A run's or an approval's activity reaches whoever reads the turn it belongs to. */
93
98
  export async function canAccessAgentThreadActivity(
94
99
  sixb: Sixb,
95
- event: AgentRunActivityEvent
100
+ event: AgentActivityEvent
96
101
  ): Promise<boolean> {
97
102
  const run = await sixb.agent.runs.getById(event.runId)
98
103
  return run?.projectId === event.projectId && run.threadId === event.threadId
@@ -311,9 +316,9 @@ async function sendVisibleActivityRecords(
311
316
  ws: { send: (message: string) => void },
312
317
  records: readonly BrokerRecord[]
313
318
  ): Promise<void> {
314
- const events: AgentRunActivityEvent[] = []
319
+ const events: AgentActivityEvent[] = []
315
320
  for (const record of records) {
316
- if (isAgentRunActivityEvent(record.payload)) events.push(record.payload)
321
+ if (isAgentActivityEvent(record.payload)) events.push(record.payload)
317
322
  }
318
323
  const visible = await Promise.all(
319
324
  events.map((event) => canAccessAgentThreadActivity(sixb, event))
@@ -156,8 +156,9 @@ export function registerEventStreamRoutes(app: Elysia, server: SixbServer) {
156
156
  (!filter.types?.length || filter.types.includes(event.type)) &&
157
157
  eventMatchesScope(event, filter),
158
158
  // The execution facade owns per-event visibility: it withholds events the caller
159
- // cannot view and omits marked properties the caller is not cleared for.
160
- view: (event) => sixb.events.readable(event),
159
+ // cannot view and omits marked properties the caller is not cleared for, as markings
160
+ // are when each batch is sent.
161
+ view: (batch) => sixb.events.visible(batch),
161
162
  replay: replayFrom
162
163
  ? {
163
164
  afterCursor: replayFrom.afterCursor,
@@ -30,10 +30,13 @@ export interface HubSource<T extends HubRecord> {
30
30
  export interface HubSubscription<T extends HubRecord> {
31
31
  matches(record: T): boolean
32
32
  /**
33
- * The matching record as this socket may read it, or `undefined` to withhold it. It keeps the
34
- * record's cursor. Omit to deliver matching records unchanged.
33
+ * The matching records of one outgoing batch as this socket may read them, in order: withheld
34
+ * records are left out, the others keep their cursor. It is applied as the batch is sent, so it
35
+ * reflects what the socket may read then, and may wait for what decides it. A batch it fails on
36
+ * is never sent unviewed: the stream closes there, so the client resumes from the last cursor it
37
+ * received. Omit to deliver matching records unchanged.
35
38
  */
36
- view?(record: T): T | undefined
39
+ view?(records: readonly T[]): readonly T[] | Promise<readonly T[]>
37
40
  /** Replays retained records after `afterCursor` (or from the oldest) before live ones. */
38
41
  readonly replay?: {
39
42
  readonly afterCursor: string | undefined
@@ -56,6 +59,8 @@ interface ClientState<T extends HubRecord> {
56
59
  queuedBytes: number
57
60
  pendingBytes: number
58
61
  flushTimer: ReturnType<typeof setTimeout> | null
62
+ /** A batch is waiting for its view: the next one is sent after it, never before. */
63
+ sending: boolean
59
64
  readonly queueProgressWaiters: Set<() => void>
60
65
  catchingUp: boolean
61
66
  closed: boolean
@@ -108,6 +113,7 @@ export class SubscriptionHub<T extends HubRecord> {
108
113
  queuedBytes: 0,
109
114
  pendingBytes: 0,
110
115
  flushTimer: null,
116
+ sending: false,
111
117
  queueProgressWaiters: new Set(),
112
118
  catchingUp: subscription.replay !== undefined,
113
119
  closed: false,
@@ -179,10 +185,9 @@ export class SubscriptionHub<T extends HubRecord> {
179
185
  private deliverLive(records: readonly T[]): void {
180
186
  for (const state of this.clients.values()) {
181
187
  for (const record of records) {
182
- const visible = visibleRecord(state.subscription, record)
183
- if (!visible) continue
184
- if (state.catchingUp) this.enqueuePendingLive(state, visible)
185
- else this.enqueue(state, visible)
188
+ if (!state.subscription.matches(record)) continue
189
+ if (state.catchingUp) this.enqueuePendingLive(state, record)
190
+ else this.enqueue(state, record)
186
191
  }
187
192
  }
188
193
  }
@@ -203,9 +208,8 @@ export class SubscriptionHub<T extends HubRecord> {
203
208
  if (state.pendingCursors.has(record.cursor)) {
204
209
  state.replayedPendingCursors.add(record.cursor)
205
210
  }
206
- const visible = visibleRecord(state.subscription, record)
207
- if (!visible) continue
208
- if (!(await this.enqueueReplay(state, visible))) return
211
+ if (!state.subscription.matches(record)) continue
212
+ if (!(await this.enqueueReplay(state, record))) return
209
213
  }
210
214
  if (state.closed) return
211
215
  afterCursor = page.cursor ?? afterCursor
@@ -311,7 +315,7 @@ export class SubscriptionHub<T extends HubRecord> {
311
315
  }
312
316
 
313
317
  private flush(state: ClientState<T>): void {
314
- if (state.closed || state.queue.length === 0) return
318
+ if (state.closed || state.sending || state.queue.length === 0) return
315
319
  if (socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
316
320
  this.scheduleFlush(state)
317
321
  return
@@ -323,8 +327,45 @@ export class SubscriptionHub<T extends HubRecord> {
323
327
  state.queuedBytes -= encodedBytes(record)
324
328
  }
325
329
  this.notifyQueueProgress(state)
330
+
331
+ const view = state.subscription.view
332
+ if (!view) {
333
+ this.sendFrames(state, records)
334
+ if (state.queue.length > 0) this.scheduleFlush(state)
335
+ return
336
+ }
337
+
338
+ state.sending = true
339
+ void this.sendViewed(state, records, view).finally(() => {
340
+ state.sending = false
341
+ if (state.queue.length > 0) this.scheduleFlush(state)
342
+ })
343
+ }
344
+
345
+ private async sendViewed(
346
+ state: ClientState<T>,
347
+ records: readonly T[],
348
+ view: NonNullable<HubSubscription<T>["view"]>
349
+ ): Promise<void> {
350
+ let visible: readonly T[]
351
+ try {
352
+ visible = await view(records)
353
+ } catch (error) {
354
+ // Fail closed, and close: a client resumes after the last cursor it received, so delivering
355
+ // later batches would skip this one for good. Reconnecting reads it again.
356
+ const message = error instanceof Error ? error.message : String(error)
357
+ console.warn(
358
+ `[SixbServer] Closed a stream subscription at cursor '${records[0]?.cursor}': ${records.length} record(s) could not be viewed: ${message}`
359
+ )
360
+ this.fail(state, "Stream records could not be viewed; reconnect from the last cursor.", 1011)
361
+ return
362
+ }
363
+
364
+ if (visible.length > 0) this.sendFrames(state, visible)
365
+ }
366
+
367
+ private sendFrames(state: ClientState<T>, records: readonly T[]): void {
326
368
  for (const frame of this.source.frames(records)) this.send(state, frame)
327
- if (state.queue.length > 0) this.scheduleFlush(state)
328
369
  }
329
370
 
330
371
  private waitForQueueProgress(state: ClientState<T>): Promise<void> {
@@ -367,14 +408,6 @@ export class SubscriptionHub<T extends HubRecord> {
367
408
  }
368
409
  }
369
410
 
370
- function visibleRecord<T extends HubRecord>(
371
- subscription: HubSubscription<T>,
372
- record: T
373
- ): T | undefined {
374
- if (!subscription.matches(record)) return undefined
375
- return subscription.view ? subscription.view(record) : record
376
- }
377
-
378
411
  function hasQueueCapacity(state: ClientState<HubRecord>, bytes: number): boolean {
379
412
  return (
380
413
  state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS &&