@sixb/server 0.1.21 → 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 (165) hide show
  1. package/dist/artifacts/frame.d.ts +5 -0
  2. package/dist/artifacts/frame.d.ts.map +1 -1
  3. package/dist/auth/browser-origin.d.ts +5 -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/index.js +10093 -7553
  13. package/dist/index.js.map +51 -39
  14. package/dist/models/display.d.ts +27 -0
  15. package/dist/models/display.d.ts.map +1 -1
  16. package/dist/openapi/components.d.ts +14 -0
  17. package/dist/openapi/components.d.ts.map +1 -0
  18. package/dist/openapi/tags.d.ts +14 -2
  19. package/dist/openapi/tags.d.ts.map +1 -1
  20. package/dist/registerRoutes.d.ts.map +1 -1
  21. package/dist/routes/actions.d.ts +5 -5
  22. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  23. package/dist/routes/agent-approval-gate.d.ts +27 -0
  24. package/dist/routes/agent-approval-gate.d.ts.map +1 -0
  25. package/dist/routes/agent-approvals.d.ts +599 -0
  26. package/dist/routes/agent-approvals.d.ts.map +1 -0
  27. package/dist/routes/agent-children.d.ts +318 -0
  28. package/dist/routes/agent-children.d.ts.map +1 -0
  29. package/dist/routes/agent-memory.d.ts +267 -0
  30. package/dist/routes/agent-memory.d.ts.map +1 -0
  31. package/dist/routes/agents.d.ts +999 -80
  32. package/dist/routes/agents.d.ts.map +1 -1
  33. package/dist/routes/ai-accounting.d.ts.map +1 -1
  34. package/dist/routes/artifact-frames.d.ts +3 -3
  35. package/dist/routes/artifact-frames.d.ts.map +1 -1
  36. package/dist/routes/artifacts.d.ts +790 -134
  37. package/dist/routes/artifacts.d.ts.map +1 -1
  38. package/dist/routes/auth.d.ts +116 -10
  39. package/dist/routes/auth.d.ts.map +1 -1
  40. package/dist/routes/connector-connection-runs.d.ts +50 -50
  41. package/dist/routes/connectors.d.ts +2 -2
  42. package/dist/routes/datasets.d.ts +20 -20
  43. package/dist/routes/events.d.ts +4 -4
  44. package/dist/routes/files.d.ts +14 -14
  45. package/dist/routes/files.d.ts.map +1 -1
  46. package/dist/routes/links.d.ts +2 -2
  47. package/dist/routes/logs.d.ts +5 -5
  48. package/dist/routes/model-calls.d.ts +155 -0
  49. package/dist/routes/model-calls.d.ts.map +1 -0
  50. package/dist/routes/model-generations.d.ts +400 -0
  51. package/dist/routes/model-generations.d.ts.map +1 -0
  52. package/dist/routes/models.d.ts +434 -1
  53. package/dist/routes/models.d.ts.map +1 -1
  54. package/dist/routes/objects.d.ts +71 -40
  55. package/dist/routes/objects.d.ts.map +1 -1
  56. package/dist/routes/observed-agent-threads.d.ts +682 -0
  57. package/dist/routes/observed-agent-threads.d.ts.map +1 -0
  58. package/dist/routes/ontology.d.ts +66 -62
  59. package/dist/routes/ontology.d.ts.map +1 -1
  60. package/dist/routes/pipelines.d.ts +24 -24
  61. package/dist/routes/projections.d.ts +55 -55
  62. package/dist/routes/rules.d.ts +2 -2
  63. package/dist/routes/share-grants.d.ts +9 -9
  64. package/dist/routes/syncs.d.ts +46 -46
  65. package/dist/routes/users.d.ts +117 -0
  66. package/dist/routes/users.d.ts.map +1 -0
  67. package/dist/routes/webhook-runs.d.ts +1 -1
  68. package/dist/routes/workflows.d.ts +118 -52
  69. package/dist/routes/workflows.d.ts.map +1 -1
  70. package/dist/routes/ws/agents.d.ts +7 -2
  71. package/dist/routes/ws/agents.d.ts.map +1 -1
  72. package/dist/routes/ws/events.d.ts +6 -6
  73. package/dist/routes/ws/logs.d.ts +14 -14
  74. package/dist/schemas/actions.d.ts +15 -15
  75. package/dist/schemas/activity.d.ts +48 -28
  76. package/dist/schemas/activity.d.ts.map +1 -1
  77. package/dist/schemas/agent-approvals.d.ts +1091 -0
  78. package/dist/schemas/agent-approvals.d.ts.map +1 -0
  79. package/dist/schemas/agent-memory.d.ts +250 -0
  80. package/dist/schemas/agent-memory.d.ts.map +1 -0
  81. package/dist/schemas/agents.d.ts +5442 -369
  82. package/dist/schemas/agents.d.ts.map +1 -1
  83. package/dist/schemas/ai-accounting.d.ts +1290 -411
  84. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  85. package/dist/schemas/ai-limits.d.ts +10 -10
  86. package/dist/schemas/ai-usage.d.ts +12 -0
  87. package/dist/schemas/ai-usage.d.ts.map +1 -1
  88. package/dist/schemas/artifacts.d.ts +650 -98
  89. package/dist/schemas/artifacts.d.ts.map +1 -1
  90. package/dist/schemas/auth.d.ts +119 -46
  91. package/dist/schemas/auth.d.ts.map +1 -1
  92. package/dist/schemas/connectors.d.ts +22 -22
  93. package/dist/schemas/datasets.d.ts +98 -98
  94. package/dist/schemas/event-payloads.d.ts +6 -6
  95. package/dist/schemas/events.d.ts +26 -26
  96. package/dist/schemas/events.d.ts.map +1 -1
  97. package/dist/schemas/files.d.ts +24 -24
  98. package/dist/schemas/links.d.ts +2 -2
  99. package/dist/schemas/logs.d.ts +32 -32
  100. package/dist/schemas/models.d.ts +8889 -10
  101. package/dist/schemas/models.d.ts.map +1 -1
  102. package/dist/schemas/objects.d.ts +48 -12
  103. package/dist/schemas/objects.d.ts.map +1 -1
  104. package/dist/schemas/ontology.d.ts +127 -104
  105. package/dist/schemas/ontology.d.ts.map +1 -1
  106. package/dist/schemas/pipelines.d.ts +132 -132
  107. package/dist/schemas/projections.d.ts +314 -314
  108. package/dist/schemas/rules.d.ts +4 -4
  109. package/dist/schemas/share-grants.d.ts +30 -30
  110. package/dist/schemas/syncs.d.ts +49 -49
  111. package/dist/schemas/users.d.ts +72 -0
  112. package/dist/schemas/users.d.ts.map +1 -0
  113. package/dist/schemas/webhook-runs.d.ts +6 -6
  114. package/dist/schemas/workflows.d.ts +701 -186
  115. package/dist/schemas/workflows.d.ts.map +1 -1
  116. package/dist/server.d.ts +1 -0
  117. package/dist/server.d.ts.map +1 -1
  118. package/dist/utils/http.d.ts.map +1 -1
  119. package/package.json +7 -7
  120. package/src/artifacts/frame.ts +6 -1
  121. package/src/auth/browser-origin.ts +8 -3
  122. package/src/auth/experience.ts +1 -1
  123. package/src/auth/guard.ts +2 -2
  124. package/src/auth/public-routes.ts +6 -0
  125. package/src/auth/responses.ts +7 -6
  126. package/src/auth/scope.ts +32 -3
  127. package/src/models/display.ts +61 -16
  128. package/src/openapi/components.ts +54 -0
  129. package/src/openapi/tags.ts +12 -0
  130. package/src/registerRoutes.ts +14 -0
  131. package/src/routes/agent-api-gateway.ts +115 -91
  132. package/src/routes/agent-approval-gate.ts +213 -0
  133. package/src/routes/agent-approvals.ts +299 -0
  134. package/src/routes/agent-children.ts +209 -0
  135. package/src/routes/agent-memory.ts +210 -0
  136. package/src/routes/agents.ts +363 -142
  137. package/src/routes/ai-accounting.ts +4 -0
  138. package/src/routes/artifact-frames.ts +14 -8
  139. package/src/routes/artifacts.ts +297 -22
  140. package/src/routes/auth.ts +306 -13
  141. package/src/routes/files.ts +6 -7
  142. package/src/routes/model-calls.ts +120 -0
  143. package/src/routes/model-generations.ts +245 -0
  144. package/src/routes/models.ts +116 -9
  145. package/src/routes/objects.ts +55 -61
  146. package/src/routes/observed-agent-threads.ts +253 -0
  147. package/src/routes/ontology.ts +1 -0
  148. package/src/routes/users.ts +73 -0
  149. package/src/routes/workflows.ts +6 -9
  150. package/src/routes/ws/agents.ts +10 -5
  151. package/src/schemas/activity.ts +2 -0
  152. package/src/schemas/agent-approvals.ts +129 -0
  153. package/src/schemas/agent-memory.ts +96 -0
  154. package/src/schemas/agents.ts +239 -0
  155. package/src/schemas/ai-accounting.ts +40 -4
  156. package/src/schemas/ai-usage.ts +10 -0
  157. package/src/schemas/artifacts.ts +91 -3
  158. package/src/schemas/auth.ts +25 -0
  159. package/src/schemas/models.ts +197 -1
  160. package/src/schemas/objects.ts +181 -0
  161. package/src/schemas/ontology.ts +1 -0
  162. package/src/schemas/users.ts +24 -0
  163. package/src/schemas/workflows.ts +2 -0
  164. package/src/server.ts +9 -10
  165. package/src/utils/http.ts +2 -0
@@ -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 (
@@ -0,0 +1,213 @@
1
+ import type { SixbHostView } from "@sixb/core"
2
+ import { bindAgentGatewayRequestExecution } from "@sixb/core/internal/agent-execution"
3
+ import {
4
+ agentRunApprovalMode,
5
+ announceAgentApprovals,
6
+ approvalCallSummary,
7
+ findAgentApiRoute,
8
+ holdAgentApprovalCall,
9
+ } from "@sixb/core/internal/agents"
10
+ import { pathSegmentsFor } from "@sixb/core/internal/http"
11
+ import {
12
+ prepareBoundActionRequest,
13
+ prepareBoundWorkflowRequest,
14
+ } from "@sixb/core/internal/request-execution"
15
+ import {
16
+ type AgentApprovalCall,
17
+ type AgentApprovalRecord,
18
+ type AgentRunRecord,
19
+ AgentStorageError,
20
+ type WorkflowAgentNodeRunRecord,
21
+ } from "@sixb/core/storage"
22
+ import { ZodError, type z } from "zod"
23
+ import type { AgentGatewayRunExecution, RequestAuthState } from "../auth/scope"
24
+ import { RequestActionBodySchema } from "../schemas/actions"
25
+ import { RequestWorkflowRunBodySchema } from "../schemas/workflows"
26
+ import { handleRouteError } from "../utils/http"
27
+
28
+ /** What the gateway does with an Agent's call: forward it, or answer it itself. */
29
+ export type AgentApiGate =
30
+ | { readonly kind: "pass" }
31
+ | { readonly kind: "answer"; readonly response: Response }
32
+
33
+ export interface AgentApiGateInput {
34
+ readonly host: SixbHostView
35
+ readonly method: string
36
+ readonly upstreamPath: string
37
+ readonly body: Uint8Array | undefined
38
+ readonly run: AgentRunRecord | WorkflowAgentNodeRunRecord
39
+ readonly agentExecution: NonNullable<RequestAuthState["agentExecution"]>
40
+ readonly runExecution: AgentGatewayRunExecution
41
+ readonly signal: AbortSignal
42
+ }
43
+
44
+ /**
45
+ * Hold an action or a workflow start the turn's approval mode does not run. Core decides; this
46
+ * reads the call the way its route would, and answers for it. A call the route would refuse is
47
+ * refused here, before anything is held.
48
+ */
49
+ export async function gateAgentApiCall(input: AgentApiGateInput): Promise<AgentApiGate> {
50
+ const effect = findAgentApiRoute(input.method, input.upstreamPath)?.effect
51
+ if (effect !== "action" && effect !== "workflow") return { kind: "pass" }
52
+ // A workflow AI task runs on its own: it has no mode.
53
+ if (input.agentExecution.kind === "workflow" || !isAgentRun(input.run)) return { kind: "pass" }
54
+ if (agentRunApprovalMode(input.run) === "auto") return { kind: "pass" }
55
+
56
+ try {
57
+ const call = effect === "action" ? await prepareActionCall(input) : prepareWorkflowCall(input)
58
+ return await answerHold(input, input.run, call)
59
+ } catch (error) {
60
+ if (error instanceof GateRefusal) return { kind: "answer", response: error.response }
61
+ throw error
62
+ }
63
+ }
64
+
65
+ async function answerHold(
66
+ input: AgentApiGateInput,
67
+ run: AgentRunRecord,
68
+ call: AgentApprovalCall
69
+ ): Promise<AgentApiGate> {
70
+ const agents = input.host.storage.agents
71
+ if (!agents) throw refusal(501, "Agent approvals are not configured for this runtime.")
72
+
73
+ let hold: Awaited<ReturnType<typeof holdAgentApprovalCall>>
74
+ try {
75
+ hold = await holdAgentApprovalCall(agents, {
76
+ projectId: input.host.id,
77
+ run,
78
+ requestedBy: input.runExecution.execution.requestedBy,
79
+ call,
80
+ })
81
+ } catch (error) {
82
+ // The run ended, or its delivery changed, since the gateway checked its capability.
83
+ if (!(error instanceof AgentStorageError)) throw error
84
+ throw refusal(403, "Agent API gateway capability is not valid for this run.")
85
+ }
86
+
87
+ switch (hold.kind) {
88
+ case "pass":
89
+ return { kind: "pass" }
90
+ case "held":
91
+ // Announced on every answer: the feed keeps one record per change.
92
+ await announceAgentApprovals(input.host.broker, [hold.approval])
93
+ return {
94
+ kind: "answer",
95
+ response: Response.json(heldCallBody(hold.approval), { status: 202 }),
96
+ }
97
+ case "denied":
98
+ throw refusal(403, "The user denied this request. It did not run.")
99
+ case "conflict":
100
+ throw refusal(
101
+ 409,
102
+ `Run id '${hold.approval.callKey}' already names another request in this conversation. Name a new run.`
103
+ )
104
+ }
105
+ }
106
+
107
+ function isAgentRun(run: AgentRunRecord | WorkflowAgentNodeRunRecord): run is AgentRunRecord {
108
+ return "kind" in run
109
+ }
110
+
111
+ /** The Action call as its route would run it: admitted, with its params normalized. */
112
+ async function prepareActionCall(input: AgentApiGateInput): Promise<AgentApprovalCall> {
113
+ const body = parseBody(input.body, RequestActionBodySchema)
114
+ const actionRunId = requiredRunId(body.runId)
115
+
116
+ try {
117
+ const prepared = await prepareBoundActionRequest(boundSixb(input), {
118
+ actionId: pathParam(input.upstreamPath),
119
+ ...(body.subject === undefined ? {} : { subject: body.subject }),
120
+ ...(body.params === undefined ? {} : { params: body.params }),
121
+ })
122
+ return { kind: "action", ...prepared, actionRunId }
123
+ } catch (error) {
124
+ throw routeRefusal(error)
125
+ }
126
+ }
127
+
128
+ /** The workflow start as its route would run it: admitted, with its input snapshotted. */
129
+ function prepareWorkflowCall(input: AgentApiGateInput): AgentApprovalCall {
130
+ const body = parseBody(input.body, RequestWorkflowRunBodySchema)
131
+ const workflowRunId = requiredRunId(body.runId)
132
+
133
+ try {
134
+ const prepared = prepareBoundWorkflowRequest(boundSixb(input), {
135
+ workflowId: pathParam(input.upstreamPath),
136
+ input: body.input ?? {},
137
+ })
138
+ return { kind: "workflow", ...prepared, workflowRunId }
139
+ } catch (error) {
140
+ throw routeRefusal(error)
141
+ }
142
+ }
143
+
144
+ function boundSixb(input: AgentApiGateInput): object {
145
+ return bindAgentGatewayRequestExecution(input.host, {
146
+ signal: input.signal,
147
+ ...input.runExecution,
148
+ })
149
+ }
150
+
151
+ /** The run id the call names is what keeps a repeated request to one approval and one run. */
152
+ function requiredRunId(runId: string | undefined): string {
153
+ if (runId !== undefined) return runId
154
+ throw refusal(
155
+ 400,
156
+ "This request needs the user's approval, so it must name its run: pass a non-empty runId."
157
+ )
158
+ }
159
+
160
+ /** `/api/actions/:actionId` and `/api/workflows/:workflowId/runs` name their target third. */
161
+ function pathParam(upstreamPath: string): string {
162
+ const segment = pathSegmentsFor(upstreamPath)[2] ?? ""
163
+ try {
164
+ return decodeURIComponent(segment)
165
+ } catch {
166
+ return segment
167
+ }
168
+ }
169
+
170
+ /** Parsed with the route's own schema, so the gate reads the body the route would. */
171
+ function parseBody<TSchema extends z.ZodTypeAny>(
172
+ body: Uint8Array | undefined,
173
+ schema: TSchema
174
+ ): z.output<TSchema> {
175
+ try {
176
+ const text = body && body.byteLength > 0 ? new TextDecoder().decode(body) : "{}"
177
+ return schema.parse(JSON.parse(text))
178
+ } catch (error) {
179
+ if (error instanceof SyntaxError) throw refusal(400, "The request body must be valid JSON.")
180
+ if (error instanceof ZodError) throw refusal(400, "The request body is not valid.")
181
+ throw error
182
+ }
183
+ }
184
+
185
+ /** The gate answers for the call itself: it never reaches its route. */
186
+ class GateRefusal extends Error {
187
+ constructor(readonly response: Response) {
188
+ super("[SixbServer] The agent API gateway answered the call itself.")
189
+ }
190
+ }
191
+
192
+ function refusal(status: number, message: string): GateRefusal {
193
+ return new GateRefusal(Response.json({ error: message }, { status }))
194
+ }
195
+
196
+ /** A call the route would refuse is answered as the route would answer it. */
197
+ function routeRefusal(error: unknown): GateRefusal {
198
+ const set: { status?: number | string } = {}
199
+ const body = handleRouteError(error, set)
200
+ return new GateRefusal(
201
+ Response.json(body, { status: typeof set.status === "number" ? set.status : 500 })
202
+ )
203
+ }
204
+
205
+ /** What the CLI prints for a held call: the model reads it and ends its turn. */
206
+ function heldCallBody(approval: AgentApprovalRecord) {
207
+ return {
208
+ status: "awaiting_approval",
209
+ approval: { id: approval.id, ...approvalCallSummary(approval.call) },
210
+ message:
211
+ "The user approves or denies this in the conversation. Do not retry it or ask in text; end your turn.",
212
+ } as const
213
+ }