@sixb/server 0.2.0 → 0.2.2

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.
@@ -1,8 +1,14 @@
1
- import type { SixbHostView } from "@sixb/core"
1
+ import {
2
+ AgentRequestError,
3
+ principalsEqual,
4
+ type SixbHostView,
5
+ stableJsonStringify,
6
+ } from "@sixb/core"
2
7
  import { sameComputerPlace } from "@sixb/core/internal/agent-run-storage-provider"
3
8
  import type { AgentRunSessionHost } from "@sixb/core/internal/agents"
4
9
  import { publishAgentComputerActivity } from "@sixb/core/internal/agents/streams"
5
10
  import type {
11
+ AgentComputerBackgroundCommand,
6
12
  AgentComputerSessionRecord,
7
13
  AgentStorage,
8
14
  AgentThreadComputer,
@@ -15,6 +21,7 @@ import { requestActor, requireRequestSixb } from "../auth/scope"
15
21
  import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
16
22
  import { OPENAPI_TAGS } from "../openapi/tags"
17
23
  import {
24
+ AgentBackgroundCommandParamsSchema,
18
25
  AgentComputerSessionParamsSchema,
19
26
  AgentRequestErrorResponseSchema,
20
27
  AgentThreadComputerInputSchema,
@@ -23,10 +30,17 @@ import {
23
30
  HoldAgentComputerSessionBodySchema,
24
31
  HoldAgentComputerSessionResponseSchema,
25
32
  MoveAgentThreadToComputerBodySchema,
33
+ StopAgentBackgroundCommandBodySchema,
34
+ StopAgentBackgroundCommandResponseSchema,
26
35
  } from "../schemas/agents"
27
36
  import { ErrorResponseSchema } from "../schemas/common"
28
37
  import { unconfiguredStorageResponse } from "../utils/http"
29
- import { handleAgentRouteError, principalKey, serializeThreadRead } from "./agents"
38
+ import {
39
+ handleAgentRouteError,
40
+ principalKey,
41
+ sameBackgroundCommand,
42
+ serializeThreadRead,
43
+ } from "./agents"
30
44
 
31
45
  // A computer's thread runs on one of its owner's computers, in one folder there: only `sixb` open
32
46
  // in that folder claims its turns. Each open `sixb` holds a session, a lease it renews, so the
@@ -35,8 +49,11 @@ import { handleAgentRouteError, principalKey, serializeThreadRead } from "./agen
35
49
 
36
50
  /** How long a session stays live without a renewal; `sixb` renews it three times as often. */
37
51
  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
52
+ /**
53
+ * How many sessions one person holds at once, a folder connected on a computer each. A computer
54
+ * keeps every folder chosen on it connected, so this only bounds abuse.
55
+ */
56
+ const MAX_SESSIONS = 200
40
57
 
41
58
  type ComputerClaim =
42
59
  | { readonly computer: AgentThreadComputer }
@@ -183,7 +200,8 @@ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
183
200
  const agents = host.storage.agents
184
201
  if (!agents) return unconfiguredStorageResponse(set, "Agent storage")
185
202
 
186
- const { computer } = HoldAgentComputerSessionBodySchema.parse(body)
203
+ const { computer, backgroundCommands = [] } =
204
+ HoldAgentComputerSessionBodySchema.parse(body)
187
205
  const ownerPrincipal = requestActor(sixb)
188
206
  const now = new Date()
189
207
  const before = await agents.computers.listLive({
@@ -197,7 +215,7 @@ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
197
215
  ) {
198
216
  set.status = 429
199
217
  return {
200
- error: `[SixbServer] You have ${MAX_SESSIONS} sixb sessions open: quit one to open another.`,
218
+ error: `[SixbServer] You have ${MAX_SESSIONS} folders connected: forget one to connect another.`,
201
219
  }
202
220
  }
203
221
  const expiresAt = new Date(now.getTime() + SESSION_MS)
@@ -207,13 +225,29 @@ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
207
225
  ownerPrincipal,
208
226
  computer,
209
227
  expiresAt,
228
+ ...(backgroundCommands.length > 0 ? { backgroundCommands } : {}),
210
229
  })
211
- if (!before.some((session) => sameComputerPlace(session.computer, computer))) {
230
+
231
+ // The web follows the folder coming online, and its commands starting and ending.
232
+ const held = before.find((session) => session.id === params.sessionId)
233
+ const reported = !sameCommands(held?.backgroundCommands ?? [], backgroundCommands)
234
+ if (
235
+ reported ||
236
+ !before.some((session) => sameComputerPlace(session.computer, computer))
237
+ ) {
212
238
  await announce(host, ownerPrincipal, computer, true)
213
239
  }
240
+
241
+ // What was asked to stop, as long as it runs: a lost answer leaves it for the next one.
242
+ const stop = (held?.stopRequests ?? []).filter((ref) =>
243
+ backgroundCommands.some(
244
+ (command) => command.status === "running" && sameBackgroundCommand(command, ref)
245
+ )
246
+ )
214
247
  return HoldAgentComputerSessionResponseSchema.parse({
215
248
  expiresAt: expiresAt.toISOString(),
216
249
  waiting: await waitingTurns(host, agents, ownerPrincipal, computer),
250
+ ...(stop.length > 0 ? { stop } : {}),
217
251
  })
218
252
  } catch (error) {
219
253
  return handleAgentRouteError(error, set)
@@ -231,13 +265,100 @@ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
231
265
  detail: {
232
266
  summary: "Open or renew a computer session",
233
267
  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.",
268
+ "`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. It reports the background commands it runs for your threads; the answer lists the turns waiting for it, and the commands someone asked to stop.",
235
269
  tags: [OPENAPI_TAGS.agentThreads.name],
236
270
  operationId: "holdAgentComputerSession",
237
271
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
238
272
  },
239
273
  }
240
274
  )
275
+ .post(
276
+ "/api/agent-threads/:threadId/background-commands/:commandId/stop",
277
+ async (context) => {
278
+ const { params, body, set } = context
279
+ const sixb = requireRequestSixb(context)
280
+ try {
281
+ const agents = host.storage.agents
282
+ if (!agents) return unconfiguredStorageResponse(set, "Agent storage")
283
+
284
+ const { startedAt } = StopAgentBackgroundCommandBodySchema.parse(body)
285
+ const thread = await sixb.agent.threads.getById(params.threadId)
286
+ if (!thread) {
287
+ throw new AgentRequestError("thread_not_found", "[SixbServer] Agent thread not found.")
288
+ }
289
+
290
+ // It runs on its owner's computer, under their account: as moving the thread, theirs to
291
+ // stop. Anyone else asks the agent, whose turn its requester can stop.
292
+ const ownerPrincipal = requestActor(sixb)
293
+ if (!principalsEqual(thread.ownerPrincipal, ownerPrincipal)) {
294
+ throw new AgentRequestError(
295
+ "not_thread_owner",
296
+ `[SixbServer] Only the owner of Agent thread '${thread.id}' stops its background commands, which run on their computer.`
297
+ )
298
+ }
299
+
300
+ // Whichever of their sixb runs it: one started in a folder runs on there once the thread
301
+ // moved to another, or to the cloud.
302
+ const ref = { threadId: thread.id, id: params.commandId, startedAt }
303
+ const live = await agents.computers.listLive({
304
+ projectId: host.id,
305
+ ownerPrincipal,
306
+ now: new Date(),
307
+ })
308
+ const running = live
309
+ .flatMap((session) =>
310
+ (session.backgroundCommands ?? []).map((command) => ({ session, command }))
311
+ )
312
+ .find(
313
+ ({ command }) => command.status === "running" && sameBackgroundCommand(command, ref)
314
+ )
315
+ // Its sixb may close between the two: the stop then has no session to wait in.
316
+ const asked =
317
+ running &&
318
+ (await agents.computers.requestStop({
319
+ projectId: host.id,
320
+ id: running.session.id,
321
+ ownerPrincipal,
322
+ command: ref,
323
+ }))
324
+ if (!running || !asked) {
325
+ set.status = 404
326
+ return {
327
+ error: `[SixbServer] Background command '${params.commandId}' does not run on an open sixb: it ended, or sixb closed.`,
328
+ }
329
+ }
330
+
331
+ // Its sixb hears it and renews at once: the stop is in the answer.
332
+ await announce(host, ownerPrincipal, running.session.computer, true)
333
+
334
+ set.status = 202
335
+ return StopAgentBackgroundCommandResponseSchema.parse({
336
+ command: { ...running.command, stopping: true },
337
+ })
338
+ } catch (error) {
339
+ return handleAgentRouteError(error, set)
340
+ }
341
+ },
342
+ {
343
+ params: AgentBackgroundCommandParamsSchema,
344
+ body: StopAgentBackgroundCommandBodySchema,
345
+ response: {
346
+ 202: StopAgentBackgroundCommandResponseSchema,
347
+ 400: AgentRequestErrorResponseSchema,
348
+ 403: AgentRequestErrorResponseSchema,
349
+ 404: AgentRequestErrorResponseSchema,
350
+ 501: ErrorResponseSchema,
351
+ },
352
+ detail: {
353
+ summary: "Stop a background command on your computer",
354
+ description:
355
+ "A command the agent ran in the background on your computer keeps running after its turn. `sixb` there stops it, and everything it started, at its next renewal, which this asks for at once. The thread's owner alone stops it.",
356
+ tags: [OPENAPI_TAGS.agentThreads.name],
357
+ operationId: "stopAgentBackgroundCommand",
358
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
359
+ },
360
+ }
361
+ )
241
362
  .delete(
242
363
  "/api/agent-computers/sessions/:sessionId",
243
364
  async (context) => {
@@ -276,6 +397,14 @@ export function registerAgentComputerRoutes(app: Elysia, host: SixbHostView) {
276
397
  )
277
398
  }
278
399
 
400
+ /** Whether two reports of a session's background commands say the same. */
401
+ function sameCommands(
402
+ before: readonly AgentComputerBackgroundCommand[],
403
+ now: readonly AgentComputerBackgroundCommand[]
404
+ ): boolean {
405
+ return stableJsonStringify(before) === stableJsonStringify(now)
406
+ }
407
+
279
408
  /** The owner's queued turns that wait for this computer, in this folder. */
280
409
  async function waitingTurns(
281
410
  host: SixbHostView,
@@ -301,7 +430,10 @@ async function waitingTurns(
301
430
  .map((run) => run.id)
302
431
  }
303
432
 
304
- /** For each folder these sessions held, say it went offline when no other session holds it. */
433
+ /**
434
+ * For each folder these sessions held, say it went offline when no other session holds it, and
435
+ * that its background commands stopped when the session that ended ran some.
436
+ */
305
437
  async function announceOffline(
306
438
  host: SixbHostView,
307
439
  agents: AgentStorage,
@@ -320,11 +452,15 @@ async function announceOffline(
320
452
  const { ownerPrincipal } = first
321
453
  const live = await agents.computers.listLive({ projectId: host.id, ownerPrincipal, now })
322
454
  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
455
+ for (const { computer, backgroundCommands = [] } of [first, ...rest]) {
456
+ if (announced.some((other) => sameComputerPlace(other, computer))) continue
457
+
458
+ // Another sixb still holds the folder: the web reads it again for the commands that stopped.
459
+ const online = live.some((other) => sameComputerPlace(other.computer, computer))
460
+ if (online && backgroundCommands.length === 0) continue
461
+
326
462
  announced.push(computer)
327
- await announce(host, ownerPrincipal, computer, false)
463
+ await announce(host, ownerPrincipal, computer, online)
328
464
  }
329
465
  }
330
466
  }
@@ -17,6 +17,8 @@ import {
17
17
  import { agentRunStreamId } from "@sixb/core/internal/agents/streams"
18
18
  import { resolveFileRefAtPath } from "@sixb/core/internal/blob-storage"
19
19
  import {
20
+ type AgentBackgroundCommandRef,
21
+ type AgentComputerBackgroundCommand,
20
22
  type AgentContextCheckpointRecord,
21
23
  type AgentMessageRecord,
22
24
  type AgentRunDiagnostic,
@@ -126,7 +128,7 @@ export async function serializeThreads(
126
128
  title: thread.title,
127
129
  sandboxParams: thread.sandboxParams,
128
130
  runsOn: thread.runsOn,
129
- computer: placeOf(thread),
131
+ ...placeOf(thread),
130
132
  movedAt: thread.movedAt ? toIsoString(thread.movedAt) : undefined,
131
133
  sandboxState: thread.sandboxState && {
132
134
  name: thread.sandboxState.name,
@@ -153,14 +155,19 @@ export async function serializeThread(
153
155
  return serialized
154
156
  }
155
157
 
156
- /** Where each of the viewer's own computer threads runs, and whether its folder is open now. */
158
+ /**
159
+ * Where each of the viewer's own computer threads runs, whether its folder is open now, and the
160
+ * background commands their `sixb` runs for it.
161
+ */
157
162
  async function computerPlaces(
158
163
  host: SixbHostView,
159
164
  threads: readonly AgentThreadView[],
160
165
  viewer: Principal
161
- ): Promise<(thread: AgentThreadView) => (AgentThreadComputer & { online: boolean }) | undefined> {
166
+ ): Promise<(thread: AgentThreadView) => ThreadComputerView> {
167
+ // A thread that moved may still have commands running where it was.
162
168
  const owned = (thread: AgentThreadView) =>
163
- thread.computer !== undefined && principalsEqual(thread.ownerPrincipal, viewer)
169
+ (thread.computer !== undefined || thread.movedAt !== undefined) &&
170
+ principalsEqual(thread.ownerPrincipal, viewer)
164
171
  const live =
165
172
  host.storage.agents && threads.some(owned)
166
173
  ? await host.storage.agents.computers.listLive({
@@ -170,13 +177,51 @@ async function computerPlaces(
170
177
  })
171
178
  : []
172
179
  return (thread) => {
180
+ if (!owned(thread)) return {}
181
+
182
+ // Its background commands, from any of its owner's sixb: a command started in one folder runs
183
+ // on there once the thread moved to another, or to the cloud. And which of them a stop is on.
184
+ const backgroundCommands = live.flatMap((session) =>
185
+ (session.backgroundCommands ?? [])
186
+ .filter((command) => command.threadId === thread.id)
187
+ .map((command) => {
188
+ const stopping =
189
+ command.status === "running" &&
190
+ (session.stopRequests ?? []).some((ref) => sameBackgroundCommand(command, ref))
191
+ return stopping ? { ...command, stopping } : command
192
+ })
193
+ )
194
+
173
195
  const computer = thread.computer
174
- if (!computer || !owned(thread)) return undefined
175
- const online = live.some((session) => sameComputerPlace(session.computer, computer))
176
- return { ...computer, online }
196
+ const online =
197
+ computer !== undefined &&
198
+ live.some((session) => sameComputerPlace(session.computer, computer))
199
+ return {
200
+ ...(computer ? { computer: { ...computer, online } } : {}),
201
+ ...(backgroundCommands.length > 0 ? { backgroundCommands } : {}),
202
+ }
177
203
  }
178
204
  }
179
205
 
206
+ interface ThreadComputerView {
207
+ readonly computer?: AgentThreadComputer & { readonly online: boolean }
208
+ readonly backgroundCommands?: readonly (AgentComputerBackgroundCommand & {
209
+ readonly stopping?: boolean
210
+ })[]
211
+ }
212
+
213
+ /** Whether a reported background command is the one `ref` names: by its start, as ids repeat. */
214
+ export function sameBackgroundCommand(
215
+ command: AgentBackgroundCommandRef,
216
+ ref: AgentBackgroundCommandRef
217
+ ): boolean {
218
+ return (
219
+ command.threadId === ref.threadId &&
220
+ command.id === ref.id &&
221
+ command.startedAt === ref.startedAt
222
+ )
223
+ }
224
+
180
225
  function serializeMessage(
181
226
  message: AgentMessageRecord,
182
227
  annotations: readonly AgentRunDiagnostic[] = [],
@@ -121,6 +121,25 @@ export const AgentThreadComputerInputSchema = z
121
121
  })
122
122
  .strict()
123
123
 
124
+ /**
125
+ * A background command `sixb` runs for one of your threads on your computer: it outlives the turn
126
+ * that started it, until it exits, the agent or you stop it, or `sixb` closes.
127
+ */
128
+ export const AgentBackgroundCommandSchema = z
129
+ .object({
130
+ threadId: z.string().min(1).max(200),
131
+ /** `bg_<hex>`, as the agent's tools name it: with `startedAt`, it names the command. */
132
+ id: z.string().min(1).max(200),
133
+ /** Its first 1,000 characters. */
134
+ command: z.string().max(1_000),
135
+ status: z.enum(["running", "exited", "stopped"]),
136
+ /** Once it ended: a stopped command's is its signal's, such as 143 for SIGTERM. */
137
+ exitCode: z.number().int().optional(),
138
+ startedAt: z.string().min(1).max(200),
139
+ endedAt: z.string().max(200).optional(),
140
+ })
141
+ .strict()
142
+
124
143
  export const CreateAgentThreadBodySchema = z
125
144
  .object({
126
145
  title: z.string().trim().min(1).optional(),
@@ -186,6 +205,14 @@ export const AgentThreadSchema = z.object({
186
205
  online: z.boolean(),
187
206
  })
188
207
  .optional(),
208
+ /**
209
+ * Its background commands on its owner's computer, as `sixb` reported them while open: the
210
+ * running ones, then the latest to end, wherever the thread runs now. `stopping` while a stop
211
+ * you asked for is on its way. Shown to its owner alone.
212
+ */
213
+ backgroundCommands: z
214
+ .array(AgentBackgroundCommandSchema.extend({ stopping: z.boolean().optional() }))
215
+ .optional(),
189
216
  /** When its turns last moved to where they run now: the files earlier turns used are not here. */
190
217
  movedAt: z.string().optional(),
191
218
  status: AgentThreadStatusSchema,
@@ -222,14 +249,46 @@ export const AgentComputerSessionParamsSchema = z.object({
222
249
  })
223
250
 
224
251
  export const HoldAgentComputerSessionBodySchema = z
225
- .object({ computer: AgentThreadComputerInputSchema })
252
+ .object({
253
+ computer: AgentThreadComputerInputSchema,
254
+ /**
255
+ * Your threads' background commands this `sixb` runs or ran: the running ones, then the latest
256
+ * to end. Absent, none.
257
+ */
258
+ backgroundCommands: z.array(AgentBackgroundCommandSchema).max(64).optional(),
259
+ })
226
260
  .strict()
227
261
 
262
+ /** A background command by its start, as its id comes again once `sixb` restarts. */
263
+ export const AgentBackgroundCommandRefSchema = z.object({
264
+ threadId: z.string(),
265
+ id: z.string(),
266
+ startedAt: z.string(),
267
+ })
268
+
228
269
  export const HoldAgentComputerSessionResponseSchema = z.object({
229
270
  /** Renew before then, or the session lapses and its threads read as offline. */
230
271
  expiresAt: z.string(),
231
272
  /** Queued turns of your threads on this computer, in this folder, for it to claim. */
232
273
  waiting: z.array(z.string()),
274
+ /** Running background commands someone asked to stop from elsewhere, for it to stop. */
275
+ stop: z.array(AgentBackgroundCommandRefSchema).optional(),
276
+ })
277
+
278
+ export const AgentBackgroundCommandParamsSchema = z.object({
279
+ threadId: z.string().trim().min(1),
280
+ commandId: z.string().trim().min(1).max(200),
281
+ })
282
+
283
+ export const StopAgentBackgroundCommandBodySchema = z
284
+ .object({
285
+ /** When it started, as reported: an id names another command once `sixb` restarts. */
286
+ startedAt: z.string().trim().min(1).max(200),
287
+ })
288
+ .strict()
289
+
290
+ export const StopAgentBackgroundCommandResponseSchema = z.object({
291
+ command: AgentBackgroundCommandSchema.extend({ stopping: z.boolean().optional() }),
233
292
  })
234
293
 
235
294
  export const AddAgentThreadParticipantsBodySchema = z
@@ -23,6 +23,7 @@ const ModelKindSchema = z.enum([
23
23
  "transcription",
24
24
  "speech",
25
25
  "reranking",
26
+ "web-search",
26
27
  ])
27
28
 
28
29
  export const AiAccountingRangeQuerySchema = z.object({