@sixb/server 0.1.5 → 0.1.7

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 (74) hide show
  1. package/dist/auth/public-routes.d.ts.map +1 -1
  2. package/dist/auth/scope.d.ts +6 -2
  3. package/dist/auth/scope.d.ts.map +1 -1
  4. package/dist/files/content.d.ts +8 -0
  5. package/dist/files/content.d.ts.map +1 -1
  6. package/dist/index.js +2507 -1573
  7. package/dist/index.js.map +22 -20
  8. package/dist/models/display.d.ts +22 -0
  9. package/dist/models/display.d.ts.map +1 -0
  10. package/dist/routes/action-runs.d.ts +2 -0
  11. package/dist/routes/action-runs.d.ts.map +1 -1
  12. package/dist/routes/actions.d.ts +1 -0
  13. package/dist/routes/actions.d.ts.map +1 -1
  14. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  15. package/dist/routes/agents.d.ts +99 -89
  16. package/dist/routes/agents.d.ts.map +1 -1
  17. package/dist/routes/ai-accounting.d.ts.map +1 -1
  18. package/dist/routes/auth.d.ts +139 -15
  19. package/dist/routes/auth.d.ts.map +1 -1
  20. package/dist/routes/events.d.ts +3 -3
  21. package/dist/routes/files.d.ts +1 -0
  22. package/dist/routes/files.d.ts.map +1 -1
  23. package/dist/routes/models.d.ts +18 -1
  24. package/dist/routes/models.d.ts.map +1 -1
  25. package/dist/routes/objects.d.ts +3 -1
  26. package/dist/routes/objects.d.ts.map +1 -1
  27. package/dist/routes/pipelines.d.ts +2 -1
  28. package/dist/routes/pipelines.d.ts.map +1 -1
  29. package/dist/routes/rules.d.ts +1 -1
  30. package/dist/routes/syncs.d.ts +1 -0
  31. package/dist/routes/syncs.d.ts.map +1 -1
  32. package/dist/routes/workflows.d.ts +57 -54
  33. package/dist/routes/workflows.d.ts.map +1 -1
  34. package/dist/routes/ws/logs.d.ts +4 -4
  35. package/dist/schemas/agents.d.ts +378 -215
  36. package/dist/schemas/agents.d.ts.map +1 -1
  37. package/dist/schemas/ai-accounting.d.ts +1847 -295
  38. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  39. package/dist/schemas/ai-limits.d.ts +2210 -0
  40. package/dist/schemas/ai-limits.d.ts.map +1 -0
  41. package/dist/schemas/auth.d.ts +202 -72
  42. package/dist/schemas/auth.d.ts.map +1 -1
  43. package/dist/schemas/events.d.ts +6 -6
  44. package/dist/schemas/files.d.ts +3 -0
  45. package/dist/schemas/files.d.ts.map +1 -1
  46. package/dist/schemas/models.d.ts +214 -14
  47. package/dist/schemas/models.d.ts.map +1 -1
  48. package/dist/schemas/objects.d.ts +4 -4
  49. package/dist/schemas/pipelines.d.ts +6 -6
  50. package/dist/schemas/rules.d.ts +6 -6
  51. package/dist/schemas/workflows.d.ts +196 -206
  52. package/dist/schemas/workflows.d.ts.map +1 -1
  53. package/dist/utils/http.d.ts +8 -4
  54. package/dist/utils/http.d.ts.map +1 -1
  55. package/package.json +6 -6
  56. package/src/auth/public-routes.ts +18 -0
  57. package/src/auth/scope.ts +3 -2
  58. package/src/files/content.ts +39 -6
  59. package/src/models/display.ts +91 -0
  60. package/src/routes/agent-api-gateway.ts +137 -38
  61. package/src/routes/agents.ts +58 -83
  62. package/src/routes/ai-accounting.ts +414 -23
  63. package/src/routes/auth.ts +297 -2
  64. package/src/routes/models.ts +12 -4
  65. package/src/routes/workflows.ts +3 -5
  66. package/src/routes/ws/agents.ts +17 -6
  67. package/src/schemas/agents.ts +40 -49
  68. package/src/schemas/ai-accounting.ts +88 -19
  69. package/src/schemas/ai-limits.ts +116 -0
  70. package/src/schemas/auth.ts +39 -0
  71. package/src/schemas/files.ts +1 -0
  72. package/src/schemas/models.ts +33 -5
  73. package/src/schemas/workflows.ts +0 -2
  74. package/src/utils/http.ts +33 -2
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"
2
2
  import type { AuthSessionAudience, GroupDefinition, SixbHostView } from "@sixb/core"
3
3
  import {
4
4
  type AuthenticatedUserRequestSession,
@@ -6,11 +6,13 @@ import {
6
6
  AuthRuntimeError,
7
7
  clearCsrfCookieHeader,
8
8
  clearSessionCookieHeader,
9
+ createAccessTokenCredential,
9
10
  createCsrfCookieHeader,
10
11
  createSessionCookieHeader,
11
12
  createSessionCredential,
12
13
  generateCsrfToken,
13
14
  getCookie,
15
+ type InviteDeliveryResult,
14
16
  isMagicLinkAuthStrategy,
15
17
  isOidcAuthStrategy,
16
18
  type MagicLinkAuthStrategy,
@@ -61,7 +63,12 @@ import {
61
63
  CreateAuthServiceAccountAccessTokenResponseSchema,
62
64
  CreateAuthServiceAccountBodySchema,
63
65
  CreateAuthServiceAccountResponseSchema,
66
+ CreateDeviceAuthorizationBodySchema,
67
+ CreateDeviceAuthorizationResponseSchema,
68
+ DeviceAuthorizationDecisionBodySchema,
64
69
  DisableAuthServiceAccountResponseSchema,
70
+ ExchangeDeviceAuthorizationBodySchema,
71
+ ExchangeDeviceAuthorizationResponseSchema,
65
72
  GetAuthAccessManagementOptionsResponseSchema,
66
73
  GetAuthInvitationOptionsResponseSchema,
67
74
  GetAuthMembershipOptionsResponseSchema,
@@ -135,6 +142,246 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
135
142
  async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
136
143
  { detail: { hide: true } }
137
144
  )
145
+ .post(
146
+ "/api/auth/device-authorizations",
147
+ async ({ body, request }) => {
148
+ const parsed = CreateDeviceAuthorizationBodySchema.parse(body)
149
+ const now = new Date()
150
+ const id = `dva_${randomUUID()}`
151
+ const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`
152
+ const userCode = createDeviceUserCode()
153
+ const expiresAt = new Date(now.getTime() + DEVICE_AUTHORIZATION_TTL_MS)
154
+ try {
155
+ await requireAuthStorage(host).deviceAuthorizations.create({
156
+ id,
157
+ projectId: host.id,
158
+ deviceCodeHash: hashDeviceCode(deviceCode),
159
+ userCode,
160
+ clientName: parsed.clientName,
161
+ tokenName: parsed.tokenName,
162
+ tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
163
+ createdAt: now,
164
+ expiresAt,
165
+ })
166
+ } catch (error) {
167
+ return authRouteErrorResponse(error)
168
+ }
169
+ const verificationUri = new URL(
170
+ "/auth/device",
171
+ options.resolveAuthRequestOrigin(request)
172
+ ).toString()
173
+ const verificationUriComplete = new URL(verificationUri)
174
+ verificationUriComplete.searchParams.set("user_code", userCode)
175
+ return jsonResponse(
176
+ {
177
+ deviceCode,
178
+ userCode,
179
+ verificationUri,
180
+ verificationUriComplete: verificationUriComplete.toString(),
181
+ expiresAt: expiresAt.toISOString(),
182
+ interval: DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS,
183
+ },
184
+ 201
185
+ )
186
+ },
187
+ {
188
+ body: CreateDeviceAuthorizationBodySchema,
189
+ response: { 201: CreateDeviceAuthorizationResponseSchema, 429: ErrorResponseSchema },
190
+ detail: {
191
+ summary: "Start device authorization",
192
+ tags: [OPENAPI_TAGS.authSessions.name],
193
+ operationId: "createDeviceAuthorization",
194
+ },
195
+ }
196
+ )
197
+ .post(
198
+ "/api/auth/device-authorizations/token",
199
+ async ({ body }) => {
200
+ const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body)
201
+ const id = parseDeviceAuthorizationId(deviceCode)
202
+ if (!id) return jsonResponse({ status: "expired" as const }, 200)
203
+ const storage = requireAuthStorage(host)
204
+ const authorization = await storage.deviceAuthorizations.getById({
205
+ projectId: host.id,
206
+ id,
207
+ })
208
+ const now = new Date()
209
+ if (
210
+ !authorization ||
211
+ authorization.deviceCodeHash !== hashDeviceCode(deviceCode) ||
212
+ authorization.expiresAt <= now ||
213
+ authorization.status === "consumed"
214
+ ) {
215
+ return jsonResponse({ status: "expired" as const }, 200)
216
+ }
217
+ if (authorization.status === "pending") {
218
+ return jsonResponse({ status: "pending" as const }, 200)
219
+ }
220
+ if (authorization.status === "denied") {
221
+ return jsonResponse({ status: "denied" as const }, 200)
222
+ }
223
+ if (!authorization.approvedUserId || !authorization.approvedSessionId) {
224
+ return jsonResponse({ status: "expired" as const }, 200)
225
+ }
226
+ const credential = createAccessTokenCredential("personal")
227
+ try {
228
+ await storage.completeDeviceAuthorization({
229
+ projectId: host.id,
230
+ id,
231
+ deviceCodeHash: hashDeviceCode(deviceCode),
232
+ completedAt: now,
233
+ accessToken: {
234
+ id: credential.tokenId,
235
+ projectId: host.id,
236
+ name: authorization.tokenName,
237
+ kind: "personal",
238
+ subjectType: "user",
239
+ subjectId: authorization.approvedUserId,
240
+ tokenHash: credential.tokenHash,
241
+ createdByPrincipal: { type: "user", id: authorization.approvedUserId },
242
+ createdBySessionId: authorization.approvedSessionId,
243
+ createdAt: now,
244
+ expiresAt: authorization.tokenExpiresAt,
245
+ },
246
+ })
247
+ } catch (error) {
248
+ if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
249
+ return jsonResponse({ status: "expired" as const }, 200)
250
+ }
251
+ throw error
252
+ }
253
+ return jsonResponse(
254
+ { status: "approved" as const, accessToken: credential.tokenValue },
255
+ 200
256
+ )
257
+ },
258
+ {
259
+ body: ExchangeDeviceAuthorizationBodySchema,
260
+ response: { 200: ExchangeDeviceAuthorizationResponseSchema },
261
+ detail: {
262
+ summary: "Exchange an approved device authorization",
263
+ tags: [OPENAPI_TAGS.authSessions.name],
264
+ operationId: "exchangeDeviceAuthorization",
265
+ },
266
+ }
267
+ )
268
+ .get(
269
+ "/auth/device",
270
+ async ({ request }) => {
271
+ const rawUserCode = new URL(request.url).searchParams.get("user_code")
272
+ if (!rawUserCode) {
273
+ return authPageResponse(
274
+ [
275
+ "<h1>Authorize a device</h1>",
276
+ '<form method="get" action="/auth/device">',
277
+ '<input name="user_code" autocomplete="one-time-code" placeholder="BCDF-HJKM" aria-label="Device code" required autofocus>',
278
+ '<button type="submit">Continue</button>',
279
+ "</form>",
280
+ ].join("")
281
+ )
282
+ }
283
+ const userCode = normalizeDeviceUserCode(rawUserCode)
284
+ if (!userCode) return authPageResponse("<h1>Invalid authorization</h1>", 400)
285
+ const authorization = await requireAuthStorage(host).deviceAuthorizations.getByUserCode({
286
+ projectId: host.id,
287
+ userCode,
288
+ })
289
+ const now = new Date()
290
+ if (
291
+ !authorization ||
292
+ authorization.status !== "pending" ||
293
+ authorization.expiresAt <= now
294
+ ) {
295
+ return authPageResponse("<h1>This authorization has expired</h1>", 400)
296
+ }
297
+ const authOptions = resolveAuthOptions(options, request)
298
+ const session = await host.auth.getSession(request, authOptions)
299
+ if (!session.authenticated) return authPageResponse("<h1>Authentication required</h1>", 401)
300
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
301
+ const csrf = resolveSessionCsrfToken({
302
+ request,
303
+ cookieOptions,
304
+ expiresAt: session.session.expiresAt,
305
+ })
306
+ const groups = session.groupIds.length
307
+ ? `<p>Groups: ${escapeHtml(session.groupIds.join(", "))}</p>`
308
+ : "<p>Groups: none</p>"
309
+ const response = authPageResponse(
310
+ [
311
+ "<h1>Authorize this device?</h1>",
312
+ `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting access.</p>`,
313
+ `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
314
+ `<p>Token: ${escapeHtml(authorization.tokenName)}</p>`,
315
+ `<p>Expires: ${escapeHtml(authorization.tokenExpiresAt.toLocaleDateString("en-US"))}</p>`,
316
+ groups,
317
+ '<form method="post" action="/auth/device">',
318
+ `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
319
+ `<input type="hidden" name="csrfToken" value="${escapeHtml(csrf.token)}">`,
320
+ '<button name="decision" value="approve" type="submit">Authorize</button>',
321
+ '<button name="decision" value="deny" type="submit">Deny</button>',
322
+ "</form>",
323
+ ].join("")
324
+ )
325
+ if (csrf.setCookie) response.headers.append("set-cookie", csrf.setCookie)
326
+ return response
327
+ },
328
+ { detail: { hide: true } }
329
+ )
330
+ .post(
331
+ "/auth/device",
332
+ async ({ body, request }) => {
333
+ const parsed = DeviceAuthorizationDecisionBodySchema.parse(body)
334
+ const authOptions = resolveAuthOptions(options, request)
335
+ const session = await host.auth.getSession(request, authOptions)
336
+ if (!session.authenticated) return authPageResponse("<h1>Authentication required</h1>", 401)
337
+ if (!sessionCanAccessApplication(host, session, authOptions.audience)) {
338
+ return authPageResponse("<h1>Access denied</h1>", 403)
339
+ }
340
+ const csrfHeaders = new Headers(request.headers)
341
+ csrfHeaders.set("x-sixb-csrf", parsed.csrfToken)
342
+ if (
343
+ !verifyDoubleSubmitCsrf(
344
+ new Request(request.url, { method: "POST", headers: csrfHeaders }),
345
+ {
346
+ cookieName: host.auth.getCookieOptions(authOptions).csrfCookieName,
347
+ }
348
+ )
349
+ ) {
350
+ return authPageResponse("<h1>Invalid authorization request</h1>", 403)
351
+ }
352
+ const storage = requireAuthStorage(host)
353
+ const authorization = await storage.deviceAuthorizations.getByUserCode({
354
+ projectId: host.id,
355
+ userCode: parsed.userCode,
356
+ })
357
+ if (!authorization) return authPageResponse("<h1>Invalid authorization</h1>", 400)
358
+ if (parsed.decision === "approve") {
359
+ await storage.deviceAuthorizations.approve({
360
+ projectId: host.id,
361
+ id: authorization.id,
362
+ userId: session.user.id,
363
+ sessionId: session.session.id,
364
+ approvedAt: new Date(),
365
+ })
366
+ return authPageResponse("<h1>Device authorized</h1><p>You can close this window.</p>")
367
+ }
368
+ await storage.deviceAuthorizations.deny({
369
+ projectId: host.id,
370
+ id: authorization.id,
371
+ deniedAt: new Date(),
372
+ })
373
+ return authPageResponse("<h1>Authorization denied</h1><p>You can close this window.</p>")
374
+ },
375
+ {
376
+ body: t.Object({
377
+ userCode: t.String(),
378
+ decision: t.Union([t.Literal("approve"), t.Literal("deny")]),
379
+ csrfToken: t.String(),
380
+ }),
381
+ parse: "urlencoded",
382
+ detail: { hide: true },
383
+ }
384
+ )
138
385
  .get(
139
386
  "/api/auth/session",
140
387
  async ({ request }) => {
@@ -901,6 +1148,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
901
1148
  groupIds: parsed.groupIds,
902
1149
  expiresAt: parseDate(parsed.expiresAt),
903
1150
  returnTo: deliveryContext.returnTo,
1151
+ revealLink: parsed.revealLink,
904
1152
  },
905
1153
  {
906
1154
  ...authOptions,
@@ -915,7 +1163,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
915
1163
  return jsonResponse(
916
1164
  {
917
1165
  invitation: serializeInvitation(result.invitation),
918
- delivery: result.delivery,
1166
+ delivery: serializeInvitationDelivery(result.delivery),
919
1167
  },
920
1168
  201
921
1169
  )
@@ -1489,6 +1737,36 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1489
1737
  )
1490
1738
  }
1491
1739
 
1740
+ const DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000
1741
+ const DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
1742
+ const DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2
1743
+ const DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789"
1744
+
1745
+ function hashDeviceCode(deviceCode: string): string {
1746
+ return createHash("sha256").update(deviceCode).digest("base64url")
1747
+ }
1748
+
1749
+ function parseDeviceAuthorizationId(deviceCode: string): string | null {
1750
+ const separator = deviceCode.indexOf(".")
1751
+ if (separator <= 0 || separator !== deviceCode.lastIndexOf(".")) return null
1752
+ const id = deviceCode.slice(0, separator)
1753
+ return /^dva_[A-Za-z0-9-]+$/.test(id) ? id : null
1754
+ }
1755
+
1756
+ function createDeviceUserCode(): string {
1757
+ const bytes = randomBytes(8)
1758
+ const characters = [...bytes].map(
1759
+ (value) => DEVICE_USER_CODE_ALPHABET[value % DEVICE_USER_CODE_ALPHABET.length]
1760
+ )
1761
+ return `${characters.slice(0, 4).join("")}-${characters.slice(4).join("")}`
1762
+ }
1763
+
1764
+ function normalizeDeviceUserCode(value: string): string | null {
1765
+ const compact = value.toUpperCase().replaceAll(/[^A-Z0-9]/g, "")
1766
+ if (compact.length !== 8) return null
1767
+ return `${compact.slice(0, 4)}-${compact.slice(4)}`
1768
+ }
1769
+
1492
1770
  // The pending cookie carries the preimage of the `requester` hash embedded in
1493
1771
  // the emailed callback URL. Only the browser that requested the link holds it,
1494
1772
  // so GET /auth/callback can distinguish that browser (sign in immediately) from
@@ -2277,6 +2555,20 @@ function serializeInvitation(invitation: InvitationRecord) {
2277
2555
  }
2278
2556
  }
2279
2557
 
2558
+ function serializeInvitationDelivery(delivery: InviteDeliveryResult) {
2559
+ return {
2560
+ status: delivery.status,
2561
+ ...(delivery.link
2562
+ ? {
2563
+ link: {
2564
+ url: delivery.link.url,
2565
+ expiresAt: delivery.link.expiresAt ? toIsoString(delivery.link.expiresAt) : undefined,
2566
+ },
2567
+ }
2568
+ : {}),
2569
+ }
2570
+ }
2571
+
2280
2572
  function serializeMemberSummary(member: MemberSummary) {
2281
2573
  return {
2282
2574
  ...serializeManagedMember(member.user, member.groupIds),
@@ -2333,6 +2625,9 @@ function authRouteErrorResponse(error: unknown): Response {
2333
2625
  }
2334
2626
 
2335
2627
  if (error instanceof AuthStorageError) {
2628
+ if (error.code === "device_authorization_limit_exceeded") {
2629
+ return jsonResponse({ error: error.message }, 429)
2630
+ }
2336
2631
  if (
2337
2632
  error.code === "missing_invitation" ||
2338
2633
  error.code === "missing_access_token" ||
@@ -1,22 +1,30 @@
1
1
  import type { LanguageModelEntry, SixbHostView } from "@sixb/core"
2
2
  import type { Elysia } from "elysia"
3
+ import { languageModelDisplay } from "../models/display"
3
4
  import { OPENAPI_TAGS } from "../openapi/tags"
4
5
  import { ModelCatalogSchema } from "../schemas/models"
5
6
 
6
- function serializeLanguageModel(entry: LanguageModelEntry, defaultRef: string) {
7
- return { provider: entry.provider, modelId: entry.modelId, isDefault: entry.ref === defaultRef }
7
+ async function serializeLanguageModel(entry: LanguageModelEntry, defaultEntry: LanguageModelEntry) {
8
+ return {
9
+ ...(await languageModelDisplay(entry)),
10
+ provider: entry.provider,
11
+ modelId: entry.modelId,
12
+ isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId,
13
+ }
8
14
  }
9
15
 
10
16
  export function registerModelRoutes(app: Elysia, host: SixbHostView) {
11
17
  return app.get(
12
18
  "/api/models",
13
- () => {
19
+ async () => {
14
20
  const language = host.definitions.models?.language
15
21
  return ModelCatalogSchema.parse({
16
22
  language:
17
23
  language === undefined
18
24
  ? []
19
- : language.list().map((entry) => serializeLanguageModel(entry, language.default.ref)),
25
+ : await Promise.all(
26
+ language.list().map((entry) => serializeLanguageModel(entry, language.default))
27
+ ),
20
28
  })
21
29
  },
22
30
  {
@@ -139,7 +139,6 @@ function serializePrincipal(principal: Principal) {
139
139
 
140
140
  function serializeWorkflowAgentExecutionSummary(execution: WorkflowAgentNodeRunView) {
141
141
  return {
142
- agentId: execution.agentId,
143
142
  status: execution.status,
144
143
  attempt: execution.attempt,
145
144
  modelId: execution.modelId,
@@ -205,7 +204,7 @@ function toWorkflowCancellationFailure(input: {
205
204
  function toAgentCancellationFailure(input: {
206
205
  readonly message: string
207
206
  readonly at: Date
208
- readonly agentId: string
207
+ readonly agentStepId: string
209
208
  readonly workflowId: string
210
209
  readonly runId: string
211
210
  readonly nodeRunId: string
@@ -213,7 +212,7 @@ function toAgentCancellationFailure(input: {
213
212
  return toSixbFailure(
214
213
  createSixbError("runtime.cancelled", input.message, {
215
214
  details: {
216
- agentId: input.agentId,
215
+ agentStepId: input.agentStepId,
217
216
  workflowId: input.workflowId,
218
217
  workflowRunId: input.runId,
219
218
  nodeRunId: input.nodeRunId,
@@ -385,7 +384,6 @@ function serializeWorkflow(
385
384
  type: "agent" as const,
386
385
  id: node.id,
387
386
  key: node.key,
388
- agentId: node.agentStep.agent.id,
389
387
  input: node.agentStep.input,
390
388
  output: node.agentStep.output,
391
389
  }
@@ -1132,7 +1130,7 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
1132
1130
  error: toAgentCancellationFailure({
1133
1131
  message: cancellationMessage,
1134
1132
  at: cancelledAt,
1135
- agentId: execution.agentId,
1133
+ agentStepId: active.nodeId,
1136
1134
  workflowId: run.workflowId,
1137
1135
  runId: run.id,
1138
1136
  nodeRunId: active.id,
@@ -82,7 +82,7 @@ export async function canAccessAgentRunStream(
82
82
  sixb: Sixb<readonly OntologySource[]>,
83
83
  runId: string
84
84
  ): Promise<{ ok: true } | { ok: false; message: string }> {
85
- const run = await sixb.agents.runs.getById(runId)
85
+ const run = await sixb.agent.runs.getById(runId)
86
86
  if (!run) {
87
87
  return { ok: false, message: "Agent run not found." }
88
88
  }
@@ -93,8 +93,8 @@ export async function canAccessAgentThreadActivity(
93
93
  sixb: Sixb<readonly OntologySource[]>,
94
94
  event: AgentRunActivityEvent
95
95
  ): Promise<boolean> {
96
- const thread = await sixb.agents.threads.getById(event.threadId)
97
- return thread?.agentId === event.agentId
96
+ const run = await sixb.agent.runs.getById(event.runId)
97
+ return run?.projectId === event.projectId && run.threadId === event.threadId
98
98
  }
99
99
 
100
100
  export function registerAgentStreamRoutes(app: Elysia, server: SixbServer) {
@@ -318,7 +318,7 @@ async function sendVisibleActivityRecords(
318
318
  events.map((event) => canAccessAgentThreadActivity(sixb, event))
319
319
  )
320
320
  for (const [index, event] of events.entries()) {
321
- if (visible[index]) safeSend(ws, { type: "activity", event })
321
+ if (visible[index]) safeSend(ws, { type: "activity", event: serializeStreamPayload(event) })
322
322
  }
323
323
  }
324
324
 
@@ -401,7 +401,7 @@ async function sendRunSnapshot(
401
401
  runId: string
402
402
  ): Promise<boolean> {
403
403
  try {
404
- const run = await sixb.agents.runs.getById(runId)
404
+ const run = await sixb.agent.runs.getById(runId)
405
405
  if (!run) {
406
406
  safeSend(ws, { type: "error", message: "Agent run not found." })
407
407
  return false
@@ -422,10 +422,21 @@ function sendRecords(
422
422
  records: readonly BrokerRecord[]
423
423
  ): void {
424
424
  for (const record of records) {
425
- safeSend(ws, { type: "record", record })
425
+ safeSend(ws, {
426
+ type: "record",
427
+ record: { ...record, payload: serializeStreamPayload(record.payload) },
428
+ })
426
429
  }
427
430
  }
428
431
 
432
+ /** Stored records may predate the public contract; do not re-expose their retired selector. */
433
+ function serializeStreamPayload(payload: unknown): unknown {
434
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return payload
435
+ if (!("agentId" in payload)) return payload
436
+ const { agentId: _agentId, ...event } = payload
437
+ return event
438
+ }
439
+
429
440
  function errorMessage(error: unknown): string {
430
441
  return error instanceof Error ? error.message : String(error)
431
442
  }
@@ -1,4 +1,4 @@
1
- import { AGENT_REASONING_LEVELS, MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core"
1
+ import { MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core"
2
2
  import {
3
3
  AGENT_RUN_DIAGNOSTIC_CODES,
4
4
  AGENT_RUN_FAILURE_CODES,
@@ -11,14 +11,11 @@ import { AiCostSummarySchema } from "./ai-accounting"
11
11
  import { AiUsageSummarySchema } from "./ai-usage"
12
12
  import { JsonValueSchema, sixbFailureSchema } from "./common"
13
13
  import { FileRefSchema } from "./files"
14
+ import { LanguageModelRefSchema, ModelReasoningLevelSchema, ModelReasoningSchema } from "./models"
14
15
 
15
16
  export const AgentRunFailureSchema: z.ZodType<SixbFailure<AgentRunFailureCode>> =
16
17
  sixbFailureSchema(AGENT_RUN_FAILURE_CODES)
17
18
 
18
- export const AgentIdParamsSchema = z.object({
19
- agentId: z.string().min(1),
20
- })
21
-
22
19
  export const AgentThreadParamsSchema = z.object({
23
20
  threadId: z.string().min(1),
24
21
  })
@@ -73,53 +70,35 @@ export const AgentContextPartSchema = AgentContextEntryInputSchema.extend({
73
70
  type: z.literal("context"),
74
71
  })
75
72
 
76
- export const AgentLoopConfigSchema = z.object({
77
- stopWhen: z
78
- .object({
79
- maxSteps: z.number().int().positive().optional(),
80
- })
81
- .optional(),
82
- context: z
83
- .object({
84
- windowTokens: z.number().int().positive().optional(),
85
- reserveTokens: z.number().int().positive().optional(),
86
- keepRecentTokens: z.number().int().positive().optional(),
87
- })
88
- .optional(),
89
- })
90
-
91
- export const AgentReasoningLevelSchema = z.enum(AGENT_REASONING_LEVELS)
73
+ export const AgentReasoningLevelSchema = ModelReasoningLevelSchema
74
+ export const AgentReasoningSchema = ModelReasoningSchema
92
75
 
93
- export const AgentCatalogItemSchema = z.object({
94
- id: z.string(),
76
+ export const AgentDescriptorSchema = z.object({
95
77
  name: z.string(),
96
- description: z.string().optional(),
97
- modelId: z.string().optional(),
98
- reasoning: AgentReasoningLevelSchema.optional(),
99
- groupIds: z.array(z.string()),
100
- loop: AgentLoopConfigSchema.optional(),
78
+ model: LanguageModelRefSchema,
101
79
  })
102
80
 
103
81
  export const AgentThreadStatusSchema = z.enum(["active", "archived"])
104
82
 
105
- export const AgentThreadListQuerySchema = z.object({
106
- agentId: z.string().optional(),
107
- status: AgentThreadStatusSchema.optional(),
108
- limit: z.string().optional(),
109
- offset: z.string().optional(),
110
- order: z.enum(["asc", "desc"]).optional(),
111
- })
112
-
113
- export const CreateAgentThreadBodySchema = z.object({
114
- agentId: z.string().min(1),
115
- title: z.string().trim().min(1).optional(),
116
- threadId: z.string().trim().min(1).optional(),
117
- })
83
+ export const AgentThreadListQuerySchema = z
84
+ .object({
85
+ status: AgentThreadStatusSchema.optional(),
86
+ limit: z.string().optional(),
87
+ offset: z.string().optional(),
88
+ order: z.enum(["asc", "desc"]).optional(),
89
+ })
90
+ .strict()
91
+
92
+ export const CreateAgentThreadBodySchema = z
93
+ .object({
94
+ title: z.string().trim().min(1).optional(),
95
+ threadId: z.string().trim().min(1).optional(),
96
+ })
97
+ .strict()
118
98
 
119
99
  export const AgentThreadSchema = z.object({
120
100
  id: z.string(),
121
101
  projectId: z.string(),
122
- agentId: z.string(),
123
102
  ownerPrincipal: AgentPrincipalSchema,
124
103
  title: z.string().optional(),
125
104
  status: AgentThreadStatusSchema,
@@ -164,6 +143,12 @@ const AgentFilePartSchema = z.object({
164
143
  providerMetadata: JsonValueSchema.optional(),
165
144
  })
166
145
 
146
+ const AgentProviderStatePartSchema = z.object({
147
+ type: z.literal("provider-state"),
148
+ providerId: z.string(),
149
+ data: JsonValueSchema,
150
+ })
151
+
167
152
  const AgentToolCallBaseSchema = z.object({
168
153
  type: z.literal("tool-call"),
169
154
  toolCallId: z.string(),
@@ -189,6 +174,7 @@ export const AgentMessagePartSchema = z.union([
189
174
  AgentReasoningPartSchema,
190
175
  AgentStepStartPartSchema,
191
176
  AgentFilePartSchema,
177
+ AgentProviderStatePartSchema,
192
178
  AgentContextPartSchema,
193
179
  AgentToolCallOutputSchema,
194
180
  AgentToolCallErrorSchema,
@@ -240,12 +226,16 @@ export const AgentMessageListResponseSchema = z.object({
240
226
  total: z.number(),
241
227
  })
242
228
 
243
- export const PostAgentMessageBodySchema = z.object({
244
- text: z.string().trim().min(1),
245
- attachments: z.array(FileRefSchema).optional(),
246
- context: z.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
247
- messageId: z.string().trim().min(1).optional(),
248
- })
229
+ export const PostAgentMessageBodySchema = z
230
+ .object({
231
+ text: z.string().trim().min(1),
232
+ model: LanguageModelRefSchema.optional(),
233
+ reasoning: ModelReasoningSchema.optional(),
234
+ attachments: z.array(FileRefSchema).optional(),
235
+ context: z.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
236
+ messageId: z.string().trim().min(1).optional(),
237
+ })
238
+ .strict()
249
239
 
250
240
  export const CancelAgentRunBodySchema = z.object({
251
241
  runId: z.string().trim().min(1),
@@ -265,10 +255,11 @@ export const AgentRunSchema = z.object({
265
255
  id: z.string(),
266
256
  projectId: z.string(),
267
257
  threadId: z.string(),
268
- agentId: z.string(),
269
258
  triggerMessageId: z.string(),
270
259
  requestedBy: AgentAuthorizablePrincipalSchema.optional(),
271
260
  status: AgentRunStatusSchema,
261
+ model: LanguageModelRefSchema.optional(),
262
+ reasoning: ModelReasoningSchema.optional(),
272
263
  modelId: z.string().optional(),
273
264
  finishReason: AgentRunFinishReasonSchema.optional(),
274
265
  usage: AiUsageSummarySchema.optional(),