@sixb/server 0.2.5 → 0.2.6

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 (56) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +525 -61
  4. package/dist/index.js.map +19 -18
  5. package/dist/registerRoutes.d.ts +1 -0
  6. package/dist/registerRoutes.d.ts.map +1 -1
  7. package/dist/routes/agent-approvals.d.ts +22 -0
  8. package/dist/routes/agent-approvals.d.ts.map +1 -1
  9. package/dist/routes/agent-computers.d.ts +36 -0
  10. package/dist/routes/agent-computers.d.ts.map +1 -1
  11. package/dist/routes/agent-thread-reads.d.ts +82 -0
  12. package/dist/routes/agent-thread-reads.d.ts.map +1 -0
  13. package/dist/routes/agents.d.ts +783 -1
  14. package/dist/routes/agents.d.ts.map +1 -1
  15. package/dist/routes/ai-accounting.d.ts.map +1 -1
  16. package/dist/routes/model-generations.d.ts +6 -0
  17. package/dist/routes/model-generations.d.ts.map +1 -1
  18. package/dist/routes/observed-agent-threads.d.ts +22 -0
  19. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  20. package/dist/routes/status.d.ts +4 -1
  21. package/dist/routes/status.d.ts.map +1 -1
  22. package/dist/routes/syncs.d.ts +175 -12
  23. package/dist/routes/syncs.d.ts.map +1 -1
  24. package/dist/routes/workflows.d.ts +6 -6
  25. package/dist/routes/ws/agents.d.ts.map +1 -1
  26. package/dist/schemas/activity.d.ts +4 -4
  27. package/dist/schemas/agents.d.ts +2602 -6
  28. package/dist/schemas/agents.d.ts.map +1 -1
  29. package/dist/schemas/ai-accounting.d.ts +3 -0
  30. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  31. package/dist/schemas/common.d.ts.map +1 -1
  32. package/dist/schemas/models.d.ts +46 -0
  33. package/dist/schemas/models.d.ts.map +1 -1
  34. package/dist/schemas/syncs.d.ts +724 -25
  35. package/dist/schemas/syncs.d.ts.map +1 -1
  36. package/dist/schemas/workflows.d.ts +22 -22
  37. package/dist/server.d.ts +16 -1
  38. package/dist/server.d.ts.map +1 -1
  39. package/package.json +5 -5
  40. package/src/index.ts +6 -1
  41. package/src/registerRoutes.ts +4 -1
  42. package/src/routes/agent-computers.ts +7 -6
  43. package/src/routes/agent-thread-reads.ts +67 -0
  44. package/src/routes/agents.ts +129 -16
  45. package/src/routes/ai-accounting.ts +1 -0
  46. package/src/routes/model-generations.ts +1 -1
  47. package/src/routes/observed-agent-threads.ts +3 -4
  48. package/src/routes/status.ts +18 -1
  49. package/src/routes/syncs.ts +135 -8
  50. package/src/routes/ws/agents.ts +43 -3
  51. package/src/schemas/agents.ts +80 -10
  52. package/src/schemas/ai-accounting.ts +12 -0
  53. package/src/schemas/common.ts +15 -9
  54. package/src/schemas/models.ts +10 -0
  55. package/src/schemas/syncs.ts +63 -1
  56. package/src/server.ts +205 -13
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // src/server.ts
3
3
  import { cors } from "@elysiajs/cors";
4
4
  import { openapi } from "@elysiajs/openapi";
5
+ import { ACTION_RUN_DRAIN_TIMEOUT_MS } from "@sixb/core/internal/actions";
5
6
  import { bindAgentRunRequestExecution as bindAgentRunRequestExecution2 } from "@sixb/core/internal/agent-execution";
6
7
  import { ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX4 } from "@sixb/core/internal/artifacts/frames";
7
8
  import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2, setRequestClientAddress } from "@sixb/core/internal/auth";
@@ -889,7 +890,8 @@ var PrincipalSchema = z.object({
889
890
  type: z.enum(["user", "serviceAccount", "system"]),
890
891
  id: z.string().min(1)
891
892
  });
892
- var JsonValueSchema = z.lazy(() => z.union([
893
+ var jsonValueUnion;
894
+ var JsonValueSchema = z.lazy(() => jsonValueUnion ??= z.union([
893
895
  z.string(),
894
896
  z.number().finite(),
895
897
  z.boolean(),
@@ -1247,6 +1249,7 @@ var AgentPreferencesSchema = z4.object({
1247
1249
  });
1248
1250
 
1249
1251
  // src/schemas/ai-accounting.ts
1252
+ import { canonicalTimeZone } from "@sixb/core/calendar";
1250
1253
  import { z as z8 } from "zod";
1251
1254
 
1252
1255
  // src/schemas/ai-usage.ts
@@ -1544,8 +1547,15 @@ var InlineAudioSchema = z7.object({
1544
1547
  var TranscriptionBodySchema = GenerationBodyBase.extend({
1545
1548
  audio: z7.union([FileRefSchema, InlineAudioSchema])
1546
1549
  });
1550
+ var TranscriptionWordSchema = z7.object({
1551
+ text: z7.string(),
1552
+ startMs: z7.number().int().nonnegative(),
1553
+ endMs: z7.number().int().nonnegative(),
1554
+ speaker: z7.string().optional()
1555
+ });
1547
1556
  var TranscriptionSchema = GenerationResultBase.extend({
1548
- text: z7.string()
1557
+ text: z7.string(),
1558
+ words: z7.array(TranscriptionWordSchema).optional()
1549
1559
  });
1550
1560
 
1551
1561
  // src/schemas/ai-accounting.ts
@@ -1578,8 +1588,12 @@ var AiAccountingRangeQuerySchema = z8.object({
1578
1588
  source: z8.string().regex(/^(agent|action|other|workflow|workflow:.+)$/).optional().describe("Calls from agent conversations and their sub-agents, actions, workflows or one as workflow:<id>, or other"),
1579
1589
  kind: ModelKindSchema.optional().describe("Calls to one kind of model")
1580
1590
  });
1591
+ var TimeZoneSchema = z8.string().trim().min(1).refine((value) => canonicalTimeZone(value) !== undefined, {
1592
+ message: "Use an IANA time zone such as America/New_York"
1593
+ });
1581
1594
  var AiAccountingOverviewQuerySchema = AiAccountingRangeQuerySchema.extend({
1582
- bucket: AiAccountingBucketSchema
1595
+ bucket: AiAccountingBucketSchema,
1596
+ timeZone: TimeZoneSchema.optional().describe("The IANA time zone whose days, weeks or hours the periods follow, such as America/New_York; UTC when absent")
1583
1597
  });
1584
1598
  var AiModelCallAccountingListQuerySchema = AiAccountingRangeQuerySchema.extend({
1585
1599
  executionId: z8.string().trim().min(1).optional(),
@@ -1921,6 +1935,31 @@ var AgentThreadParticipantSchema = z9.object({
1921
1935
  addedAt: z9.string(),
1922
1936
  addedBy: AgentPrincipalSchema
1923
1937
  });
1938
+ var AgentRunStatusSchema = z9.enum([
1939
+ "queued",
1940
+ "running",
1941
+ "succeeded",
1942
+ "failed",
1943
+ "cancelled"
1944
+ ]);
1945
+ var AgentRunFinishReasonSchema = z9.enum(AGENT_RUN_FINISH_REASONS);
1946
+ var AgentThreadReadSchema = z9.object({
1947
+ threadId: z9.string(),
1948
+ throughSeq: z9.number(),
1949
+ headSeq: z9.number(),
1950
+ unread: z9.number(),
1951
+ readAt: z9.string().optional()
1952
+ });
1953
+ var AgentThreadLastRunSchema = z9.object({
1954
+ id: z9.string(),
1955
+ status: AgentRunStatusSchema,
1956
+ finishReason: AgentRunFinishReasonSchema.optional(),
1957
+ errorCode: z9.enum(AGENT_RUN_FAILURE_CODES).optional(),
1958
+ completedAt: z9.string().optional(),
1959
+ requestedBy: AgentAuthorizablePrincipalSchema.optional()
1960
+ });
1961
+ var MarkAgentThreadReadBodySchema = z9.object({ throughMessageId: z9.string().trim().min(1).optional() }).strict();
1962
+ var MarkAgentThreadReadResponseSchema = z9.object({ read: AgentThreadReadSchema });
1924
1963
  var AgentThreadSchema = z9.object({
1925
1964
  sandboxState: z9.object({
1926
1965
  name: z9.string(),
@@ -1955,6 +1994,8 @@ var AgentThreadSchema = z9.object({
1955
1994
  messageCount: z9.number(),
1956
1995
  createdAt: z9.string(),
1957
1996
  updatedAt: z9.string(),
1997
+ read: AgentThreadReadSchema.optional(),
1998
+ lastRun: AgentThreadLastRunSchema.optional(),
1958
1999
  approvalMode: AgentApprovalModeSchema.optional(),
1959
2000
  approvalModeSource: AgentApprovalModeSourceSchema.optional()
1960
2001
  });
@@ -2131,6 +2172,17 @@ var AgentMessageListResponseSchema = z9.object({
2131
2172
  hasMore: z9.boolean(),
2132
2173
  total: z9.number()
2133
2174
  });
2175
+ var EditAgentMessageBodySchema = z9.object({
2176
+ text: z9.string().trim().min(1).optional(),
2177
+ model: LanguageModelRefSchema.optional(),
2178
+ reasoning: ModelReasoningSchema.optional(),
2179
+ timeZone: z9.string().trim().min(1).max(100).optional(),
2180
+ locale: z9.string().trim().min(1).max(100).optional(),
2181
+ approvalMode: AgentApprovalModeSchema.optional(),
2182
+ attachments: z9.array(FileRefSchema).optional(),
2183
+ context: z9.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
2184
+ nextMessageId: z9.string().trim().min(1).optional()
2185
+ }).strict();
2134
2186
  var PostAgentMessageBodySchema = z9.object({
2135
2187
  text: z9.string().trim().min(1).optional(),
2136
2188
  continue: z9.literal(true).optional(),
@@ -2150,14 +2202,6 @@ var AgentRequestErrorResponseSchema = ErrorResponseSchema.extend({
2150
2202
  var CancelAgentRunBodySchema = z9.object({
2151
2203
  runId: z9.string().trim().min(1)
2152
2204
  });
2153
- var AgentRunStatusSchema = z9.enum([
2154
- "queued",
2155
- "running",
2156
- "succeeded",
2157
- "failed",
2158
- "cancelled"
2159
- ]);
2160
- var AgentRunFinishReasonSchema = z9.enum(AGENT_RUN_FINISH_REASONS);
2161
2205
  var AgentRunSchema = z9.object({
2162
2206
  id: z9.string(),
2163
2207
  projectId: z9.string(),
@@ -2172,6 +2216,7 @@ var AgentRunSchema = z9.object({
2172
2216
  reasoning: ModelReasoningSchema.optional(),
2173
2217
  approvalMode: AgentApprovalModeSchema.optional(),
2174
2218
  runsOn: z9.literal("computer").optional(),
2219
+ computer: z9.object({ id: z9.string(), folder: z9.string() }).optional(),
2175
2220
  modelId: z9.string().optional(),
2176
2221
  finishReason: AgentRunFinishReasonSchema.optional(),
2177
2222
  usage: AiUsageSummarySchema.optional(),
@@ -2201,6 +2246,7 @@ var AgentInboxItemSchema = z9.object({
2201
2246
  timeZone: z9.string().optional(),
2202
2247
  locale: z9.string().optional(),
2203
2248
  immediate: z9.boolean().optional(),
2249
+ replacesMessageId: z9.string().optional(),
2204
2250
  createdAt: z9.string(),
2205
2251
  updatedAt: z9.string()
2206
2252
  });
@@ -2225,6 +2271,10 @@ var PostAgentMessageResponseSchema = z9.object({
2225
2271
  run: AgentRunSchema.optional(),
2226
2272
  item: AgentInboxItemSchema.optional()
2227
2273
  });
2274
+ var EditAgentMessageResponseSchema = z9.object({
2275
+ run: AgentRunSchema.optional(),
2276
+ item: AgentInboxItemSchema.optional()
2277
+ });
2228
2278
  var CancelAgentRunResponseSchema = z9.object({
2229
2279
  run: AgentRunSchema
2230
2280
  });
@@ -4509,7 +4559,22 @@ async function serializeThreads(host, threads, viewer) {
4509
4559
  lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
4510
4560
  messageCount: thread.messageCount,
4511
4561
  createdAt: toIsoString(thread.createdAt),
4512
- updatedAt: toIsoString(thread.updatedAt)
4562
+ updatedAt: toIsoString(thread.updatedAt),
4563
+ read: thread.read && {
4564
+ threadId: thread.read.threadId,
4565
+ throughSeq: thread.read.throughSeq,
4566
+ headSeq: thread.read.headSeq,
4567
+ unread: thread.read.unread,
4568
+ readAt: thread.read.readAt ? toIsoString(thread.read.readAt) : undefined
4569
+ },
4570
+ lastRun: thread.lastRun && {
4571
+ id: thread.lastRun.id,
4572
+ status: thread.lastRun.status,
4573
+ finishReason: thread.lastRun.finishReason,
4574
+ errorCode: thread.lastRun.errorCode,
4575
+ completedAt: thread.lastRun.completedAt ? toIsoString(thread.lastRun.completedAt) : undefined,
4576
+ requestedBy: thread.lastRun.requestedBy
4577
+ }
4513
4578
  }));
4514
4579
  }
4515
4580
  async function serializeThread(host, thread, viewer) {
@@ -4544,7 +4609,7 @@ function sameBackgroundCommand(command, ref) {
4544
4609
  return command.threadId === ref.threadId && command.id === ref.id && command.startedAt === ref.startedAt;
4545
4610
  }
4546
4611
  function serializeMessage(message, annotations = [], checkpoint) {
4547
- return AgentMessageSchema.parse({
4612
+ return {
4548
4613
  id: message.id,
4549
4614
  projectId: message.projectId,
4550
4615
  threadId: message.threadId,
@@ -4552,7 +4617,7 @@ function serializeMessage(message, annotations = [], checkpoint) {
4552
4617
  role: message.role,
4553
4618
  authorPrincipal: message.authorPrincipal,
4554
4619
  seq: message.seq,
4555
- parts: message.parts,
4620
+ parts: message.parts.map(withoutReplayState),
4556
4621
  annotations,
4557
4622
  compaction: checkpoint ? {
4558
4623
  checkpointId: checkpoint.id,
@@ -4564,7 +4629,15 @@ function serializeMessage(message, annotations = [], checkpoint) {
4564
4629
  contentVersion: message.contentVersion,
4565
4630
  createdAt: toIsoString(message.createdAt),
4566
4631
  completedAt: message.completedAt ? toIsoString(message.completedAt) : undefined
4567
- });
4632
+ };
4633
+ }
4634
+ function withoutReplayState(part) {
4635
+ if (part.type === "provider-state")
4636
+ return { ...part, data: null };
4637
+ if (!("providerMetadata" in part) || part.providerMetadata === undefined)
4638
+ return part;
4639
+ const { providerMetadata: _replay, ...shown } = part;
4640
+ return shown;
4568
4641
  }
4569
4642
  function serializeAgentInboxItem(item) {
4570
4643
  return AgentInboxItemSchema.parse({
@@ -4580,11 +4653,12 @@ function serializeAgentInboxItem(item) {
4580
4653
  timeZone: item.timeZone,
4581
4654
  locale: item.locale,
4582
4655
  immediate: item.immediate === true ? true : undefined,
4656
+ replacesMessageId: item.replacesMessageId,
4583
4657
  createdAt: toIsoString(item.createdAt),
4584
4658
  updatedAt: toIsoString(item.updatedAt)
4585
4659
  });
4586
4660
  }
4587
- function serializeAgentRun(run) {
4661
+ function serializeAgentRun(run, { ownerReads = false } = {}) {
4588
4662
  return AgentRunSchema.parse({
4589
4663
  id: run.id,
4590
4664
  projectId: run.projectId,
@@ -4599,6 +4673,7 @@ function serializeAgentRun(run) {
4599
4673
  reasoning: run.spec?.reasoning,
4600
4674
  approvalMode: run.spec?.approvalMode,
4601
4675
  runsOn: run.kind === "conversation" ? run.spec?.runsOn : undefined,
4676
+ computer: ownerReads && run.kind === "conversation" ? run.spec?.computer : undefined,
4602
4677
  modelId: run.modelId,
4603
4678
  finishReason: run.finishReason,
4604
4679
  usage: run.usage,
@@ -4652,12 +4727,14 @@ function handleAgentRouteError(error, set) {
4652
4727
  if (error instanceof AgentRequestError) {
4653
4728
  switch (error.code) {
4654
4729
  case "agent_not_found":
4730
+ case "message_not_found":
4655
4731
  case "run_not_found":
4656
4732
  case "thread_not_found":
4657
4733
  case "approval_not_found":
4658
4734
  set.status = 404;
4659
4735
  break;
4660
4736
  case "active_run_exists":
4737
+ case "message_not_editable":
4661
4738
  case "thread_not_conversation":
4662
4739
  case "run_not_retryable":
4663
4740
  case "run_not_active":
@@ -4667,6 +4744,7 @@ function handleAgentRouteError(error, set) {
4667
4744
  set.status = 409;
4668
4745
  break;
4669
4746
  case "authority_not_inheritable":
4747
+ case "not_message_author":
4670
4748
  case "not_thread_owner":
4671
4749
  case "not_run_requester":
4672
4750
  set.status = 403;
@@ -5081,7 +5159,7 @@ function registerAgentRoutes(app, host) {
5081
5159
  return { error: "Agent thread not found" };
5082
5160
  }
5083
5161
  const parsed = AgentMessagesQuerySchema.parse(query);
5084
- return AgentMessageListResponseSchema.parse(await readThreadMessages(host, storage, thread, parsed));
5162
+ return await readThreadMessages(host, storage, thread, parsed);
5085
5163
  } catch (error) {
5086
5164
  return handleAgentRouteError(error, set);
5087
5165
  }
@@ -5263,6 +5341,52 @@ function registerAgentRoutes(app, host) {
5263
5341
  operationId: "withdrawAgentThreadInboxItem",
5264
5342
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5265
5343
  }
5344
+ }).post("/api/agent-threads/:threadId/messages/:messageId/edit", async (context) => {
5345
+ const { params, body, set } = context;
5346
+ const sixb = requireRequestSixb(context);
5347
+ try {
5348
+ const storage = host.storage.agents;
5349
+ if (!storage) {
5350
+ return missingAgentStorageResponse(set);
5351
+ }
5352
+ const parsed = EditAgentMessageBodySchema.parse(body);
5353
+ const result = await sixb.agent.runs.editMessage({
5354
+ threadId: params.threadId,
5355
+ messageId: params.messageId,
5356
+ text: parsed.text,
5357
+ model: parsed.model,
5358
+ reasoning: parsed.reasoning,
5359
+ timeZone: parsed.timeZone,
5360
+ locale: parsed.locale,
5361
+ approvalMode: parsed.approvalMode,
5362
+ attachments: parsed.attachments,
5363
+ context: parsed.context,
5364
+ nextMessageId: parsed.nextMessageId
5365
+ });
5366
+ set.status = 202;
5367
+ return EditAgentMessageResponseSchema.parse(result.kind === "turn" ? { run: serializeAgentRun(result.run) } : { item: serializeAgentInboxItem(result.item) });
5368
+ } catch (error) {
5369
+ return handleAgentInboxRouteError(error, set);
5370
+ }
5371
+ }, {
5372
+ params: AgentMessageFileContentParamsSchema,
5373
+ body: EditAgentMessageBodySchema,
5374
+ response: {
5375
+ 202: EditAgentMessageResponseSchema,
5376
+ 400: AgentRequestErrorResponseSchema,
5377
+ 403: AgentRequestErrorResponseSchema,
5378
+ 404: ErrorResponseSchema,
5379
+ 409: AgentRequestErrorResponseSchema,
5380
+ 429: AiUsageLimitErrorResponseSchema,
5381
+ 501: ErrorResponseSchema
5382
+ },
5383
+ detail: {
5384
+ summary: "Edit an agent thread message and restart from that turn",
5385
+ description: "Replaces a user-authored message in place, removes any messages and compaction summaries from that turn onward, and starts a new turn from the edited message. While a turn runs, the edit stops it and waits in the thread's inbox: the turn's end rewinds the thread and starts the edited message.",
5386
+ tags: [OPENAPI_TAGS.agentThreads.name],
5387
+ operationId: "editAgentThreadMessage",
5388
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5389
+ }
5266
5390
  }).post("/api/agent-threads/:threadId/cancel", async (context) => {
5267
5391
  const { params, body, set } = context;
5268
5392
  const sixb = requireRequestSixb(context);
@@ -5431,18 +5555,22 @@ function registerAgentRoutes(app, host) {
5431
5555
  return missingAgentStorageResponse(set);
5432
5556
  }
5433
5557
  const parsed = AgentRunListQuerySchema.parse(query);
5434
- const result = await sixb.agent.runs.listForThread(params.threadId, {
5435
- statuses: parsed.status ? [parsed.status] : undefined,
5436
- limit: parseOptionalInt(parsed.limit),
5437
- offset: parseOptionalInt(parsed.offset),
5438
- order: parsed.order
5439
- });
5558
+ const [result, thread] = await Promise.all([
5559
+ sixb.agent.runs.listForThread(params.threadId, {
5560
+ statuses: parsed.status ? [parsed.status] : undefined,
5561
+ limit: parseOptionalInt(parsed.limit),
5562
+ offset: parseOptionalInt(parsed.offset),
5563
+ order: parsed.order
5564
+ }),
5565
+ storage.threads.getById({ projectId: host.id, id: params.threadId })
5566
+ ]);
5440
5567
  if (!result) {
5441
5568
  set.status = 404;
5442
5569
  return { error: "Agent thread not found" };
5443
5570
  }
5571
+ const ownerReads = thread !== null && principalsEqual(thread.ownerPrincipal, requestActor(sixb));
5444
5572
  return AgentRunListResponseSchema.parse({
5445
- runs: result.runs.map(serializeAgentRun),
5573
+ runs: result.runs.map((run) => serializeAgentRun(run, { ownerReads })),
5446
5574
  hasMore: result.hasMore,
5447
5575
  total: result.total
5448
5576
  });
@@ -5980,7 +6108,7 @@ function registerAgentComputerRoutes(app, host) {
5980
6108
  },
5981
6109
  detail: {
5982
6110
  summary: "Move a thread to one of your computers, in a folder there",
5983
- description: "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.",
6111
+ description: "Its turns run there alone from now on, in that folder: only `sixb` open in it claims them. Its owner moves it from the cloud or from another folder or computer, as often as they need; files from where it ran before stay there. Refused while a turn runs or waits on approvals.",
5984
6112
  tags: [OPENAPI_TAGS.agentThreads.name],
5985
6113
  operationId: "moveAgentThreadToComputer",
5986
6114
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -6008,7 +6136,7 @@ function registerAgentComputerRoutes(app, host) {
6008
6136
  },
6009
6137
  detail: {
6010
6138
  summary: "Move a thread from your computer to the cloud",
6011
- description: "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.",
6139
+ description: "Its turns run in the cloud from now on, starting with the one waiting for the computer, if any, and its owner can move it to a computer or folder again later. The files it worked on stay on the computer. Refused while a turn runs there or waits on approvals.",
6012
6140
  tags: [OPENAPI_TAGS.agentThreads.name],
6013
6141
  operationId: "moveAgentThreadToCloud",
6014
6142
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -6590,6 +6718,48 @@ function answer(body, status = 200) {
6590
6718
  });
6591
6719
  }
6592
6720
 
6721
+ // src/routes/agent-thread-reads.ts
6722
+ var MARKING = "Record that your reading of a conversation reached a message, or its newest when `throughMessageId` is omitted, which is what a Done button sends. It never moves backwards, so another device that read further keeps its place; a message a retry or an edit took away marks nothing. Session routes only: a runner has no reading.";
6723
+ function registerAgentThreadReadRoutes(app, host) {
6724
+ return app.put("/api/agent-threads/:threadId/read", async (context) => {
6725
+ const { set } = context;
6726
+ try {
6727
+ if (!host.storage.agents) {
6728
+ return unconfiguredStorageResponse(set, "Agent storage");
6729
+ }
6730
+ const body = MarkAgentThreadReadBodySchema.parse(context.body ?? {});
6731
+ const read = await requireRequestSixb(context).agent.threads.markRead(context.params.threadId, body);
6732
+ return MarkAgentThreadReadResponseSchema.parse({
6733
+ read: {
6734
+ threadId: read.threadId,
6735
+ throughSeq: read.throughSeq,
6736
+ headSeq: read.headSeq,
6737
+ unread: read.unread,
6738
+ readAt: read.readAt ? toIsoString(read.readAt) : undefined
6739
+ }
6740
+ });
6741
+ } catch (error) {
6742
+ return handleAgentRouteError(error, set);
6743
+ }
6744
+ }, {
6745
+ params: AgentThreadParamsSchema,
6746
+ body: MarkAgentThreadReadBodySchema,
6747
+ response: {
6748
+ 200: MarkAgentThreadReadResponseSchema,
6749
+ 400: AgentRequestErrorResponseSchema,
6750
+ 404: AgentRequestErrorResponseSchema,
6751
+ 501: ErrorResponseSchema
6752
+ },
6753
+ detail: {
6754
+ summary: "Mark how far you have read an Agent thread",
6755
+ description: MARKING,
6756
+ tags: [OPENAPI_TAGS.agentThreads.name],
6757
+ operationId: "markAgentThreadRead",
6758
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
6759
+ }
6760
+ });
6761
+ }
6762
+
6593
6763
  // src/routes/ai-accounting.ts
6594
6764
  import { AiLimitStorageError } from "@sixb/core/storage";
6595
6765
 
@@ -6910,6 +7080,7 @@ function registerAiAccountingRoutes(app, host) {
6910
7080
  from: new Date(parsed.from),
6911
7081
  to: new Date(parsed.to),
6912
7082
  bucket: parsed.bucket,
7083
+ ...parsed.timeZone === undefined ? {} : { timeZone: parsed.timeZone },
6913
7084
  providerId: parsed.providerId,
6914
7085
  modelId: parsed.modelId,
6915
7086
  ...accountingFilters(parsed)
@@ -13355,7 +13526,7 @@ function registerModelGenerationRoutes(app, host) {
13355
13526
  model: entry.model,
13356
13527
  signal: request.signal
13357
13528
  });
13358
- return TranscriptionSchema.parse({ ...result(entry, call), text: call.output.text });
13529
+ return TranscriptionSchema.parse({ ...result(entry, call), ...call.output });
13359
13530
  } catch (error) {
13360
13531
  return generationError(error, set);
13361
13532
  }
@@ -13502,7 +13673,7 @@ function registerObservedAgentThreadRoutes(app, host) {
13502
13673
  return threadNotFound(context.set);
13503
13674
  }
13504
13675
  const query = AgentMessagesQuerySchema.parse(context.query);
13505
- return AgentMessageListResponseSchema.parse(await readThreadMessages(host, storage, thread, query));
13676
+ return await readThreadMessages(host, storage, thread, query);
13506
13677
  } catch (error) {
13507
13678
  return handleAgentRouteError(error, context.set);
13508
13679
  }
@@ -13555,7 +13726,7 @@ function registerObservedAgentThreadRoutes(app, host) {
13555
13726
  return threadNotFound(context.set);
13556
13727
  }
13557
13728
  return AgentRunListResponseSchema.parse({
13558
- runs: result.runs.map(serializeAgentRun),
13729
+ runs: result.runs.map((run) => serializeAgentRun(run)),
13559
13730
  hasMore: result.hasMore,
13560
13731
  total: result.total
13561
13732
  });
@@ -15072,7 +15243,7 @@ var StatusResponseSchema = z37.object({
15072
15243
  });
15073
15244
 
15074
15245
  // src/routes/status.ts
15075
- function registerStatusRoutes(app, host) {
15246
+ function registerStatusRoutes(app, host, options = {}) {
15076
15247
  app.get("/health", () => ({ status: "ok" }), {
15077
15248
  response: { 200: HealthResponseSchema },
15078
15249
  detail: {
@@ -15083,6 +15254,14 @@ function registerStatusRoutes(app, host) {
15083
15254
  }
15084
15255
  });
15085
15256
  app.get("/ready", async ({ set }) => {
15257
+ if (options.isStopping?.()) {
15258
+ set.status = 503;
15259
+ return {
15260
+ status: "unready",
15261
+ storage: { reachable: false, schemaValid: false },
15262
+ reason: "Server is shutting down."
15263
+ };
15264
+ }
15086
15265
  const readiness = await host.checkReadiness();
15087
15266
  if (readiness.status === "unready")
15088
15267
  set.status = 503;
@@ -15113,6 +15292,9 @@ function registerStatusRoutes(app, host) {
15113
15292
  });
15114
15293
  }
15115
15294
 
15295
+ // src/routes/syncs.ts
15296
+ import { isOAuthConnectorDefinition as isOAuthConnectorDefinition3 } from "@sixb/core/internal/connector-connections";
15297
+
15116
15298
  // src/schemas/syncs.ts
15117
15299
  import {
15118
15300
  SYNC_RUN_FAILURE_CODES
@@ -15126,6 +15308,7 @@ var SyncRunStatusSchema = z38.enum(["queued", "running", "succeeded", "failed",
15126
15308
  var SyncModeSchema = z38.enum(["snapshot", "append", "merge"]);
15127
15309
  var SyncRunsQuerySchema = z38.object({
15128
15310
  syncId: z38.string().optional(),
15311
+ connectionId: z38.string().optional(),
15129
15312
  datasetId: z38.string().optional(),
15130
15313
  status: SyncRunStatusSchema.optional(),
15131
15314
  startedAfter: z38.string().optional(),
@@ -15135,6 +15318,7 @@ var SyncRunsQuerySchema = z38.object({
15135
15318
  order: z38.enum(["asc", "desc"]).optional()
15136
15319
  });
15137
15320
  var RequestSyncRunBodySchema = z38.object({
15321
+ connectionId: z38.string().optional(),
15138
15322
  expectedLatestVersionId: z38.string().optional(),
15139
15323
  commitMessage: z38.string().optional()
15140
15324
  });
@@ -15146,6 +15330,7 @@ var SyncRunSchema = z38.object({
15146
15330
  id: z38.string(),
15147
15331
  projectId: z38.string(),
15148
15332
  syncId: z38.string(),
15333
+ connectionId: z38.string().optional(),
15149
15334
  datasetId: z38.string(),
15150
15335
  mode: SyncModeSchema,
15151
15336
  status: SyncRunStatusSchema,
@@ -15162,6 +15347,33 @@ var SyncRunSchema = z38.object({
15162
15347
  commitMessage: z38.string().optional(),
15163
15348
  error: SyncRunFailureSchema.optional()
15164
15349
  });
15350
+ var SyncAccountConnectionSchema = z38.object({
15351
+ id: z38.string(),
15352
+ owner: z38.discriminatedUnion("type", [
15353
+ z38.object({ type: z38.literal("project") }),
15354
+ z38.object({ type: z38.literal("user"), id: z38.string() })
15355
+ ]),
15356
+ slot: z38.string(),
15357
+ account: z38.object({ id: z38.string(), label: z38.string() })
15358
+ });
15359
+ var ConnectorAccountSchema2 = z38.object({
15360
+ connection: SyncAccountConnectionSchema,
15361
+ latestRuns: z38.array(SyncRunSchema)
15362
+ });
15363
+ var ConnectorAccountListResponseSchema = z38.object({
15364
+ accounts: z38.array(ConnectorAccountSchema2)
15365
+ });
15366
+ var ConnectorAccountsParamsSchema = z38.object({
15367
+ connectorId: z38.string().min(1)
15368
+ });
15369
+ var SyncAccountSummarySchema = z38.object({
15370
+ total: z38.number(),
15371
+ running: z38.number(),
15372
+ needsReconnecting: z38.number(),
15373
+ failing: z38.number(),
15374
+ synced: z38.number(),
15375
+ lastSyncedAt: z38.string().optional()
15376
+ });
15165
15377
  var SyncSchema = z38.object({
15166
15378
  id: z38.string(),
15167
15379
  mode: SyncModeSchema,
@@ -15174,19 +15386,31 @@ var SyncSchema = z38.object({
15174
15386
  dataset: DatasetDefinitionSchema
15175
15387
  }),
15176
15388
  triggers: z38.array(SyncTriggerSchema),
15177
- latestRun: SyncRunSchema.nullable()
15389
+ latestRun: SyncRunSchema.nullable(),
15390
+ accounts: SyncAccountSummarySchema.optional()
15391
+ });
15392
+ var ConnectionSyncRunsParamsSchema = z38.object({
15393
+ connectorId: z38.string().min(1),
15394
+ connectionId: z38.string().min(1)
15395
+ });
15396
+ var ConnectionSyncRunsResponseSchema = z38.object({
15397
+ runs: z38.array(SyncRunSchema)
15178
15398
  });
15179
15399
  var SyncRunListResponseSchema = z38.object({
15180
15400
  runs: z38.array(SyncRunSchema),
15181
15401
  hasMore: z38.boolean(),
15182
15402
  total: z38.number()
15183
15403
  });
15184
- var RequestSyncRunResponseSchema = z38.object({
15404
+ var RequestedSyncRunSchema = z38.object({
15185
15405
  runId: z38.string(),
15186
15406
  jobId: z38.string(),
15187
15407
  syncId: z38.string(),
15408
+ connectionId: z38.string().optional(),
15188
15409
  queuedAt: z38.string()
15189
15410
  });
15411
+ var RequestSyncRunResponseSchema = z38.object({
15412
+ runs: z38.array(RequestedSyncRunSchema)
15413
+ });
15190
15414
 
15191
15415
  // src/routes/syncs.ts
15192
15416
  function serializeSyncRun(run) {
@@ -15194,6 +15418,7 @@ function serializeSyncRun(run) {
15194
15418
  id: run.id,
15195
15419
  projectId: run.projectId,
15196
15420
  syncId: run.syncId,
15421
+ connectionId: run.connectionId,
15197
15422
  datasetId: run.datasetId,
15198
15423
  mode: run.mode,
15199
15424
  status: run.status,
@@ -15220,7 +15445,48 @@ async function getLatestSyncRuns(sixb, syncIds) {
15220
15445
  const result = await sixb.syncs.runs.listLatest(syncIds);
15221
15446
  return new Map(result.runs.map((run) => [run.syncId, serializeSyncRun(run)]));
15222
15447
  }
15223
- function serializeSync(sync, latestRun) {
15448
+ function serializeAccount(account) {
15449
+ const { id, owner, slot, account: candidate } = account.connection;
15450
+ return {
15451
+ connection: { id, owner, slot, account: { id: candidate.id, label: candidate.label } },
15452
+ latestRuns: account.latestRuns.map(serializeSyncRun)
15453
+ };
15454
+ }
15455
+ function connectorAccounts(sixb) {
15456
+ const byConnector = new Map;
15457
+ return (connectorId) => {
15458
+ let accounts = byConnector.get(connectorId);
15459
+ if (!accounts) {
15460
+ accounts = sixb.syncs.accounts.list(connectorId);
15461
+ byConnector.set(connectorId, accounts);
15462
+ }
15463
+ return accounts;
15464
+ };
15465
+ }
15466
+ async function summarizeAccounts(sync, accountsOf) {
15467
+ if (!isOAuthConnectorDefinition3(sync.connector))
15468
+ return;
15469
+ return summarizeSyncAccounts(sync.id, await accountsOf(sync.connector.id));
15470
+ }
15471
+ function summarizeSyncAccounts(syncId, accounts) {
15472
+ const latest = accounts.flatMap(({ latestRuns }) => latestRuns.filter((run) => run.syncId === syncId));
15473
+ const count = (matches) => latest.filter(matches).length;
15474
+ const reconnect = (run) => run.error?.code === "connector.authorization_required";
15475
+ const synced = latest.filter((run) => run.status === "succeeded");
15476
+ const lastSyncedAt = synced.reduce((last, run) => {
15477
+ const at = run.finishedAt ?? run.queuedAt;
15478
+ return last && last >= at ? last : at;
15479
+ }, undefined);
15480
+ return {
15481
+ total: accounts.length,
15482
+ running: count((run) => run.status === "queued" || run.status === "running"),
15483
+ needsReconnecting: count((run) => run.status === "failed" && reconnect(run)),
15484
+ failing: count((run) => run.status === "failed" && !reconnect(run)),
15485
+ synced: synced.length,
15486
+ ...lastSyncedAt === undefined ? {} : { lastSyncedAt: toIsoString(lastSyncedAt) }
15487
+ };
15488
+ }
15489
+ function serializeSync(sync, latestRun, accounts) {
15224
15490
  return SyncSchema.parse({
15225
15491
  id: sync.id,
15226
15492
  mode: sync.config.mode,
@@ -15233,7 +15499,8 @@ function serializeSync(sync, latestRun) {
15233
15499
  dataset: sync.target.dataset
15234
15500
  },
15235
15501
  triggers: sync.triggers,
15236
- latestRun
15502
+ latestRun,
15503
+ ...accounts === undefined ? {} : { accounts }
15237
15504
  });
15238
15505
  }
15239
15506
  function registerSyncRoutes(app, host) {
@@ -15241,7 +15508,8 @@ function registerSyncRoutes(app, host) {
15241
15508
  const sixb = requireRequestSixb(context);
15242
15509
  const syncs = sixb.syncs.list();
15243
15510
  const latestRuns = await getLatestSyncRuns(sixb, syncs.map((sync) => sync.id));
15244
- return syncs.map((sync) => serializeSync(sync, latestRuns.get(sync.id) ?? null));
15511
+ const accountsOf = connectorAccounts(sixb);
15512
+ return Promise.all(syncs.map(async (sync) => serializeSync(sync, latestRuns.get(sync.id) ?? null, await summarizeAccounts(sync, accountsOf))));
15245
15513
  }, {
15246
15514
  response: { 200: SyncSchema.array() },
15247
15515
  detail: {
@@ -15258,7 +15526,7 @@ function registerSyncRoutes(app, host) {
15258
15526
  set.status = 404;
15259
15527
  return { error: "Sync not found" };
15260
15528
  }
15261
- return serializeSync(sync, await getLatestSyncRun(sixb, sync.id));
15529
+ return serializeSync(sync, await getLatestSyncRun(sixb, sync.id), await summarizeAccounts(sync, connectorAccounts(sixb)));
15262
15530
  }, {
15263
15531
  params: SyncParamsSchema,
15264
15532
  response: { 200: SyncSchema, 404: ErrorResponseSchema },
@@ -15268,6 +15536,35 @@ function registerSyncRoutes(app, host) {
15268
15536
  operationId: "getSync",
15269
15537
  security: accessTokenSecurityRequirement("getSync")
15270
15538
  }
15539
+ }).get("/api/connectors/:connectorId/accounts", async (context) => {
15540
+ const { params } = context;
15541
+ const sixb = requireRequestSixb(context);
15542
+ const accounts = await sixb.syncs.accounts.list(params.connectorId);
15543
+ return { accounts: accounts.map(serializeAccount) };
15544
+ }, {
15545
+ params: ConnectorAccountsParamsSchema,
15546
+ response: { 200: ConnectorAccountListResponseSchema },
15547
+ detail: {
15548
+ summary: "List a connector's accounts and how they synced",
15549
+ description: "On an OAuth connector, each connected account you may see, with the latest run of each of its syncs you may run. Empty for a static connector.",
15550
+ tags: [OPENAPI_TAGS.connectorConnections.name],
15551
+ operationId: "listConnectorAccounts",
15552
+ security: accessTokenSecurityRequirement("listConnectorAccounts")
15553
+ }
15554
+ }).get("/api/connectors/:connectorId/connections/:connectionId/sync-runs", async (context) => {
15555
+ const { params } = context;
15556
+ const sixb = requireRequestSixb(context);
15557
+ const runs = await sixb.syncs.accounts.latestRuns(params.connectorId, params.connectionId);
15558
+ return { runs: runs.map(serializeSyncRun) };
15559
+ }, {
15560
+ params: ConnectionSyncRunsParamsSchema,
15561
+ response: { 200: ConnectionSyncRunsResponseSchema },
15562
+ detail: {
15563
+ summary: "Latest sync runs of a connection",
15564
+ description: "The latest run of each sync of one connection: your own, or anyone's with can.manage on its connector. Empty for a connection you don't see.",
15565
+ tags: [OPENAPI_TAGS.connectorConnections.name],
15566
+ operationId: "listConnectorConnectionSyncRuns"
15567
+ }
15271
15568
  }).get("/api/sync-runs", async (context) => {
15272
15569
  const { query, set } = context;
15273
15570
  const sixb = requireRequestSixb(context);
@@ -15279,6 +15576,7 @@ function registerSyncRoutes(app, host) {
15279
15576
  }
15280
15577
  const result = await sixb.syncs.runs.list({
15281
15578
  syncId: parsed.syncId,
15579
+ ...parsed.connectionId === undefined ? {} : { connectionId: parsed.connectionId },
15282
15580
  datasetId: parsed.datasetId,
15283
15581
  statuses: parsed.status ? [parsed.status] : undefined,
15284
15582
  startedAfter: parseDate(parsed.startedAfter),
@@ -15316,10 +15614,13 @@ function registerSyncRoutes(app, host) {
15316
15614
  const result = await sixb.syncs.request({ syncId: params.syncId, ...parsedBody });
15317
15615
  set.status = 202;
15318
15616
  return {
15319
- runId: result.runId,
15320
- jobId: result.jobId ?? "",
15321
- syncId: result.syncId,
15322
- queuedAt: result.queuedAt
15617
+ runs: result.runs.map((run) => ({
15618
+ runId: run.runId,
15619
+ jobId: run.jobId ?? "",
15620
+ syncId: run.syncId,
15621
+ connectionId: run.connectionId,
15622
+ queuedAt: run.queuedAt
15623
+ }))
15323
15624
  };
15324
15625
  } catch (error) {
15325
15626
  return handleRouteError(error, set);
@@ -16739,7 +17040,7 @@ function registerHttpRoutes(app, host, options) {
16739
17040
  registerModelCallRoutes(app, host);
16740
17041
  registerModelGenerationRoutes(app, host);
16741
17042
  registerProjectRoutes(app, host);
16742
- registerStatusRoutes(app, host);
17043
+ registerStatusRoutes(app, host, { isStopping: options.isStopping });
16743
17044
  registerConnectorRoutes(app, host);
16744
17045
  registerConnectorConnectionRoutes(app, host);
16745
17046
  registerConnectorConnectionRunRoutes(app, host, options.connectorConnections);
@@ -16758,6 +17059,7 @@ function registerHttpRoutes(app, host, options) {
16758
17059
  registerFileDownloadRoutes(app, host);
16759
17060
  registerActionRunRoutes(app, host);
16760
17061
  registerAgentRoutes(app, host);
17062
+ registerAgentThreadReadRoutes(app, host);
16761
17063
  registerAgentChildRoutes(app, host);
16762
17064
  registerAgentRunnerRoutes(app, host);
16763
17065
  registerAgentComputerRoutes(app, host);
@@ -19603,7 +19905,9 @@ import { BrokerCursorExpiredError } from "@sixb/core/broker";
19603
19905
  import {
19604
19906
  agentActivityStreamDefinition,
19605
19907
  agentRunStreamDefinition,
19606
- agentRunStreamId as agentRunStreamId3
19908
+ agentRunStreamId as agentRunStreamId3,
19909
+ coveredBySteps,
19910
+ readAgentRunSteps
19607
19911
  } from "@sixb/core/internal/agents/streams";
19608
19912
  import { z as z43 } from "zod";
19609
19913
 
@@ -19773,12 +20077,17 @@ async function subscribeAgentStream(states, server, ws, message) {
19773
20077
  states.set(wsStateKey(ws), state);
19774
20078
  const buffered = [];
19775
20079
  let live = false;
20080
+ let steps = null;
20081
+ const send = (records) => {
20082
+ const current = steps;
20083
+ sendRecords(ws, current ? records.filter((record) => !coveredBySteps(current, record.payload)) : records);
20084
+ };
19776
20085
  const receive = (records) => {
19777
20086
  if (!live) {
19778
20087
  buffered.push(...records);
19779
20088
  return;
19780
20089
  }
19781
- sendRecords(ws, records);
20090
+ send(records);
19782
20091
  };
19783
20092
  let resumedFromEarliest = false;
19784
20093
  try {
@@ -19816,13 +20125,34 @@ async function subscribeAgentStream(states, server, ws, message) {
19816
20125
  runId: message.runId,
19817
20126
  afterCursor: resumedFromEarliest ? null : message.afterCursor ?? null
19818
20127
  });
19819
- sendRecords(ws, buffered.splice(0));
20128
+ if (message.afterCursor === undefined || resumedFromEarliest) {
20129
+ steps = await readRunSteps(server, sixb, message.runId);
20130
+ if (steps)
20131
+ safeSend(ws, { type: "run.steps", event: steps });
20132
+ }
20133
+ send(buffered.splice(0));
19820
20134
  if (!await sendRunSnapshot(sixb, ws, message.runId)) {
19821
20135
  stopSubscription(state);
19822
20136
  return;
19823
20137
  }
19824
20138
  live = true;
19825
- sendRecords(ws, buffered.splice(0));
20139
+ send(buffered.splice(0));
20140
+ }
20141
+ async function readRunSteps(server, sixb, runId) {
20142
+ try {
20143
+ const run = await sixb.agent.runs.getById(runId);
20144
+ if (!run || run.status !== "queued" && run.status !== "running")
20145
+ return null;
20146
+ const host = server.getHost();
20147
+ return await readAgentRunSteps(host.broker, {
20148
+ projectId: host.id,
20149
+ runId,
20150
+ attempt: run.attempt
20151
+ });
20152
+ } catch (error) {
20153
+ console.error(`[SixbServer] Agent run '${runId}' finished steps could not be read:`, error);
20154
+ return null;
20155
+ }
19826
20156
  }
19827
20157
  async function subscribeAgentActivity(states, server, ws) {
19828
20158
  const host = server.getHost();
@@ -21732,6 +22062,7 @@ function registerWebSocketRoutes(app, server, sharedAccess) {
21732
22062
 
21733
22063
  // src/server.ts
21734
22064
  var MAX_WEBSOCKET_MESSAGE_BYTES = 64 * 1024;
22065
+ var SERVICE_RESTART_CLOSE_CODE = 1012;
21735
22066
  function createSixbServer(options) {
21736
22067
  return new SixbServer(options);
21737
22068
  }
@@ -21750,10 +22081,13 @@ class SixbServer {
21750
22081
  timing;
21751
22082
  app = null;
21752
22083
  bunServer = null;
22084
+ closeWebSockets = null;
22085
+ stopping = false;
21753
22086
  hostsOntologyMaintenance;
21754
22087
  flushesIngestion;
21755
22088
  maintenance = null;
21756
22089
  stopSweeper = null;
22090
+ inProgressStop = null;
21757
22091
  constructor(options) {
21758
22092
  this.hostRuntime = options.host;
21759
22093
  this.port = options.port ?? 3000;
@@ -21799,10 +22133,17 @@ class SixbServer {
21799
22133
  getSharedAccessOptions() {
21800
22134
  return this.sharedAccessOptions;
21801
22135
  }
22136
+ markStopping() {
22137
+ this.stopping = true;
22138
+ }
22139
+ isStopping() {
22140
+ return this.stopping;
22141
+ }
21802
22142
  async start() {
21803
22143
  if (this.app !== null || this.bunServer !== null || this.maintenance !== null) {
21804
22144
  throw new Error("[SixbServer] Server is already running.");
21805
22145
  }
22146
+ this.stopping = false;
21806
22147
  await checkPipelineMarkings({
21807
22148
  definitions: this.hostRuntime.definitions,
21808
22149
  lakeStorage: this.hostRuntime.lakeStorage
@@ -21814,15 +22155,18 @@ class SixbServer {
21814
22155
  this.maintenance = maintenance;
21815
22156
  try {
21816
22157
  this.app = createSixbApi(this);
21817
- this.bunServer = startApiServer(this.app, {
22158
+ const started = startApiServer(this.app, {
21818
22159
  host: this.hostname,
21819
22160
  port: this.port,
21820
22161
  resolveClientAddress: this.resolveClientAddress,
21821
22162
  timing: this.timing
21822
22163
  });
22164
+ this.bunServer = started.bunServer;
22165
+ this.closeWebSockets = started.closeWebSockets;
21823
22166
  } catch (error) {
21824
22167
  this.app = null;
21825
22168
  this.bunServer = null;
22169
+ this.closeWebSockets = null;
21826
22170
  this.maintenance = null;
21827
22171
  await maintenance?.stop();
21828
22172
  const message = error instanceof Error ? error.message : String(error);
@@ -21840,17 +22184,42 @@ class SixbServer {
21840
22184
  if (ingest)
21841
22185
  ingest.writesInline = inline;
21842
22186
  }
21843
- async stop() {
22187
+ async stop(options = {}) {
22188
+ const timeoutMs = resolveStopTimeoutMs(options.timeoutMs, ACTION_RUN_DRAIN_TIMEOUT_MS);
22189
+ if (this.inProgressStop) {
22190
+ this.inProgressStop.deadline.bringForward(timeoutMs);
22191
+ return this.inProgressStop.done;
22192
+ }
22193
+ const deadline = new StopDeadline(timeoutMs);
22194
+ const done = this.stopUntil(deadline).finally(() => {
22195
+ this.inProgressStop = null;
22196
+ });
22197
+ this.inProgressStop = { deadline, done };
22198
+ return done;
22199
+ }
22200
+ async stopUntil(deadline) {
22201
+ this.stopping = true;
21844
22202
  this.setIngestFlush(false);
21845
22203
  this.stopSweeper?.();
21846
22204
  this.stopSweeper = null;
21847
- if (this.bunServer) {
21848
- this.bunServer.stop(true);
21849
- this.bunServer = null;
21850
- }
21851
- if (this.app) {
21852
- await this.app.stop();
21853
- this.app = null;
22205
+ const bunServer = this.bunServer;
22206
+ const closeWebSockets = this.closeWebSockets;
22207
+ const app = this.app;
22208
+ this.bunServer = null;
22209
+ this.closeWebSockets = null;
22210
+ this.app = null;
22211
+ const stopAppAndSockets = async () => {
22212
+ try {
22213
+ if (app)
22214
+ await stopElysiaHooks(app);
22215
+ } finally {
22216
+ closeWebSockets?.();
22217
+ }
22218
+ };
22219
+ if (bunServer) {
22220
+ await drainBunServer(bunServer, deadline, stopAppAndSockets);
22221
+ } else {
22222
+ await stopAppAndSockets();
21854
22223
  }
21855
22224
  const maintenance = this.maintenance;
21856
22225
  this.maintenance = null;
@@ -22055,6 +22424,7 @@ function createSixbApi(server) {
22055
22424
  registerHttpRoutes(app, host, {
22056
22425
  sharedAccess,
22057
22426
  browserPolicy: apiBrowserPolicy,
22427
+ isStopping: () => server.isStopping(),
22058
22428
  connectorConnections: {
22059
22429
  resolveReturnTo: (request, returnTo) => server.resolveAuthRedirectContext(request, { returnTo }).returnTo,
22060
22430
  resolveCallbackUrl: (request) => new URL("/auth/connectors/callback", server.resolveAuthRequestOrigin(request)).toString()
@@ -22110,6 +22480,7 @@ function rejectDisallowedBrowserOrigin(request, policy) {
22110
22480
  });
22111
22481
  }
22112
22482
  function startApiServer(app, options) {
22483
+ const openSockets = new Set;
22113
22484
  const bunServer = Bun.serve({
22114
22485
  port: options.port,
22115
22486
  hostname: options.host,
@@ -22123,26 +22494,119 @@ function startApiServer(app, options) {
22123
22494
  }
22124
22495
  return timeRequest(request, options.timing, () => app.fetch(request));
22125
22496
  },
22126
- websocket: getElysiaWsHandler(app)
22497
+ websocket: getElysiaWsHandler(app, openSockets)
22127
22498
  });
22128
22499
  attachBunServer(app, bunServer);
22129
- return bunServer;
22500
+ return {
22501
+ bunServer,
22502
+ closeWebSockets: () => {
22503
+ for (const ws of [...openSockets]) {
22504
+ try {
22505
+ ws.close(SERVICE_RESTART_CLOSE_CODE, "Service Restart");
22506
+ } catch {}
22507
+ }
22508
+ openSockets.clear();
22509
+ }
22510
+ };
22130
22511
  }
22131
- function getElysiaWsHandler(app) {
22512
+ function getElysiaWsHandler(app, openSockets) {
22132
22513
  const cfg = app.config;
22133
- return {
22514
+ const base = {
22134
22515
  ...elysiaWebSocket,
22135
- ...cfg?.websocket ?? {},
22136
- maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES
22516
+ ...cfg?.websocket ?? {}
22517
+ };
22518
+ return {
22519
+ ...base,
22520
+ maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES,
22521
+ open(ws) {
22522
+ openSockets.add(ws);
22523
+ return base.open?.(ws);
22524
+ },
22525
+ close(ws, code, reason) {
22526
+ openSockets.delete(ws);
22527
+ return base.close?.(ws, code, reason);
22528
+ }
22137
22529
  };
22138
22530
  }
22531
+ function resolveStopTimeoutMs(timeoutMs, fallbackMs) {
22532
+ const resolved = timeoutMs ?? fallbackMs;
22533
+ if (!Number.isFinite(resolved) || resolved < 0) {
22534
+ throw new Error("[SixbServer] Stop timeout must be a non-negative finite number.");
22535
+ }
22536
+ return resolved;
22537
+ }
22538
+
22539
+ class StopDeadline {
22540
+ at;
22541
+ constructor(timeoutMs) {
22542
+ this.at = Date.now() + timeoutMs;
22543
+ }
22544
+ remainingMs() {
22545
+ return this.at - Date.now();
22546
+ }
22547
+ bringForward(timeoutMs) {
22548
+ this.at = Math.min(this.at, Date.now() + timeoutMs);
22549
+ }
22550
+ }
22551
+ async function drainBunServer(server, deadline, beforeWait) {
22552
+ if (deadline.remainingMs() <= 0) {
22553
+ try {
22554
+ await beforeWait();
22555
+ } finally {
22556
+ await server.stop(true);
22557
+ }
22558
+ return;
22559
+ }
22560
+ const draining = server.stop(false);
22561
+ try {
22562
+ await beforeWait();
22563
+ } catch (error) {
22564
+ await server.stop(true);
22565
+ await draining;
22566
+ throw error;
22567
+ }
22568
+ await waitUntilIdleOrTimeout(server, draining, deadline);
22569
+ await server.stop(true);
22570
+ await draining;
22571
+ }
22572
+ async function waitUntilIdleOrTimeout(server, draining, deadline) {
22573
+ let settled = false;
22574
+ draining.then(() => {
22575
+ settled = true;
22576
+ }, () => {
22577
+ settled = true;
22578
+ });
22579
+ while (!settled && (server.pendingRequests > 0 || server.pendingWebSockets > 0)) {
22580
+ const remaining = deadline.remainingMs();
22581
+ if (remaining <= 0)
22582
+ return;
22583
+ let timer;
22584
+ try {
22585
+ await Promise.race([
22586
+ draining,
22587
+ new Promise((resolve) => {
22588
+ timer = setTimeout(resolve, Math.min(remaining, 25));
22589
+ })
22590
+ ]);
22591
+ } finally {
22592
+ if (timer !== undefined)
22593
+ clearTimeout(timer);
22594
+ }
22595
+ }
22596
+ }
22139
22597
  function attachBunServer(app, bunServer) {
22140
22598
  app.server = bunServer;
22141
22599
  }
22600
+ async function stopElysiaHooks(app) {
22601
+ const internal = app;
22602
+ const hooks = internal.event?.stop ?? [];
22603
+ internal.server = null;
22604
+ await Promise.all(hooks.map((hook) => Promise.resolve(hook.fn(app))));
22605
+ }
22142
22606
  export {
22143
22607
  SixbServer,
22144
22608
  createSixbServer,
22145
22609
  requestTimingOptionsFromEnv
22146
22610
  };
22147
22611
 
22148
- //# debugId=39E8C6B2A92C4BF064756E2164756E21
22612
+ //# debugId=FA111C44817B2F5664756E2164756E21