@sixb/server 0.1.6 → 0.1.8

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 (120) hide show
  1. package/dist/auth/access-token-boundary.d.ts +3 -0
  2. package/dist/auth/access-token-boundary.d.ts.map +1 -1
  3. package/dist/auth/public-routes.d.ts.map +1 -1
  4. package/dist/auth/scope.d.ts +6 -2
  5. package/dist/auth/scope.d.ts.map +1 -1
  6. package/dist/auth/shared-access.d.ts +66 -0
  7. package/dist/auth/shared-access.d.ts.map +1 -0
  8. package/dist/files/content.d.ts +8 -0
  9. package/dist/files/content.d.ts.map +1 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3402 -1693
  13. package/dist/index.js.map +35 -28
  14. package/dist/models/display.d.ts +22 -0
  15. package/dist/models/display.d.ts.map +1 -0
  16. package/dist/openapi/security.d.ts +15 -1
  17. package/dist/openapi/security.d.ts.map +1 -1
  18. package/dist/openapi/tags.d.ts +6 -2
  19. package/dist/openapi/tags.d.ts.map +1 -1
  20. package/dist/registerRoutes.d.ts +2 -0
  21. package/dist/registerRoutes.d.ts.map +1 -1
  22. package/dist/routes/action-runs.d.ts +2 -0
  23. package/dist/routes/action-runs.d.ts.map +1 -1
  24. package/dist/routes/actions.d.ts +1 -0
  25. package/dist/routes/actions.d.ts.map +1 -1
  26. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  27. package/dist/routes/agents.d.ts +100 -90
  28. package/dist/routes/agents.d.ts.map +1 -1
  29. package/dist/routes/ai-accounting.d.ts.map +1 -1
  30. package/dist/routes/auth.d.ts +143 -24
  31. package/dist/routes/auth.d.ts.map +1 -1
  32. package/dist/routes/connector-connection-runs.d.ts +8 -8
  33. package/dist/routes/connector-connections.d.ts +4 -4
  34. package/dist/routes/datasets.d.ts +5 -3
  35. package/dist/routes/datasets.d.ts.map +1 -1
  36. package/dist/routes/events.d.ts +3 -3
  37. package/dist/routes/files.d.ts +1 -0
  38. package/dist/routes/files.d.ts.map +1 -1
  39. package/dist/routes/logs.d.ts +1 -1
  40. package/dist/routes/models.d.ts +18 -1
  41. package/dist/routes/models.d.ts.map +1 -1
  42. package/dist/routes/objects.d.ts +3 -1
  43. package/dist/routes/objects.d.ts.map +1 -1
  44. package/dist/routes/pipelines.d.ts +6 -1
  45. package/dist/routes/pipelines.d.ts.map +1 -1
  46. package/dist/routes/rules.d.ts +1 -1
  47. package/dist/routes/share-grants.d.ts +264 -0
  48. package/dist/routes/share-grants.d.ts.map +1 -0
  49. package/dist/routes/shared-access.d.ts +155 -0
  50. package/dist/routes/shared-access.d.ts.map +1 -0
  51. package/dist/routes/syncs.d.ts +3 -0
  52. package/dist/routes/syncs.d.ts.map +1 -1
  53. package/dist/routes/workflows.d.ts +58 -55
  54. package/dist/routes/workflows.d.ts.map +1 -1
  55. package/dist/routes/ws/logs.d.ts +4 -4
  56. package/dist/schemas/agents.d.ts +385 -230
  57. package/dist/schemas/agents.d.ts.map +1 -1
  58. package/dist/schemas/ai-accounting.d.ts +1847 -295
  59. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  60. package/dist/schemas/ai-limits.d.ts +2210 -0
  61. package/dist/schemas/ai-limits.d.ts.map +1 -0
  62. package/dist/schemas/auth.d.ts +195 -112
  63. package/dist/schemas/auth.d.ts.map +1 -1
  64. package/dist/schemas/datasets.d.ts +28 -22
  65. package/dist/schemas/datasets.d.ts.map +1 -1
  66. package/dist/schemas/events.d.ts +6 -6
  67. package/dist/schemas/files.d.ts +3 -0
  68. package/dist/schemas/files.d.ts.map +1 -1
  69. package/dist/schemas/logs.d.ts +6 -6
  70. package/dist/schemas/models.d.ts +214 -14
  71. package/dist/schemas/models.d.ts.map +1 -1
  72. package/dist/schemas/objects.d.ts +4 -4
  73. package/dist/schemas/pipelines.d.ts +42 -6
  74. package/dist/schemas/pipelines.d.ts.map +1 -1
  75. package/dist/schemas/rules.d.ts +6 -6
  76. package/dist/schemas/share-grants.d.ts +518 -0
  77. package/dist/schemas/share-grants.d.ts.map +1 -0
  78. package/dist/schemas/shared-access.d.ts +42 -0
  79. package/dist/schemas/shared-access.d.ts.map +1 -0
  80. package/dist/schemas/syncs.d.ts +7 -0
  81. package/dist/schemas/syncs.d.ts.map +1 -1
  82. package/dist/schemas/workflows.d.ts +200 -210
  83. package/dist/schemas/workflows.d.ts.map +1 -1
  84. package/dist/server.d.ts +5 -0
  85. package/dist/server.d.ts.map +1 -1
  86. package/dist/utils/http.d.ts +8 -4
  87. package/dist/utils/http.d.ts.map +1 -1
  88. package/package.json +4 -4
  89. package/src/auth/access-token-boundary.ts +17 -2
  90. package/src/auth/public-routes.ts +23 -0
  91. package/src/auth/scope.ts +3 -2
  92. package/src/auth/shared-access.ts +376 -0
  93. package/src/files/content.ts +39 -6
  94. package/src/index.ts +1 -0
  95. package/src/models/display.ts +91 -0
  96. package/src/openapi/security.ts +20 -1
  97. package/src/openapi/tags.ts +4 -0
  98. package/src/registerRoutes.ts +6 -0
  99. package/src/routes/actions.ts +5 -10
  100. package/src/routes/agent-api-gateway.ts +137 -38
  101. package/src/routes/agents.ts +58 -83
  102. package/src/routes/ai-accounting.ts +414 -23
  103. package/src/routes/auth.ts +280 -1
  104. package/src/routes/models.ts +12 -4
  105. package/src/routes/share-grants.ts +238 -0
  106. package/src/routes/shared-access.ts +165 -0
  107. package/src/routes/workflows.ts +3 -5
  108. package/src/routes/ws/agents.ts +17 -6
  109. package/src/schemas/agents.ts +38 -50
  110. package/src/schemas/ai-accounting.ts +88 -19
  111. package/src/schemas/ai-limits.ts +116 -0
  112. package/src/schemas/auth.ts +32 -0
  113. package/src/schemas/datasets.ts +2 -1
  114. package/src/schemas/files.ts +1 -0
  115. package/src/schemas/models.ts +33 -5
  116. package/src/schemas/share-grants.ts +109 -0
  117. package/src/schemas/shared-access.ts +31 -0
  118. package/src/schemas/workflows.ts +0 -2
  119. package/src/server.ts +91 -1
  120. package/src/utils/http.ts +33 -2
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto"
1
2
  import { type BlobInfo, type BlobStorage, type FileRef, isFileRef } from "@sixb/core"
2
3
  import { BlobStorageError, supportsRangeRead } from "@sixb/core/blob-storage/server"
3
4
  import { ZodError } from "zod"
@@ -10,6 +11,8 @@ export interface FileContentResponseInput {
10
11
  readonly disposition?: FileContentDisposition
11
12
  readonly head?: boolean
12
13
  readonly rangeHeader?: string | null
14
+ readonly ifNoneMatchHeader?: string | null
15
+ readonly ifRangeHeader?: string | null
13
16
  }
14
17
 
15
18
  export interface FileContentQuery {
@@ -82,6 +85,9 @@ export function fileContentGetResponses(options: FileContentResponsesOptions = {
82
85
  },
83
86
  },
84
87
  },
88
+ 304: {
89
+ description: "File representation is unchanged; reuse the privately cached content",
90
+ },
85
91
  400: {
86
92
  description: "Response for status 400",
87
93
  content: {
@@ -113,6 +119,9 @@ export function fileContentHeadResponses(options: FileContentResponsesOptions =
113
119
  206: {
114
120
  description: "Partial file content headers",
115
121
  },
122
+ 304: {
123
+ description: "File representation is unchanged; reuse the privately cached content",
124
+ },
116
125
  400: {
117
126
  description: "Response for status 400",
118
127
  content: {
@@ -146,7 +155,18 @@ export async function createFileContentResponse(
146
155
 
147
156
  const canReadRange = supportsRangeRead(input.blobStorage)
148
157
  const headers = fileContentHeaders(input.fileRef, stat, input.disposition, canReadRange)
149
- if (canReadRange && input.rangeHeader) {
158
+ const etag = headers.get("etag")!
159
+ if (matchesIfNoneMatch(input.ifNoneMatchHeader, etag)) {
160
+ headers.delete("content-length")
161
+ return new Response(null, { status: 304, headers })
162
+ }
163
+
164
+ // Date validators are unsupported: only a strong ETag can validate a range.
165
+ if (
166
+ canReadRange &&
167
+ input.rangeHeader &&
168
+ (input.ifRangeHeader == null || input.ifRangeHeader.trim() === etag)
169
+ ) {
150
170
  const range = parseSingleByteRange(input.rangeHeader, stat.sizeBytes)
151
171
  if (!range) {
152
172
  return rangeNotSatisfiableResponse(stat.sizeBytes)
@@ -213,6 +233,8 @@ export async function createContextualFileContentResponse<TQuery extends FileCon
213
233
  disposition: parsed.disposition,
214
234
  head: input.head,
215
235
  rangeHeader: input.request.headers.get("range"),
236
+ ifNoneMatchHeader: input.request.headers.get("if-none-match"),
237
+ ifRangeHeader: input.request.headers.get("if-range"),
216
238
  })
217
239
  if (!response) {
218
240
  return fileContentNotFound(input.set, missingMessage)
@@ -254,6 +276,13 @@ function blobMatchesFileRef(stat: BlobInfo, fileRef: FileRef): boolean {
254
276
  )
255
277
  }
256
278
 
279
+ function matchesIfNoneMatch(header: string | null | undefined, etag: string): boolean {
280
+ return (
281
+ header?.trim() === "*" ||
282
+ (header?.split(",").some((value) => value.trim().replace(/^W\//, "") === etag) ?? false)
283
+ )
284
+ }
285
+
257
286
  function resolveJsonPointer(root: unknown, pointer: string): unknown {
258
287
  if (pointer === "") {
259
288
  return root
@@ -307,12 +336,16 @@ function fileContentHeaders(
307
336
  headers.set("content-type", mediaType)
308
337
  headers.set("content-length", stat.sizeBytes.toString())
309
338
  headers.set("content-disposition", contentDispositionHeader(disposition, fileNameFor(fileRef)))
310
- headers.set("etag", `"${fileRef.digest}"`)
339
+ // Metadata belongs to the reference, not the blob; changing it must also invalidate caches.
340
+ const representation = JSON.stringify([
341
+ fileRef.digest,
342
+ mediaType,
343
+ headers.get("content-disposition"),
344
+ ])
345
+ headers.set("etag", `"sha256:${createHash("sha256").update(representation).digest("hex")}"`)
311
346
  headers.set("x-content-type-options", "nosniff")
312
- // Blobs are content-addressed and immutable, so responses can be cached
313
- // aggressively — but only privately: reads are grant-enforced and must never
314
- // land in a shared cache.
315
- headers.set("cache-control", "private, max-age=31536000, immutable")
347
+ // The containing record is mutable even though its referenced blob is immutable.
348
+ headers.set("cache-control", "private, no-cache")
316
349
  if (canReadRange) {
317
350
  headers.set("accept-ranges", "bytes")
318
351
  }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export type { SixbApiBrowserPolicy, SixbBrowserOrigin } from "./auth/browser-origin"
2
2
  export type { SixbAuthExperienceOptions } from "./auth/experience"
3
+ export type { SixbSharedAccessOptions } from "./auth/shared-access"
3
4
  export { createSixbServer, SixbServer, type SixbServerOptions } from "./server"
@@ -0,0 +1,91 @@
1
+ import type { LanguageModelEntry } from "@sixb/core"
2
+ import {
3
+ defineLanguageModel,
4
+ type LanguageModelDefinition,
5
+ ModelCatalogUnavailableError,
6
+ type ModelReasoningLevel,
7
+ } from "@sixb/core/models"
8
+
9
+ /** Presentation only; the configured provider remains the source of model capabilities. */
10
+ export async function languageModelDisplay(entry: LanguageModelEntry) {
11
+ let definition = entry.model.definition
12
+ try {
13
+ const resolved = await entry.model.resolve?.()
14
+ if (resolved) {
15
+ if (resolved.providerId !== entry.provider || resolved.modelId !== entry.modelId) {
16
+ throw new Error("[SixbServer] Resolved model identity does not match its catalog entry.")
17
+ }
18
+ definition = resolved.definition
19
+ }
20
+ } catch (error) {
21
+ if (!(error instanceof ModelCatalogUnavailableError)) throw error
22
+ console.warn(
23
+ `[SixbServer] Model metadata is unavailable for '${entry.provider}/${entry.modelId}'; using its configured definition.`
24
+ )
25
+ }
26
+ definition = defineLanguageModel(definition)
27
+ if (definition.providerId !== entry.provider || definition.modelId !== entry.modelId) {
28
+ throw new Error("[SixbServer] Model definition identity does not match its catalog entry.")
29
+ }
30
+ const gateway = entry.provider === "vercel-ai-gateway"
31
+ const publisherId = gateway ? entry.modelId.split("/")[0]! : entry.provider
32
+ const capabilities = definition.capabilities
33
+ const media = capabilities.inputMediaTypes
34
+ const input = ["text"]
35
+ for (const [kind, mime] of [
36
+ ["image", "image/"],
37
+ ["audio", "audio/"],
38
+ ["video", "video/"],
39
+ ["pdf", "application/pdf"],
40
+ ]) {
41
+ if (media === "any" || media?.some((type) => type.startsWith(mime!))) input.push(kind!)
42
+ }
43
+ return {
44
+ name: definition.name ?? entry.modelId,
45
+ ...(definition.description === undefined ? {} : { description: definition.description }),
46
+ publisher: { id: publisherId, name: publisherName(publisherId) },
47
+ ...(gateway ? { via: "AI Gateway" } : {}),
48
+ capabilities: {
49
+ input,
50
+ output: ["text"],
51
+ ...(media === undefined ? {} : { attachments: media === "any" || media.length > 0 }),
52
+ ...(capabilities.reasoning === undefined
53
+ ? {}
54
+ : { reasoning: capabilities.reasoning !== false }),
55
+ ...(capabilities.localTools === undefined ? {} : { tools: capabilities.localTools }),
56
+ ...(capabilities.nativeStructuredOutput === undefined
57
+ ? {}
58
+ : { structuredOutput: capabilities.nativeStructuredOutput }),
59
+ ...(definition.contextWindow === undefined
60
+ ? {}
61
+ : { contextWindowTokens: definition.contextWindow }),
62
+ },
63
+ reasoningLevels: reasoningLevels(definition),
64
+ }
65
+ }
66
+
67
+ function reasoningLevels(definition: LanguageModelDefinition): readonly ModelReasoningLevel[] {
68
+ const reasoning = definition.capabilities.reasoning
69
+ if (!reasoning) return []
70
+ return [
71
+ "provider-default",
72
+ ...(reasoning.canDisable ? ["none" as const] : []),
73
+ ...(reasoning.efforts ?? []),
74
+ ]
75
+ }
76
+
77
+ function publisherName(id: string): string {
78
+ const names: Readonly<Record<string, string>> = {
79
+ openai: "OpenAI",
80
+ anthropic: "Anthropic",
81
+ deepseek: "DeepSeek",
82
+ google: "Google",
83
+ xai: "xAI",
84
+ spacexai: "xAI",
85
+ zai: "Z.ai",
86
+ meta: "Meta",
87
+ moonshotai: "Moonshot AI",
88
+ nvidia: "NVIDIA",
89
+ }
90
+ return Object.hasOwn(names, id) ? names[id]! : id
91
+ }
@@ -1,7 +1,9 @@
1
1
  import { CSRF_HEADER_NAME } from "@sixb/core/internal/auth"
2
+ import { SHARED_ACCESS_GRANT_HEADER_NAME } from "../auth/shared-access"
2
3
 
3
4
  export const SIXB_CSRF_SECURITY_SCHEME_ID = "sixbCsrf"
4
5
  export const SIXB_BEARER_SECURITY_SCHEME_ID = "sixbBearer"
6
+ export const SIXB_SHARED_GRANT_SECURITY_SCHEME_ID = "sixbSharedGrant"
5
7
 
6
8
  export const SIXB_CSRF_SECURITY_REQUIREMENT = [
7
9
  {
@@ -20,12 +22,21 @@ export const SIXB_CSRF_OR_BEARER_SECURITY_REQUIREMENT = [
20
22
  ...SIXB_BEARER_SECURITY_REQUIREMENT,
21
23
  ]
22
24
 
25
+ export const SIXB_SHARED_READ_SECURITY_REQUIREMENT = {
26
+ [SIXB_SHARED_GRANT_SECURITY_SCHEME_ID]: [] as string[],
27
+ }
28
+
29
+ export const SIXB_SHARED_MUTATION_SECURITY_REQUIREMENT = {
30
+ [SIXB_SHARED_GRANT_SECURITY_SCHEME_ID]: [] as string[],
31
+ [SIXB_CSRF_SECURITY_SCHEME_ID]: [] as string[],
32
+ }
33
+
23
34
  export const SIXB_CSRF_SECURITY_SCHEME = {
24
35
  type: "apiKey",
25
36
  in: "header",
26
37
  name: CSRF_HEADER_NAME,
27
38
  description:
28
- "Required for authenticated mutating requests. Use the csrfToken returned by GET /api/auth/session.",
39
+ "Required for cookie-authenticated mutating requests. Use the csrfToken returned by the corresponding session endpoint.",
29
40
  } as const
30
41
 
31
42
  export const SIXB_BEARER_SECURITY_SCHEME = {
@@ -35,3 +46,11 @@ export const SIXB_BEARER_SECURITY_SCHEME = {
35
46
  description:
36
47
  "Use a Sixb personal access token or service-account token. Bearer tokens are accepted only on routes that explicitly document this scheme.",
37
48
  } as const
49
+
50
+ export const SIXB_SHARED_GRANT_SECURITY_SCHEME = {
51
+ type: "apiKey",
52
+ in: "header",
53
+ name: SHARED_ACCESS_GRANT_HEADER_NAME,
54
+ description:
55
+ "Selects the shared grant whose grant-specific HttpOnly session cookie must authenticate the request.",
56
+ } as const
@@ -159,6 +159,10 @@ export const OPENAPI_TAGS = {
159
159
  name: "Auth Service Accounts",
160
160
  description: "Service accounts and service-account access tokens",
161
161
  },
162
+ sharedAccess: {
163
+ name: "Shared Access",
164
+ description: "Scoped shared-access grant lifecycle",
165
+ },
162
166
  } as const
163
167
 
164
168
  export const OPENAPI_TAG_METADATA = Object.values(OPENAPI_TAGS).map(({ name, description }) => ({
@@ -1,5 +1,6 @@
1
1
  import type { SixbHostView } from "@sixb/core"
2
2
  import type { Elysia } from "elysia"
3
+ import type { SharedAccessBoundary } from "./auth/shared-access"
3
4
  import { registerActionRunRoutes } from "./routes/action-runs"
4
5
  import { registerActionRoutes } from "./routes/actions"
5
6
  import { registerAgentApiGatewayRoutes } from "./routes/agent-api-gateway"
@@ -23,6 +24,8 @@ import { registerPipelineRoutes } from "./routes/pipelines"
23
24
  import { registerProjectRoutes } from "./routes/project"
24
25
  import { registerProjectionRoutes } from "./routes/projections"
25
26
  import { registerRuleRoutes } from "./routes/rules"
27
+ import { registerShareGrantRoutes } from "./routes/share-grants"
28
+ import { registerSharedAccessRoutes } from "./routes/shared-access"
26
29
  import { registerStatusRoutes } from "./routes/status"
27
30
  import { registerSyncRoutes } from "./routes/syncs"
28
31
  import { registerTelemetryRoutes } from "./routes/telemetry"
@@ -31,6 +34,7 @@ import { registerWorkflowRoutes } from "./routes/workflows"
31
34
 
32
35
  export interface HttpRouteOptions {
33
36
  readonly connectorConnections: ConnectorConnectionRouteOptions
37
+ readonly sharedAccess: SharedAccessBoundary
34
38
  }
35
39
 
36
40
  export function registerHttpRoutes(app: Elysia, host: SixbHostView, options: HttpRouteOptions) {
@@ -46,6 +50,8 @@ export function registerHttpRoutes(app: Elysia, host: SixbHostView, options: Htt
46
50
  registerPipelineRoutes(app, host)
47
51
  registerWorkflowRoutes(app, host)
48
52
  registerRuleRoutes(app, host)
53
+ registerShareGrantRoutes(app, host)
54
+ registerSharedAccessRoutes(app, options.sharedAccess)
49
55
  registerOntologyRoutes(app, host)
50
56
  registerObjectRoutes(app, host)
51
57
  registerActionRoutes(app, host)
@@ -1,4 +1,4 @@
1
- import type { ActionDefinition, SixbHostView } from "@sixb/core"
1
+ import type { ActionDescriptor, SixbHostView } from "@sixb/core"
2
2
  import { schemaFieldsToJsonSchema } from "@sixb/core/internal/ontology"
3
3
  import type { Elysia } from "elysia"
4
4
  import { bearerSecurityRequirement } from "../auth/access-token-boundary"
@@ -15,13 +15,13 @@ import { ErrorResponseSchema } from "../schemas/common"
15
15
  import { handleRouteError } from "../utils/http"
16
16
 
17
17
  function serializeAction(
18
- action: ActionDefinition
18
+ action: ActionDescriptor
19
19
  ): ReturnType<typeof ActionCatalogItemSchema.parse> {
20
20
  return ActionCatalogItemSchema.parse({
21
21
  id: action.id,
22
22
  name: action.id,
23
23
  description: action.description,
24
- ...(action.binding.kind === "object" ? { objectTypeId: action.binding.objectType.id } : {}),
24
+ ...(action.binding.kind === "object" ? { objectTypeId: action.binding.objectTypeId } : {}),
25
25
  params: Object.entries(action.params).map(([id, config]) => ({
26
26
  id,
27
27
  name: id,
@@ -31,17 +31,12 @@ function serializeAction(
31
31
  description: config.description,
32
32
  semanticType: config.semanticType,
33
33
  })),
34
- phases: {
35
- validate: action.phases.validate.length > 0,
36
- writeback: action.phases.writeback !== undefined,
37
- edits: action.phases.edits !== undefined,
38
- effects: action.phases.effects !== undefined,
39
- },
34
+ phases: action.phases,
40
35
  })
41
36
  }
42
37
 
43
38
  function serializeActionDetail(
44
- action: ActionDefinition,
39
+ action: ActionDescriptor,
45
40
  host: SixbHostView
46
41
  ): ReturnType<typeof ActionDetailSchema.parse> {
47
42
  return ActionDetailSchema.parse({
@@ -1,15 +1,25 @@
1
- import type { AuthorizationContext, SixbHostView } from "@sixb/core"
1
+ import type { SixbHostView } from "@sixb/core"
2
2
  import { assertAgentExecutionRecord } from "@sixb/core/internal/agent-execution"
3
3
  import {
4
4
  AGENT_API_GATEWAY_PREFIX,
5
5
  AGENT_API_ROUTES,
6
+ type AgentExecutionAuthorization,
6
7
  isAllowedAgentApiRequest,
7
8
  isValidAgentApiGatewayCapability,
8
9
  resolveAgentExecutionAuthorization,
10
+ resolveInheritedAgentExecutionAuthorization,
9
11
  } from "@sixb/core/internal/agents"
10
12
  import { normalizeRoutePath, pathSegmentsFor } from "@sixb/core/internal/http"
13
+ import type { RequestExecutionAuthorization } from "@sixb/core/internal/request-execution"
14
+ import type {
15
+ AgentRunRecord,
16
+ AuthStorage,
17
+ ConversationAgentRunRecord,
18
+ ExecutionRecord,
19
+ WorkflowAgentNodeRunRecord,
20
+ } from "@sixb/core/storage"
11
21
  import type { Elysia } from "elysia"
12
- import { registerInternalRequestAuthState } from "../auth/scope"
22
+ import { type InternalRequestAuthState, registerInternalRequestAuthState } from "../auth/scope"
13
23
  import { DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES } from "./files"
14
24
 
15
25
  const MAX_AGENT_API_BODY_BYTES = 1_000_000
@@ -78,11 +88,16 @@ async function handleAgentApiGatewayRequest(input: {
78
88
  return authState
79
89
  }
80
90
  if (
81
- authState.agentExecution.kind === "workflow" &&
91
+ authState.agentExecution.kind !== "conversation" &&
82
92
  input.request.method === "POST" &&
83
93
  matchesWorkflowRunStart(upstreamPath)
84
94
  ) {
85
- return jsonError(409, "Workflow agent nodes cannot start another workflow run.")
95
+ return jsonError(
96
+ 409,
97
+ authState.agentExecution.kind === "workflow"
98
+ ? "Workflow agent nodes cannot start another workflow run."
99
+ : "Child agents cannot start a workflow run."
100
+ )
86
101
  }
87
102
 
88
103
  let body: ArrayBuffer | undefined
@@ -128,32 +143,26 @@ async function resolveAgentRunAuthState(
128
143
  return jsonError(501, "Agent API gateway is not configured for this runtime.")
129
144
  }
130
145
 
131
- const conversationalRun = await agentStorage?.runs.getById({
146
+ const storedAgentRun = await agentStorage?.runs.getById({
132
147
  projectId: host.id,
133
148
  id: input.runId,
134
149
  })
135
- const workflowRun = conversationalRun
150
+ const workflowRun = storedAgentRun
136
151
  ? null
137
152
  : await workflowRuns?.agentNodes.getByNodeRunId({
138
153
  projectId: host.id,
139
154
  nodeRunId: input.runId,
140
155
  })
141
- const run = conversationalRun ?? workflowRun
142
- const agentExecution = conversationalRun
143
- ? ({ kind: "conversation", runId: conversationalRun.id } as const)
144
- : workflowRun
145
- ? ({ kind: "workflow", nodeRunId: workflowRun.nodeRunId } as const)
146
- : null
156
+ const runState = toGatewayRunState(storedAgentRun ?? null, workflowRun ?? null)
147
157
  if (
148
- !run ||
149
- !agentExecution ||
150
- run.status !== "running" ||
151
- !run.execution ||
152
- run.execution.queueLeaseExpiresAt.getTime() <= Date.now() ||
158
+ !runState ||
159
+ runState.run.status !== "running" ||
160
+ !runState.run.execution ||
161
+ runState.run.execution.queueLeaseExpiresAt.getTime() <= Date.now() ||
153
162
  !isValidAgentApiGatewayCapability({
154
163
  projectId: host.id,
155
164
  runId: input.runId,
156
- executionToken: run.execution.token,
165
+ executionToken: runState.run.execution.token,
157
166
  capability: input.capability,
158
167
  })
159
168
  ) {
@@ -163,8 +172,8 @@ async function resolveAgentRunAuthState(
163
172
  if (!host.auth.isEnabled()) {
164
173
  return {
165
174
  authorization: { type: "disabled" as const },
166
- agentExecution,
167
- ...(conversationalRun ? { agentRun: conversationalRun } : {}),
175
+ agentExecution: runState.agentExecution,
176
+ ...(runState.agentRun === undefined ? {} : { agentRun: runState.agentRun }),
168
177
  }
169
178
  }
170
179
 
@@ -174,36 +183,126 @@ async function resolveAgentRunAuthState(
174
183
  }
175
184
  const execution = await host.storage.executions.getById({
176
185
  projectId: host.id,
177
- id: run.executionId,
186
+ id: runState.run.executionId,
178
187
  })
179
188
  if (!execution) {
180
189
  return jsonError(403, "Agent run execution is not available.")
181
190
  }
182
191
 
183
- let authz: AuthorizationContext
192
+ let authorization: RequestExecutionAuthorization
184
193
  try {
185
- const resolved = await resolveAgentExecutionAuthorization({
186
- auth,
187
- projectId: host.id,
188
- agentId: run.agentId,
189
- authorizationRef: execution.authorizationRef,
190
- security: host.definitions.security,
194
+ authorization = await resolveGatewayRunAuthorization({ host, auth, runState, execution })
195
+ } catch {
196
+ return jsonError(403, "Agent run execution authority is not valid.")
197
+ }
198
+
199
+ return {
200
+ authorization,
201
+ agentExecution: runState.agentExecution,
202
+ ...(runState.agentRun === undefined ? {} : { agentRun: runState.agentRun }),
203
+ }
204
+ }
205
+
206
+ type GatewayRunState = {
207
+ readonly run: AgentRunRecord | WorkflowAgentNodeRunRecord
208
+ readonly runId: string
209
+ readonly agentExecution: NonNullable<InternalRequestAuthState["agentExecution"]>
210
+ readonly agentRun?: ConversationAgentRunRecord
211
+ } & (
212
+ | { readonly authority: "inherited" }
213
+ | { readonly authority: "managed"; readonly actorId: string }
214
+ )
215
+
216
+ function toGatewayRunState(
217
+ storedRun: AgentRunRecord | null,
218
+ workflowRun: WorkflowAgentNodeRunRecord | null
219
+ ): GatewayRunState | null {
220
+ if (storedRun?.kind === "subagent") {
221
+ return {
222
+ run: storedRun,
223
+ runId: storedRun.id,
224
+ agentExecution: {
225
+ kind: "subagent",
226
+ runId: storedRun.id,
227
+ parentRunId: storedRun.parentRunId,
228
+ },
229
+ authority: "inherited",
230
+ }
231
+ }
232
+
233
+ if (storedRun?.kind === "conversation") {
234
+ const common = {
235
+ run: storedRun,
236
+ runId: storedRun.id,
237
+ agentExecution: { kind: "conversation", runId: storedRun.id } as const,
238
+ agentRun: storedRun,
239
+ }
240
+ return { ...common, authority: "inherited" }
241
+ }
242
+
243
+ if (!workflowRun) return null
244
+ const common = {
245
+ run: workflowRun,
246
+ runId: workflowRun.nodeRunId,
247
+ agentExecution: { kind: "workflow", nodeRunId: workflowRun.nodeRunId } as const,
248
+ }
249
+ return { ...common, authority: "managed", actorId: workflowRun.actorId }
250
+ }
251
+
252
+ async function resolveGatewayRunAuthorization(input: {
253
+ readonly host: SixbHostView
254
+ readonly auth: AuthStorage
255
+ readonly runState: GatewayRunState
256
+ readonly execution: ExecutionRecord
257
+ }): Promise<RequestExecutionAuthorization> {
258
+ if (input.runState.authority === "inherited") {
259
+ const resolved = await resolveInheritedAgentExecutionAuthorization({
260
+ auth: input.auth,
261
+ projectId: input.host.id,
262
+ authorizationRef: input.execution.authorizationRef,
263
+ security: input.host.definitions.security,
191
264
  })
265
+ const authorization = inheritedRequestAuthorization(resolved, input.execution.authorizationRef)
192
266
  assertAgentExecutionRecord({
193
- execution,
194
- agentId: run.agentId,
195
- runId: input.runId,
196
- authorization: resolved.context,
267
+ execution: input.execution,
268
+ runId: input.runState.runId,
269
+ authorization,
197
270
  })
198
- authz = resolved.context
199
- } catch {
200
- return jsonError(403, "Agent run execution authority is not valid.")
271
+ return authorization
201
272
  }
202
273
 
274
+ const resolved = await resolveAgentExecutionAuthorization({
275
+ auth: input.auth,
276
+ projectId: input.host.id,
277
+ actorId: input.runState.actorId,
278
+ authorizationRef: input.execution.authorizationRef,
279
+ security: input.host.definitions.security,
280
+ })
281
+ const authorization = { type: "principal", context: resolved.context } as const
282
+ assertAgentExecutionRecord({
283
+ execution: input.execution,
284
+ actorId: input.runState.actorId,
285
+ runId: input.runState.runId,
286
+ authorization,
287
+ })
288
+ return authorization
289
+ }
290
+
291
+ function inheritedRequestAuthorization(
292
+ resolved: AgentExecutionAuthorization,
293
+ authorizationRef: ExecutionRecord["authorizationRef"]
294
+ ): Extract<RequestExecutionAuthorization, { readonly type: "principal" | "disabled" }> {
295
+ if (
296
+ resolved.type !== "principal" ||
297
+ authorizationRef.type !== "principal" ||
298
+ authorizationRef.credential === undefined
299
+ ) {
300
+ return resolved
301
+ }
203
302
  return {
204
- authorization: { type: "principal" as const, context: authz },
205
- agentExecution,
206
- ...(conversationalRun ? { agentRun: conversationalRun } : {}),
303
+ type: "principal",
304
+ context: resolved.context,
305
+ credential: authorizationRef.credential,
207
306
  }
208
307
  }
209
308