@sixb/server 0.1.24 → 0.1.26
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.
- package/dist/auth/public-routes.d.ts.map +1 -1
- package/dist/auth/run-token.d.ts +28 -0
- package/dist/auth/run-token.d.ts.map +1 -0
- package/dist/auth/scope.d.ts +11 -13
- package/dist/auth/scope.d.ts.map +1 -1
- package/dist/index.js +3500 -2989
- package/dist/index.js.map +30 -28
- package/dist/registerRoutes.d.ts.map +1 -1
- package/dist/routes/agent-approval-gate.d.ts +7 -4
- package/dist/routes/agent-approval-gate.d.ts.map +1 -1
- package/dist/routes/agent-approvals.d.ts +4 -1
- package/dist/routes/agent-approvals.d.ts.map +1 -1
- package/dist/routes/agent-computers.d.ts +134 -0
- package/dist/routes/agent-computers.d.ts.map +1 -0
- package/dist/routes/agent-runners.d.ts +74 -0
- package/dist/routes/agent-runners.d.ts.map +1 -0
- package/dist/routes/agents.d.ts +28 -0
- package/dist/routes/agents.d.ts.map +1 -1
- package/dist/routes/artifacts.d.ts +5 -28
- package/dist/routes/artifacts.d.ts.map +1 -1
- package/dist/routes/auth.d.ts +1 -1
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/datasets.d.ts.map +1 -1
- package/dist/routes/observed-agent-threads.d.ts +3 -0
- package/dist/routes/observed-agent-threads.d.ts.map +1 -1
- package/dist/routes/pipelines.d.ts.map +1 -1
- package/dist/routes/projections.d.ts +2 -0
- package/dist/routes/projections.d.ts.map +1 -1
- package/dist/routes/shared-access.d.ts +2 -2
- package/dist/routes/syncs.d.ts +34 -34
- package/dist/routes/syncs.d.ts.map +1 -1
- package/dist/routes/users.d.ts +1 -0
- package/dist/routes/users.d.ts.map +1 -1
- package/dist/routes/workflows.d.ts +4 -4
- package/dist/schemas/agents.d.ts +79 -1
- package/dist/schemas/agents.d.ts.map +1 -1
- package/dist/schemas/auth.d.ts +2 -2
- package/dist/schemas/projections.d.ts +14 -0
- package/dist/schemas/projections.d.ts.map +1 -1
- package/dist/schemas/shared-access.d.ts +2 -2
- package/dist/schemas/syncs.d.ts +24 -24
- package/dist/schemas/users.d.ts +8 -0
- package/dist/schemas/users.d.ts.map +1 -1
- package/dist/server.d.ts +1 -0
- package/dist/server.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/auth/public-routes.ts +0 -6
- package/src/auth/run-token.ts +327 -0
- package/src/auth/scope.ts +16 -37
- package/src/registerRoutes.ts +4 -2
- package/src/routes/agent-approval-gate.ts +40 -14
- package/src/routes/agent-approvals.ts +1 -1
- package/src/routes/agent-computers.ts +126 -0
- package/src/routes/agent-runners.ts +181 -0
- package/src/routes/agents.ts +7 -2
- package/src/routes/artifacts.ts +55 -11
- package/src/routes/auth.ts +391 -37
- package/src/routes/datasets.ts +5 -0
- package/src/routes/pipelines.ts +5 -0
- package/src/routes/syncs.ts +4 -0
- package/src/routes/users.ts +15 -2
- package/src/schemas/agents.ts +16 -1
- package/src/schemas/artifacts.ts +1 -1
- package/src/schemas/projections.ts +2 -0
- package/src/schemas/users.ts +6 -0
- package/src/server.ts +35 -13
- package/dist/routes/agent-api-gateway.d.ts +0 -4
- package/dist/routes/agent-api-gateway.d.ts.map +0 -1
- package/src/routes/agent-api-gateway.ts +0 -404
package/src/schemas/agents.ts
CHANGED
|
@@ -109,6 +109,8 @@ export const CreateAgentThreadBodySchema = z
|
|
|
109
109
|
title: z.string().trim().min(1).optional(),
|
|
110
110
|
threadId: z.string().trim().min(1).optional(),
|
|
111
111
|
sandbox: z.record(z.string(), JsonValueSchema).optional(),
|
|
112
|
+
/** Run its turns on your computer, which claims them, instead of in the cloud. */
|
|
113
|
+
runsOn: z.literal("computer").optional(),
|
|
112
114
|
})
|
|
113
115
|
.strict()
|
|
114
116
|
|
|
@@ -151,6 +153,10 @@ export const AgentThreadSchema = z.object({
|
|
|
151
153
|
participants: z.array(AgentThreadParticipantSchema),
|
|
152
154
|
title: z.string().optional(),
|
|
153
155
|
sandboxParams: z.record(z.string(), JsonValueSchema).optional(),
|
|
156
|
+
/** Its turns run on its owner's computer; absent, in the cloud. */
|
|
157
|
+
runsOn: z.literal("computer").optional(),
|
|
158
|
+
/** Which of its owner's computers runs it; absent until one claims its first turn. */
|
|
159
|
+
computerId: z.string().optional(),
|
|
154
160
|
status: AgentThreadStatusSchema,
|
|
155
161
|
activeRunId: z.string().nullable(),
|
|
156
162
|
lastMessageAt: z.string().optional(),
|
|
@@ -176,6 +182,13 @@ export const CreateAgentThreadResponseSchema = z.object({
|
|
|
176
182
|
thread: AgentThreadSchema,
|
|
177
183
|
})
|
|
178
184
|
|
|
185
|
+
export const MoveAgentThreadToComputerBodySchema = z
|
|
186
|
+
.object({
|
|
187
|
+
/** The id `sixb` keeps for the computer, beside its sign-in. */
|
|
188
|
+
computerId: z.string().trim().min(1).max(200),
|
|
189
|
+
})
|
|
190
|
+
.strict()
|
|
191
|
+
|
|
179
192
|
export const AddAgentThreadParticipantsBodySchema = z
|
|
180
193
|
.object({
|
|
181
194
|
/**
|
|
@@ -349,7 +362,7 @@ export const AgentMessageListResponseSchema = z.object({
|
|
|
349
362
|
|
|
350
363
|
export const PostAgentMessageBodySchema = z
|
|
351
364
|
.object({
|
|
352
|
-
/** Required unless `continue` is set. */
|
|
365
|
+
/** Required unless `continue` is set or `attachments` are the whole message. */
|
|
353
366
|
text: z.string().trim().min(1).optional(),
|
|
354
367
|
/** Continue the previous answer after it reached the turn limit, without text of its own. */
|
|
355
368
|
continue: z.literal(true).optional(),
|
|
@@ -403,6 +416,8 @@ export const AgentRunSchema = z.object({
|
|
|
403
416
|
reasoning: ModelReasoningSchema.optional(),
|
|
404
417
|
/** What the turn could change without asking. Absent on turns from before approval modes. */
|
|
405
418
|
approvalMode: AgentApprovalModeSchema.optional(),
|
|
419
|
+
/** Its owner's computer claims it; absent, the cloud runs it. */
|
|
420
|
+
runsOn: z.literal("computer").optional(),
|
|
406
421
|
modelId: z.string().optional(),
|
|
407
422
|
/**
|
|
408
423
|
* `awaiting_approval`: the turn succeeded and paused on calls waiting for its requester. It stays
|
package/src/schemas/artifacts.ts
CHANGED
|
@@ -237,7 +237,7 @@ export const ArtifactErrorResponseSchema = ErrorResponseSchema.extend({
|
|
|
237
237
|
.string()
|
|
238
238
|
.optional()
|
|
239
239
|
.describe(
|
|
240
|
-
"Stable machine-readable failure code: artifact_not_found, artifact_kind_mismatch, artifact_moved, invalid_artifact, invalid_state, state_full, not_allowed, not_shared (it exists but no conversation you read shares it), read_only (you observe the conversation that shares it), query_not_found, query_invalid (the ontology no longer admits the query), or storage_unavailable."
|
|
240
|
+
"Stable machine-readable failure code: artifact_not_found, artifact_kind_mismatch, artifact_moved, invalid_artifact, invalid_state, state_full, not_allowed, not_shared (it exists but no conversation you read shares it), read_only (you observe the conversation that shares it), query_not_found, query_invalid (the ontology no longer admits the query), execution_lost (a run token's run ended or moved to another runner), or storage_unavailable."
|
|
241
241
|
),
|
|
242
242
|
latest: z
|
|
243
243
|
.object({ version: z.number().int(), author: PrincipalSchema })
|
|
@@ -96,6 +96,8 @@ export const ObjectProjectionSchema = z.object({
|
|
|
96
96
|
objectTypeId: z.string(),
|
|
97
97
|
datasetId: z.string(),
|
|
98
98
|
properties: z.record(z.string()),
|
|
99
|
+
/** The `ref.user()` properties whose column holds a member's email. */
|
|
100
|
+
users: z.record(z.literal("email")).optional(),
|
|
99
101
|
links: z.record(ForeignKeyDescriptorSchema),
|
|
100
102
|
conflictResolution: SourceEditConflictResolutionSchema,
|
|
101
103
|
latestRun: ProjectionRunSchema.nullable(),
|
package/src/schemas/users.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { UserProfileSchema } from "./auth"
|
|
|
3
3
|
|
|
4
4
|
export const MAX_USERS_PAGE_LIMIT = 200
|
|
5
5
|
export const MAX_USERS_SEARCH_LENGTH = 200
|
|
6
|
+
export const MAX_USER_EMAIL_LENGTH = 320
|
|
6
7
|
|
|
7
8
|
export const ListUsersQuerySchema = z.object({
|
|
8
9
|
/** Which members to list. Defaults to `active`. */
|
|
@@ -11,6 +12,11 @@ export const ListUsersQuerySchema = z.object({
|
|
|
11
12
|
search: z.string().max(MAX_USERS_SEARCH_LENGTH).optional(),
|
|
12
13
|
limit: z.coerce.number().int().min(1).max(MAX_USERS_PAGE_LIMIT).optional(),
|
|
13
14
|
offset: z.coerce.number().int().min(0).optional(),
|
|
15
|
+
/**
|
|
16
|
+
* The member with exactly this email, ignoring case, suspended or not: a page of at most one.
|
|
17
|
+
* Takes no other option.
|
|
18
|
+
*/
|
|
19
|
+
email: z.string().min(1).max(MAX_USER_EMAIL_LENGTH).optional(),
|
|
14
20
|
})
|
|
15
21
|
|
|
16
22
|
export const ListUsersResponseSchema = z.object({
|
package/src/server.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { cors } from "@elysiajs/cors"
|
|
2
2
|
import { openapi } from "@elysiajs/openapi"
|
|
3
3
|
import type { OntologyMaintenanceHandle, SixbHostView } from "@sixb/core"
|
|
4
|
-
import {
|
|
4
|
+
import { bindAgentRunRequestExecution } from "@sixb/core/internal/agent-execution"
|
|
5
5
|
import { ARTIFACT_FRAME_ROUTE_PREFIX } from "@sixb/core/internal/artifacts/frames"
|
|
6
6
|
import { CSRF_HEADER_NAME, setRequestClientAddress } from "@sixb/core/internal/auth"
|
|
7
7
|
import { bindRequestExecution } from "@sixb/core/internal/request-execution"
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "./auth/csrf"
|
|
34
34
|
import type { SixbAuthExperienceOptions } from "./auth/experience"
|
|
35
35
|
import { ServerAuthGuard } from "./auth/guard"
|
|
36
|
-
import {
|
|
36
|
+
import { type RunTokenDecision, requestRunToken, resolveRunTokenRequest } from "./auth/run-token"
|
|
37
37
|
import { SESSION_ACTIVITY_HEADER_NAME } from "./auth/session-activity"
|
|
38
38
|
import { createSessionRenewalCookieHeaders } from "./auth/session-cookies"
|
|
39
39
|
import {
|
|
@@ -55,6 +55,7 @@ import {
|
|
|
55
55
|
} from "./openapi/security"
|
|
56
56
|
import { OPENAPI_TAG_METADATA } from "./openapi/tags"
|
|
57
57
|
import { registerHttpRoutes } from "./registerRoutes"
|
|
58
|
+
import { agentRunSessionHandler, startLapsedRunSweeper } from "./routes/agent-runners"
|
|
58
59
|
import { registerAuthRoutes } from "./routes/auth"
|
|
59
60
|
import { DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES } from "./routes/files"
|
|
60
61
|
import { registerWebhookRoutes } from "./routes/webhooks"
|
|
@@ -100,6 +101,7 @@ export class SixbServer {
|
|
|
100
101
|
private app: SixbApp | null = null
|
|
101
102
|
private bunServer: ReturnType<typeof Bun.serve> | null = null
|
|
102
103
|
private maintenance: OntologyMaintenanceHandle | null = null
|
|
104
|
+
private stopSweeper: (() => void) | null = null
|
|
103
105
|
|
|
104
106
|
constructor(options: SixbServerOptions) {
|
|
105
107
|
this.hostRuntime = options.host
|
|
@@ -199,6 +201,9 @@ export class SixbServer {
|
|
|
199
201
|
throw new Error(`[SixbServer] Failed to listen on ${this.hostname}:${this.port}: ${message}`)
|
|
200
202
|
}
|
|
201
203
|
|
|
204
|
+
// A runner on a computer has no worker behind it: the API ends the runs it stops renewing.
|
|
205
|
+
this.stopSweeper = startLapsedRunSweeper(this.hostRuntime)
|
|
206
|
+
|
|
202
207
|
if (!this.quiet) {
|
|
203
208
|
const base = `http://${this.hostname}:${this.getPort()}`
|
|
204
209
|
console.log(`Sixb server running at ${base}`)
|
|
@@ -207,6 +212,8 @@ export class SixbServer {
|
|
|
207
212
|
}
|
|
208
213
|
|
|
209
214
|
async stop(): Promise<void> {
|
|
215
|
+
this.stopSweeper?.()
|
|
216
|
+
this.stopSweeper = null
|
|
210
217
|
if (this.bunServer) {
|
|
211
218
|
this.bunServer.stop(true)
|
|
212
219
|
this.bunServer = null
|
|
@@ -234,6 +241,7 @@ export function createSixbApi(server: SixbServer) {
|
|
|
234
241
|
Request,
|
|
235
242
|
Awaited<ReturnType<SharedAccessBoundary["resolveRequest"]>>
|
|
236
243
|
>()
|
|
244
|
+
const preparedRunToken = new WeakMap<Request, RunTokenDecision>()
|
|
237
245
|
guard.assertCanServeHttp({ production: process.env.NODE_ENV === "production" })
|
|
238
246
|
const apiBrowserPolicy = server.getApiBrowserPolicy()
|
|
239
247
|
|
|
@@ -261,7 +269,20 @@ export function createSixbApi(server: SixbServer) {
|
|
|
261
269
|
maxAge: 600,
|
|
262
270
|
})
|
|
263
271
|
)
|
|
272
|
+
// A runner's session requests, before anything parses them: a runner token speaks only there.
|
|
273
|
+
const serveRunnerSession = agentRunSessionHandler(host)
|
|
274
|
+
app.onRequest(async ({ request }) => (await serveRunnerSession(request)) ?? undefined)
|
|
275
|
+
app.onRequest(async ({ request }) => {
|
|
276
|
+
// An Agent's commands, as their run: decided before Elysia parses the body, which the approval
|
|
277
|
+
// gate reads from a copy. No session, share or cookie speaks for such a request.
|
|
278
|
+
const runToken = requestRunToken(request)
|
|
279
|
+
if (runToken === undefined) return undefined
|
|
280
|
+
const decision = await resolveRunTokenRequest({ host, request, token: runToken })
|
|
281
|
+
preparedRunToken.set(request, decision)
|
|
282
|
+
return decision.kind === "deny" ? decision.response : undefined
|
|
283
|
+
})
|
|
264
284
|
app.onRequest(async ({ request, set }) => {
|
|
285
|
+
if (preparedRunToken.has(request)) return undefined
|
|
265
286
|
// Resolve Share intent before Elysia parses route inputs. Otherwise an unsupported route or an
|
|
266
287
|
// invalid shared session could escape through a route-specific 4xx before this boundary ran.
|
|
267
288
|
// CORS is registered first so allowed app origins can read these generic boundary responses.
|
|
@@ -286,6 +307,18 @@ export function createSixbApi(server: SixbServer) {
|
|
|
286
307
|
// never choose between a principal SDK and the ambient runtime themselves.
|
|
287
308
|
app
|
|
288
309
|
.derive(async ({ request }) => {
|
|
310
|
+
const runToken = preparedRunToken.get(request)
|
|
311
|
+
preparedRunToken.delete(request)
|
|
312
|
+
if (runToken?.kind === "allow") {
|
|
313
|
+
const { runExecution, ...agentState } = runToken.state
|
|
314
|
+
return {
|
|
315
|
+
auth: { kind: "allow" as const, session: null },
|
|
316
|
+
sharedAccessCookies: null,
|
|
317
|
+
...agentState,
|
|
318
|
+
sixb: bindAgentRunRequestExecution(host, { signal: request.signal, ...runExecution }),
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
289
322
|
const shared =
|
|
290
323
|
preparedSharedAccess.get(request) ?? (await sharedAccess.resolveRequest(request))
|
|
291
324
|
preparedSharedAccess.delete(request)
|
|
@@ -315,17 +348,6 @@ export function createSixbApi(server: SixbServer) {
|
|
|
315
348
|
}
|
|
316
349
|
}
|
|
317
350
|
|
|
318
|
-
const internalAuthState = consumeInternalRequestAuthState(request)
|
|
319
|
-
if (internalAuthState) {
|
|
320
|
-
const { runExecution, ...agentState } = internalAuthState
|
|
321
|
-
return {
|
|
322
|
-
auth: { kind: "allow" as const, session: null },
|
|
323
|
-
sharedAccessCookies: null,
|
|
324
|
-
...agentState,
|
|
325
|
-
sixb: bindAgentGatewayRequestExecution(host, { signal: request.signal, ...runExecution }),
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
351
|
const auth = await guard.resolve(request)
|
|
330
352
|
if (auth.kind === "deny" || !auth.session?.authenticated) {
|
|
331
353
|
return {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-api-gateway.d.ts","sourceRoot":"","sources":["../../src/routes/agent-api-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAiB9C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAkBpC,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,QAuB5E"}
|
|
@@ -1,404 +0,0 @@
|
|
|
1
|
-
import type { SixbHostView } from "@sixb/core"
|
|
2
|
-
import {
|
|
3
|
-
AGENT_API_GATEWAY_PREFIX,
|
|
4
|
-
AGENT_API_ROUTES,
|
|
5
|
-
type AgentRunExecutionScope,
|
|
6
|
-
AgentRunScopeError,
|
|
7
|
-
isAllowedAgentApiRequest,
|
|
8
|
-
isValidAgentApiGatewayCapability,
|
|
9
|
-
resolveAgentRunExecutionScope,
|
|
10
|
-
} from "@sixb/core/internal/agents"
|
|
11
|
-
import { normalizeRoutePath, pathSegmentsFor } from "@sixb/core/internal/http"
|
|
12
|
-
import type {
|
|
13
|
-
AgentRunRecord,
|
|
14
|
-
ConversationAgentRunRecord,
|
|
15
|
-
SubagentRunRecord,
|
|
16
|
-
WorkflowAgentNodeRunRecord,
|
|
17
|
-
} from "@sixb/core/storage"
|
|
18
|
-
import type { Elysia } from "elysia"
|
|
19
|
-
import { type InternalRequestAuthState, registerInternalRequestAuthState } from "../auth/scope"
|
|
20
|
-
import { RequestBodyTooLargeError, readRequestBodyWithLimit } from "../utils/request-body"
|
|
21
|
-
import { gateAgentApiCall } from "./agent-approval-gate"
|
|
22
|
-
import { DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES } from "./files"
|
|
23
|
-
|
|
24
|
-
const MAX_AGENT_API_BODY_BYTES = 1_000_000
|
|
25
|
-
const HOP_BY_HOP_RESPONSE_HEADERS = new Set([
|
|
26
|
-
"connection",
|
|
27
|
-
"keep-alive",
|
|
28
|
-
"proxy-authenticate",
|
|
29
|
-
"proxy-authorization",
|
|
30
|
-
"te",
|
|
31
|
-
"trailer",
|
|
32
|
-
"transfer-encoding",
|
|
33
|
-
"upgrade",
|
|
34
|
-
])
|
|
35
|
-
|
|
36
|
-
export function registerAgentApiGatewayRoutes(app: Elysia, host: SixbHostView) {
|
|
37
|
-
for (const route of AGENT_API_ROUTES) {
|
|
38
|
-
const path = `${AGENT_API_GATEWAY_PREFIX}/:agentGatewayRunId/:agentGatewayCapability${route.path}`
|
|
39
|
-
const handler = async (context: AgentApiGatewayRouteContext) =>
|
|
40
|
-
handleAgentApiGatewayRequest({
|
|
41
|
-
host,
|
|
42
|
-
app,
|
|
43
|
-
request: context.request,
|
|
44
|
-
agentRunId: context.params.agentGatewayRunId ?? "",
|
|
45
|
-
capability: context.params.agentGatewayCapability ?? "",
|
|
46
|
-
})
|
|
47
|
-
|
|
48
|
-
if (route.method === "GET") {
|
|
49
|
-
app.get(path, handler, { detail: { hide: true } })
|
|
50
|
-
continue
|
|
51
|
-
}
|
|
52
|
-
if (route.method === "POST") {
|
|
53
|
-
app.post(path, handler, { detail: { hide: true } })
|
|
54
|
-
continue
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
throw new Error(`[SixbServer] Unsupported agent API gateway method '${route.method}'.`)
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
interface AgentApiGatewayRouteContext {
|
|
62
|
-
readonly request: Request
|
|
63
|
-
readonly params: Readonly<Record<string, string | undefined>>
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
async function handleAgentApiGatewayRequest(input: {
|
|
67
|
-
readonly host: SixbHostView
|
|
68
|
-
readonly app: Elysia
|
|
69
|
-
readonly request: Request
|
|
70
|
-
readonly agentRunId: string
|
|
71
|
-
readonly capability: string
|
|
72
|
-
}): Promise<Response> {
|
|
73
|
-
const sourceUrl = new URL(input.request.url)
|
|
74
|
-
const upstreamPath = gatewayUpstreamPath(sourceUrl.pathname)
|
|
75
|
-
if (!isAllowedAgentApiRequest(input.request.method, upstreamPath)) {
|
|
76
|
-
return jsonError(
|
|
77
|
-
403,
|
|
78
|
-
`Agent API gateway does not allow ${input.request.method} ${upstreamPath}.`
|
|
79
|
-
)
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const resolved = await resolveAgentRunAuthState(input.host, {
|
|
83
|
-
runId: input.agentRunId,
|
|
84
|
-
capability: input.capability,
|
|
85
|
-
})
|
|
86
|
-
if (resolved instanceof Response) {
|
|
87
|
-
return resolved
|
|
88
|
-
}
|
|
89
|
-
const { authState, run } = resolved
|
|
90
|
-
if (
|
|
91
|
-
authState.agentExecution.kind !== "conversation" &&
|
|
92
|
-
input.request.method === "POST" &&
|
|
93
|
-
matchesWorkflowRunStart(upstreamPath)
|
|
94
|
-
) {
|
|
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
|
-
)
|
|
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
|
-
}
|
|
134
|
-
|
|
135
|
-
let body: Uint8Array<ArrayBuffer> | undefined
|
|
136
|
-
try {
|
|
137
|
-
body = await readGatewayRequestBody(input.request, upstreamPath)
|
|
138
|
-
} catch (error) {
|
|
139
|
-
if (error instanceof RequestBodyTooLargeError) {
|
|
140
|
-
return jsonError(413, error.message)
|
|
141
|
-
}
|
|
142
|
-
throw error
|
|
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
|
-
|
|
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.
|
|
161
|
-
const internalRequest = new Request(internalUrl, {
|
|
162
|
-
method: input.request.method,
|
|
163
|
-
headers: forwardedRequestHeaders(input.request.headers),
|
|
164
|
-
body,
|
|
165
|
-
signal: input.request.signal,
|
|
166
|
-
})
|
|
167
|
-
|
|
168
|
-
registerInternalRequestAuthState(internalRequest, authState)
|
|
169
|
-
|
|
170
|
-
const response = await input.app.fetch(internalRequest)
|
|
171
|
-
return new Response(response.body, {
|
|
172
|
-
status: response.status,
|
|
173
|
-
statusText: response.statusText,
|
|
174
|
-
headers: forwardedResponseHeaders(response.headers),
|
|
175
|
-
})
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
async function resolveAgentRunAuthState(
|
|
179
|
-
host: SixbHostView,
|
|
180
|
-
input: { readonly runId: string; readonly capability: string }
|
|
181
|
-
) {
|
|
182
|
-
const agentStorage = host.storage.agents
|
|
183
|
-
const workflowRuns = host.storage.workflowRuns
|
|
184
|
-
if (!agentStorage && !workflowRuns) {
|
|
185
|
-
// 501, not 403: nothing about the caller is being refused — neither storage role
|
|
186
|
-
// that could hold an agent run is configured, so no request can ever succeed here.
|
|
187
|
-
return jsonError(501, "Agent API gateway is not configured for this runtime.")
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const storedAgentRun = await agentStorage?.runs.getById({
|
|
191
|
-
projectId: host.id,
|
|
192
|
-
id: input.runId,
|
|
193
|
-
})
|
|
194
|
-
const workflowRun = storedAgentRun
|
|
195
|
-
? null
|
|
196
|
-
: await workflowRuns?.agentNodes.getByNodeRunId({
|
|
197
|
-
projectId: host.id,
|
|
198
|
-
nodeRunId: input.runId,
|
|
199
|
-
})
|
|
200
|
-
const runState = toGatewayRunState(storedAgentRun ?? null, workflowRun ?? null)
|
|
201
|
-
if (
|
|
202
|
-
!runState ||
|
|
203
|
-
runState.run.status !== "running" ||
|
|
204
|
-
!runState.run.execution ||
|
|
205
|
-
runState.run.execution.queueLeaseExpiresAt.getTime() <= Date.now() ||
|
|
206
|
-
!isValidAgentApiGatewayCapability({
|
|
207
|
-
projectId: host.id,
|
|
208
|
-
runId: input.runId,
|
|
209
|
-
executionToken: runState.run.execution.token,
|
|
210
|
-
capability: input.capability,
|
|
211
|
-
})
|
|
212
|
-
) {
|
|
213
|
-
return jsonError(403, "Agent API gateway capability is not valid for this run.")
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
let scope: AgentRunExecutionScope
|
|
217
|
-
try {
|
|
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)
|
|
229
|
-
}
|
|
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.
|
|
237
|
-
return {
|
|
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,
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
type GatewayRunState = {
|
|
248
|
-
readonly run: AgentRunRecord | WorkflowAgentNodeRunRecord
|
|
249
|
-
readonly runId: string
|
|
250
|
-
readonly agentExecution: NonNullable<InternalRequestAuthState["agentExecution"]>
|
|
251
|
-
readonly agentRun?: ConversationAgentRunRecord
|
|
252
|
-
} & (
|
|
253
|
-
| { readonly authority: "inherited" }
|
|
254
|
-
| { readonly authority: "managed"; readonly actorId: string }
|
|
255
|
-
)
|
|
256
|
-
|
|
257
|
-
function toGatewayRunState(
|
|
258
|
-
storedRun: AgentRunRecord | null,
|
|
259
|
-
workflowRun: WorkflowAgentNodeRunRecord | null
|
|
260
|
-
): GatewayRunState | null {
|
|
261
|
-
if (storedRun?.kind === "subagent") {
|
|
262
|
-
return {
|
|
263
|
-
run: storedRun,
|
|
264
|
-
runId: storedRun.id,
|
|
265
|
-
agentExecution: {
|
|
266
|
-
kind: "subagent",
|
|
267
|
-
runId: storedRun.id,
|
|
268
|
-
parentRunId: storedRun.parentRunId,
|
|
269
|
-
},
|
|
270
|
-
authority: "inherited",
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
if (storedRun?.kind === "conversation") {
|
|
275
|
-
const common = {
|
|
276
|
-
run: storedRun,
|
|
277
|
-
runId: storedRun.id,
|
|
278
|
-
agentExecution: { kind: "conversation", runId: storedRun.id } as const,
|
|
279
|
-
agentRun: storedRun,
|
|
280
|
-
}
|
|
281
|
-
return { ...common, authority: "inherited" }
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
if (!workflowRun) return null
|
|
285
|
-
const common = {
|
|
286
|
-
run: workflowRun,
|
|
287
|
-
runId: workflowRun.nodeRunId,
|
|
288
|
-
agentExecution: { kind: "workflow", nodeRunId: workflowRun.nodeRunId } as const,
|
|
289
|
-
}
|
|
290
|
-
return { ...common, authority: "managed", actorId: workflowRun.actorId }
|
|
291
|
-
}
|
|
292
|
-
|
|
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.")
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function gatewayUpstreamPath(pathname: string): string {
|
|
305
|
-
const prefixLength = pathSegmentsFor(AGENT_API_GATEWAY_PREFIX).length
|
|
306
|
-
const segments = pathSegmentsFor(pathname)
|
|
307
|
-
const upstreamSegments = segments.slice(prefixLength + 2)
|
|
308
|
-
return normalizeRoutePath(`/${upstreamSegments.join("/")}`)
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function forwardedRequestHeaders(source: Headers): Headers {
|
|
312
|
-
const headers = new Headers()
|
|
313
|
-
copyHeader(source, headers, "accept")
|
|
314
|
-
copyHeader(source, headers, "content-type")
|
|
315
|
-
return headers
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
function forwardedResponseHeaders(source: Headers): Headers {
|
|
319
|
-
const headers = new Headers()
|
|
320
|
-
for (const [key, value] of source) {
|
|
321
|
-
const normalized = key.toLowerCase()
|
|
322
|
-
if (
|
|
323
|
-
HOP_BY_HOP_RESPONSE_HEADERS.has(normalized) ||
|
|
324
|
-
normalized === "content-length" ||
|
|
325
|
-
normalized === "set-cookie"
|
|
326
|
-
) {
|
|
327
|
-
continue
|
|
328
|
-
}
|
|
329
|
-
headers.append(key, value)
|
|
330
|
-
}
|
|
331
|
-
return headers
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
function copyHeader(source: Headers, target: Headers, name: string): void {
|
|
335
|
-
const value = source.get(name)
|
|
336
|
-
if (value !== null) {
|
|
337
|
-
target.set(name, value)
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
async function readGatewayRequestBody(
|
|
342
|
-
request: Request,
|
|
343
|
-
upstreamPath: string
|
|
344
|
-
): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
345
|
-
if (!request.body || request.method === "GET" || request.method === "HEAD") {
|
|
346
|
-
return undefined
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
if (isSimpleFileUpload(request.method, upstreamPath)) {
|
|
350
|
-
return readRequestBodyWithLimit(
|
|
351
|
-
request,
|
|
352
|
-
DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES,
|
|
353
|
-
`Agent API gateway file upload request body exceeds the ${DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES} byte limit.`
|
|
354
|
-
)
|
|
355
|
-
}
|
|
356
|
-
return readRequestBodyWithLimit(
|
|
357
|
-
request,
|
|
358
|
-
MAX_AGENT_API_BODY_BYTES,
|
|
359
|
-
"Agent API gateway request body exceeds 1MB."
|
|
360
|
-
)
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
function isSimpleFileUpload(method: string, pathname: string): boolean {
|
|
364
|
-
return method === "POST" && normalizeRoutePath(pathname) === "/api/files"
|
|
365
|
-
}
|
|
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
|
-
|
|
392
|
-
function matchesWorkflowRunStart(pathname: string): boolean {
|
|
393
|
-
const segments = pathSegmentsFor(pathname)
|
|
394
|
-
return (
|
|
395
|
-
segments.length === 4 &&
|
|
396
|
-
segments[0] === "api" &&
|
|
397
|
-
segments[1] === "workflows" &&
|
|
398
|
-
segments[3] === "runs"
|
|
399
|
-
)
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
function jsonError(status: number, message: string): Response {
|
|
403
|
-
return Response.json({ error: message }, { status })
|
|
404
|
-
}
|