@sixb/server 0.1.25 → 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 +3240 -3042
- package/dist/index.js.map +29 -27
- 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/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/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/registerRoutes.ts
CHANGED
|
@@ -5,10 +5,11 @@ import type { SharedAccessBoundary } from "./auth/shared-access"
|
|
|
5
5
|
import { registerActionRunRoutes } from "./routes/action-runs"
|
|
6
6
|
import { registerActionRoutes } from "./routes/actions"
|
|
7
7
|
import { registerActivityRoutes } from "./routes/activity"
|
|
8
|
-
import { registerAgentApiGatewayRoutes } from "./routes/agent-api-gateway"
|
|
9
8
|
import { registerAgentApprovalRoutes } from "./routes/agent-approvals"
|
|
10
9
|
import { registerAgentChildRoutes } from "./routes/agent-children"
|
|
10
|
+
import { registerAgentComputerRoutes } from "./routes/agent-computers"
|
|
11
11
|
import { registerAgentMemoryRoutes } from "./routes/agent-memory"
|
|
12
|
+
import { registerAgentRunnerRoutes } from "./routes/agent-runners"
|
|
12
13
|
import { registerAgentRoutes } from "./routes/agents"
|
|
13
14
|
import { registerAiAccountingRoutes } from "./routes/ai-accounting"
|
|
14
15
|
import { registerArtifactFrameRoutes } from "./routes/artifact-frames"
|
|
@@ -52,7 +53,6 @@ export interface HttpRouteOptions {
|
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
export function registerHttpRoutes(app: Elysia, host: SixbHostView, options: HttpRouteOptions) {
|
|
55
|
-
registerAgentApiGatewayRoutes(app, host)
|
|
56
56
|
registerAiAccountingRoutes(app, host)
|
|
57
57
|
registerModelCallRoutes(app, host)
|
|
58
58
|
registerModelGenerationRoutes(app, host)
|
|
@@ -76,6 +76,8 @@ export function registerHttpRoutes(app: Elysia, host: SixbHostView, options: Htt
|
|
|
76
76
|
registerActionRunRoutes(app, host)
|
|
77
77
|
registerAgentRoutes(app, host)
|
|
78
78
|
registerAgentChildRoutes(app, host)
|
|
79
|
+
registerAgentRunnerRoutes(app, host)
|
|
80
|
+
registerAgentComputerRoutes(app, host)
|
|
79
81
|
registerAgentApprovalRoutes(app, host)
|
|
80
82
|
registerObservedAgentThreadRoutes(app, host)
|
|
81
83
|
registerAgentMemoryRoutes(app)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SixbHostView } from "@sixb/core"
|
|
2
|
-
import {
|
|
2
|
+
import { bindAgentRunRequestExecution } from "@sixb/core/internal/agent-execution"
|
|
3
3
|
import {
|
|
4
4
|
agentRunApprovalMode,
|
|
5
5
|
announceAgentApprovals,
|
|
@@ -20,12 +20,13 @@ import {
|
|
|
20
20
|
type WorkflowAgentNodeRunRecord,
|
|
21
21
|
} from "@sixb/core/storage"
|
|
22
22
|
import { ZodError, type z } from "zod"
|
|
23
|
-
import type {
|
|
23
|
+
import type { AgentRunRequestExecution, RequestAuthState } from "../auth/scope"
|
|
24
24
|
import { RequestActionBodySchema } from "../schemas/actions"
|
|
25
25
|
import { RequestWorkflowRunBodySchema } from "../schemas/workflows"
|
|
26
26
|
import { handleRouteError } from "../utils/http"
|
|
27
|
+
import { RequestBodyTooLargeError } from "../utils/request-body"
|
|
27
28
|
|
|
28
|
-
/** What
|
|
29
|
+
/** What happens to an Agent's call: it goes on to its route, or is answered here. */
|
|
29
30
|
export type AgentApiGate =
|
|
30
31
|
| { readonly kind: "pass" }
|
|
31
32
|
| { readonly kind: "answer"; readonly response: Response }
|
|
@@ -34,10 +35,13 @@ export interface AgentApiGateInput {
|
|
|
34
35
|
readonly host: SixbHostView
|
|
35
36
|
readonly method: string
|
|
36
37
|
readonly upstreamPath: string
|
|
37
|
-
|
|
38
|
+
/** Read only for a call the gate may hold, so other calls' bodies stay unread. */
|
|
39
|
+
readBody(): Promise<Uint8Array | undefined>
|
|
40
|
+
/** The request's Content-Type: the route parses the body by it, so the gate must agree. */
|
|
41
|
+
readonly contentType: string | null
|
|
38
42
|
readonly run: AgentRunRecord | WorkflowAgentNodeRunRecord
|
|
39
43
|
readonly agentExecution: NonNullable<RequestAuthState["agentExecution"]>
|
|
40
|
-
readonly runExecution:
|
|
44
|
+
readonly runExecution: AgentRunRequestExecution
|
|
41
45
|
readonly signal: AbortSignal
|
|
42
46
|
}
|
|
43
47
|
|
|
@@ -54,7 +58,8 @@ export async function gateAgentApiCall(input: AgentApiGateInput): Promise<AgentA
|
|
|
54
58
|
if (agentRunApprovalMode(input.run) === "auto") return { kind: "pass" }
|
|
55
59
|
|
|
56
60
|
try {
|
|
57
|
-
const call =
|
|
61
|
+
const call =
|
|
62
|
+
effect === "action" ? await prepareActionCall(input) : await prepareWorkflowCall(input)
|
|
58
63
|
return await answerHold(input, input.run, call)
|
|
59
64
|
} catch (error) {
|
|
60
65
|
if (error instanceof GateRefusal) return { kind: "answer", response: error.response }
|
|
@@ -79,9 +84,9 @@ async function answerHold(
|
|
|
79
84
|
call,
|
|
80
85
|
})
|
|
81
86
|
} catch (error) {
|
|
82
|
-
// The run ended, or its delivery changed, since
|
|
87
|
+
// The run ended, or its delivery changed, since its token was checked.
|
|
83
88
|
if (!(error instanceof AgentStorageError)) throw error
|
|
84
|
-
throw refusal(403, "
|
|
89
|
+
throw refusal(403, "The run token is not valid: its run has ended or moved.")
|
|
85
90
|
}
|
|
86
91
|
|
|
87
92
|
switch (hold.kind) {
|
|
@@ -110,7 +115,7 @@ function isAgentRun(run: AgentRunRecord | WorkflowAgentNodeRunRecord): run is Ag
|
|
|
110
115
|
|
|
111
116
|
/** The Action call as its route would run it: admitted, with its params normalized. */
|
|
112
117
|
async function prepareActionCall(input: AgentApiGateInput): Promise<AgentApprovalCall> {
|
|
113
|
-
const body = parseBody(input
|
|
118
|
+
const body = parseBody(await readBody(input), RequestActionBodySchema)
|
|
114
119
|
const actionRunId = requiredRunId(body.runId)
|
|
115
120
|
|
|
116
121
|
try {
|
|
@@ -126,8 +131,8 @@ async function prepareActionCall(input: AgentApiGateInput): Promise<AgentApprova
|
|
|
126
131
|
}
|
|
127
132
|
|
|
128
133
|
/** 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
|
|
134
|
+
async function prepareWorkflowCall(input: AgentApiGateInput): Promise<AgentApprovalCall> {
|
|
135
|
+
const body = parseBody(await readBody(input), RequestWorkflowRunBodySchema)
|
|
131
136
|
const workflowRunId = requiredRunId(body.runId)
|
|
132
137
|
|
|
133
138
|
try {
|
|
@@ -142,7 +147,7 @@ function prepareWorkflowCall(input: AgentApiGateInput): AgentApprovalCall {
|
|
|
142
147
|
}
|
|
143
148
|
|
|
144
149
|
function boundSixb(input: AgentApiGateInput): object {
|
|
145
|
-
return
|
|
150
|
+
return bindAgentRunRequestExecution(input.host, {
|
|
146
151
|
signal: input.signal,
|
|
147
152
|
...input.runExecution,
|
|
148
153
|
})
|
|
@@ -167,7 +172,28 @@ function pathParam(upstreamPath: string): string {
|
|
|
167
172
|
}
|
|
168
173
|
}
|
|
169
174
|
|
|
170
|
-
/**
|
|
175
|
+
/**
|
|
176
|
+
* Parsed with the route's own schema, so the gate reads the body the route would. Only as JSON:
|
|
177
|
+
* the route parses by Content-Type, so a body the two read differently would let an approved call
|
|
178
|
+
* through as another.
|
|
179
|
+
*/
|
|
180
|
+
async function readBody(input: AgentApiGateInput): Promise<Uint8Array | undefined> {
|
|
181
|
+
let body: Uint8Array | undefined
|
|
182
|
+
try {
|
|
183
|
+
body = await input.readBody()
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (error instanceof RequestBodyTooLargeError) throw refusal(413, error.message)
|
|
186
|
+
throw error
|
|
187
|
+
}
|
|
188
|
+
// Exactly as the route reads it: Elysia cuts the type at ";" and matches it case-sensitively,
|
|
189
|
+
// so `Application/JSON` reaches the route without a body.
|
|
190
|
+
const mediaType = input.contentType?.split(";")[0]
|
|
191
|
+
if (body && body.byteLength > 0 && mediaType !== "application/json") {
|
|
192
|
+
throw refusal(415, "A call that may need approval sends its body as application/json.")
|
|
193
|
+
}
|
|
194
|
+
return body
|
|
195
|
+
}
|
|
196
|
+
|
|
171
197
|
function parseBody<TSchema extends z.ZodTypeAny>(
|
|
172
198
|
body: Uint8Array | undefined,
|
|
173
199
|
schema: TSchema
|
|
@@ -185,7 +211,7 @@ function parseBody<TSchema extends z.ZodTypeAny>(
|
|
|
185
211
|
/** The gate answers for the call itself: it never reaches its route. */
|
|
186
212
|
class GateRefusal extends Error {
|
|
187
213
|
constructor(readonly response: Response) {
|
|
188
|
-
super("[SixbServer] The
|
|
214
|
+
super("[SixbServer] The Agent's call was answered before its route.")
|
|
189
215
|
}
|
|
190
216
|
}
|
|
191
217
|
|
|
@@ -64,7 +64,7 @@ function serializeApproval(approval: AgentApprovalRecord, callerKey?: string): S
|
|
|
64
64
|
})
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
/** Approval modes and held calls. Session routes only, and never
|
|
67
|
+
/** Approval modes and held calls. Session routes only, and never open to run tokens. */
|
|
68
68
|
export function registerAgentApprovalRoutes(app: Elysia, host: SixbHostView) {
|
|
69
69
|
const missingStorage = (set: { status?: number | string }) =>
|
|
70
70
|
unconfiguredStorageResponse(set, "Agent storage")
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { AgentRequestError, principalsEqual, type SixbHostView } from "@sixb/core"
|
|
2
|
+
import type { AgentRunSessionHost } from "@sixb/core/internal/agents"
|
|
3
|
+
import type { ConversationAgentRunRecord } from "@sixb/core/storage"
|
|
4
|
+
import type { Elysia } from "elysia"
|
|
5
|
+
import { requestActor, requireRequestSixb } from "../auth/scope"
|
|
6
|
+
import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
|
|
7
|
+
import { OPENAPI_TAGS } from "../openapi/tags"
|
|
8
|
+
import {
|
|
9
|
+
AgentRequestErrorResponseSchema,
|
|
10
|
+
AgentThreadParamsSchema,
|
|
11
|
+
AgentThreadSchema,
|
|
12
|
+
MoveAgentThreadToComputerBodySchema,
|
|
13
|
+
} from "../schemas/agents"
|
|
14
|
+
import { ErrorResponseSchema } from "../schemas/common"
|
|
15
|
+
import { unconfiguredStorageResponse } from "../utils/http"
|
|
16
|
+
import { handleAgentRouteError, serializeThread } from "./agents"
|
|
17
|
+
|
|
18
|
+
// A computer's thread runs on one of its owner's computers: the first that claims one of its
|
|
19
|
+
// turns, until its owner moves it to another. Each claim names the computer it comes from, so two
|
|
20
|
+
// computers of the same person never both run its turns.
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Why a computer's turn is not this computer's to claim, or null when it is. A thread no computer
|
|
24
|
+
* runs yet is assigned the one claiming its first turn.
|
|
25
|
+
*/
|
|
26
|
+
export async function refuseOtherComputer(
|
|
27
|
+
sessions: AgentRunSessionHost,
|
|
28
|
+
run: ConversationAgentRunRecord,
|
|
29
|
+
body: unknown
|
|
30
|
+
): Promise<{ readonly status: 400 | 403; readonly error: Record<string, string> } | null> {
|
|
31
|
+
const computerId = (body as { readonly computerId?: unknown } | null)?.computerId
|
|
32
|
+
if (typeof computerId !== "string" || computerId.trim() === "") {
|
|
33
|
+
return {
|
|
34
|
+
status: 400,
|
|
35
|
+
error: {
|
|
36
|
+
kind: "Error",
|
|
37
|
+
message: "[SixbServer] A claim of a computer's turn names the computer it comes from.",
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const { threads } = sessions.storage.agents
|
|
43
|
+
const thread = await threads.getById({ projectId: run.projectId, id: run.threadId })
|
|
44
|
+
const assigned =
|
|
45
|
+
thread?.computerId ??
|
|
46
|
+
(
|
|
47
|
+
await threads.assignComputer({
|
|
48
|
+
projectId: run.projectId,
|
|
49
|
+
id: run.threadId,
|
|
50
|
+
computerId,
|
|
51
|
+
ifUnassigned: true,
|
|
52
|
+
})
|
|
53
|
+
).computerId
|
|
54
|
+
if (assigned === computerId) return null
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
status: 403,
|
|
58
|
+
error: {
|
|
59
|
+
kind: "AgentRunRefusedError",
|
|
60
|
+
message: `[SixbServer] Agent thread '${run.threadId}' runs on another of your computers: move it to this one to run its turns here.`,
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
|
|
66
|
+
return app.post(
|
|
67
|
+
"/api/agent-threads/:threadId/computer",
|
|
68
|
+
async (context) => {
|
|
69
|
+
const { params, body, set } = context
|
|
70
|
+
const sixb = requireRequestSixb(context)
|
|
71
|
+
try {
|
|
72
|
+
const agents = host.storage.agents
|
|
73
|
+
if (!agents) return unconfiguredStorageResponse(set, "Agent storage")
|
|
74
|
+
|
|
75
|
+
const { computerId } = MoveAgentThreadToComputerBodySchema.parse(body)
|
|
76
|
+
const thread = await sixb.agent.threads.getById(params.threadId)
|
|
77
|
+
if (!thread) {
|
|
78
|
+
throw new AgentRequestError(
|
|
79
|
+
"thread_not_found",
|
|
80
|
+
`[SixbServer] Agent thread '${params.threadId}' not found.`
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
if (!principalsEqual(thread.ownerPrincipal, requestActor(sixb))) {
|
|
84
|
+
throw new AgentRequestError(
|
|
85
|
+
"not_thread_owner",
|
|
86
|
+
`[SixbServer] Only the owner of Agent thread '${params.threadId}' moves it to a computer.`
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
if (thread.runsOn !== "computer") {
|
|
90
|
+
throw new AgentRequestError(
|
|
91
|
+
"invalid_message",
|
|
92
|
+
`[SixbServer] Agent thread '${params.threadId}' runs in the cloud, on no computer.`
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const moved = await agents.threads.assignComputer({
|
|
97
|
+
projectId: host.id,
|
|
98
|
+
id: params.threadId,
|
|
99
|
+
computerId,
|
|
100
|
+
})
|
|
101
|
+
return serializeThread(host, { ...moved, participants: thread.participants })
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return handleAgentRouteError(error, set)
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
params: AgentThreadParamsSchema,
|
|
108
|
+
body: MoveAgentThreadToComputerBodySchema,
|
|
109
|
+
response: {
|
|
110
|
+
200: AgentThreadSchema,
|
|
111
|
+
400: AgentRequestErrorResponseSchema,
|
|
112
|
+
403: AgentRequestErrorResponseSchema,
|
|
113
|
+
404: AgentRequestErrorResponseSchema,
|
|
114
|
+
501: ErrorResponseSchema,
|
|
115
|
+
},
|
|
116
|
+
detail: {
|
|
117
|
+
summary: "Move a thread to another of your computers",
|
|
118
|
+
description:
|
|
119
|
+
"A thread that runs on its owner's computer runs there alone: its turns are claimed by that computer only. Its owner moves it to another.",
|
|
120
|
+
tags: [OPENAPI_TAGS.agentThreads.name],
|
|
121
|
+
operationId: "moveAgentThreadToComputer",
|
|
122
|
+
security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
)
|
|
126
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { principalsEqual, type SixbHostView, SYSTEM_PRINCIPAL } from "@sixb/core"
|
|
2
|
+
import {
|
|
3
|
+
AgentRunRefusedError,
|
|
4
|
+
type AgentRunSessionHost,
|
|
5
|
+
afterAgentRunFinished,
|
|
6
|
+
claimAgentRunForRunner,
|
|
7
|
+
createBrokerStreamSink,
|
|
8
|
+
encodeWireError,
|
|
9
|
+
encodeWireValue,
|
|
10
|
+
endLapsedAgentRuns,
|
|
11
|
+
isAgentRunnerToken,
|
|
12
|
+
isolateStreamSink,
|
|
13
|
+
serveAgentRunSession,
|
|
14
|
+
withAgentActivityStream,
|
|
15
|
+
} from "@sixb/core/internal/agents"
|
|
16
|
+
import { enqueueAiModelCallRecovery } from "@sixb/core/internal/model-execution"
|
|
17
|
+
import type { Elysia } from "elysia"
|
|
18
|
+
import { requestActor, requireRequestSixb } from "../auth/scope"
|
|
19
|
+
import { refuseOtherComputer } from "./agent-computers"
|
|
20
|
+
|
|
21
|
+
// A runner outside the worker, such as one on a person's computer, runs a turn through the API:
|
|
22
|
+
// it claims the turn as the person who asked for it, then reaches the turn's session with the
|
|
23
|
+
// runner token the claim returns (see serveAgentRunSession). Neither route is part of the public
|
|
24
|
+
// API.
|
|
25
|
+
|
|
26
|
+
/** The session host the API opens a run's session against: the worker's, without the worker. */
|
|
27
|
+
export function agentRunSessionHost(host: SixbHostView): AgentRunSessionHost | null {
|
|
28
|
+
const { storage } = host
|
|
29
|
+
if (!storage.agents || !storage.auth || !storage.aiUsage || !storage.aiCosts) return null
|
|
30
|
+
const sessions: AgentRunSessionHost = {
|
|
31
|
+
projectId: host.id,
|
|
32
|
+
storage: storage as AgentRunSessionHost["storage"],
|
|
33
|
+
broker: host.broker,
|
|
34
|
+
recoverAiModelCall: (input) => enqueueAiModelCallRecovery(host.queues.agents, input),
|
|
35
|
+
events: isolateStreamSink(
|
|
36
|
+
withAgentActivityStream(
|
|
37
|
+
createBrokerStreamSink({ broker: host.broker, projectId: host.id }),
|
|
38
|
+
host.broker
|
|
39
|
+
)
|
|
40
|
+
),
|
|
41
|
+
security: host.definitions.security,
|
|
42
|
+
sdk: host,
|
|
43
|
+
definitions: host.definitions,
|
|
44
|
+
logging: host.logging,
|
|
45
|
+
// A turn a runner finished here stops its children and resumes on calls already decided.
|
|
46
|
+
afterFinish: (run) => afterAgentRunFinished(sessions, run),
|
|
47
|
+
}
|
|
48
|
+
return sessions
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** How often the API ends the runs no runner renews any more. */
|
|
52
|
+
const SWEEP_INTERVAL_MS = 30_000
|
|
53
|
+
/** How long the claim that ends a lapsed run holds it: as long as recording the end takes. */
|
|
54
|
+
const SWEEP_CLAIM_MS = 60_000
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* End the runs whose runner stopped renewing them, as the worker's repair pass does: a runner on
|
|
58
|
+
* a computer has no worker behind it. Several API servers may sweep at once: each run is ended
|
|
59
|
+
* once, by whichever takes it over. Returns the stop.
|
|
60
|
+
*/
|
|
61
|
+
export function startLapsedRunSweeper(host: SixbHostView): () => void {
|
|
62
|
+
const sessions = agentRunSessionHost(host)
|
|
63
|
+
if (!sessions) return () => {}
|
|
64
|
+
const sweep = () => {
|
|
65
|
+
void endLapsedAgentRuns(sessions, { leaseMs: SWEEP_CLAIM_MS }).catch((error: unknown) => {
|
|
66
|
+
console.error("[SixbServer] Could not end lapsed agent runs; retrying.", error)
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
sweep()
|
|
70
|
+
const timer = setInterval(sweep, SWEEP_INTERVAL_MS)
|
|
71
|
+
return () => clearInterval(timer)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Answer a runner's session request before the API parses it: its runner token speaks only for its
|
|
76
|
+
* run's session, and any other route refuses it. Null for any other request.
|
|
77
|
+
*/
|
|
78
|
+
export function agentRunSessionHandler(
|
|
79
|
+
host: SixbHostView
|
|
80
|
+
): (request: Request) => Promise<Response | null> {
|
|
81
|
+
let sessions: AgentRunSessionHost | null | undefined
|
|
82
|
+
return async (request) => {
|
|
83
|
+
sessions ??= agentRunSessionHost(host)
|
|
84
|
+
const served = sessions ? await serveAgentRunSession(sessions, request) : null
|
|
85
|
+
if (served) return served
|
|
86
|
+
|
|
87
|
+
// It carries the runner's authority over its run, not anyone's over the project.
|
|
88
|
+
const token = request.headers.get("authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1]
|
|
89
|
+
if (token === undefined || !isAgentRunnerToken(token)) return null
|
|
90
|
+
const { pathname } = new URL(request.url)
|
|
91
|
+
return Response.json(
|
|
92
|
+
{
|
|
93
|
+
error: `[SixbServer] A runner token cannot call ${request.method} ${pathname}: it reaches only its run's session.`,
|
|
94
|
+
},
|
|
95
|
+
{ status: 403 }
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function registerAgentRunnerRoutes(app: Elysia, host: SixbHostView) {
|
|
101
|
+
return app.post(
|
|
102
|
+
"/api/agent-runs/:runId/claim",
|
|
103
|
+
async (context) => {
|
|
104
|
+
const sessions = agentRunSessionHost(host)
|
|
105
|
+
if (!sessions) return answer({ error: notAvailable() }, 501)
|
|
106
|
+
try {
|
|
107
|
+
const sixb = requireRequestSixb(context)
|
|
108
|
+
const runId = (context.params as { readonly runId: string }).runId
|
|
109
|
+
// Elysia parsed it already: a lease is a plain string, nothing the wire tags.
|
|
110
|
+
const { leaseExpiresAt } = (context.body ?? {}) as { readonly leaseExpiresAt?: string }
|
|
111
|
+
if (typeof leaseExpiresAt !== "string") {
|
|
112
|
+
return answer(
|
|
113
|
+
{ error: { kind: "Error", message: "[SixbServer] A claim names its lease." } },
|
|
114
|
+
400
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
// As its reader: a run the caller cannot read is none of theirs.
|
|
118
|
+
const visible = await sixb.agent.runs.getById(runId)
|
|
119
|
+
const run = visible
|
|
120
|
+
? await sessions.storage.agents.runs.getById({ projectId: host.id, id: runId })
|
|
121
|
+
: null
|
|
122
|
+
const execution =
|
|
123
|
+
run &&
|
|
124
|
+
(await sessions.storage.executions.getById({ projectId: host.id, id: run.executionId }))
|
|
125
|
+
// With sign-in off, no one asked for a turn: the system did, as such a request acts.
|
|
126
|
+
if (
|
|
127
|
+
run?.kind !== "conversation" ||
|
|
128
|
+
!execution ||
|
|
129
|
+
!principalsEqual(execution.requestedBy ?? SYSTEM_PRINCIPAL, requestActor(sixb))
|
|
130
|
+
) {
|
|
131
|
+
return answer(
|
|
132
|
+
{
|
|
133
|
+
error: {
|
|
134
|
+
kind: "AgentRunRefusedError",
|
|
135
|
+
message: `[SixbServer] Only the person who asked for agent run '${runId}' runs it.`,
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
403
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
// A cloud turn is the agent worker's: a runner here would race it, and skip the sandbox
|
|
142
|
+
// the thread chose.
|
|
143
|
+
if (run.spec?.runsOn !== "computer") {
|
|
144
|
+
return answer(
|
|
145
|
+
{
|
|
146
|
+
error: {
|
|
147
|
+
kind: "AgentRunRefusedError",
|
|
148
|
+
message: `[SixbServer] Agent run '${runId}' runs in the cloud: only a computer's turns are claimed here.`,
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
403
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
const elsewhere = await refuseOtherComputer(sessions, run, context.body)
|
|
155
|
+
if (elsewhere) return answer({ error: elsewhere.error }, elsewhere.status)
|
|
156
|
+
return answer({ result: await claimAgentRunForRunner(sessions, { run, leaseExpiresAt }) })
|
|
157
|
+
} catch (error) {
|
|
158
|
+
// A turn whose runner stopped ends interrupted rather than being claimed again.
|
|
159
|
+
return answer(
|
|
160
|
+
{ error: encodeWireError(error) },
|
|
161
|
+
error instanceof AgentRunRefusedError ? 409 : 400
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
{ detail: { hide: true } }
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function notAvailable() {
|
|
170
|
+
return {
|
|
171
|
+
kind: "Error",
|
|
172
|
+
message: "[SixbServer] Agent runs are not available: this runtime stores none.",
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function answer(body: unknown, status = 200): Response {
|
|
177
|
+
return new Response(encodeWireValue(body), {
|
|
178
|
+
status,
|
|
179
|
+
headers: { "content-type": "application/json" },
|
|
180
|
+
})
|
|
181
|
+
}
|
package/src/routes/agents.ts
CHANGED
|
@@ -71,7 +71,7 @@ const AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
|
|
|
71
71
|
})
|
|
72
72
|
|
|
73
73
|
const SHARING =
|
|
74
|
-
"Only the thread's owner adds participants: active users of the project, by id or by email. They read the whole conversation, its files and its live stream, and send messages that run with their own rights. Nothing checks what they may see: the conversation holds what the Agent read with the rights of whoever asked."
|
|
74
|
+
"Only the thread's owner adds participants: active users of the project, by id or by email. They read the whole conversation, its files and its live stream, and send messages that run with their own rights; a thread that runs on its owner's computer they only read. Nothing checks what they may see: the conversation holds what the Agent read with the rights of whoever asked."
|
|
75
75
|
|
|
76
76
|
/** Threads as the API returns them, their owner and participants named by their accounts. */
|
|
77
77
|
export async function serializeThreads(
|
|
@@ -102,6 +102,8 @@ export async function serializeThreads(
|
|
|
102
102
|
})),
|
|
103
103
|
title: thread.title,
|
|
104
104
|
sandboxParams: thread.sandboxParams,
|
|
105
|
+
runsOn: thread.runsOn,
|
|
106
|
+
computerId: thread.computerId,
|
|
105
107
|
sandboxState: thread.sandboxState && {
|
|
106
108
|
name: thread.sandboxState.name,
|
|
107
109
|
status: thread.sandboxState.status,
|
|
@@ -169,6 +171,7 @@ export function serializeAgentRun(run: AgentRunView): ReturnType<typeof AgentRun
|
|
|
169
171
|
tier: run.spec?.tier,
|
|
170
172
|
reasoning: run.spec?.reasoning,
|
|
171
173
|
approvalMode: run.spec?.approvalMode,
|
|
174
|
+
runsOn: run.kind === "conversation" ? run.spec?.runsOn : undefined,
|
|
172
175
|
modelId: run.modelId,
|
|
173
176
|
finishReason: run.finishReason,
|
|
174
177
|
usage: run.usage,
|
|
@@ -516,6 +519,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
516
519
|
...(parsed.threadId === undefined ? {} : { id: parsed.threadId }),
|
|
517
520
|
...(parsed.title === undefined ? {} : { title: parsed.title }),
|
|
518
521
|
...(parsed.sandbox === undefined ? {} : { sandbox: parsed.sandbox }),
|
|
522
|
+
...(parsed.runsOn === undefined ? {} : { runsOn: parsed.runsOn }),
|
|
519
523
|
})
|
|
520
524
|
|
|
521
525
|
set.status = 201
|
|
@@ -855,7 +859,8 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
855
859
|
response: {
|
|
856
860
|
202: PostAgentMessageResponseSchema,
|
|
857
861
|
400: AgentRequestErrorResponseSchema,
|
|
858
|
-
|
|
862
|
+
// Coded: `not_thread_owner` when the thread runs on its owner's computer.
|
|
863
|
+
403: AgentRequestErrorResponseSchema,
|
|
859
864
|
404: ErrorResponseSchema,
|
|
860
865
|
409: AgentRequestErrorResponseSchema,
|
|
861
866
|
429: AiUsageLimitErrorResponseSchema,
|
package/src/routes/artifacts.ts
CHANGED
|
@@ -8,6 +8,11 @@ import {
|
|
|
8
8
|
type PublishedArtifact,
|
|
9
9
|
type SixbHostView,
|
|
10
10
|
} from "@sixb/core"
|
|
11
|
+
import {
|
|
12
|
+
AgentExecutionLostError,
|
|
13
|
+
type AgentRunArtifacts,
|
|
14
|
+
agentRunArtifacts,
|
|
15
|
+
} from "@sixb/core/internal/agents"
|
|
11
16
|
import {
|
|
12
17
|
createArtifactFrame,
|
|
13
18
|
serializeArtifactQueryResult,
|
|
@@ -15,7 +20,7 @@ import {
|
|
|
15
20
|
import type { Elysia } from "elysia"
|
|
16
21
|
import { ZodError } from "zod"
|
|
17
22
|
import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
|
|
18
|
-
import { requireRequestSixb } from "../auth/scope"
|
|
23
|
+
import { requestAuthState, requireRequestSixb } from "../auth/scope"
|
|
19
24
|
import {
|
|
20
25
|
createFileContentResponse,
|
|
21
26
|
fileContentGetResponses,
|
|
@@ -107,6 +112,33 @@ function contentInput(body: {
|
|
|
107
112
|
}
|
|
108
113
|
}
|
|
109
114
|
|
|
115
|
+
/**
|
|
116
|
+
* What a request with a run token publishes through: its run's conversation, by a run's rules
|
|
117
|
+
* (`AgentRunArtifacts.publish`), as the run's session does in a worker. `null` for any other
|
|
118
|
+
* caller, who publishes as themselves.
|
|
119
|
+
*/
|
|
120
|
+
async function runTokenArtifacts(
|
|
121
|
+
host: SixbHostView,
|
|
122
|
+
context: unknown
|
|
123
|
+
): Promise<AgentRunArtifacts | null> {
|
|
124
|
+
const { agentExecution, sixb } = requestAuthState(context)
|
|
125
|
+
if (!agentExecution) return null
|
|
126
|
+
if (agentExecution.kind === "workflow") {
|
|
127
|
+
throw new ArtifactRequestError(
|
|
128
|
+
"not_allowed",
|
|
129
|
+
"[SixbServer] Workflow agent nodes publish no artifacts: they have no conversation."
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
// Fenced with the execution the request was admitted under: a run reclaimed since refuses it.
|
|
133
|
+
const { runId, executionToken } = agentExecution
|
|
134
|
+
const run = await host.storage.agents?.runs.getById({ projectId: host.id, id: runId })
|
|
135
|
+
if (!run || !sixb) throw new AgentExecutionLostError(runId)
|
|
136
|
+
|
|
137
|
+
return agentRunArtifacts({ projectId: host.id, storage: host.storage }, run, executionToken, () =>
|
|
138
|
+
Promise.resolve(sixb)
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
|
|
110
142
|
function versionParam(value: string): number | "latest" {
|
|
111
143
|
return value === "latest" ? "latest" : Number(value)
|
|
112
144
|
}
|
|
@@ -169,6 +201,13 @@ function handleArtifactRouteError(error: unknown, set: RouteSet) {
|
|
|
169
201
|
...(error.latest ? { latest: error.latest } : {}),
|
|
170
202
|
}
|
|
171
203
|
}
|
|
204
|
+
if (error instanceof AgentExecutionLostError) {
|
|
205
|
+
set.status = 409
|
|
206
|
+
return {
|
|
207
|
+
error: "[SixbServer] The run has ended or moved to another runner, so nothing was published.",
|
|
208
|
+
code: "execution_lost",
|
|
209
|
+
}
|
|
210
|
+
}
|
|
172
211
|
if (error instanceof ZodError) {
|
|
173
212
|
set.status = 400
|
|
174
213
|
return { error: "Invalid artifact request" }
|
|
@@ -283,7 +322,10 @@ export function registerArtifactRoutes(app: Elysia, host: SixbHostView) {
|
|
|
283
322
|
async (context) => {
|
|
284
323
|
try {
|
|
285
324
|
const body = PublishArtifactBodySchema.parse(context.body)
|
|
286
|
-
const
|
|
325
|
+
const run = await runTokenArtifacts(host, context)
|
|
326
|
+
const published = run
|
|
327
|
+
? await run.publish(contentInput(body))
|
|
328
|
+
: await requireRequestSixb(context).artifacts.create(contentInput(body))
|
|
287
329
|
context.set.status = 201
|
|
288
330
|
return serializePublished(published)
|
|
289
331
|
} catch (error) {
|
|
@@ -296,7 +338,7 @@ export function registerArtifactRoutes(app: Elysia, host: SixbHostView) {
|
|
|
296
338
|
detail: {
|
|
297
339
|
summary: "Create an artifact",
|
|
298
340
|
description:
|
|
299
|
-
"Creates an artifact owned by the caller, with its first version. Store each file with POST /api/files first.",
|
|
341
|
+
"Creates an artifact owned by the caller, with its first version. Store each file with POST /api/files first. With a run token, it is created in the run's conversation, owned by the conversation's owner and authored by the run's requester.",
|
|
300
342
|
tags: [OPENAPI_TAGS.artifacts.name],
|
|
301
343
|
operationId: "createArtifact",
|
|
302
344
|
security: accessTokenSecurityRequirement("createArtifact"),
|
|
@@ -525,13 +567,15 @@ export function registerArtifactRoutes(app: Elysia, host: SixbHostView) {
|
|
|
525
567
|
async (context) => {
|
|
526
568
|
try {
|
|
527
569
|
const body = PublishArtifactVersionBodySchema.parse(context.body)
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
570
|
+
const { artifactId } = context.params
|
|
571
|
+
const content = {
|
|
572
|
+
...contentInput(body),
|
|
573
|
+
...(body.baseVersion === undefined ? {} : { baseVersion: body.baseVersion }),
|
|
574
|
+
}
|
|
575
|
+
const run = await runTokenArtifacts(host, context)
|
|
576
|
+
const published = run
|
|
577
|
+
? await run.publish({ ...content, artifactId })
|
|
578
|
+
: await requireRequestSixb(context).artifacts.publish(artifactId, content)
|
|
535
579
|
context.set.status = 201
|
|
536
580
|
return serializePublished(published)
|
|
537
581
|
} catch (error) {
|
|
@@ -545,7 +589,7 @@ export function registerArtifactRoutes(app: Elysia, host: SixbHostView) {
|
|
|
545
589
|
detail: {
|
|
546
590
|
summary: "Publish an artifact's next version",
|
|
547
591
|
description:
|
|
548
|
-
"The kind must be the artifact's. The new version becomes the latest. With baseVersion, it is refused with 409 artifact_moved when another version was published since.",
|
|
592
|
+
"The kind must be the artifact's. The new version becomes the latest. With baseVersion, it is refused with 409 artifact_moved when another version was published since. With a run token, only an artifact the run's conversation shares or its requester owns; the version is shared in that conversation. A run that lost its execution gets 409 execution_lost.",
|
|
549
593
|
tags: [OPENAPI_TAGS.artifacts.name],
|
|
550
594
|
operationId: "publishArtifactVersion",
|
|
551
595
|
security: accessTokenSecurityRequirement("publishArtifactVersion"),
|
package/src/routes/datasets.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type {
|
|
|
6
6
|
DatasetVersion,
|
|
7
7
|
} from "@sixb/core/lake-storage"
|
|
8
8
|
import type { Elysia } from "elysia"
|
|
9
|
+
import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
|
|
9
10
|
import { requireRequestSixb } from "../auth/scope"
|
|
10
11
|
import { OPENAPI_TAGS } from "../openapi/tags"
|
|
11
12
|
import { codedErrorResponseSchema, ErrorResponseSchema } from "../schemas/common"
|
|
@@ -213,6 +214,7 @@ export function registerDatasetRoutes(app: Elysia, host: SixbHostView) {
|
|
|
213
214
|
summary: "List registered datasets",
|
|
214
215
|
tags: [OPENAPI_TAGS.datasets.name],
|
|
215
216
|
operationId: "listDatasets",
|
|
217
|
+
security: accessTokenSecurityRequirement("listDatasets"),
|
|
216
218
|
},
|
|
217
219
|
}
|
|
218
220
|
)
|
|
@@ -241,6 +243,7 @@ export function registerDatasetRoutes(app: Elysia, host: SixbHostView) {
|
|
|
241
243
|
summary: "Get dataset metadata",
|
|
242
244
|
tags: [OPENAPI_TAGS.datasets.name],
|
|
243
245
|
operationId: "getDataset",
|
|
246
|
+
security: accessTokenSecurityRequirement("getDataset"),
|
|
244
247
|
},
|
|
245
248
|
}
|
|
246
249
|
)
|
|
@@ -275,6 +278,7 @@ export function registerDatasetRoutes(app: Elysia, host: SixbHostView) {
|
|
|
275
278
|
summary: "List dataset versions",
|
|
276
279
|
tags: [OPENAPI_TAGS.datasetVersions.name],
|
|
277
280
|
operationId: "listDatasetVersions",
|
|
281
|
+
security: accessTokenSecurityRequirement("listDatasetVersions"),
|
|
278
282
|
},
|
|
279
283
|
}
|
|
280
284
|
)
|
|
@@ -366,6 +370,7 @@ export function registerDatasetRoutes(app: Elysia, host: SixbHostView) {
|
|
|
366
370
|
summary: "Preview dataset rows",
|
|
367
371
|
tags: [OPENAPI_TAGS.datasetRows.name],
|
|
368
372
|
operationId: "listDatasetRows",
|
|
373
|
+
security: accessTokenSecurityRequirement("listDatasetRows"),
|
|
369
374
|
},
|
|
370
375
|
}
|
|
371
376
|
)
|