@sixb/server 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/dist/artifacts/frame.d.ts +18 -0
  2. package/dist/artifacts/frame.d.ts.map +1 -0
  3. package/dist/auth/browser-origin.d.ts +10 -1
  4. package/dist/auth/browser-origin.d.ts.map +1 -1
  5. package/dist/auth/experience.d.ts +1 -0
  6. package/dist/auth/experience.d.ts.map +1 -1
  7. package/dist/auth/public-routes.d.ts.map +1 -1
  8. package/dist/auth/responses.d.ts +1 -1
  9. package/dist/auth/responses.d.ts.map +1 -1
  10. package/dist/auth/scope.d.ts +19 -3
  11. package/dist/auth/scope.d.ts.map +1 -1
  12. package/dist/files/content.d.ts +2 -3
  13. package/dist/files/content.d.ts.map +1 -1
  14. package/dist/index.js +10636 -7071
  15. package/dist/index.js.map +56 -38
  16. package/dist/models/display.d.ts +27 -0
  17. package/dist/models/display.d.ts.map +1 -1
  18. package/dist/openapi/components.d.ts +14 -0
  19. package/dist/openapi/components.d.ts.map +1 -0
  20. package/dist/openapi/tags.d.ts +22 -2
  21. package/dist/openapi/tags.d.ts.map +1 -1
  22. package/dist/registerRoutes.d.ts +3 -0
  23. package/dist/registerRoutes.d.ts.map +1 -1
  24. package/dist/routes/actions.d.ts +5 -5
  25. package/dist/routes/activity.d.ts +35 -0
  26. package/dist/routes/activity.d.ts.map +1 -0
  27. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  28. package/dist/routes/agent-approval-gate.d.ts +27 -0
  29. package/dist/routes/agent-approval-gate.d.ts.map +1 -0
  30. package/dist/routes/agent-approvals.d.ts +599 -0
  31. package/dist/routes/agent-approvals.d.ts.map +1 -0
  32. package/dist/routes/agent-children.d.ts +318 -0
  33. package/dist/routes/agent-children.d.ts.map +1 -0
  34. package/dist/routes/agent-memory.d.ts +267 -0
  35. package/dist/routes/agent-memory.d.ts.map +1 -0
  36. package/dist/routes/agents.d.ts +1008 -98
  37. package/dist/routes/agents.d.ts.map +1 -1
  38. package/dist/routes/ai-accounting.d.ts.map +1 -1
  39. package/dist/routes/artifact-frames.d.ts +98 -0
  40. package/dist/routes/artifact-frames.d.ts.map +1 -0
  41. package/dist/routes/artifacts.d.ts +1508 -0
  42. package/dist/routes/artifacts.d.ts.map +1 -0
  43. package/dist/routes/auth.d.ts +117 -11
  44. package/dist/routes/auth.d.ts.map +1 -1
  45. package/dist/routes/connector-connection-runs.d.ts +84 -84
  46. package/dist/routes/connector-connections.d.ts +2 -2
  47. package/dist/routes/connectors.d.ts +2 -2
  48. package/dist/routes/datasets.d.ts +27 -27
  49. package/dist/routes/events.d.ts +5 -5
  50. package/dist/routes/files.d.ts +14 -14
  51. package/dist/routes/files.d.ts.map +1 -1
  52. package/dist/routes/links.d.ts +2 -2
  53. package/dist/routes/logs.d.ts +5 -5
  54. package/dist/routes/model-calls.d.ts +155 -0
  55. package/dist/routes/model-calls.d.ts.map +1 -0
  56. package/dist/routes/model-generations.d.ts +400 -0
  57. package/dist/routes/model-generations.d.ts.map +1 -0
  58. package/dist/routes/models.d.ts +434 -1
  59. package/dist/routes/models.d.ts.map +1 -1
  60. package/dist/routes/objects.d.ts +71 -40
  61. package/dist/routes/objects.d.ts.map +1 -1
  62. package/dist/routes/observed-agent-threads.d.ts +682 -0
  63. package/dist/routes/observed-agent-threads.d.ts.map +1 -0
  64. package/dist/routes/ontology.d.ts +66 -62
  65. package/dist/routes/ontology.d.ts.map +1 -1
  66. package/dist/routes/pipelines.d.ts +53 -53
  67. package/dist/routes/projections.d.ts +63 -63
  68. package/dist/routes/rules.d.ts +2 -2
  69. package/dist/routes/share-grants.d.ts +4 -4
  70. package/dist/routes/syncs.d.ts +18 -18
  71. package/dist/routes/users.d.ts +117 -0
  72. package/dist/routes/users.d.ts.map +1 -0
  73. package/dist/routes/webhook-runs.d.ts +1 -1
  74. package/dist/routes/workflows.d.ts +142 -76
  75. package/dist/routes/workflows.d.ts.map +1 -1
  76. package/dist/routes/ws/agents.d.ts +7 -2
  77. package/dist/routes/ws/agents.d.ts.map +1 -1
  78. package/dist/routes/ws/events.d.ts +6 -6
  79. package/dist/routes/ws/events.d.ts.map +1 -1
  80. package/dist/routes/ws/logs.d.ts +14 -14
  81. package/dist/routes/ws/subscription-hub.d.ts +8 -3
  82. package/dist/routes/ws/subscription-hub.d.ts.map +1 -1
  83. package/dist/schemas/actions.d.ts +15 -15
  84. package/dist/schemas/activity.d.ts +1298 -0
  85. package/dist/schemas/activity.d.ts.map +1 -0
  86. package/dist/schemas/agent-approvals.d.ts +1091 -0
  87. package/dist/schemas/agent-approvals.d.ts.map +1 -0
  88. package/dist/schemas/agent-memory.d.ts +250 -0
  89. package/dist/schemas/agent-memory.d.ts.map +1 -0
  90. package/dist/schemas/agents.d.ts +5485 -460
  91. package/dist/schemas/agents.d.ts.map +1 -1
  92. package/dist/schemas/ai-accounting.d.ts +1315 -436
  93. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  94. package/dist/schemas/ai-limits.d.ts +36 -36
  95. package/dist/schemas/ai-usage.d.ts +12 -0
  96. package/dist/schemas/ai-usage.d.ts.map +1 -1
  97. package/dist/schemas/artifacts.d.ts +1857 -0
  98. package/dist/schemas/artifacts.d.ts.map +1 -0
  99. package/dist/schemas/auth.d.ts +125 -52
  100. package/dist/schemas/auth.d.ts.map +1 -1
  101. package/dist/schemas/connectors.d.ts +42 -42
  102. package/dist/schemas/datasets.d.ts +108 -108
  103. package/dist/schemas/event-payloads.d.ts +6 -6
  104. package/dist/schemas/events.d.ts +32 -32
  105. package/dist/schemas/events.d.ts.map +1 -1
  106. package/dist/schemas/files.d.ts +24 -24
  107. package/dist/schemas/links.d.ts +2 -2
  108. package/dist/schemas/logs.d.ts +32 -32
  109. package/dist/schemas/models.d.ts +8889 -10
  110. package/dist/schemas/models.d.ts.map +1 -1
  111. package/dist/schemas/objects.d.ts +48 -12
  112. package/dist/schemas/objects.d.ts.map +1 -1
  113. package/dist/schemas/ontology.d.ts +127 -104
  114. package/dist/schemas/ontology.d.ts.map +1 -1
  115. package/dist/schemas/pipelines.d.ts +166 -166
  116. package/dist/schemas/projections.d.ts +346 -346
  117. package/dist/schemas/rules.d.ts +4 -4
  118. package/dist/schemas/share-grants.d.ts +14 -14
  119. package/dist/schemas/syncs.d.ts +40 -40
  120. package/dist/schemas/users.d.ts +72 -0
  121. package/dist/schemas/users.d.ts.map +1 -0
  122. package/dist/schemas/webhook-runs.d.ts +6 -6
  123. package/dist/schemas/workflows.d.ts +769 -254
  124. package/dist/schemas/workflows.d.ts.map +1 -1
  125. package/dist/server.d.ts +1 -0
  126. package/dist/server.d.ts.map +1 -1
  127. package/dist/utils/http.d.ts.map +1 -1
  128. package/package.json +7 -7
  129. package/src/artifacts/frame.ts +51 -0
  130. package/src/auth/browser-origin.ts +20 -5
  131. package/src/auth/experience.ts +1 -1
  132. package/src/auth/guard.ts +2 -2
  133. package/src/auth/public-routes.ts +16 -0
  134. package/src/auth/responses.ts +7 -6
  135. package/src/auth/scope.ts +32 -3
  136. package/src/files/content.ts +9 -13
  137. package/src/models/display.ts +61 -16
  138. package/src/openapi/components.ts +54 -0
  139. package/src/openapi/tags.ts +20 -0
  140. package/src/registerRoutes.ts +23 -0
  141. package/src/routes/activity.ts +327 -0
  142. package/src/routes/agent-api-gateway.ts +115 -91
  143. package/src/routes/agent-approval-gate.ts +213 -0
  144. package/src/routes/agent-approvals.ts +299 -0
  145. package/src/routes/agent-children.ts +209 -0
  146. package/src/routes/agent-memory.ts +210 -0
  147. package/src/routes/agents.ts +364 -143
  148. package/src/routes/ai-accounting.ts +4 -0
  149. package/src/routes/artifact-frames.ts +144 -0
  150. package/src/routes/artifacts.ts +717 -0
  151. package/src/routes/auth.ts +306 -13
  152. package/src/routes/file-downloads.ts +1 -3
  153. package/src/routes/files.ts +6 -7
  154. package/src/routes/model-calls.ts +120 -0
  155. package/src/routes/model-generations.ts +245 -0
  156. package/src/routes/models.ts +116 -9
  157. package/src/routes/objects.ts +55 -61
  158. package/src/routes/observed-agent-threads.ts +253 -0
  159. package/src/routes/ontology.ts +1 -0
  160. package/src/routes/users.ts +73 -0
  161. package/src/routes/workflows.ts +6 -9
  162. package/src/routes/ws/agents.ts +10 -5
  163. package/src/routes/ws/events.ts +3 -2
  164. package/src/routes/ws/subscription-hub.ts +53 -20
  165. package/src/schemas/activity.ts +287 -0
  166. package/src/schemas/agent-approvals.ts +129 -0
  167. package/src/schemas/agent-memory.ts +96 -0
  168. package/src/schemas/agents.ts +240 -2
  169. package/src/schemas/ai-accounting.ts +40 -4
  170. package/src/schemas/ai-usage.ts +10 -0
  171. package/src/schemas/artifacts.ts +246 -0
  172. package/src/schemas/auth.ts +25 -0
  173. package/src/schemas/models.ts +197 -1
  174. package/src/schemas/objects.ts +181 -0
  175. package/src/schemas/ontology.ts +1 -0
  176. package/src/schemas/users.ts +24 -0
  177. package/src/schemas/workflows.ts +2 -0
  178. package/src/server.ts +34 -19
  179. package/src/utils/http.ts +2 -0
@@ -2,25 +2,21 @@ import {
2
2
  AgentRequestError,
3
3
  type AgentRequestErrorCode,
4
4
  type AgentRunView,
5
+ type AgentThreadView,
5
6
  type FileRef,
6
7
  type SixbHostView,
7
8
  } from "@sixb/core"
8
- import {
9
- isRetryableAgentRun,
10
- publishAgentRunCancel,
11
- publishAgentRunFinished,
12
- } from "@sixb/core/internal/agents"
9
+ import { assertConversationThread, isRetryableAgentRun } from "@sixb/core/internal/agents"
13
10
  import { agentRunStreamId } from "@sixb/core/internal/agents/streams"
14
11
  import { resolveFileRefAtPath } from "@sixb/core/internal/blob-storage"
15
12
  import {
16
13
  type AgentContextCheckpointRecord,
17
14
  type AgentMessageRecord,
18
15
  type AgentRunDiagnostic,
19
- type AgentRunRecord,
20
16
  type AgentStorage,
21
17
  AgentStorageError,
22
18
  type AgentThreadRecord,
23
- type ConversationAgentRunRecord,
19
+ type Principal,
24
20
  } from "@sixb/core/storage"
25
21
  import type { Elysia } from "elysia"
26
22
  import { ZodError, z } from "zod"
@@ -34,6 +30,7 @@ import {
34
30
  import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
35
31
  import { OPENAPI_TAGS } from "../openapi/tags"
36
32
  import {
33
+ AddAgentThreadParticipantsBodySchema,
37
34
  AgentDescriptorSchema,
38
35
  AgentMessageFileContentParamsSchema,
39
36
  AgentMessageListResponseSchema,
@@ -47,6 +44,7 @@ import {
47
44
  AgentThreadListQuerySchema,
48
45
  AgentThreadListResponseSchema,
49
46
  AgentThreadParamsSchema,
47
+ AgentThreadParticipantParamsSchema,
50
48
  AgentThreadSchema,
51
49
  CancelAgentRunBodySchema,
52
50
  CancelAgentRunResponseSchema,
@@ -72,25 +70,60 @@ const AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
72
70
  .regex(/^\/parts(?:\/|$)/, "Agent message file content paths must start with /parts/"),
73
71
  })
74
72
 
75
- function serializeThread(thread: AgentThreadRecord): ReturnType<typeof AgentThreadSchema.parse> {
76
- return AgentThreadSchema.parse({
77
- id: thread.id,
78
- projectId: thread.projectId,
79
- ownerPrincipal: thread.ownerPrincipal,
80
- title: thread.title,
81
- sandboxParams: thread.sandboxParams,
82
- sandboxState: thread.sandboxState && {
83
- name: thread.sandboxState.name,
84
- status: thread.sandboxState.status,
85
- initialized: thread.sandboxState.initialized,
86
- },
87
- status: thread.status,
88
- activeRunId: thread.activeRunId,
89
- lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
90
- messageCount: thread.messageCount,
91
- createdAt: toIsoString(thread.createdAt),
92
- updatedAt: toIsoString(thread.updatedAt),
93
- })
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."
75
+
76
+ /** Threads as the API returns them, their owner and participants named by their accounts. */
77
+ export async function serializeThreads(
78
+ host: SixbHostView,
79
+ threads: readonly AgentThreadView[]
80
+ ): Promise<ReturnType<typeof AgentThreadSchema.parse>[]> {
81
+ const people = await namePrincipals(
82
+ host,
83
+ threads.flatMap((thread) => [
84
+ thread.ownerPrincipal,
85
+ ...thread.participants.map((participant) => participant.principal),
86
+ ])
87
+ )
88
+ const named = (principal: Principal) => people.get(principalKey(principal)) ?? principal
89
+
90
+ return threads.map((thread) =>
91
+ AgentThreadSchema.parse({
92
+ id: thread.id,
93
+ projectId: thread.projectId,
94
+ kind: thread.kind,
95
+ parent: thread.parent,
96
+ ownerPrincipal: thread.ownerPrincipal,
97
+ owner: named(thread.ownerPrincipal),
98
+ participants: thread.participants.map((participant) => ({
99
+ principal: named(participant.principal),
100
+ addedAt: toIsoString(participant.addedAt),
101
+ addedBy: participant.addedBy,
102
+ })),
103
+ title: thread.title,
104
+ sandboxParams: thread.sandboxParams,
105
+ sandboxState: thread.sandboxState && {
106
+ name: thread.sandboxState.name,
107
+ status: thread.sandboxState.status,
108
+ initialized: thread.sandboxState.initialized,
109
+ },
110
+ status: thread.status,
111
+ activeRunId: thread.activeRunId,
112
+ lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
113
+ messageCount: thread.messageCount,
114
+ createdAt: toIsoString(thread.createdAt),
115
+ updatedAt: toIsoString(thread.updatedAt),
116
+ })
117
+ )
118
+ }
119
+
120
+ export async function serializeThread(
121
+ host: SixbHostView,
122
+ thread: AgentThreadView
123
+ ): Promise<ReturnType<typeof AgentThreadSchema.parse>> {
124
+ const [serialized] = await serializeThreads(host, [thread])
125
+ if (!serialized) throw new Error(`[SixbServer] Could not serialize Agent thread '${thread.id}'.`)
126
+ return serialized
94
127
  }
95
128
 
96
129
  function serializeMessage(
@@ -126,12 +159,16 @@ export function serializeAgentRun(run: AgentRunView): ReturnType<typeof AgentRun
126
159
  return AgentRunSchema.parse({
127
160
  id: run.id,
128
161
  projectId: run.projectId,
162
+ kind: run.kind,
129
163
  threadId: run.threadId,
130
164
  triggerMessageId: run.triggerMessageId,
165
+ parentRunId: run.kind === "subagent" ? run.parentRunId : undefined,
131
166
  requestedBy: run.requestedBy,
132
167
  status: run.status,
133
168
  model: run.spec?.model,
169
+ tier: run.spec?.tier,
134
170
  reasoning: run.spec?.reasoning,
171
+ approvalMode: run.spec?.approvalMode,
135
172
  modelId: run.modelId,
136
173
  finishReason: run.finishReason,
137
174
  usage: run.usage,
@@ -166,19 +203,7 @@ async function getAgentMessageFileContentThread(params: {
166
203
  return params.authState.sixb.agent.threads.getById(params.threadId)
167
204
  }
168
205
 
169
- /** Publish the terminal record core owns; stream delivery stays best-effort at this boundary. */
170
- async function publishQueuedRunCancellation(
171
- host: SixbHostView,
172
- run: AgentRunRecord
173
- ): Promise<void> {
174
- try {
175
- await publishAgentRunFinished(host.broker, run)
176
- } catch (error) {
177
- console.error(`[SixbServer] Agent run '${run.id}' cancellation stream publish failed:`, error)
178
- }
179
- }
180
-
181
- function handleAgentRouteError(
206
+ export function handleAgentRouteError(
182
207
  error: unknown,
183
208
  set: { status?: number | string; headers?: unknown }
184
209
  ):
@@ -194,6 +219,10 @@ function handleAgentRouteError(
194
219
  set.status = 409
195
220
  return { error: "This conversation already has a response in progress" }
196
221
  }
222
+ if (error instanceof AgentStorageError && error.code === "thread_not_conversation") {
223
+ set.status = 409
224
+ return { error: "Only a conversation takes this change", code: error.code }
225
+ }
197
226
 
198
227
  if (error instanceof AgentRequestError) {
199
228
  // Core performs visibility checks before workspace state transitions.
@@ -201,14 +230,21 @@ function handleAgentRouteError(
201
230
  case "agent_not_found":
202
231
  case "run_not_found":
203
232
  case "thread_not_found":
233
+ case "approval_not_found":
204
234
  set.status = 404
205
235
  break
206
236
  case "active_run_exists":
237
+ case "thread_not_conversation":
207
238
  case "run_not_retryable":
239
+ case "run_not_active":
208
240
  case "sandbox_execution_unavailable":
241
+ case "approval_not_pending":
242
+ case "approval_expired":
209
243
  set.status = 409
210
244
  break
211
245
  case "authority_not_inheritable":
246
+ case "not_thread_owner":
247
+ case "not_run_requester":
212
248
  set.status = 403
213
249
  break
214
250
  case "storage_unavailable":
@@ -220,6 +256,8 @@ function handleAgentRouteError(
220
256
  case "invalid_model_selection":
221
257
  case "invalid_locale":
222
258
  case "invalid_message":
259
+ case "invalid_participant":
260
+ case "invalid_approval_mode":
223
261
  case "model_not_found":
224
262
  set.status = 400
225
263
  break
@@ -235,7 +273,7 @@ function missingAgentStorageResponse(set: { status?: number | string }): { error
235
273
  return unconfiguredStorageResponse(set, "Agent storage")
236
274
  }
237
275
 
238
- async function agentMessageFileContentResponse(
276
+ export async function agentMessageFileContentResponse(
239
277
  host: SixbHostView,
240
278
  context: {
241
279
  readonly params: { readonly threadId: string; readonly messageId: string }
@@ -243,7 +281,11 @@ async function agentMessageFileContentResponse(
243
281
  readonly request: Request
244
282
  readonly set: { status?: number | string }
245
283
  },
246
- options: { readonly head?: boolean } = {}
284
+ options: {
285
+ readonly head?: boolean
286
+ /** Who may read the thread. Default: its owner, or the Agent run working in it. */
287
+ readonly readThread?: () => Promise<Pick<AgentThreadRecord, "id"> | null>
288
+ } = {}
247
289
  ) {
248
290
  const authState = requestAuthState(context)
249
291
 
@@ -254,12 +296,14 @@ async function agentMessageFileContentResponse(
254
296
  }
255
297
 
256
298
  const parsed = AgentMessageFileContentQuerySchema.parse(context.query)
257
- const thread = await getAgentMessageFileContentThread({
258
- authState,
259
- storage,
260
- projectId: host.id,
261
- threadId: context.params.threadId,
262
- })
299
+ const thread = options.readThread
300
+ ? await options.readThread()
301
+ : await getAgentMessageFileContentThread({
302
+ authState,
303
+ storage,
304
+ projectId: host.id,
305
+ threadId: context.params.threadId,
306
+ })
263
307
  if (!thread) {
264
308
  context.set.status = 404
265
309
  return { error: "File not found" }
@@ -285,7 +329,7 @@ async function agentMessageFileContentResponse(
285
329
  fileRef,
286
330
  disposition: parsed.disposition,
287
331
  head: options.head,
288
- rangeHeader: context.request.headers.get("range"),
332
+ request: context.request,
289
333
  })
290
334
  if (!response) {
291
335
  context.set.status = 404
@@ -303,6 +347,94 @@ async function agentMessageFileContentResponse(
303
347
  }
304
348
  }
305
349
 
350
+ /** A page of a thread's messages, with their runs' diagnostics and compactions, and authors. */
351
+ export async function readThreadMessages(
352
+ host: SixbHostView,
353
+ storage: AgentStorage,
354
+ thread: AgentThreadRecord,
355
+ query: z.infer<typeof AgentMessagesQuerySchema>
356
+ ) {
357
+ const projectId = host.id
358
+ const result = await storage.messages.list({
359
+ projectId,
360
+ threadId: thread.id,
361
+ roles: query.role ? [query.role] : undefined,
362
+ limit: parseOptionalInt(query.limit),
363
+ offset: parseOptionalInt(query.offset),
364
+ order: query.order,
365
+ })
366
+ const runIds = result.messages.flatMap((message) =>
367
+ message.runId === null ? [] : [message.runId]
368
+ )
369
+ const [runs, checkpoints] = await Promise.all([
370
+ storage.runs.getByIds({ projectId, ids: runIds }),
371
+ storage.checkpoints.getByRunIds({ projectId, threadId: thread.id, runIds }),
372
+ ])
373
+ // A message's run is written by the store, never by a client: a message a fork copied keeps
374
+ // the run that produced it, in the source thread, and shows that run's diagnostics. In a
375
+ // sub-agent's thread, they are its runs'.
376
+ const diagnosticsByRunId = new Map(runs.map((run) => [run.id, run.diagnostics ?? []] as const))
377
+ const checkpointsByRunId = new Map(
378
+ checkpoints.map((checkpoint) => [checkpoint.createdByRunId, checkpoint] as const)
379
+ )
380
+
381
+ return {
382
+ messages: result.messages.map((message) =>
383
+ serializeMessage(
384
+ message,
385
+ message.runId === null ? [] : (diagnosticsByRunId.get(message.runId) ?? []),
386
+ message.runId === null ? undefined : checkpointsByRunId.get(message.runId)
387
+ )
388
+ ),
389
+ authors: await readAuthors(host, result.messages),
390
+ hasMore: result.hasMore,
391
+ total: result.total,
392
+ }
393
+ }
394
+
395
+ /** The page's distinct authors, in the order they first wrote. */
396
+ async function readAuthors(
397
+ host: SixbHostView,
398
+ messages: readonly Pick<AgentMessageRecord, "authorPrincipal">[]
399
+ ) {
400
+ const authors = messages.flatMap(({ authorPrincipal }) =>
401
+ authorPrincipal ? [authorPrincipal] : []
402
+ )
403
+ const people = await namePrincipals(host, authors)
404
+ return [...people.values()]
405
+ }
406
+
407
+ /**
408
+ * Distinct principals with their account's display name, in first-occurrence order. An account
409
+ * adds its display name and nothing else of its profile: never an email.
410
+ */
411
+ async function namePrincipals(
412
+ host: SixbHostView,
413
+ principals: readonly Principal[]
414
+ ): Promise<ReadonlyMap<string, Principal & { readonly displayName?: string }>> {
415
+ const unique = new Map(principals.map((principal) => [principalKey(principal), principal]))
416
+
417
+ const named = await Promise.all(
418
+ [...unique.entries()].map(async ([key, principal]) => {
419
+ const user =
420
+ principal.type === "user"
421
+ ? await host.storage.auth?.users.getById({ projectId: host.id, id: principal.id })
422
+ : null
423
+
424
+ const person = {
425
+ ...principal,
426
+ ...(user?.displayName ? { displayName: user.displayName } : {}),
427
+ }
428
+ return [key, person] as const
429
+ })
430
+ )
431
+ return new Map(named)
432
+ }
433
+
434
+ function principalKey(principal: Principal): string {
435
+ return `${principal.type}:${principal.id}`
436
+ }
437
+
306
438
  export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
307
439
  return app
308
440
  .get(
@@ -337,6 +469,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
337
469
 
338
470
  const parsed = AgentThreadListQuerySchema.parse(query)
339
471
  const listInput = {
472
+ sharedWithMe: parsed.sharedWithMe === "true",
340
473
  statuses: parsed.status ? [parsed.status] : undefined,
341
474
  limit: parseOptionalInt(parsed.limit),
342
475
  offset: parseOptionalInt(parsed.offset),
@@ -345,7 +478,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
345
478
  const result = await sixb.agent.threads.list(listInput)
346
479
 
347
480
  return AgentThreadListResponseSchema.parse({
348
- threads: result.threads.map(serializeThread),
481
+ threads: await serializeThreads(host, result.threads),
349
482
  hasMore: result.hasMore,
350
483
  total: result.total,
351
484
  })
@@ -386,7 +519,9 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
386
519
  })
387
520
 
388
521
  set.status = 201
389
- return CreateAgentThreadResponseSchema.parse({ thread: serializeThread(thread) })
522
+ return CreateAgentThreadResponseSchema.parse({
523
+ thread: await serializeThread(host, thread),
524
+ })
390
525
  } catch (error) {
391
526
  return handleAgentRouteError(error, set)
392
527
  }
@@ -426,7 +561,8 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
426
561
  return { error: "Agent thread not found" }
427
562
  }
428
563
 
429
- return serializeThread(thread)
564
+ const approvalMode = await sixb.agent.threads.getApprovalMode(thread.id)
565
+ return { ...(await serializeThread(host, thread)), ...approvalMode }
430
566
  } catch (error) {
431
567
  return handleAgentRouteError(error, set)
432
568
  }
@@ -446,6 +582,123 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
446
582
  },
447
583
  }
448
584
  )
585
+ .post(
586
+ "/api/agent-threads/:threadId/participants",
587
+ async (context) => {
588
+ const { params, body, set } = context
589
+ const sixb = requireRequestSixb(context)
590
+ try {
591
+ if (!host.storage.agents) {
592
+ return missingAgentStorageResponse(set)
593
+ }
594
+
595
+ const parsed = AddAgentThreadParticipantsBodySchema.parse(body)
596
+ const thread = await sixb.agent.threads.participants.add(params.threadId, parsed.users)
597
+
598
+ return serializeThread(host, thread)
599
+ } catch (error) {
600
+ return handleAgentRouteError(error, set)
601
+ }
602
+ },
603
+ {
604
+ params: AgentThreadParamsSchema,
605
+ body: AddAgentThreadParticipantsBodySchema,
606
+ response: {
607
+ 200: AgentThreadSchema,
608
+ 400: AgentRequestErrorResponseSchema,
609
+ 403: AgentRequestErrorResponseSchema,
610
+ 404: ErrorResponseSchema,
611
+ 409: AgentRequestErrorResponseSchema,
612
+ 501: ErrorResponseSchema,
613
+ },
614
+ detail: {
615
+ summary: "Add participants to an agent thread",
616
+ description: SHARING,
617
+ tags: [OPENAPI_TAGS.agentThreads.name],
618
+ operationId: "addAgentThreadParticipants",
619
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
620
+ },
621
+ }
622
+ )
623
+ .delete(
624
+ "/api/agent-threads/:threadId/participants/:userId",
625
+ async (context) => {
626
+ const { params, set } = context
627
+ const sixb = requireRequestSixb(context)
628
+ try {
629
+ if (!host.storage.agents) {
630
+ return missingAgentStorageResponse(set)
631
+ }
632
+
633
+ await sixb.agent.threads.participants.remove(params.threadId, {
634
+ type: "user",
635
+ id: params.userId,
636
+ })
637
+
638
+ set.status = 204
639
+ return
640
+ } catch (error) {
641
+ return handleAgentRouteError(error, set)
642
+ }
643
+ },
644
+ {
645
+ params: AgentThreadParticipantParamsSchema,
646
+ response: {
647
+ 204: z.void(),
648
+ 400: AgentRequestErrorResponseSchema,
649
+ 403: AgentRequestErrorResponseSchema,
650
+ 404: ErrorResponseSchema,
651
+ 409: AgentRequestErrorResponseSchema,
652
+ 501: ErrorResponseSchema,
653
+ },
654
+ detail: {
655
+ summary: "Remove a participant from an agent thread",
656
+ description:
657
+ "The thread's owner removes anyone; a participant removes only themself, to leave. Removing someone who does not take part changes nothing.",
658
+ tags: [OPENAPI_TAGS.agentThreads.name],
659
+ operationId: "removeAgentThreadParticipant",
660
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
661
+ },
662
+ }
663
+ )
664
+ .post(
665
+ "/api/agent-threads/:threadId/fork",
666
+ async (context) => {
667
+ const { params, set } = context
668
+ const sixb = requireRequestSixb(context)
669
+ try {
670
+ if (!host.storage.agents) {
671
+ return missingAgentStorageResponse(set)
672
+ }
673
+
674
+ const thread = await sixb.agent.threads.fork(params.threadId)
675
+
676
+ set.status = 201
677
+ return CreateAgentThreadResponseSchema.parse({
678
+ thread: await serializeThread(host, thread),
679
+ })
680
+ } catch (error) {
681
+ return handleAgentRouteError(error, set)
682
+ }
683
+ },
684
+ {
685
+ params: AgentThreadParamsSchema,
686
+ response: {
687
+ 201: CreateAgentThreadResponseSchema,
688
+ // Coded: the source's sandbox params may not suit the current sandbox configuration.
689
+ 400: AgentRequestErrorResponseSchema,
690
+ 404: ErrorResponseSchema,
691
+ 409: AgentRequestErrorResponseSchema,
692
+ 501: ErrorResponseSchema,
693
+ },
694
+ detail: {
695
+ summary: "Continue an agent thread in a new one the caller owns",
696
+ tags: [OPENAPI_TAGS.agentThreads.name],
697
+ operationId: "forkAgentThread",
698
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
699
+ },
700
+ }
701
+ )
449
702
  .post(
450
703
  "/api/agent-threads/:threadId/sandbox/recreate",
451
704
  async (context) => {
@@ -455,7 +708,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
455
708
  context.params.threadId,
456
709
  context.body
457
710
  )
458
- return serializeThread(thread)
711
+ return serializeThread(host, thread)
459
712
  } catch (error) {
460
713
  if (error instanceof AgentStorageError && error.code === "invalid_state") {
461
714
  context.set.status = 409
@@ -470,8 +723,9 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
470
723
  response: {
471
724
  200: AgentThreadSchema,
472
725
  400: ErrorResponseSchema,
726
+ 403: AgentRequestErrorResponseSchema,
473
727
  404: ErrorResponseSchema,
474
- 409: ErrorResponseSchema,
728
+ 409: AgentRequestErrorResponseSchema,
475
729
  },
476
730
  detail: {
477
731
  summary:
@@ -500,45 +754,9 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
500
754
  }
501
755
 
502
756
  const parsed = AgentMessagesQuerySchema.parse(query)
503
- const limit = parseOptionalInt(parsed.limit)
504
- const offset = parseOptionalInt(parsed.offset)
505
- const result = await storage.messages.list({
506
- projectId: host.id,
507
- threadId: thread.id,
508
- roles: parsed.role ? [parsed.role] : undefined,
509
- limit,
510
- offset,
511
- order: parsed.order,
512
- })
513
- const runIds = result.messages.flatMap((message) =>
514
- message.runId === null ? [] : [message.runId]
757
+ return AgentMessageListResponseSchema.parse(
758
+ await readThreadMessages(host, storage, thread, parsed)
515
759
  )
516
- const [runs, checkpoints] = await Promise.all([
517
- storage.runs.getByIds({ projectId: host.id, ids: runIds }),
518
- storage.checkpoints.getByRunIds({ projectId: host.id, runIds }),
519
- ])
520
- const diagnosticsByRunId = new Map(
521
- runs
522
- .filter((run) => run.kind === "conversation" && run.threadId === thread.id)
523
- .map((run) => [run.id, run.diagnostics ?? []] as const)
524
- )
525
- const checkpointsByRunId = new Map(
526
- checkpoints
527
- .filter((checkpoint) => checkpoint.threadId === thread.id)
528
- .map((checkpoint) => [checkpoint.createdByRunId, checkpoint] as const)
529
- )
530
-
531
- return AgentMessageListResponseSchema.parse({
532
- messages: result.messages.map((message) =>
533
- serializeMessage(
534
- message,
535
- message.runId === null ? [] : (diagnosticsByRunId.get(message.runId) ?? []),
536
- message.runId === null ? undefined : checkpointsByRunId.get(message.runId)
537
- )
538
- ),
539
- hasMore: result.hasMore,
540
- total: result.total,
541
- })
542
760
  } catch (error) {
543
761
  return handleAgentRouteError(error, set)
544
762
  }
@@ -616,6 +834,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
616
834
  reasoning: parsed.reasoning,
617
835
  timeZone: parsed.timeZone,
618
836
  locale: parsed.locale,
837
+ approvalMode: parsed.approvalMode,
619
838
  attachments: parsed.attachments as readonly FileRef[] | undefined,
620
839
  context: parsed.context,
621
840
  messageId: parsed.messageId,
@@ -638,7 +857,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
638
857
  400: AgentRequestErrorResponseSchema,
639
858
  403: ErrorResponseSchema,
640
859
  404: ErrorResponseSchema,
641
- 409: ErrorResponseSchema,
860
+ 409: AgentRequestErrorResponseSchema,
642
861
  429: AiUsageLimitErrorResponseSchema,
643
862
  501: ErrorResponseSchema,
644
863
  },
@@ -667,62 +886,18 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
667
886
  return { error: "Agent thread not found" }
668
887
  }
669
888
 
889
+ assertConversationThread(thread)
670
890
  const parsed = CancelAgentRunBodySchema.parse(body)
671
891
  const run = await sixb.agent.runs.getById(parsed.runId)
672
892
  if (!run || run.threadId !== thread.id) {
673
893
  set.status = 404
674
894
  return { error: "Agent run not found" }
675
895
  }
676
- let current = run
677
- let cancelledRun: ConversationAgentRunRecord | undefined
678
- if (current.status === "queued") {
679
- try {
680
- const cancelled = await storage.runs.finishQueued({
681
- projectId: host.id,
682
- id: current.id,
683
- status: "cancelled",
684
- })
685
- if (cancelled.kind !== "conversation") {
686
- throw new Error(`[SixbServer] Agent run '${cancelled.id}' changed kind.`)
687
- }
688
- current = cancelled
689
- cancelledRun = cancelled
690
- } catch (error) {
691
- if (!(error instanceof AgentStorageError) || error.code !== "invalid_state") {
692
- throw error
693
- }
694
-
695
- // The worker may have started the run after our read but before finishQueued locked
696
- // it. Re-read so that pickup race becomes a running-run cancellation instead of an
697
- // invalid-state response. A retained control record is safe even if the worker has
698
- // not attached its cancel subscription yet.
699
- const refreshed = await sixb.agent.runs.getById(current.id)
700
- if (!refreshed || refreshed.threadId !== thread.id) {
701
- set.status = 404
702
- return { error: "Agent run not found" }
703
- }
704
- current = refreshed
705
- }
706
- }
707
896
 
708
- if (cancelledRun) {
709
- await publishQueuedRunCancellation(host, cancelledRun)
710
- } else if (current.status === "running") {
711
- await publishAgentRunCancel(host.broker, { projectId: host.id, runId: current.id })
712
- } else {
713
- set.status = 409
714
- return { error: "Agent run is not active" }
715
- }
897
+ const current = await sixb.agent.runs.cancel(run.id)
716
898
 
717
899
  set.status = 202
718
- const currentView = await sixb.agent.runs.getById(current.id)
719
- if (!currentView) {
720
- set.status = 404
721
- return { error: "Agent run not found" }
722
- }
723
- return CancelAgentRunResponseSchema.parse({
724
- run: serializeAgentRun(currentView),
725
- })
900
+ return CancelAgentRunResponseSchema.parse({ run: serializeAgentRun(current) })
726
901
  } catch (error) {
727
902
  return handleAgentRouteError(error, set)
728
903
  }
@@ -732,13 +907,15 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
732
907
  body: CancelAgentRunBodySchema,
733
908
  response: {
734
909
  202: CancelAgentRunResponseSchema,
735
- 400: ErrorResponseSchema,
910
+ 400: AgentRequestErrorResponseSchema,
911
+ 403: AgentRequestErrorResponseSchema,
736
912
  404: ErrorResponseSchema,
737
- 409: ErrorResponseSchema,
913
+ 409: AgentRequestErrorResponseSchema,
738
914
  501: ErrorResponseSchema,
739
915
  },
740
916
  detail: {
741
917
  summary: "Cancel an agent thread's active run",
918
+ description: "Whoever asked for the run, or the thread's owner, can cancel it.",
742
919
  tags: [OPENAPI_TAGS.agentRuns.name],
743
920
  operationId: "cancelAgentRun",
744
921
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
@@ -762,6 +939,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
762
939
  return { error: "Agent thread not found" }
763
940
  }
764
941
 
942
+ assertConversationThread(thread)
765
943
  const failedRun = await sixb.agent.runs.getById(params.runId)
766
944
  if (!failedRun || failedRun.threadId !== thread.id) {
767
945
  set.status = 404
@@ -786,14 +964,17 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
786
964
  params: AgentRunParamsSchema.extend({ threadId: z.string().trim().min(1) }),
787
965
  response: {
788
966
  202: RetryAgentRunResponseSchema,
789
- 400: ErrorResponseSchema,
967
+ 400: AgentRequestErrorResponseSchema,
968
+ 403: AgentRequestErrorResponseSchema,
790
969
  404: ErrorResponseSchema,
791
- 409: ErrorResponseSchema,
970
+ 409: AgentRequestErrorResponseSchema,
792
971
  429: AiUsageLimitErrorResponseSchema,
793
972
  501: ErrorResponseSchema,
794
973
  },
795
974
  detail: {
796
975
  summary: "Retry a failed or interrupted agent run",
976
+ description:
977
+ "Only whoever asked for the run can retry it: it runs again with their rights.",
797
978
  tags: [OPENAPI_TAGS.agentRuns.name],
798
979
  operationId: "retryAgentRun",
799
980
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
@@ -880,9 +1061,49 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
880
1061
  },
881
1062
  detail: {
882
1063
  summary: "Get agent run",
1064
+ description:
1065
+ "A conversation's turn, or a sub-agent's run (`kind: \"subagent\"`), read through its thread: a sub-agent's run is visible exactly when its conversation is.",
883
1066
  tags: [OPENAPI_TAGS.agentRuns.name],
884
1067
  operationId: "getAgentRun",
885
1068
  },
886
1069
  }
887
1070
  )
1071
+ .post(
1072
+ "/api/agent-runs/:runId/cancel",
1073
+ async (context) => {
1074
+ const { params, set } = context
1075
+ const sixb = requireRequestSixb(context)
1076
+ try {
1077
+ if (!host.storage.agents) {
1078
+ return missingAgentStorageResponse(set)
1079
+ }
1080
+
1081
+ const current = await sixb.agent.runs.cancel(params.runId)
1082
+
1083
+ set.status = 202
1084
+ return CancelAgentRunResponseSchema.parse({ run: serializeAgentRun(current) })
1085
+ } catch (error) {
1086
+ return handleAgentRouteError(error, set)
1087
+ }
1088
+ },
1089
+ {
1090
+ params: AgentRunParamsSchema,
1091
+ response: {
1092
+ 202: CancelAgentRunResponseSchema,
1093
+ 400: AgentRequestErrorResponseSchema,
1094
+ 403: AgentRequestErrorResponseSchema,
1095
+ 404: ErrorResponseSchema,
1096
+ 409: AgentRequestErrorResponseSchema,
1097
+ 501: ErrorResponseSchema,
1098
+ },
1099
+ detail: {
1100
+ summary: "Stop an agent run",
1101
+ description:
1102
+ "A turn, or a sub-agent's run. Whoever asked for the turn, or the conversation's owner, can stop it, and a sub-agent's run as its turn. A queued run is cancelled at once; a running one is still running in the response, with the stop signal sent. A sub-agent's parent reads that it was stopped.",
1103
+ tags: [OPENAPI_TAGS.agentRuns.name],
1104
+ operationId: "cancelAgentRunById",
1105
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1106
+ },
1107
+ }
1108
+ )
888
1109
  }