@sixb/server 0.1.25 → 0.2.0

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 (135) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/public-routes.d.ts.map +1 -1
  3. package/dist/auth/run-token.d.ts +28 -0
  4. package/dist/auth/run-token.d.ts.map +1 -0
  5. package/dist/auth/scope.d.ts +11 -13
  6. package/dist/auth/scope.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +4999 -4151
  10. package/dist/index.js.map +47 -43
  11. package/dist/registerRoutes.d.ts.map +1 -1
  12. package/dist/routes/actions.d.ts +1 -1
  13. package/dist/routes/agent-approval-gate.d.ts +7 -4
  14. package/dist/routes/agent-approval-gate.d.ts.map +1 -1
  15. package/dist/routes/agent-approvals.d.ts +14 -5
  16. package/dist/routes/agent-approvals.d.ts.map +1 -1
  17. package/dist/routes/agent-children.d.ts +2 -2
  18. package/dist/routes/agent-computers.d.ts +338 -0
  19. package/dist/routes/agent-computers.d.ts.map +1 -0
  20. package/dist/routes/agent-runners.d.ts +74 -0
  21. package/dist/routes/agent-runners.d.ts.map +1 -0
  22. package/dist/routes/agents.d.ts +250 -16
  23. package/dist/routes/agents.d.ts.map +1 -1
  24. package/dist/routes/ai-accounting.d.ts.map +1 -1
  25. package/dist/routes/artifacts.d.ts +5 -28
  26. package/dist/routes/artifacts.d.ts.map +1 -1
  27. package/dist/routes/auth.d.ts +10 -1
  28. package/dist/routes/auth.d.ts.map +1 -1
  29. package/dist/routes/datasets.d.ts +93 -17
  30. package/dist/routes/datasets.d.ts.map +1 -1
  31. package/dist/routes/events.d.ts +1 -1
  32. package/dist/routes/links.d.ts +121 -81
  33. package/dist/routes/links.d.ts.map +1 -1
  34. package/dist/routes/logs.d.ts +3 -3
  35. package/dist/routes/objects.d.ts +149 -58
  36. package/dist/routes/objects.d.ts.map +1 -1
  37. package/dist/routes/observed-agent-threads.d.ts +25 -4
  38. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  39. package/dist/routes/pipelines.d.ts +2 -2
  40. package/dist/routes/pipelines.d.ts.map +1 -1
  41. package/dist/routes/projections.d.ts +124 -122
  42. package/dist/routes/projections.d.ts.map +1 -1
  43. package/dist/routes/rules.d.ts +2 -2
  44. package/dist/routes/shared-access.d.ts +2 -2
  45. package/dist/routes/syncs.d.ts +34 -34
  46. package/dist/routes/syncs.d.ts.map +1 -1
  47. package/dist/routes/telemetry.d.ts +0 -50
  48. package/dist/routes/telemetry.d.ts.map +1 -1
  49. package/dist/routes/users.d.ts +1 -0
  50. package/dist/routes/users.d.ts.map +1 -1
  51. package/dist/routes/webhook-runs.d.ts +1 -1
  52. package/dist/routes/workflows.d.ts +25 -14
  53. package/dist/routes/workflows.d.ts.map +1 -1
  54. package/dist/routes/ws/agents.d.ts +4 -1
  55. package/dist/routes/ws/agents.d.ts.map +1 -1
  56. package/dist/routes/ws/logs.d.ts +10 -10
  57. package/dist/schemas/actions.d.ts +3 -3
  58. package/dist/schemas/activity.d.ts +4 -4
  59. package/dist/schemas/agent-approvals.d.ts +21 -21
  60. package/dist/schemas/agents.d.ts +819 -88
  61. package/dist/schemas/agents.d.ts.map +1 -1
  62. package/dist/schemas/ai-accounting.d.ts +1114 -6
  63. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  64. package/dist/schemas/auth.d.ts +49 -2
  65. package/dist/schemas/auth.d.ts.map +1 -1
  66. package/dist/schemas/datasets.d.ts +303 -60
  67. package/dist/schemas/datasets.d.ts.map +1 -1
  68. package/dist/schemas/event-payloads.d.ts +6 -6
  69. package/dist/schemas/events.d.ts +8 -8
  70. package/dist/schemas/lineage.d.ts +1272 -0
  71. package/dist/schemas/lineage.d.ts.map +1 -0
  72. package/dist/schemas/links.d.ts +4 -27
  73. package/dist/schemas/links.d.ts.map +1 -1
  74. package/dist/schemas/logs.d.ts +22 -22
  75. package/dist/schemas/objects.d.ts +7 -26
  76. package/dist/schemas/objects.d.ts.map +1 -1
  77. package/dist/schemas/pipelines.d.ts +12 -12
  78. package/dist/schemas/projections.d.ts +747 -733
  79. package/dist/schemas/projections.d.ts.map +1 -1
  80. package/dist/schemas/rules.d.ts +4 -4
  81. package/dist/schemas/shared-access.d.ts +2 -2
  82. package/dist/schemas/syncs.d.ts +24 -24
  83. package/dist/schemas/telemetry.d.ts +0 -13
  84. package/dist/schemas/telemetry.d.ts.map +1 -1
  85. package/dist/schemas/users.d.ts +8 -0
  86. package/dist/schemas/users.d.ts.map +1 -1
  87. package/dist/schemas/webhook-runs.d.ts +2 -2
  88. package/dist/schemas/workflows.d.ts +133 -44
  89. package/dist/schemas/workflows.d.ts.map +1 -1
  90. package/dist/server.d.ts +5 -0
  91. package/dist/server.d.ts.map +1 -1
  92. package/dist/utils/request-body.d.ts +5 -0
  93. package/dist/utils/request-body.d.ts.map +1 -1
  94. package/dist/utils/request-timing.d.ts +18 -0
  95. package/dist/utils/request-timing.d.ts.map +1 -0
  96. package/package.json +7 -7
  97. package/src/auth/public-routes.ts +0 -6
  98. package/src/auth/run-token.ts +327 -0
  99. package/src/auth/scope.ts +16 -37
  100. package/src/index.ts +1 -0
  101. package/src/registerRoutes.ts +4 -2
  102. package/src/routes/agent-approval-gate.ts +40 -14
  103. package/src/routes/agent-approvals.ts +3 -3
  104. package/src/routes/agent-computers.ts +348 -0
  105. package/src/routes/agent-runners.ts +205 -0
  106. package/src/routes/agents.ts +193 -26
  107. package/src/routes/ai-accounting.ts +149 -12
  108. package/src/routes/artifacts.ts +55 -11
  109. package/src/routes/auth.ts +24 -2
  110. package/src/routes/datasets.ts +60 -5
  111. package/src/routes/links.ts +43 -76
  112. package/src/routes/objects.ts +49 -42
  113. package/src/routes/observed-agent-threads.ts +2 -2
  114. package/src/routes/pipelines.ts +5 -0
  115. package/src/routes/syncs.ts +4 -0
  116. package/src/routes/telemetry.ts +1 -42
  117. package/src/routes/users.ts +15 -2
  118. package/src/routes/ws/agents.ts +10 -1
  119. package/src/schemas/agents.ts +131 -1
  120. package/src/schemas/ai-accounting.ts +78 -15
  121. package/src/schemas/artifacts.ts +1 -1
  122. package/src/schemas/auth.ts +19 -0
  123. package/src/schemas/datasets.ts +36 -0
  124. package/src/schemas/lineage.ts +115 -0
  125. package/src/schemas/links.ts +3 -11
  126. package/src/schemas/objects.ts +6 -10
  127. package/src/schemas/projections.ts +2 -0
  128. package/src/schemas/telemetry.ts +0 -6
  129. package/src/schemas/users.ts +6 -0
  130. package/src/server.ts +53 -15
  131. package/src/utils/request-body.ts +10 -4
  132. package/src/utils/request-timing.ts +136 -0
  133. package/dist/routes/agent-api-gateway.d.ts +0 -4
  134. package/dist/routes/agent-api-gateway.d.ts.map +0 -1
  135. package/src/routes/agent-api-gateway.ts +0 -404
@@ -1,5 +1,5 @@
1
1
  import type { SixbHostView } from "@sixb/core"
2
- import { bindAgentGatewayRequestExecution } from "@sixb/core/internal/agent-execution"
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 { AgentGatewayRunExecution, RequestAuthState } from "../auth/scope"
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 the gateway does with an Agent's call: forward it, or answer it itself. */
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
- readonly body: Uint8Array | undefined
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: AgentGatewayRunExecution
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 = effect === "action" ? await prepareActionCall(input) : prepareWorkflowCall(input)
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 the gateway checked its capability.
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, "Agent API gateway capability is not valid for this run.")
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.body, RequestActionBodySchema)
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.body, RequestWorkflowRunBodySchema)
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 bindAgentGatewayRequestExecution(input.host, {
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
- /** Parsed with the route's own schema, so the gate reads the body the route would. */
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 agent API gateway answered the call itself.")
214
+ super("[SixbServer] The Agent's call was answered before its route.")
189
215
  }
190
216
  }
191
217
 
@@ -2,7 +2,7 @@ import type { AgentApprovalRecord, SixbHostView } from "@sixb/core"
2
2
  import { agentApprovalCallers } from "@sixb/core/internal/agents"
3
3
  import type { AgentStorage } from "@sixb/core/storage"
4
4
  import type { Elysia } from "elysia"
5
- import { requireRequestSixb } from "../auth/scope"
5
+ import { requestActor, requireRequestSixb } from "../auth/scope"
6
6
  import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
7
7
  import { OPENAPI_TAGS } from "../openapi/tags"
8
8
  import {
@@ -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 on the agent API gateway. */
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")
@@ -146,7 +146,7 @@ export function registerAgentApprovalRoutes(app: Elysia, host: SixbHostView) {
146
146
  return { error: "Agent thread not found" }
147
147
  }
148
148
 
149
- return { ...(await serializeThread(host, thread)), ...approvalMode }
149
+ return { ...(await serializeThread(host, thread, requestActor(sixb))), ...approvalMode }
150
150
  } catch (error) {
151
151
  return handleAgentRouteError(error, set)
152
152
  }
@@ -0,0 +1,348 @@
1
+ import type { SixbHostView } from "@sixb/core"
2
+ import { sameComputerPlace } from "@sixb/core/internal/agent-run-storage-provider"
3
+ import type { AgentRunSessionHost } from "@sixb/core/internal/agents"
4
+ import { publishAgentComputerActivity } from "@sixb/core/internal/agents/streams"
5
+ import type {
6
+ AgentComputerSessionRecord,
7
+ AgentStorage,
8
+ AgentThreadComputer,
9
+ ConversationAgentRunRecord,
10
+ Principal,
11
+ } from "@sixb/core/storage"
12
+ import type { Elysia } from "elysia"
13
+ import { z } from "zod"
14
+ import { requestActor, requireRequestSixb } from "../auth/scope"
15
+ import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
16
+ import { OPENAPI_TAGS } from "../openapi/tags"
17
+ import {
18
+ AgentComputerSessionParamsSchema,
19
+ AgentRequestErrorResponseSchema,
20
+ AgentThreadComputerInputSchema,
21
+ AgentThreadParamsSchema,
22
+ AgentThreadSchema,
23
+ HoldAgentComputerSessionBodySchema,
24
+ HoldAgentComputerSessionResponseSchema,
25
+ MoveAgentThreadToComputerBodySchema,
26
+ } from "../schemas/agents"
27
+ import { ErrorResponseSchema } from "../schemas/common"
28
+ import { unconfiguredStorageResponse } from "../utils/http"
29
+ import { handleAgentRouteError, principalKey, serializeThreadRead } from "./agents"
30
+
31
+ // A computer's thread runs on one of its owner's computers, in one folder there: only `sixb` open
32
+ // in that folder claims its turns. Each open `sixb` holds a session, a lease it renews, so the
33
+ // thread reads as online while one is live, and its owner can send from anywhere. Moving it to
34
+ // another folder, or to the cloud, is its owner's call.
35
+
36
+ /** How long a session stays live without a renewal; `sixb` renews it three times as often. */
37
+ const SESSION_MS = 60_000
38
+ /** How many sessions one person holds at once: one per open `sixb`, a terminal each. */
39
+ const MAX_SESSIONS = 20
40
+
41
+ type ComputerClaim =
42
+ | { readonly computer: AgentThreadComputer }
43
+ | {
44
+ readonly refused: {
45
+ readonly status: 400 | 403
46
+ readonly error: Record<string, string>
47
+ }
48
+ }
49
+
50
+ /**
51
+ * The computer and folder claiming a computer's turn, or why the turn is not theirs: its thread
52
+ * runs on the claiming computer, in the folder it names. It reads as of now, for a refusal that
53
+ * says why; the run's start is what decides, should the thread move right after.
54
+ */
55
+ export async function computerClaiming(
56
+ sessions: AgentRunSessionHost,
57
+ run: ConversationAgentRunRecord,
58
+ body: unknown
59
+ ): Promise<ComputerClaim> {
60
+ const claimed = AgentThreadComputerInputSchema.safeParse(
61
+ (body as { readonly computer?: unknown } | null)?.computer
62
+ )
63
+ if (!claimed.success) {
64
+ return {
65
+ refused: {
66
+ status: 400,
67
+ error: {
68
+ kind: "Error",
69
+ message:
70
+ "[SixbServer] A claim of a computer's turn names the computer and folder it comes from.",
71
+ },
72
+ },
73
+ }
74
+ }
75
+
76
+ const thread = await sessions.storage.agents.threads.getById({
77
+ projectId: run.projectId,
78
+ id: run.threadId,
79
+ })
80
+ const place = thread?.computer
81
+ if (place && sameComputerPlace(place, claimed.data)) return { computer: claimed.data }
82
+ return {
83
+ refused: {
84
+ status: 403,
85
+ error: {
86
+ kind: "AgentRunRefusedError",
87
+ message: !place
88
+ ? `[SixbServer] Agent thread '${run.threadId}' has no folder yet: move it to this one to run its turns here.`
89
+ : place.id === claimed.data.id
90
+ ? `[SixbServer] Agent thread '${run.threadId}' works in ${place.folder}: open sixb there, or move it to this folder.`
91
+ : `[SixbServer] Agent thread '${run.threadId}' runs on ${place.name}: move it to this computer to run its turns here.`,
92
+ },
93
+ },
94
+ }
95
+ }
96
+
97
+ /** End the sessions no `sixb` renewed, and say so for each folder left with none. */
98
+ export async function endLapsedComputerSessions(host: SixbHostView): Promise<void> {
99
+ const agents = host.storage.agents
100
+ if (!agents) return
101
+ const lapsed = await agents.computers.removeLapsed({ projectId: host.id, now: new Date() })
102
+ await announceOffline(host, agents, lapsed)
103
+ }
104
+
105
+ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
106
+ return app
107
+ .post(
108
+ "/api/agent-threads/:threadId/computer",
109
+ async (context) => {
110
+ const { params, body, set } = context
111
+ const sixb = requireRequestSixb(context)
112
+ try {
113
+ if (!host.storage.agents) return unconfiguredStorageResponse(set, "Agent storage")
114
+
115
+ const { computer } = MoveAgentThreadToComputerBodySchema.parse(body)
116
+ const moved = await sixb.agent.threads.moveToComputer(params.threadId, computer)
117
+ return await serializeThreadRead(host, sixb, moved)
118
+ } catch (error) {
119
+ return handleAgentRouteError(error, set)
120
+ }
121
+ },
122
+ {
123
+ params: AgentThreadParamsSchema,
124
+ body: MoveAgentThreadToComputerBodySchema,
125
+ response: {
126
+ 200: AgentThreadSchema,
127
+ 400: AgentRequestErrorResponseSchema,
128
+ 403: AgentRequestErrorResponseSchema,
129
+ 404: AgentRequestErrorResponseSchema,
130
+ 409: AgentRequestErrorResponseSchema,
131
+ 501: ErrorResponseSchema,
132
+ },
133
+ detail: {
134
+ summary: "Move a thread to one of your computers, in a folder there",
135
+ description:
136
+ "A thread that runs on its owner's computer runs there alone, in one folder: only `sixb` open in that folder claims its turns. Its owner moves it to another folder or computer. Refused while a turn runs or waits on approvals.",
137
+ tags: [OPENAPI_TAGS.agentThreads.name],
138
+ operationId: "moveAgentThreadToComputer",
139
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
140
+ },
141
+ }
142
+ )
143
+ .delete(
144
+ "/api/agent-threads/:threadId/computer",
145
+ async (context) => {
146
+ const { params, set } = context
147
+ const sixb = requireRequestSixb(context)
148
+ try {
149
+ if (!host.storage.agents) return unconfiguredStorageResponse(set, "Agent storage")
150
+
151
+ const moved = await sixb.agent.threads.moveToCloud(params.threadId)
152
+ return await serializeThreadRead(host, sixb, moved)
153
+ } catch (error) {
154
+ return handleAgentRouteError(error, set)
155
+ }
156
+ },
157
+ {
158
+ params: AgentThreadParamsSchema,
159
+ response: {
160
+ 200: AgentThreadSchema,
161
+ 400: AgentRequestErrorResponseSchema,
162
+ 403: AgentRequestErrorResponseSchema,
163
+ 404: AgentRequestErrorResponseSchema,
164
+ 409: AgentRequestErrorResponseSchema,
165
+ 501: ErrorResponseSchema,
166
+ },
167
+ detail: {
168
+ summary: "Move a thread from your computer to the cloud",
169
+ description:
170
+ "Its turns run in the cloud from now on, starting with the one waiting for the computer, if any. The files it worked on stay on the computer. Refused while a turn runs there or waits on approvals.",
171
+ tags: [OPENAPI_TAGS.agentThreads.name],
172
+ operationId: "moveAgentThreadToCloud",
173
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
174
+ },
175
+ }
176
+ )
177
+ .put(
178
+ "/api/agent-computers/sessions/:sessionId",
179
+ async (context) => {
180
+ const { params, body, set } = context
181
+ const sixb = requireRequestSixb(context)
182
+ try {
183
+ const agents = host.storage.agents
184
+ if (!agents) return unconfiguredStorageResponse(set, "Agent storage")
185
+
186
+ const { computer } = HoldAgentComputerSessionBodySchema.parse(body)
187
+ const ownerPrincipal = requestActor(sixb)
188
+ const now = new Date()
189
+ const before = await agents.computers.listLive({
190
+ projectId: host.id,
191
+ ownerPrincipal,
192
+ now,
193
+ })
194
+ if (
195
+ before.length >= MAX_SESSIONS &&
196
+ !before.some((session) => session.id === params.sessionId)
197
+ ) {
198
+ set.status = 429
199
+ return {
200
+ error: `[SixbServer] You have ${MAX_SESSIONS} sixb sessions open: quit one to open another.`,
201
+ }
202
+ }
203
+ const expiresAt = new Date(now.getTime() + SESSION_MS)
204
+ await agents.computers.hold({
205
+ projectId: host.id,
206
+ id: params.sessionId,
207
+ ownerPrincipal,
208
+ computer,
209
+ expiresAt,
210
+ })
211
+ if (!before.some((session) => sameComputerPlace(session.computer, computer))) {
212
+ await announce(host, ownerPrincipal, computer, true)
213
+ }
214
+ return HoldAgentComputerSessionResponseSchema.parse({
215
+ expiresAt: expiresAt.toISOString(),
216
+ waiting: await waitingTurns(host, agents, ownerPrincipal, computer),
217
+ })
218
+ } catch (error) {
219
+ return handleAgentRouteError(error, set)
220
+ }
221
+ },
222
+ {
223
+ params: AgentComputerSessionParamsSchema,
224
+ body: HoldAgentComputerSessionBodySchema,
225
+ response: {
226
+ 200: HoldAgentComputerSessionResponseSchema,
227
+ 400: AgentRequestErrorResponseSchema,
228
+ 429: ErrorResponseSchema,
229
+ 501: ErrorResponseSchema,
230
+ },
231
+ detail: {
232
+ summary: "Open or renew a computer session",
233
+ description:
234
+ "`sixb` holds one while it is open: your threads on this computer, in this folder, read as online, and you can continue them from anywhere. It lapses a minute after its last renewal. The answer lists the turns waiting for it.",
235
+ tags: [OPENAPI_TAGS.agentThreads.name],
236
+ operationId: "holdAgentComputerSession",
237
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
238
+ },
239
+ }
240
+ )
241
+ .delete(
242
+ "/api/agent-computers/sessions/:sessionId",
243
+ async (context) => {
244
+ const { params, set } = context
245
+ const sixb = requireRequestSixb(context)
246
+ try {
247
+ const agents = host.storage.agents
248
+ if (!agents) return unconfiguredStorageResponse(set, "Agent storage")
249
+
250
+ const released = await agents.computers.release({
251
+ projectId: host.id,
252
+ id: params.sessionId,
253
+ ownerPrincipal: requestActor(sixb),
254
+ })
255
+ if (released) await announceOffline(host, agents, [released])
256
+ set.status = 204
257
+ return
258
+ } catch (error) {
259
+ return handleAgentRouteError(error, set)
260
+ }
261
+ },
262
+ {
263
+ params: AgentComputerSessionParamsSchema,
264
+ response: {
265
+ 204: z.void(),
266
+ 501: ErrorResponseSchema,
267
+ },
268
+ detail: {
269
+ summary: "Close a computer session",
270
+ description: "`sixb` closes its session when it quits.",
271
+ tags: [OPENAPI_TAGS.agentThreads.name],
272
+ operationId: "releaseAgentComputerSession",
273
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
274
+ },
275
+ }
276
+ )
277
+ }
278
+
279
+ /** The owner's queued turns that wait for this computer, in this folder. */
280
+ async function waitingTurns(
281
+ host: SixbHostView,
282
+ agents: AgentStorage,
283
+ ownerPrincipal: Principal,
284
+ computer: AgentThreadComputer
285
+ ): Promise<string[]> {
286
+ // Their own threads there with a turn active: nobody else's turns, however many, crowd them out.
287
+ const { threads } = await agents.threads.list({
288
+ projectId: host.id,
289
+ ownerPrincipal,
290
+ activeOnComputer: computer,
291
+ limit: 100,
292
+ })
293
+ const active = threads.flatMap((thread) => (thread.activeRunId ? [thread.activeRunId] : []))
294
+ if (active.length === 0) return []
295
+ const runs = await agents.runs.getByIds({ projectId: host.id, ids: active })
296
+ return runs
297
+ .filter(
298
+ (run) =>
299
+ run.kind === "conversation" && run.status === "queued" && run.spec?.runsOn === "computer"
300
+ )
301
+ .map((run) => run.id)
302
+ }
303
+
304
+ /** For each folder these sessions held, say it went offline when no other session holds it. */
305
+ async function announceOffline(
306
+ host: SixbHostView,
307
+ agents: AgentStorage,
308
+ ended: readonly AgentComputerSessionRecord[]
309
+ ): Promise<void> {
310
+ const now = new Date()
311
+ const byOwner = new Map<string, AgentComputerSessionRecord[]>()
312
+ for (const session of ended) {
313
+ const key = principalKey(session.ownerPrincipal)
314
+ const sessions = byOwner.get(key)
315
+ if (sessions) sessions.push(session)
316
+ else byOwner.set(key, [session])
317
+ }
318
+ for (const [first, ...rest] of byOwner.values()) {
319
+ if (!first) continue
320
+ const { ownerPrincipal } = first
321
+ const live = await agents.computers.listLive({ projectId: host.id, ownerPrincipal, now })
322
+ const announced: AgentThreadComputer[] = []
323
+ for (const { computer } of [first, ...rest]) {
324
+ const stillHeld = [...live.map((other) => other.computer), ...announced]
325
+ if (stillHeld.some((other) => sameComputerPlace(other, computer))) continue
326
+ announced.push(computer)
327
+ await announce(host, ownerPrincipal, computer, false)
328
+ }
329
+ }
330
+ }
331
+
332
+ /** Presence is a hint the web follows: a lost announcement only delays its badge. */
333
+ async function announce(
334
+ host: SixbHostView,
335
+ ownerPrincipal: Principal,
336
+ computer: AgentThreadComputer,
337
+ online: boolean
338
+ ): Promise<void> {
339
+ await publishAgentComputerActivity(host.broker, {
340
+ projectId: host.id,
341
+ ownerPrincipal,
342
+ computerId: computer.id,
343
+ folder: computer.folder,
344
+ online,
345
+ }).catch((error: unknown) => {
346
+ console.error("[SixbServer] Could not announce a computer session.", error)
347
+ })
348
+ }