@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,327 @@
1
+ import {
2
+ type ActivityConnection,
3
+ type ActivityTimelineEntry,
4
+ type ActivityVisitTimeline,
5
+ type ActivityVisitView,
6
+ AuthorizationError,
7
+ type SixbHostView,
8
+ } from "@sixb/core"
9
+ import { getActivityCaptureRuntime } from "@sixb/core/internal/runtime"
10
+ import type { Elysia } from "elysia"
11
+ import { accessTokenSecurityRequirement, credentialTransport } from "../auth/access-token-boundary"
12
+ import { requestCaller, requireRequestSixb } from "../auth/scope"
13
+ import {
14
+ SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
15
+ SIXB_SESSION_SECURITY_REQUIREMENT,
16
+ SIXB_SHARED_MUTATION_SECURITY_REQUIREMENT,
17
+ SIXB_SHARED_READ_SECURITY_REQUIREMENT,
18
+ } from "../openapi/security"
19
+ import { OPENAPI_TAGS } from "../openapi/tags"
20
+ import {
21
+ ActivityCalendarQuerySchema,
22
+ ActivityCalendarSchema,
23
+ ActivityCaptureOptionsSchema,
24
+ ActivityCaptureResultSchema,
25
+ ActivityConnectionsPageSchema,
26
+ ActivityConnectionsQuerySchema,
27
+ ActivityPageQuerySchema,
28
+ ActivityPeriodQuerySchema,
29
+ ActivitySummarySchema,
30
+ ActivityUsersPageSchema,
31
+ ActivityVisitParamsSchema,
32
+ ActivityVisitsPageSchema,
33
+ ActivityVisitTimelineSchema,
34
+ CaptureActivityBodySchema,
35
+ } from "../schemas/activity"
36
+ import { ErrorResponseSchema } from "../schemas/common"
37
+ import { handleRouteError } from "../utils/http"
38
+
39
+ const errors = { 400: ErrorResponseSchema, 403: ErrorResponseSchema }
40
+
41
+ /**
42
+ * Recording and reading take different authority: a browser session records only its own visits,
43
+ * and reading needs `can.observe(project.activity)`.
44
+ */
45
+ export function registerActivityRoutes(app: Elysia, _host: SixbHostView) {
46
+ app.get(
47
+ "/api/activity/capture-config",
48
+ (context) => {
49
+ try {
50
+ assertBrowserCapture(context)
51
+ return getActivityCaptureRuntime(requireRequestSixb(context)).captureOptions()
52
+ } catch (error) {
53
+ return handleRouteError(error, context.set)
54
+ }
55
+ },
56
+ {
57
+ response: { 200: ActivityCaptureOptionsSchema, ...errors },
58
+ detail: {
59
+ summary: "Read whether this browser session records activity",
60
+ description: "A browser or shared-link session only; a native client's session gets 403.",
61
+ tags: [OPENAPI_TAGS.activity.name],
62
+ operationId: "getActivityCaptureConfig",
63
+ security: [...SIXB_SESSION_SECURITY_REQUIREMENT, SIXB_SHARED_READ_SECURITY_REQUIREMENT],
64
+ },
65
+ }
66
+ )
67
+
68
+ app.post(
69
+ "/api/activity/events",
70
+ async (context) => {
71
+ try {
72
+ assertBrowserCapture(context)
73
+ const capture = getActivityCaptureRuntime(requireRequestSixb(context))
74
+ const result = await capture.capture(context.body.events)
75
+
76
+ if (result.status === "throttled") {
77
+ context.set.status = 429
78
+ context.set.headers["retry-after"] = "60"
79
+ }
80
+ return result
81
+ } catch (error) {
82
+ return handleRouteError(error, context.set)
83
+ }
84
+ },
85
+ {
86
+ body: CaptureActivityBodySchema,
87
+ response: { 200: ActivityCaptureResultSchema, 429: ActivityCaptureResultSchema, ...errors },
88
+ detail: {
89
+ summary: "Record page views, activity and interactions for this browser session",
90
+ description:
91
+ "A browser or shared-link session only; a native client's session gets 403. The visit belongs to the calling session.",
92
+ tags: [OPENAPI_TAGS.activity.name],
93
+ operationId: "captureActivity",
94
+ security: [
95
+ ...SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
96
+ SIXB_SHARED_MUTATION_SECURITY_REQUIREMENT,
97
+ ],
98
+ },
99
+ }
100
+ )
101
+
102
+ app.get(
103
+ "/api/activity/visits",
104
+ async (context) => {
105
+ try {
106
+ const page = await requireRequestSixb(context).activity.list(pageQuery(context.query))
107
+ return { visits: page.visits.map(serializeVisit), hasMore: page.hasMore }
108
+ } catch (error) {
109
+ return handleRouteError(error, context.set)
110
+ }
111
+ },
112
+ {
113
+ query: ActivityPageQuerySchema,
114
+ response: { 200: ActivityVisitsPageSchema, ...errors },
115
+ detail: {
116
+ summary: "List the visits active in a period",
117
+ tags: [OPENAPI_TAGS.activity.name],
118
+ operationId: "listActivityVisits",
119
+ security: accessTokenSecurityRequirement("listActivityVisits"),
120
+ },
121
+ }
122
+ )
123
+
124
+ app.get(
125
+ "/api/activity/users",
126
+ async (context) => {
127
+ try {
128
+ const page = await requireRequestSixb(context).activity.users(pageQuery(context.query))
129
+ return {
130
+ users: page.users.map((user) => ({ ...user, lastSeenAt: user.lastSeenAt.toISOString() })),
131
+ hasMore: page.hasMore,
132
+ }
133
+ } catch (error) {
134
+ return handleRouteError(error, context.set)
135
+ }
136
+ },
137
+ {
138
+ query: ActivityPageQuerySchema,
139
+ response: { 200: ActivityUsersPageSchema, ...errors },
140
+ detail: {
141
+ summary: "List the signed-in users active in a period",
142
+ tags: [OPENAPI_TAGS.activity.name],
143
+ operationId: "listActivityUsers",
144
+ security: accessTokenSecurityRequirement("listActivityUsers"),
145
+ },
146
+ }
147
+ )
148
+
149
+ app.get(
150
+ "/api/activity/summary",
151
+ async (context) => {
152
+ try {
153
+ return await requireRequestSixb(context).activity.summarize({
154
+ from: new Date(context.query.from),
155
+ to: new Date(context.query.to),
156
+ userId: context.query.userId,
157
+ })
158
+ } catch (error) {
159
+ return handleRouteError(error, context.set)
160
+ }
161
+ },
162
+ {
163
+ query: ActivityPeriodQuerySchema,
164
+ response: { 200: ActivitySummarySchema, ...errors },
165
+ detail: {
166
+ summary: "Count the users, visits and page views of a period",
167
+ tags: [OPENAPI_TAGS.activity.name],
168
+ operationId: "getActivitySummary",
169
+ security: accessTokenSecurityRequirement("getActivitySummary"),
170
+ },
171
+ }
172
+ )
173
+
174
+ app.get(
175
+ "/api/activity/calendar",
176
+ async (context) => {
177
+ try {
178
+ const calendar = await requireRequestSixb(context).activity.calendar(context.query)
179
+ return { ...calendar, days: [...calendar.days] }
180
+ } catch (error) {
181
+ return handleRouteError(error, context.set)
182
+ }
183
+ },
184
+ {
185
+ query: ActivityCalendarQuerySchema,
186
+ response: { 200: ActivityCalendarSchema, ...errors },
187
+ detail: {
188
+ summary: "Read a user's active days in a UTC year",
189
+ tags: [OPENAPI_TAGS.activity.name],
190
+ operationId: "getActivityCalendar",
191
+ security: accessTokenSecurityRequirement("getActivityCalendar"),
192
+ },
193
+ }
194
+ )
195
+
196
+ app.get(
197
+ "/api/activity/visits/:visitId/timeline",
198
+ async (context) => {
199
+ try {
200
+ const timeline = await requireRequestSixb(context).activity.timeline(context.params.visitId)
201
+ if (!timeline) {
202
+ context.set.status = 404
203
+ return { error: "Activity visit not found" }
204
+ }
205
+
206
+ return serializeTimeline(timeline)
207
+ } catch (error) {
208
+ return handleRouteError(error, context.set)
209
+ }
210
+ },
211
+ {
212
+ params: ActivityVisitParamsSchema,
213
+ response: { 200: ActivityVisitTimelineSchema, 404: ErrorResponseSchema, ...errors },
214
+ detail: {
215
+ summary: "Read what one visit did",
216
+ description:
217
+ "Its page views and interactions, with the actions, workflows and Agent runs its session started, and the connection it came through. At most 200 page views and interactions, and 200 recorded executions: see truncated.",
218
+ tags: [OPENAPI_TAGS.activity.name],
219
+ operationId: "getActivityVisitTimeline",
220
+ security: accessTokenSecurityRequirement("getActivityVisitTimeline"),
221
+ },
222
+ }
223
+ )
224
+
225
+ app.get(
226
+ "/api/activity/connections",
227
+ async (context) => {
228
+ try {
229
+ const page = await requireRequestSixb(context).activity.connections(context.query)
230
+ return {
231
+ connections: page.connections.map((connection) => ({
232
+ ...serializeConnection(connection),
233
+ latestVisits: connection.latestVisits.map(serializeVisit),
234
+ })),
235
+ ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
236
+ }
237
+ } catch (error) {
238
+ return handleRouteError(error, context.set)
239
+ }
240
+ },
241
+ {
242
+ query: ActivityConnectionsQuerySchema,
243
+ response: { 200: ActivityConnectionsPageSchema, ...errors },
244
+ detail: {
245
+ summary: "List a user's sign-ins with the visits each opened",
246
+ description: "Newest first, revoked and expired sessions included.",
247
+ tags: [OPENAPI_TAGS.activity.name],
248
+ operationId: "listActivityConnections",
249
+ security: accessTokenSecurityRequirement("listActivityConnections"),
250
+ },
251
+ }
252
+ )
253
+
254
+ return app
255
+ }
256
+
257
+ function pageQuery(query: {
258
+ readonly from: string
259
+ readonly to: string
260
+ readonly userId?: string
261
+ readonly limit?: number
262
+ readonly beforeAt?: string
263
+ readonly beforeId?: string
264
+ }) {
265
+ return {
266
+ from: new Date(query.from),
267
+ to: new Date(query.to),
268
+ userId: query.userId,
269
+ limit: query.limit,
270
+ before:
271
+ query.beforeAt !== undefined && query.beforeId !== undefined
272
+ ? { at: new Date(query.beforeAt), id: query.beforeId }
273
+ : undefined,
274
+ }
275
+ }
276
+
277
+ function serializeVisit(visit: ActivityVisitView) {
278
+ return {
279
+ ...visit,
280
+ startedAt: visit.startedAt.toISOString(),
281
+ lastSeenAt: visit.lastSeenAt.toISOString(),
282
+ }
283
+ }
284
+
285
+ function serializeTimeline(timeline: ActivityVisitTimeline) {
286
+ return {
287
+ visit: serializeVisit(timeline.visit),
288
+ ...(timeline.connection ? { connection: serializeConnection(timeline.connection) } : {}),
289
+ entries: timeline.entries.map(serializeEntry),
290
+ truncated: timeline.truncated,
291
+ }
292
+ }
293
+
294
+ function serializeEntry(entry: ActivityTimelineEntry) {
295
+ const at = entry.at.toISOString()
296
+ if (entry.kind !== "agent") {
297
+ return { ...entry, at }
298
+ }
299
+
300
+ const { cost, ...run } = entry
301
+ return { ...run, at, ...(cost ? { cost: { ...cost, amounts: [...cost.amounts] } } : {}) }
302
+ }
303
+
304
+ function serializeConnection<T extends ActivityConnection>(connection: T) {
305
+ return {
306
+ ...connection,
307
+ createdAt: connection.createdAt.toISOString(),
308
+ ...(connection.type === "session" && connection.lastSeenAt
309
+ ? { lastSeenAt: connection.lastSeenAt.toISOString() }
310
+ : {}),
311
+ ...(connection.revokedAt ? { revokedAt: connection.revokedAt.toISOString() } : {}),
312
+ }
313
+ }
314
+
315
+ /**
316
+ * A signed-in browser records through its cookie. A native client's bearer session is not a
317
+ * visit; a shared-link session has no caller here and is checked by the runtime.
318
+ */
319
+ function assertBrowserCapture(context: unknown): void {
320
+ const caller = requestCaller(context)
321
+ if (caller && credentialTransport(caller) !== "cookie") {
322
+ throw new AuthorizationError(
323
+ "activity.capture",
324
+ "[SixbServer] Activity is recorded only through a browser or shared-link session."
325
+ )
326
+ }
327
+ }
@@ -1,26 +1,24 @@
1
1
  import type { SixbHostView } from "@sixb/core"
2
- import { assertAgentExecutionRecord } from "@sixb/core/internal/agent-execution"
3
2
  import {
4
3
  AGENT_API_GATEWAY_PREFIX,
5
4
  AGENT_API_ROUTES,
6
- type AgentExecutionAuthorization,
5
+ type AgentRunExecutionScope,
6
+ AgentRunScopeError,
7
7
  isAllowedAgentApiRequest,
8
8
  isValidAgentApiGatewayCapability,
9
- resolveAgentExecutionAuthorization,
10
- resolveInheritedAgentExecutionAuthorization,
9
+ resolveAgentRunExecutionScope,
11
10
  } from "@sixb/core/internal/agents"
12
11
  import { normalizeRoutePath, pathSegmentsFor } from "@sixb/core/internal/http"
13
- import type { RequestExecutionAuthorization } from "@sixb/core/internal/request-execution"
14
12
  import type {
15
13
  AgentRunRecord,
16
- AuthStorage,
17
14
  ConversationAgentRunRecord,
18
- ExecutionRecord,
15
+ SubagentRunRecord,
19
16
  WorkflowAgentNodeRunRecord,
20
17
  } from "@sixb/core/storage"
21
18
  import type { Elysia } from "elysia"
22
19
  import { type InternalRequestAuthState, registerInternalRequestAuthState } from "../auth/scope"
23
20
  import { RequestBodyTooLargeError, readRequestBodyWithLimit } from "../utils/request-body"
21
+ import { gateAgentApiCall } from "./agent-approval-gate"
24
22
  import { DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES } from "./files"
25
23
 
26
24
  const MAX_AGENT_API_BODY_BYTES = 1_000_000
@@ -81,13 +79,14 @@ async function handleAgentApiGatewayRequest(input: {
81
79
  )
82
80
  }
83
81
 
84
- const authState = await resolveAgentRunAuthState(input.host, {
82
+ const resolved = await resolveAgentRunAuthState(input.host, {
85
83
  runId: input.agentRunId,
86
84
  capability: input.capability,
87
85
  })
88
- if (authState instanceof Response) {
89
- return authState
86
+ if (resolved instanceof Response) {
87
+ return resolved
90
88
  }
89
+ const { authState, run } = resolved
91
90
  if (
92
91
  authState.agentExecution.kind !== "conversation" &&
93
92
  input.request.method === "POST" &&
@@ -100,6 +99,38 @@ async function handleAgentApiGatewayRequest(input: {
100
99
  : "Child agents cannot start a workflow run."
101
100
  )
102
101
  }
102
+ // A workflow step is a fixed assignment: what it does must not change because a conversation
103
+ // saved a note.
104
+ if (authState.agentExecution.kind === "workflow" && matchesAgentMemory(upstreamPath)) {
105
+ return jsonError(403, "Workflow agent nodes have no Agent memory.")
106
+ }
107
+ // A child works for its turn: once the turn has ended, or a retry has taken back its work, the
108
+ // child changes nothing more.
109
+ if ("kind" in run && run.kind === "subagent" && !(await parentRunActive(input.host, run))) {
110
+ return jsonError(409, "The child agent's parent run has ended.")
111
+ }
112
+ // A child reads what its parent's conversation remembers; only the conversation saves to it.
113
+ if (
114
+ authState.agentExecution.kind === "subagent" &&
115
+ input.request.method !== "GET" &&
116
+ matchesAgentMemory(upstreamPath)
117
+ ) {
118
+ return jsonError(403, "Child agents cannot save Agent memory.")
119
+ }
120
+
121
+ // Others read a shared conversation: whoever sends the turn, their own memory stays out of it.
122
+ // Anything but the project's exact path is refused, as a route parameter is percent-decoded.
123
+ if (
124
+ authState.agentRun &&
125
+ matchesAgentMemory(upstreamPath) &&
126
+ pathSegmentsFor(upstreamPath)[2] !== "project" &&
127
+ (await hasParticipants(input.host, authState.agentRun))
128
+ ) {
129
+ return jsonError(
130
+ 403,
131
+ "A shared conversation reaches only the project's memory. Save nothing about one person here."
132
+ )
133
+ }
103
134
 
104
135
  let body: Uint8Array<ArrayBuffer> | undefined
105
136
  try {
@@ -110,11 +141,28 @@ async function handleAgentApiGatewayRequest(input: {
110
141
  }
111
142
  throw error
112
143
  }
144
+
145
+ // The run's approval mode decides, never the model: a held call does not reach its route.
146
+ const gate = await gateAgentApiCall({
147
+ host: input.host,
148
+ method: input.request.method,
149
+ upstreamPath,
150
+ body,
151
+ run,
152
+ agentExecution: authState.agentExecution,
153
+ runExecution: authState.runExecution,
154
+ signal: input.request.signal,
155
+ })
156
+ if (gate.kind === "answer") return gate.response
157
+
113
158
  const internalUrl = new URL(`${upstreamPath}${sourceUrl.search}`, input.request.url)
159
+ // The caller's signal travels with the request: a sandbox client that gives up cancels the
160
+ // forwarded work, model calls included.
114
161
  const internalRequest = new Request(internalUrl, {
115
162
  method: input.request.method,
116
163
  headers: forwardedRequestHeaders(input.request.headers),
117
164
  body,
165
+ signal: input.request.signal,
118
166
  })
119
167
 
120
168
  registerInternalRequestAuthState(internalRequest, authState)
@@ -165,37 +213,34 @@ async function resolveAgentRunAuthState(
165
213
  return jsonError(403, "Agent API gateway capability is not valid for this run.")
166
214
  }
167
215
 
168
- if (!host.auth.isEnabled()) {
169
- return {
170
- authorization: { type: "disabled" as const },
171
- agentExecution: runState.agentExecution,
172
- ...(runState.agentRun === undefined ? {} : { agentRun: runState.agentRun }),
173
- }
174
- }
175
-
176
- const auth = host.storage.auth
177
- if (!auth) {
178
- return jsonError(501, "Agent API gateway is not configured for authenticated agent access.")
179
- }
180
- const execution = await host.storage.executions.getById({
181
- projectId: host.id,
182
- id: runState.run.executionId,
183
- })
184
- if (!execution) {
185
- return jsonError(403, "Agent run execution is not available.")
186
- }
187
-
188
- let authorization: RequestExecutionAuthorization
216
+ let scope: AgentRunExecutionScope
189
217
  try {
190
- authorization = await resolveGatewayRunAuthorization({ host, auth, runState, execution })
191
- } catch {
192
- return jsonError(403, "Agent run execution authority is not valid.")
218
+ scope = await resolveAgentRunExecutionScope(host, {
219
+ runId: runState.runId,
220
+ executionId: runState.run.executionId,
221
+ authority:
222
+ runState.authority === "managed"
223
+ ? { type: "managed", actorId: runState.actorId }
224
+ : { type: "inherited" },
225
+ })
226
+ } catch (error) {
227
+ if (!(error instanceof AgentRunScopeError)) throw error
228
+ return scopeErrorResponse(error)
193
229
  }
194
230
 
231
+ // The request runs inside the run's own execution, restored from server-side records only
232
+ // (run, then its execution record): what it starts is a child of the run and keeps the run's
233
+ // requester and correlation, whatever the request's headers say. Authority is the record's
234
+ // current grants, resolved on every request when it is admitted; a request admitted before the
235
+ // run ends finishes under it, like an in-process tool call. An agent execution also gets
236
+ // provider access (blobs, models, connectors), and so does any route added to the allowlist.
195
237
  return {
196
- authorization,
197
- agentExecution: runState.agentExecution,
198
- ...(runState.agentRun === undefined ? {} : { agentRun: runState.agentRun }),
238
+ authState: {
239
+ runExecution: { ...scope, attempt: runState.run.attempt },
240
+ agentExecution: runState.agentExecution,
241
+ ...(runState.agentRun === undefined ? {} : { agentRun: runState.agentRun }),
242
+ },
243
+ run: runState.run,
199
244
  }
200
245
  }
201
246
 
@@ -245,60 +290,14 @@ function toGatewayRunState(
245
290
  return { ...common, authority: "managed", actorId: workflowRun.actorId }
246
291
  }
247
292
 
248
- async function resolveGatewayRunAuthorization(input: {
249
- readonly host: SixbHostView
250
- readonly auth: AuthStorage
251
- readonly runState: GatewayRunState
252
- readonly execution: ExecutionRecord
253
- }): Promise<RequestExecutionAuthorization> {
254
- if (input.runState.authority === "inherited") {
255
- const resolved = await resolveInheritedAgentExecutionAuthorization({
256
- auth: input.auth,
257
- projectId: input.host.id,
258
- authorizationRef: input.execution.authorizationRef,
259
- security: input.host.definitions.security,
260
- })
261
- const authorization = inheritedRequestAuthorization(resolved, input.execution.authorizationRef)
262
- assertAgentExecutionRecord({
263
- execution: input.execution,
264
- runId: input.runState.runId,
265
- authorization,
266
- })
267
- return authorization
268
- }
269
-
270
- const resolved = await resolveAgentExecutionAuthorization({
271
- auth: input.auth,
272
- projectId: input.host.id,
273
- actorId: input.runState.actorId,
274
- authorizationRef: input.execution.authorizationRef,
275
- security: input.host.definitions.security,
276
- })
277
- const authorization = { type: "principal", context: resolved.context } as const
278
- assertAgentExecutionRecord({
279
- execution: input.execution,
280
- actorId: input.runState.actorId,
281
- runId: input.runState.runId,
282
- authorization,
283
- })
284
- return authorization
285
- }
286
-
287
- function inheritedRequestAuthorization(
288
- resolved: AgentExecutionAuthorization,
289
- authorizationRef: ExecutionRecord["authorizationRef"]
290
- ): Extract<RequestExecutionAuthorization, { readonly type: "principal" | "disabled" }> {
291
- if (
292
- resolved.type !== "principal" ||
293
- authorizationRef.type !== "principal" ||
294
- authorizationRef.credential === undefined
295
- ) {
296
- return resolved
297
- }
298
- return {
299
- type: "principal",
300
- context: resolved.context,
301
- credential: authorizationRef.credential,
293
+ function scopeErrorResponse(error: AgentRunScopeError): Response {
294
+ switch (error.code) {
295
+ case "execution_unavailable":
296
+ return jsonError(403, "Agent run execution is not available.")
297
+ case "auth_unavailable":
298
+ return jsonError(501, "Agent API gateway is not configured for authenticated agent access.")
299
+ case "authority_invalid":
300
+ return jsonError(403, "Agent run execution authority is not valid.")
302
301
  }
303
302
  }
304
303
 
@@ -365,6 +364,31 @@ function isSimpleFileUpload(method: string, pathname: string): boolean {
365
364
  return method === "POST" && normalizeRoutePath(pathname) === "/api/files"
366
365
  }
367
366
 
367
+ async function parentRunActive(host: SixbHostView, run: SubagentRunRecord): Promise<boolean> {
368
+ const parent = await host.storage.agents?.runs.getById({
369
+ projectId: host.id,
370
+ id: run.parentRunId,
371
+ })
372
+ return parent?.status === "queued" || parent?.status === "running"
373
+ }
374
+
375
+ function matchesAgentMemory(pathname: string): boolean {
376
+ const segments = pathSegmentsFor(pathname)
377
+ return segments[0] === "api" && segments[1] === "agent-memory"
378
+ }
379
+
380
+ /** Anyone added to the run's thread, even one who cannot read it now, as the worker counts them. */
381
+ async function hasParticipants(
382
+ host: SixbHostView,
383
+ run: ConversationAgentRunRecord
384
+ ): Promise<boolean> {
385
+ const participants = await host.storage.agents?.threads.listParticipants({
386
+ projectId: run.projectId,
387
+ threadIds: [run.threadId],
388
+ })
389
+ return (participants?.length ?? 0) > 0
390
+ }
391
+
368
392
  function matchesWorkflowRunStart(pathname: string): boolean {
369
393
  const segments = pathSegmentsFor(pathname)
370
394
  return (