@sixb/server 0.2.5 → 0.2.7

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 (106) hide show
  1. package/dist/auth/run-token.d.ts.map +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +596 -92
  5. package/dist/index.js.map +36 -35
  6. package/dist/registerRoutes.d.ts +1 -0
  7. package/dist/registerRoutes.d.ts.map +1 -1
  8. package/dist/routes/actions.d.ts +2 -0
  9. package/dist/routes/actions.d.ts.map +1 -1
  10. package/dist/routes/agent-approvals.d.ts +23 -1
  11. package/dist/routes/agent-approvals.d.ts.map +1 -1
  12. package/dist/routes/agent-computers.d.ts +36 -0
  13. package/dist/routes/agent-computers.d.ts.map +1 -1
  14. package/dist/routes/agent-thread-reads.d.ts +82 -0
  15. package/dist/routes/agent-thread-reads.d.ts.map +1 -0
  16. package/dist/routes/agents.d.ts +795 -13
  17. package/dist/routes/agents.d.ts.map +1 -1
  18. package/dist/routes/ai-accounting.d.ts.map +1 -1
  19. package/dist/routes/connectors.d.ts +2 -0
  20. package/dist/routes/connectors.d.ts.map +1 -1
  21. package/dist/routes/datasets.d.ts +2 -0
  22. package/dist/routes/datasets.d.ts.map +1 -1
  23. package/dist/routes/model-generations.d.ts +6 -0
  24. package/dist/routes/model-generations.d.ts.map +1 -1
  25. package/dist/routes/observed-agent-threads.d.ts +24 -2
  26. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  27. package/dist/routes/ontology.d.ts +2 -0
  28. package/dist/routes/ontology.d.ts.map +1 -1
  29. package/dist/routes/pipelines.d.ts +2 -0
  30. package/dist/routes/pipelines.d.ts.map +1 -1
  31. package/dist/routes/projections.d.ts +6 -0
  32. package/dist/routes/projections.d.ts.map +1 -1
  33. package/dist/routes/rules.d.ts +2 -0
  34. package/dist/routes/rules.d.ts.map +1 -1
  35. package/dist/routes/status.d.ts +5 -2
  36. package/dist/routes/status.d.ts.map +1 -1
  37. package/dist/routes/syncs.d.ts +177 -12
  38. package/dist/routes/syncs.d.ts.map +1 -1
  39. package/dist/routes/workflows.d.ts +8 -6
  40. package/dist/routes/workflows.d.ts.map +1 -1
  41. package/dist/routes/ws/agents.d.ts.map +1 -1
  42. package/dist/schemas/actions.d.ts +6 -0
  43. package/dist/schemas/actions.d.ts.map +1 -1
  44. package/dist/schemas/activity.d.ts +4 -4
  45. package/dist/schemas/agents.d.ts +2657 -61
  46. package/dist/schemas/agents.d.ts.map +1 -1
  47. package/dist/schemas/ai-accounting.d.ts +3 -0
  48. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  49. package/dist/schemas/common.d.ts +5 -0
  50. package/dist/schemas/common.d.ts.map +1 -1
  51. package/dist/schemas/connectors.d.ts +3 -0
  52. package/dist/schemas/connectors.d.ts.map +1 -1
  53. package/dist/schemas/datasets.d.ts +3 -0
  54. package/dist/schemas/datasets.d.ts.map +1 -1
  55. package/dist/schemas/models.d.ts +46 -0
  56. package/dist/schemas/models.d.ts.map +1 -1
  57. package/dist/schemas/ontology.d.ts +3 -0
  58. package/dist/schemas/ontology.d.ts.map +1 -1
  59. package/dist/schemas/pipelines.d.ts +3 -0
  60. package/dist/schemas/pipelines.d.ts.map +1 -1
  61. package/dist/schemas/projections.d.ts +33 -0
  62. package/dist/schemas/projections.d.ts.map +1 -1
  63. package/dist/schemas/rules.d.ts +3 -0
  64. package/dist/schemas/rules.d.ts.map +1 -1
  65. package/dist/schemas/status.d.ts +2 -2
  66. package/dist/schemas/syncs.d.ts +727 -25
  67. package/dist/schemas/syncs.d.ts.map +1 -1
  68. package/dist/schemas/workflows.d.ts +25 -22
  69. package/dist/schemas/workflows.d.ts.map +1 -1
  70. package/dist/server.d.ts +16 -1
  71. package/dist/server.d.ts.map +1 -1
  72. package/package.json +5 -5
  73. package/src/auth/run-token.ts +59 -9
  74. package/src/index.ts +6 -1
  75. package/src/registerRoutes.ts +4 -1
  76. package/src/routes/actions.ts +7 -3
  77. package/src/routes/agent-computers.ts +7 -6
  78. package/src/routes/agent-thread-reads.ts +67 -0
  79. package/src/routes/agents.ts +129 -16
  80. package/src/routes/ai-accounting.ts +1 -0
  81. package/src/routes/connectors.ts +1 -0
  82. package/src/routes/datasets.ts +11 -3
  83. package/src/routes/model-generations.ts +1 -1
  84. package/src/routes/observed-agent-threads.ts +3 -4
  85. package/src/routes/ontology.ts +17 -3
  86. package/src/routes/pipelines.ts +13 -3
  87. package/src/routes/projections.ts +14 -9
  88. package/src/routes/rules.ts +9 -3
  89. package/src/routes/status.ts +18 -1
  90. package/src/routes/syncs.ts +139 -8
  91. package/src/routes/workflows.ts +13 -3
  92. package/src/routes/ws/agents.ts +43 -3
  93. package/src/schemas/actions.ts +7 -1
  94. package/src/schemas/agents.ts +80 -10
  95. package/src/schemas/ai-accounting.ts +12 -0
  96. package/src/schemas/common.ts +24 -9
  97. package/src/schemas/connectors.ts +2 -1
  98. package/src/schemas/datasets.ts +2 -1
  99. package/src/schemas/models.ts +10 -0
  100. package/src/schemas/ontology.ts +2 -0
  101. package/src/schemas/pipelines.ts +2 -1
  102. package/src/schemas/projections.ts +4 -1
  103. package/src/schemas/rules.ts +2 -0
  104. package/src/schemas/syncs.ts +65 -2
  105. package/src/schemas/workflows.ts +7 -1
  106. 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";
@@ -836,6 +837,7 @@ class ServerAuthGuard {
836
837
 
837
838
  // src/auth/run-token.ts
838
839
  import {
840
+ AGENT_RUN_HEADER,
839
841
  AgentRunScopeError,
840
842
  agentRunTokenRunId,
841
843
  findAgentApiRoute as findAgentApiRoute2,
@@ -884,12 +886,14 @@ function codedErrorResponseSchema(codes) {
884
886
  });
885
887
  }
886
888
  var RedactionsSchema = z.record(z.object({ reason: z.literal("missing_clearance") }));
889
+ var DefinitionFolderSchema = z.string().optional().describe("Folder below the definition's directory, such as `raw/erp`; absent at its top.");
887
890
  var SuccessResponseSchema = z.object({ success: z.boolean() });
888
891
  var PrincipalSchema = z.object({
889
892
  type: z.enum(["user", "serviceAccount", "system"]),
890
893
  id: z.string().min(1)
891
894
  });
892
- var JsonValueSchema = z.lazy(() => z.union([
895
+ var jsonValueUnion;
896
+ var JsonValueSchema = z.lazy(() => jsonValueUnion ??= z.union([
893
897
  z.string(),
894
898
  z.number().finite(),
895
899
  z.boolean(),
@@ -995,6 +999,7 @@ var ActionSchema = z2.object({
995
999
  });
996
1000
  var ObjectTypeSchema = z2.object({
997
1001
  id: z2.string(),
1002
+ folder: DefinitionFolderSchema,
998
1003
  name: z2.string(),
999
1004
  description: z2.string().optional(),
1000
1005
  extends: z2.string().optional(),
@@ -1048,6 +1053,7 @@ var ActionRequestFailedResponseSchema = codedErrorResponseSchema(SIXB_ERROR_CODE
1048
1053
  var RuntimeStoppingResponseSchema = codedErrorResponseSchema(["runtime.stopping"]);
1049
1054
  var ActionCatalogItemSchema = z3.object({
1050
1055
  id: z3.string(),
1056
+ folder: DefinitionFolderSchema,
1051
1057
  name: z3.string(),
1052
1058
  description: z3.string().optional(),
1053
1059
  objectTypeId: z3.string().optional(),
@@ -1247,6 +1253,7 @@ var AgentPreferencesSchema = z4.object({
1247
1253
  });
1248
1254
 
1249
1255
  // src/schemas/ai-accounting.ts
1256
+ import { canonicalTimeZone } from "@sixb/core/calendar";
1250
1257
  import { z as z8 } from "zod";
1251
1258
 
1252
1259
  // src/schemas/ai-usage.ts
@@ -1544,8 +1551,15 @@ var InlineAudioSchema = z7.object({
1544
1551
  var TranscriptionBodySchema = GenerationBodyBase.extend({
1545
1552
  audio: z7.union([FileRefSchema, InlineAudioSchema])
1546
1553
  });
1554
+ var TranscriptionWordSchema = z7.object({
1555
+ text: z7.string(),
1556
+ startMs: z7.number().int().nonnegative(),
1557
+ endMs: z7.number().int().nonnegative(),
1558
+ speaker: z7.string().optional()
1559
+ });
1547
1560
  var TranscriptionSchema = GenerationResultBase.extend({
1548
- text: z7.string()
1561
+ text: z7.string(),
1562
+ words: z7.array(TranscriptionWordSchema).optional()
1549
1563
  });
1550
1564
 
1551
1565
  // src/schemas/ai-accounting.ts
@@ -1578,8 +1592,12 @@ var AiAccountingRangeQuerySchema = z8.object({
1578
1592
  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
1593
  kind: ModelKindSchema.optional().describe("Calls to one kind of model")
1580
1594
  });
1595
+ var TimeZoneSchema = z8.string().trim().min(1).refine((value) => canonicalTimeZone(value) !== undefined, {
1596
+ message: "Use an IANA time zone such as America/New_York"
1597
+ });
1581
1598
  var AiAccountingOverviewQuerySchema = AiAccountingRangeQuerySchema.extend({
1582
- bucket: AiAccountingBucketSchema
1599
+ bucket: AiAccountingBucketSchema,
1600
+ 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
1601
  });
1584
1602
  var AiModelCallAccountingListQuerySchema = AiAccountingRangeQuerySchema.extend({
1585
1603
  executionId: z8.string().trim().min(1).optional(),
@@ -1921,6 +1939,31 @@ var AgentThreadParticipantSchema = z9.object({
1921
1939
  addedAt: z9.string(),
1922
1940
  addedBy: AgentPrincipalSchema
1923
1941
  });
1942
+ var AgentRunStatusSchema = z9.enum([
1943
+ "queued",
1944
+ "running",
1945
+ "succeeded",
1946
+ "failed",
1947
+ "cancelled"
1948
+ ]);
1949
+ var AgentRunFinishReasonSchema = z9.enum(AGENT_RUN_FINISH_REASONS);
1950
+ var AgentThreadReadSchema = z9.object({
1951
+ threadId: z9.string(),
1952
+ throughSeq: z9.number(),
1953
+ headSeq: z9.number(),
1954
+ unread: z9.number(),
1955
+ readAt: z9.string().optional()
1956
+ });
1957
+ var AgentThreadLastRunSchema = z9.object({
1958
+ id: z9.string(),
1959
+ status: AgentRunStatusSchema,
1960
+ finishReason: AgentRunFinishReasonSchema.optional(),
1961
+ errorCode: z9.enum(AGENT_RUN_FAILURE_CODES).optional(),
1962
+ completedAt: z9.string().optional(),
1963
+ requestedBy: AgentAuthorizablePrincipalSchema.optional()
1964
+ });
1965
+ var MarkAgentThreadReadBodySchema = z9.object({ throughMessageId: z9.string().trim().min(1).optional() }).strict();
1966
+ var MarkAgentThreadReadResponseSchema = z9.object({ read: AgentThreadReadSchema });
1924
1967
  var AgentThreadSchema = z9.object({
1925
1968
  sandboxState: z9.object({
1926
1969
  name: z9.string(),
@@ -1955,6 +1998,8 @@ var AgentThreadSchema = z9.object({
1955
1998
  messageCount: z9.number(),
1956
1999
  createdAt: z9.string(),
1957
2000
  updatedAt: z9.string(),
2001
+ read: AgentThreadReadSchema.optional(),
2002
+ lastRun: AgentThreadLastRunSchema.optional(),
1958
2003
  approvalMode: AgentApprovalModeSchema.optional(),
1959
2004
  approvalModeSource: AgentApprovalModeSourceSchema.optional()
1960
2005
  });
@@ -2131,6 +2176,17 @@ var AgentMessageListResponseSchema = z9.object({
2131
2176
  hasMore: z9.boolean(),
2132
2177
  total: z9.number()
2133
2178
  });
2179
+ var EditAgentMessageBodySchema = z9.object({
2180
+ text: z9.string().trim().min(1).optional(),
2181
+ model: LanguageModelRefSchema.optional(),
2182
+ reasoning: ModelReasoningSchema.optional(),
2183
+ timeZone: z9.string().trim().min(1).max(100).optional(),
2184
+ locale: z9.string().trim().min(1).max(100).optional(),
2185
+ approvalMode: AgentApprovalModeSchema.optional(),
2186
+ attachments: z9.array(FileRefSchema).optional(),
2187
+ context: z9.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
2188
+ nextMessageId: z9.string().trim().min(1).optional()
2189
+ }).strict();
2134
2190
  var PostAgentMessageBodySchema = z9.object({
2135
2191
  text: z9.string().trim().min(1).optional(),
2136
2192
  continue: z9.literal(true).optional(),
@@ -2150,14 +2206,6 @@ var AgentRequestErrorResponseSchema = ErrorResponseSchema.extend({
2150
2206
  var CancelAgentRunBodySchema = z9.object({
2151
2207
  runId: z9.string().trim().min(1)
2152
2208
  });
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
2209
  var AgentRunSchema = z9.object({
2162
2210
  id: z9.string(),
2163
2211
  projectId: z9.string(),
@@ -2172,6 +2220,7 @@ var AgentRunSchema = z9.object({
2172
2220
  reasoning: ModelReasoningSchema.optional(),
2173
2221
  approvalMode: AgentApprovalModeSchema.optional(),
2174
2222
  runsOn: z9.literal("computer").optional(),
2223
+ computer: z9.object({ id: z9.string(), folder: z9.string() }).optional(),
2175
2224
  modelId: z9.string().optional(),
2176
2225
  finishReason: AgentRunFinishReasonSchema.optional(),
2177
2226
  usage: AiUsageSummarySchema.optional(),
@@ -2201,6 +2250,7 @@ var AgentInboxItemSchema = z9.object({
2201
2250
  timeZone: z9.string().optional(),
2202
2251
  locale: z9.string().optional(),
2203
2252
  immediate: z9.boolean().optional(),
2253
+ replacesMessageId: z9.string().optional(),
2204
2254
  createdAt: z9.string(),
2205
2255
  updatedAt: z9.string()
2206
2256
  });
@@ -2225,6 +2275,10 @@ var PostAgentMessageResponseSchema = z9.object({
2225
2275
  run: AgentRunSchema.optional(),
2226
2276
  item: AgentInboxItemSchema.optional()
2227
2277
  });
2278
+ var EditAgentMessageResponseSchema = z9.object({
2279
+ run: AgentRunSchema.optional(),
2280
+ item: AgentInboxItemSchema.optional()
2281
+ });
2228
2282
  var CancelAgentRunResponseSchema = z9.object({
2229
2283
  run: AgentRunSchema
2230
2284
  });
@@ -2526,6 +2580,7 @@ var WorkflowInterventionSchema = z10.object({
2526
2580
  });
2527
2581
  var WorkflowSchema = z10.object({
2528
2582
  id: z10.string(),
2583
+ folder: DefinitionFolderSchema,
2529
2584
  input: WorkflowIOSnapshotSchema,
2530
2585
  triggers: z10.array(WorkflowTriggerSchema),
2531
2586
  nodes: z10.array(WorkflowNodeSchema),
@@ -2921,7 +2976,7 @@ async function resolveRunTokenRequest(input) {
2921
2976
  if (!isAllowedAgentApiRequest(method, path)) {
2922
2977
  return deny(403, `A run token cannot call ${method} ${path}.`);
2923
2978
  }
2924
- const resolved = await resolveRunState(host, input.token);
2979
+ const resolved = await resolveRunState(host, input.token, request.headers.get(AGENT_RUN_HEADER) ?? undefined);
2925
2980
  if (resolved.kind === "deny")
2926
2981
  return resolved;
2927
2982
  const { state, run } = resolved;
@@ -2966,7 +3021,7 @@ async function runPolicyRefusal(host, input) {
2966
3021
  }
2967
3022
  return;
2968
3023
  }
2969
- async function resolveRunState(host, token) {
3024
+ async function resolveRunState(host, token, actingRunId) {
2970
3025
  const agentStorage = host.storage.agents;
2971
3026
  const workflowRuns = host.storage.workflowRuns;
2972
3027
  if (!agentStorage && !workflowRuns) {
@@ -2975,15 +3030,23 @@ async function resolveRunState(host, token) {
2975
3030
  const runId = agentRunTokenRunId(token);
2976
3031
  const storedAgentRun = runId ? await agentStorage?.runs.getById({ projectId: host.id, id: runId }) : undefined;
2977
3032
  const workflowRun = runId && !storedAgentRun ? await workflowRuns?.agentNodes.getByNodeRunId({ projectId: host.id, nodeRunId: runId }) : undefined;
2978
- const runState = toRunState(storedAgentRun ?? null, workflowRun ?? null);
2979
- if (!runId || !runState || runState.run.status !== "running" || "cancelRequestedAt" in runState.run && runState.run.cancelRequestedAt || !runState.run.execution || runState.run.execution.queueLeaseExpiresAt.getTime() <= Date.now() || !isValidAgentRunToken({
3033
+ const tokenState = toRunState(storedAgentRun ?? null, workflowRun ?? null);
3034
+ if (!runId || !tokenState || tokenState.run.status !== "running" || "cancelRequestedAt" in tokenState.run && tokenState.run.cancelRequestedAt || !tokenState.run.execution || tokenState.run.execution.queueLeaseExpiresAt.getTime() <= Date.now() || !isValidAgentRunToken({
2980
3035
  projectId: host.id,
2981
3036
  runId,
2982
- executionToken: runState.run.execution.token,
3037
+ executionToken: tokenState.run.execution.token,
2983
3038
  token
2984
3039
  })) {
2985
3040
  return deny(403, "The run token is not valid: its run has ended, moved or been stopped.");
2986
3041
  }
3042
+ let runState = tokenState;
3043
+ if (actingRunId !== undefined && actingRunId !== runId) {
3044
+ const child = await childActingFor(host, tokenState, actingRunId);
3045
+ if (!child) {
3046
+ return deny(403, `The run token cannot act as run '${actingRunId}': only as a sub-agent of its own run still at work.`);
3047
+ }
3048
+ runState = child;
3049
+ }
2987
3050
  let scope;
2988
3051
  try {
2989
3052
  scope = await resolveAgentRunExecutionScope(host, {
@@ -3040,6 +3103,15 @@ function toRunState(storedRun, workflowRun) {
3040
3103
  actorId: workflowRun.actorId
3041
3104
  };
3042
3105
  }
3106
+ async function childActingFor(host, parent, childRunId) {
3107
+ if (!parent.agentRun)
3108
+ return null;
3109
+ const child = await host.storage.agents?.runs.getById({ projectId: host.id, id: childRunId });
3110
+ if (child?.kind !== "subagent" || child.parentRunId !== parent.runId || child.status !== "running" || child.cancelRequestedAt || !child.execution) {
3111
+ return null;
3112
+ }
3113
+ return toRunState(child, null);
3114
+ }
3043
3115
  function scopeErrorResponse(error) {
3044
3116
  switch (error.code) {
3045
3117
  case "execution_unavailable":
@@ -3829,9 +3901,10 @@ function registerActionRunRoutes(app, host) {
3829
3901
 
3830
3902
  // src/routes/actions.ts
3831
3903
  import { schemaFieldsToJsonSchema } from "@sixb/core/internal/ontology";
3832
- function serializeAction(action) {
3904
+ function serializeAction(action, folder) {
3833
3905
  return ActionCatalogItemSchema.parse({
3834
3906
  id: action.id,
3907
+ folder,
3835
3908
  name: action.id,
3836
3909
  description: action.description,
3837
3910
  ...action.binding.kind === "object" ? { objectTypeId: action.binding.objectTypeId } : {},
@@ -3849,7 +3922,7 @@ function serializeAction(action) {
3849
3922
  }
3850
3923
  function serializeActionDetail(action, host) {
3851
3924
  return ActionDetailSchema.parse({
3852
- ...serializeAction(action),
3925
+ ...serializeAction(action, host.definitions.folders.actions?.get(action.id)),
3853
3926
  inputSchema: schemaFieldsToJsonSchema({
3854
3927
  fields: action.params,
3855
3928
  valueTypesById: host.definitions.ontology.getValueTypesById()
@@ -3859,7 +3932,7 @@ function serializeActionDetail(action, host) {
3859
3932
  function registerActionRoutes(app, host) {
3860
3933
  return app.get("/api/actions", async (context) => {
3861
3934
  const actions = requireRequestSixb(context).actions.list();
3862
- return actions.map(serializeAction);
3935
+ return actions.map((action) => serializeAction(action, host.definitions.folders.actions?.get(action.id)));
3863
3936
  }, {
3864
3937
  response: { 200: ActionCatalogItemSchema.array() },
3865
3938
  detail: {
@@ -4509,7 +4582,22 @@ async function serializeThreads(host, threads, viewer) {
4509
4582
  lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
4510
4583
  messageCount: thread.messageCount,
4511
4584
  createdAt: toIsoString(thread.createdAt),
4512
- updatedAt: toIsoString(thread.updatedAt)
4585
+ updatedAt: toIsoString(thread.updatedAt),
4586
+ read: thread.read && {
4587
+ threadId: thread.read.threadId,
4588
+ throughSeq: thread.read.throughSeq,
4589
+ headSeq: thread.read.headSeq,
4590
+ unread: thread.read.unread,
4591
+ readAt: thread.read.readAt ? toIsoString(thread.read.readAt) : undefined
4592
+ },
4593
+ lastRun: thread.lastRun && {
4594
+ id: thread.lastRun.id,
4595
+ status: thread.lastRun.status,
4596
+ finishReason: thread.lastRun.finishReason,
4597
+ errorCode: thread.lastRun.errorCode,
4598
+ completedAt: thread.lastRun.completedAt ? toIsoString(thread.lastRun.completedAt) : undefined,
4599
+ requestedBy: thread.lastRun.requestedBy
4600
+ }
4513
4601
  }));
4514
4602
  }
4515
4603
  async function serializeThread(host, thread, viewer) {
@@ -4544,7 +4632,7 @@ function sameBackgroundCommand(command, ref) {
4544
4632
  return command.threadId === ref.threadId && command.id === ref.id && command.startedAt === ref.startedAt;
4545
4633
  }
4546
4634
  function serializeMessage(message, annotations = [], checkpoint) {
4547
- return AgentMessageSchema.parse({
4635
+ return {
4548
4636
  id: message.id,
4549
4637
  projectId: message.projectId,
4550
4638
  threadId: message.threadId,
@@ -4552,7 +4640,7 @@ function serializeMessage(message, annotations = [], checkpoint) {
4552
4640
  role: message.role,
4553
4641
  authorPrincipal: message.authorPrincipal,
4554
4642
  seq: message.seq,
4555
- parts: message.parts,
4643
+ parts: message.parts.map(withoutReplayState),
4556
4644
  annotations,
4557
4645
  compaction: checkpoint ? {
4558
4646
  checkpointId: checkpoint.id,
@@ -4564,7 +4652,15 @@ function serializeMessage(message, annotations = [], checkpoint) {
4564
4652
  contentVersion: message.contentVersion,
4565
4653
  createdAt: toIsoString(message.createdAt),
4566
4654
  completedAt: message.completedAt ? toIsoString(message.completedAt) : undefined
4567
- });
4655
+ };
4656
+ }
4657
+ function withoutReplayState(part) {
4658
+ if (part.type === "provider-state")
4659
+ return { ...part, data: null };
4660
+ if (!("providerMetadata" in part) || part.providerMetadata === undefined)
4661
+ return part;
4662
+ const { providerMetadata: _replay, ...shown } = part;
4663
+ return shown;
4568
4664
  }
4569
4665
  function serializeAgentInboxItem(item) {
4570
4666
  return AgentInboxItemSchema.parse({
@@ -4580,11 +4676,12 @@ function serializeAgentInboxItem(item) {
4580
4676
  timeZone: item.timeZone,
4581
4677
  locale: item.locale,
4582
4678
  immediate: item.immediate === true ? true : undefined,
4679
+ replacesMessageId: item.replacesMessageId,
4583
4680
  createdAt: toIsoString(item.createdAt),
4584
4681
  updatedAt: toIsoString(item.updatedAt)
4585
4682
  });
4586
4683
  }
4587
- function serializeAgentRun(run) {
4684
+ function serializeAgentRun(run, { ownerReads = false } = {}) {
4588
4685
  return AgentRunSchema.parse({
4589
4686
  id: run.id,
4590
4687
  projectId: run.projectId,
@@ -4599,6 +4696,7 @@ function serializeAgentRun(run) {
4599
4696
  reasoning: run.spec?.reasoning,
4600
4697
  approvalMode: run.spec?.approvalMode,
4601
4698
  runsOn: run.kind === "conversation" ? run.spec?.runsOn : undefined,
4699
+ computer: ownerReads && run.kind === "conversation" ? run.spec?.computer : undefined,
4602
4700
  modelId: run.modelId,
4603
4701
  finishReason: run.finishReason,
4604
4702
  usage: run.usage,
@@ -4652,12 +4750,14 @@ function handleAgentRouteError(error, set) {
4652
4750
  if (error instanceof AgentRequestError) {
4653
4751
  switch (error.code) {
4654
4752
  case "agent_not_found":
4753
+ case "message_not_found":
4655
4754
  case "run_not_found":
4656
4755
  case "thread_not_found":
4657
4756
  case "approval_not_found":
4658
4757
  set.status = 404;
4659
4758
  break;
4660
4759
  case "active_run_exists":
4760
+ case "message_not_editable":
4661
4761
  case "thread_not_conversation":
4662
4762
  case "run_not_retryable":
4663
4763
  case "run_not_active":
@@ -4667,6 +4767,7 @@ function handleAgentRouteError(error, set) {
4667
4767
  set.status = 409;
4668
4768
  break;
4669
4769
  case "authority_not_inheritable":
4770
+ case "not_message_author":
4670
4771
  case "not_thread_owner":
4671
4772
  case "not_run_requester":
4672
4773
  set.status = 403;
@@ -5081,7 +5182,7 @@ function registerAgentRoutes(app, host) {
5081
5182
  return { error: "Agent thread not found" };
5082
5183
  }
5083
5184
  const parsed = AgentMessagesQuerySchema.parse(query);
5084
- return AgentMessageListResponseSchema.parse(await readThreadMessages(host, storage, thread, parsed));
5185
+ return await readThreadMessages(host, storage, thread, parsed);
5085
5186
  } catch (error) {
5086
5187
  return handleAgentRouteError(error, set);
5087
5188
  }
@@ -5263,6 +5364,52 @@ function registerAgentRoutes(app, host) {
5263
5364
  operationId: "withdrawAgentThreadInboxItem",
5264
5365
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5265
5366
  }
5367
+ }).post("/api/agent-threads/:threadId/messages/:messageId/edit", async (context) => {
5368
+ const { params, body, set } = context;
5369
+ const sixb = requireRequestSixb(context);
5370
+ try {
5371
+ const storage = host.storage.agents;
5372
+ if (!storage) {
5373
+ return missingAgentStorageResponse(set);
5374
+ }
5375
+ const parsed = EditAgentMessageBodySchema.parse(body);
5376
+ const result = await sixb.agent.runs.editMessage({
5377
+ threadId: params.threadId,
5378
+ messageId: params.messageId,
5379
+ text: parsed.text,
5380
+ model: parsed.model,
5381
+ reasoning: parsed.reasoning,
5382
+ timeZone: parsed.timeZone,
5383
+ locale: parsed.locale,
5384
+ approvalMode: parsed.approvalMode,
5385
+ attachments: parsed.attachments,
5386
+ context: parsed.context,
5387
+ nextMessageId: parsed.nextMessageId
5388
+ });
5389
+ set.status = 202;
5390
+ return EditAgentMessageResponseSchema.parse(result.kind === "turn" ? { run: serializeAgentRun(result.run) } : { item: serializeAgentInboxItem(result.item) });
5391
+ } catch (error) {
5392
+ return handleAgentInboxRouteError(error, set);
5393
+ }
5394
+ }, {
5395
+ params: AgentMessageFileContentParamsSchema,
5396
+ body: EditAgentMessageBodySchema,
5397
+ response: {
5398
+ 202: EditAgentMessageResponseSchema,
5399
+ 400: AgentRequestErrorResponseSchema,
5400
+ 403: AgentRequestErrorResponseSchema,
5401
+ 404: ErrorResponseSchema,
5402
+ 409: AgentRequestErrorResponseSchema,
5403
+ 429: AiUsageLimitErrorResponseSchema,
5404
+ 501: ErrorResponseSchema
5405
+ },
5406
+ detail: {
5407
+ summary: "Edit an agent thread message and restart from that turn",
5408
+ 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.",
5409
+ tags: [OPENAPI_TAGS.agentThreads.name],
5410
+ operationId: "editAgentThreadMessage",
5411
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5412
+ }
5266
5413
  }).post("/api/agent-threads/:threadId/cancel", async (context) => {
5267
5414
  const { params, body, set } = context;
5268
5415
  const sixb = requireRequestSixb(context);
@@ -5431,18 +5578,22 @@ function registerAgentRoutes(app, host) {
5431
5578
  return missingAgentStorageResponse(set);
5432
5579
  }
5433
5580
  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
- });
5581
+ const [result, thread] = await Promise.all([
5582
+ sixb.agent.runs.listForThread(params.threadId, {
5583
+ statuses: parsed.status ? [parsed.status] : undefined,
5584
+ limit: parseOptionalInt(parsed.limit),
5585
+ offset: parseOptionalInt(parsed.offset),
5586
+ order: parsed.order
5587
+ }),
5588
+ storage.threads.getById({ projectId: host.id, id: params.threadId })
5589
+ ]);
5440
5590
  if (!result) {
5441
5591
  set.status = 404;
5442
5592
  return { error: "Agent thread not found" };
5443
5593
  }
5594
+ const ownerReads = thread !== null && principalsEqual(thread.ownerPrincipal, requestActor(sixb));
5444
5595
  return AgentRunListResponseSchema.parse({
5445
- runs: result.runs.map(serializeAgentRun),
5596
+ runs: result.runs.map((run) => serializeAgentRun(run, { ownerReads })),
5446
5597
  hasMore: result.hasMore,
5447
5598
  total: result.total
5448
5599
  });
@@ -5980,7 +6131,7 @@ function registerAgentComputerRoutes(app, host) {
5980
6131
  },
5981
6132
  detail: {
5982
6133
  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.",
6134
+ 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
6135
  tags: [OPENAPI_TAGS.agentThreads.name],
5985
6136
  operationId: "moveAgentThreadToComputer",
5986
6137
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -6008,7 +6159,7 @@ function registerAgentComputerRoutes(app, host) {
6008
6159
  },
6009
6160
  detail: {
6010
6161
  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.",
6162
+ 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
6163
  tags: [OPENAPI_TAGS.agentThreads.name],
6013
6164
  operationId: "moveAgentThreadToCloud",
6014
6165
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -6590,6 +6741,48 @@ function answer(body, status = 200) {
6590
6741
  });
6591
6742
  }
6592
6743
 
6744
+ // src/routes/agent-thread-reads.ts
6745
+ 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.";
6746
+ function registerAgentThreadReadRoutes(app, host) {
6747
+ return app.put("/api/agent-threads/:threadId/read", async (context) => {
6748
+ const { set } = context;
6749
+ try {
6750
+ if (!host.storage.agents) {
6751
+ return unconfiguredStorageResponse(set, "Agent storage");
6752
+ }
6753
+ const body = MarkAgentThreadReadBodySchema.parse(context.body ?? {});
6754
+ const read = await requireRequestSixb(context).agent.threads.markRead(context.params.threadId, body);
6755
+ return MarkAgentThreadReadResponseSchema.parse({
6756
+ read: {
6757
+ threadId: read.threadId,
6758
+ throughSeq: read.throughSeq,
6759
+ headSeq: read.headSeq,
6760
+ unread: read.unread,
6761
+ readAt: read.readAt ? toIsoString(read.readAt) : undefined
6762
+ }
6763
+ });
6764
+ } catch (error) {
6765
+ return handleAgentRouteError(error, set);
6766
+ }
6767
+ }, {
6768
+ params: AgentThreadParamsSchema,
6769
+ body: MarkAgentThreadReadBodySchema,
6770
+ response: {
6771
+ 200: MarkAgentThreadReadResponseSchema,
6772
+ 400: AgentRequestErrorResponseSchema,
6773
+ 404: AgentRequestErrorResponseSchema,
6774
+ 501: ErrorResponseSchema
6775
+ },
6776
+ detail: {
6777
+ summary: "Mark how far you have read an Agent thread",
6778
+ description: MARKING,
6779
+ tags: [OPENAPI_TAGS.agentThreads.name],
6780
+ operationId: "markAgentThreadRead",
6781
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
6782
+ }
6783
+ });
6784
+ }
6785
+
6593
6786
  // src/routes/ai-accounting.ts
6594
6787
  import { AiLimitStorageError } from "@sixb/core/storage";
6595
6788
 
@@ -6910,6 +7103,7 @@ function registerAiAccountingRoutes(app, host) {
6910
7103
  from: new Date(parsed.from),
6911
7104
  to: new Date(parsed.to),
6912
7105
  bucket: parsed.bucket,
7106
+ ...parsed.timeZone === undefined ? {} : { timeZone: parsed.timeZone },
6913
7107
  providerId: parsed.providerId,
6914
7108
  modelId: parsed.modelId,
6915
7109
  ...accountingFilters(parsed)
@@ -7863,6 +8057,7 @@ var DatasetLatestVersionSummarySchema = z19.object({
7863
8057
  });
7864
8058
  var DatasetCatalogItemSchema = DatasetDefinitionSchema.extend({
7865
8059
  kind: z19.literal("dataset"),
8060
+ folder: DefinitionFolderSchema,
7866
8061
  materialized: z19.boolean(),
7867
8062
  latestVersion: DatasetLatestVersionSummarySchema.nullable(),
7868
8063
  syncIds: z19.array(z19.string()),
@@ -11416,6 +11611,7 @@ var ConnectorWebhookSchema = z26.object({
11416
11611
  });
11417
11612
  var ConnectorSchema = z26.object({
11418
11613
  id: z26.string(),
11614
+ folder: DefinitionFolderSchema,
11419
11615
  type: z26.string(),
11420
11616
  connection: z26.object({ authentication: z26.literal("oauth2") }).nullable(),
11421
11617
  syncIds: z26.array(z26.string()),
@@ -11960,6 +12156,7 @@ import { isOAuthConnectorDefinition as isOAuthConnectorDefinition2 } from "@sixb
11960
12156
  function serializeConnector(connector, host, execution) {
11961
12157
  return {
11962
12158
  id: connector.id,
12159
+ folder: host.definitions.folders.connectors?.get(connector.id),
11963
12160
  type: connector.adapter.type,
11964
12161
  connection: isOAuthConnectorDefinition2(connector) ? { authentication: "oauth2" } : null,
11965
12162
  syncIds: execution.syncs.list().filter((sync) => sync.connector.id === connector.id).map((sync) => sync.id),
@@ -12100,9 +12297,10 @@ function serializeLatestVersionSummary(summary) {
12100
12297
  rowCount: summary.rowCount
12101
12298
  };
12102
12299
  }
12103
- function serializeDatasetCatalogItem(dataset, state, references) {
12300
+ function serializeDatasetCatalogItem(dataset, state, references, folder) {
12104
12301
  return DatasetCatalogItemSchema.parse({
12105
12302
  ...dataset,
12303
+ folder,
12106
12304
  materialized: state?.materialized ?? false,
12107
12305
  latestVersion: state?.latestVersion ? serializeLatestVersionSummary(state.latestVersion) : null,
12108
12306
  syncIds: references.syncIds,
@@ -12115,7 +12313,7 @@ async function serializeDatasetCatalogItems(host, definitions, sixb) {
12115
12313
  const references = buildDatasetReferenceIndex(sixb);
12116
12314
  const states = await host.lakeStorage.listDatasetCatalogState(definitions.map((d) => d.id));
12117
12315
  const stateByDatasetId = new Map(states.map((state) => [state.datasetId, state]));
12118
- return definitions.map((definition) => serializeDatasetCatalogItem(definition, stateByDatasetId.get(definition.id), references.get(definition.id) ?? EMPTY_DATASET_REFERENCES));
12316
+ return definitions.map((definition) => serializeDatasetCatalogItem(definition, stateByDatasetId.get(definition.id), references.get(definition.id) ?? EMPTY_DATASET_REFERENCES, host.definitions.folders.datasets?.get(definition.id)));
12119
12317
  }
12120
12318
  function requireDataset(sixb, datasetId) {
12121
12319
  const dataset = sixb.datasets.getById(datasetId);
@@ -12164,7 +12362,7 @@ function registerDatasetRoutes(app, host) {
12164
12362
  const dataset = requireDataset(sixb, params.datasetId);
12165
12363
  const [state] = await host.lakeStorage.listDatasetCatalogState([dataset.id]);
12166
12364
  const references = buildDatasetReferenceIndex(sixb).get(dataset.id);
12167
- return serializeDatasetCatalogItem(dataset, state, references ?? EMPTY_DATASET_REFERENCES);
12365
+ return serializeDatasetCatalogItem(dataset, state, references ?? EMPTY_DATASET_REFERENCES, host.definitions.folders.datasets?.get(dataset.id));
12168
12366
  } catch (error) {
12169
12367
  return handleRouteError(error, set);
12170
12368
  }
@@ -13355,7 +13553,7 @@ function registerModelGenerationRoutes(app, host) {
13355
13553
  model: entry.model,
13356
13554
  signal: request.signal
13357
13555
  });
13358
- return TranscriptionSchema.parse({ ...result(entry, call), text: call.output.text });
13556
+ return TranscriptionSchema.parse({ ...result(entry, call), ...call.output });
13359
13557
  } catch (error) {
13360
13558
  return generationError(error, set);
13361
13559
  }
@@ -13502,7 +13700,7 @@ function registerObservedAgentThreadRoutes(app, host) {
13502
13700
  return threadNotFound(context.set);
13503
13701
  }
13504
13702
  const query = AgentMessagesQuerySchema.parse(context.query);
13505
- return AgentMessageListResponseSchema.parse(await readThreadMessages(host, storage, thread, query));
13703
+ return await readThreadMessages(host, storage, thread, query);
13506
13704
  } catch (error) {
13507
13705
  return handleAgentRouteError(error, context.set);
13508
13706
  }
@@ -13555,7 +13753,7 @@ function registerObservedAgentThreadRoutes(app, host) {
13555
13753
  return threadNotFound(context.set);
13556
13754
  }
13557
13755
  return AgentRunListResponseSchema.parse({
13558
- runs: result.runs.map(serializeAgentRun),
13756
+ runs: result.runs.map((run) => serializeAgentRun(run)),
13559
13757
  hasMore: result.hasMore,
13560
13758
  total: result.total
13561
13759
  });
@@ -13671,9 +13869,10 @@ function serializeSearch(search) {
13671
13869
  ])) : undefined
13672
13870
  };
13673
13871
  }
13674
- function serializeObjectType(execution, valueTypesById, objectType) {
13872
+ function serializeObjectType(execution, valueTypesById, objectType, folder) {
13675
13873
  return {
13676
13874
  id: objectType.id,
13875
+ folder,
13677
13876
  name: objectType.name,
13678
13877
  description: objectType.description,
13679
13878
  extends: objectType.extends,
@@ -13708,7 +13907,7 @@ function registerOntologyRoutes(app, host) {
13708
13907
  return app.get("/api/object-types", async (context) => {
13709
13908
  const sixb = requireRequestSixb(context);
13710
13909
  const valueTypesById = host.definitions.ontology.getValueTypesById();
13711
- return sixb.objects.listTypes().map((objectType) => serializeObjectType(sixb, valueTypesById, objectType));
13910
+ return sixb.objects.listTypes().map((objectType) => serializeObjectType(sixb, valueTypesById, objectType, host.definitions.folders.objectTypes?.get(objectType.id)));
13712
13911
  }, {
13713
13912
  response: { 200: ObjectTypeSchema.array() },
13714
13913
  detail: {
@@ -13725,7 +13924,7 @@ function registerOntologyRoutes(app, host) {
13725
13924
  set.status = 404;
13726
13925
  return { error: "Object type not found" };
13727
13926
  }
13728
- return serializeObjectType(sixb, host.definitions.ontology.getValueTypesById(), objectType);
13927
+ return serializeObjectType(sixb, host.definitions.ontology.getValueTypesById(), objectType, host.definitions.folders.objectTypes?.get(objectType.id));
13729
13928
  }, {
13730
13929
  params: ObjectTypeParamsSchema,
13731
13930
  response: { 200: ObjectTypeSchema, 404: ErrorResponseSchema },
@@ -13824,6 +14023,7 @@ var PipelineStepSchema = z31.object({
13824
14023
  });
13825
14024
  var PipelineSchema = z31.object({
13826
14025
  id: z31.string(),
14026
+ folder: DefinitionFolderSchema,
13827
14027
  triggers: z31.array(PipelineTriggerSchema),
13828
14028
  graph: z31.object({
13829
14029
  kind: z31.literal("sequence"),
@@ -13908,9 +14108,10 @@ async function getLatestPipelineRuns(sixb, pipelineIds) {
13908
14108
  const result = await sixb.pipelines.runs.listLatest(pipelineIds);
13909
14109
  return new Map(result.runs.map((run) => [run.pipelineId, serializePipelineRun(run)]));
13910
14110
  }
13911
- function serializePipeline(pipeline, latestRun) {
14111
+ function serializePipeline(pipeline, latestRun, folder) {
13912
14112
  return PipelineSchema.parse({
13913
14113
  id: pipeline.id,
14114
+ folder,
13914
14115
  triggers: pipeline.triggers,
13915
14116
  graph: {
13916
14117
  kind: pipeline.graph.kind,
@@ -13936,7 +14137,7 @@ function registerPipelineRoutes(app, host) {
13936
14137
  const sixb = requireRequestSixb(context);
13937
14138
  const pipelines = sixb.pipelines.list();
13938
14139
  const latestRuns = await getLatestPipelineRuns(sixb, pipelines.map((pipeline) => pipeline.id));
13939
- return pipelines.map((pipeline) => serializePipeline(pipeline, latestRuns.get(pipeline.id) ?? null));
14140
+ return pipelines.map((pipeline) => serializePipeline(pipeline, latestRuns.get(pipeline.id) ?? null, host.definitions.folders.pipelines?.get(pipeline.id)));
13940
14141
  }, {
13941
14142
  response: { 200: PipelineSchema.array() },
13942
14143
  detail: {
@@ -13953,7 +14154,7 @@ function registerPipelineRoutes(app, host) {
13953
14154
  set.status = 404;
13954
14155
  return { error: "Pipeline not found" };
13955
14156
  }
13956
- return serializePipeline(pipeline, await getLatestPipelineRun(sixb, pipeline.id));
14157
+ return serializePipeline(pipeline, await getLatestPipelineRun(sixb, pipeline.id), host.definitions.folders.pipelines?.get(pipeline.id));
13957
14158
  }, {
13958
14159
  params: PipelineParamsSchema,
13959
14160
  response: { 200: PipelineSchema, 404: ErrorResponseSchema },
@@ -14177,6 +14378,7 @@ var SourceEditConflictResolutionSchema = z33.union([
14177
14378
  var ObjectProjectionSchema = z33.object({
14178
14379
  _tag: z33.literal("ObjectProjectionDefinition"),
14179
14380
  id: z33.string(),
14381
+ folder: DefinitionFolderSchema,
14180
14382
  objectTypeId: z33.string(),
14181
14383
  datasetId: z33.string(),
14182
14384
  properties: z33.record(z33.string()),
@@ -14189,6 +14391,7 @@ var ObjectProjectionSchema = z33.object({
14189
14391
  var LinkProjectionSchema = z33.object({
14190
14392
  _tag: z33.literal("LinkProjectionDefinition"),
14191
14393
  id: z33.string(),
14394
+ folder: DefinitionFolderSchema,
14192
14395
  linkId: z33.string(),
14193
14396
  sourceObjectTypeId: z33.string(),
14194
14397
  targetObjectTypeId: z33.string(),
@@ -14200,6 +14403,7 @@ var LinkProjectionSchema = z33.object({
14200
14403
  var TelemetryProjectionSchema = z33.object({
14201
14404
  _tag: z33.literal("TelemetryProjectionDefinition"),
14202
14405
  id: z33.string(),
14406
+ folder: DefinitionFolderSchema,
14203
14407
  objectTypeId: z33.string(),
14204
14408
  datasetId: z33.string(),
14205
14409
  objectIdField: z33.string(),
@@ -14282,22 +14486,24 @@ function projectionCatalogIds(catalog) {
14282
14486
  ...catalog.telemetryProjections
14283
14487
  ].map((projection) => projection.id);
14284
14488
  }
14285
- function serializeProjection(projection, latestRuns) {
14489
+ function serializeProjection(projection, latestRuns, folders) {
14286
14490
  const latestRun = latestRuns.get(projection.id) ?? null;
14491
+ const folder = folders?.get(projection.id);
14287
14492
  if (projection._tag === "ObjectProjectionDefinition") {
14288
14493
  return {
14289
14494
  ...projection,
14495
+ folder,
14290
14496
  conflictResolution: projection.conflictResolution ?? { strategy: "editsWin" },
14291
14497
  latestRun
14292
14498
  };
14293
14499
  }
14294
- return { ...projection, latestRun };
14500
+ return { ...projection, folder, latestRun };
14295
14501
  }
14296
- function serializeProjectionCatalog(catalog, latestRuns) {
14502
+ function serializeProjectionCatalog(catalog, latestRuns, folders) {
14297
14503
  return {
14298
- objectProjections: catalog.objectProjections.map((projection) => serializeProjection(projection, latestRuns)),
14299
- linkProjections: catalog.linkProjections.map((projection) => serializeProjection(projection, latestRuns)),
14300
- telemetryProjections: catalog.telemetryProjections.map((projection) => serializeProjection(projection, latestRuns))
14504
+ objectProjections: catalog.objectProjections.map((projection) => serializeProjection(projection, latestRuns, folders)),
14505
+ linkProjections: catalog.linkProjections.map((projection) => serializeProjection(projection, latestRuns, folders)),
14506
+ telemetryProjections: catalog.telemetryProjections.map((projection) => serializeProjection(projection, latestRuns, folders))
14301
14507
  };
14302
14508
  }
14303
14509
  function registerProjectionRoutes(app, host) {
@@ -14305,7 +14511,7 @@ function registerProjectionRoutes(app, host) {
14305
14511
  const sixb = requireRequestSixb(context);
14306
14512
  const catalog = listViewableProjections(sixb);
14307
14513
  const latestRuns = await getLatestProjectionRuns(sixb, projectionCatalogIds(catalog));
14308
- return serializeProjectionCatalog(catalog, latestRuns);
14514
+ return serializeProjectionCatalog(catalog, latestRuns, host.definitions.folders.projections);
14309
14515
  }, {
14310
14516
  response: { 200: ProjectionListResponseSchema },
14311
14517
  detail: {
@@ -14322,7 +14528,7 @@ function registerProjectionRoutes(app, host) {
14322
14528
  return { error: `Projection '${params.projectionId}' not found` };
14323
14529
  }
14324
14530
  const latestRuns = await getLatestProjectionRuns(sixb, [found.id]);
14325
- return serializeProjection(found, latestRuns);
14531
+ return serializeProjection(found, latestRuns, host.definitions.folders.projections);
14326
14532
  }, {
14327
14533
  params: ProjectionParamsSchema,
14328
14534
  response: { 200: ProjectionResponseSchema, 404: ErrorResponseSchema },
@@ -14477,6 +14683,7 @@ var RuleEventDependencySchema = z34.union([
14477
14683
  var RuleSchema = z34.object({
14478
14684
  kind: z34.literal("rule"),
14479
14685
  id: z34.string(),
14686
+ folder: DefinitionFolderSchema,
14480
14687
  subject: RuleSubjectSchema,
14481
14688
  predicate: RulePredicateSchema,
14482
14689
  dependencies: z34.array(RuleEventDependencySchema)
@@ -14494,9 +14701,10 @@ var RuleStateListResponseSchema = z34.object({
14494
14701
  });
14495
14702
 
14496
14703
  // src/routes/rules.ts
14497
- function serializeRule(rule) {
14704
+ function serializeRule(rule, folder) {
14498
14705
  return RuleSchema.parse({
14499
14706
  ...rule,
14707
+ folder,
14500
14708
  dependencies: deriveRuleEventDependencies(rule)
14501
14709
  });
14502
14710
  }
@@ -14505,7 +14713,7 @@ function serializeRuleState(state) {
14505
14713
  }
14506
14714
  function registerRuleRoutes(app, host) {
14507
14715
  return app.get("/api/rules", (context) => {
14508
- return requireRequestSixb(context).rules.list().map(serializeRule);
14716
+ return requireRequestSixb(context).rules.list().map((rule) => serializeRule(rule, host.definitions.folders.rules?.get(rule.id)));
14509
14717
  }, {
14510
14718
  response: { 200: RuleSchema.array() },
14511
14719
  detail: {
@@ -14520,7 +14728,7 @@ function registerRuleRoutes(app, host) {
14520
14728
  set.status = 404;
14521
14729
  return { error: "Rule not found" };
14522
14730
  }
14523
- return serializeRule(rule);
14731
+ return serializeRule(rule, host.definitions.folders.rules?.get(rule.id));
14524
14732
  }, {
14525
14733
  params: RuleParamsSchema,
14526
14734
  response: { 200: RuleSchema, 404: ErrorResponseSchema },
@@ -15072,7 +15280,7 @@ var StatusResponseSchema = z37.object({
15072
15280
  });
15073
15281
 
15074
15282
  // src/routes/status.ts
15075
- function registerStatusRoutes(app, host) {
15283
+ function registerStatusRoutes(app, host, options = {}) {
15076
15284
  app.get("/health", () => ({ status: "ok" }), {
15077
15285
  response: { 200: HealthResponseSchema },
15078
15286
  detail: {
@@ -15083,6 +15291,14 @@ function registerStatusRoutes(app, host) {
15083
15291
  }
15084
15292
  });
15085
15293
  app.get("/ready", async ({ set }) => {
15294
+ if (options.isStopping?.()) {
15295
+ set.status = 503;
15296
+ return {
15297
+ status: "unready",
15298
+ storage: { reachable: false, schemaValid: false },
15299
+ reason: "Server is shutting down."
15300
+ };
15301
+ }
15086
15302
  const readiness = await host.checkReadiness();
15087
15303
  if (readiness.status === "unready")
15088
15304
  set.status = 503;
@@ -15113,6 +15329,9 @@ function registerStatusRoutes(app, host) {
15113
15329
  });
15114
15330
  }
15115
15331
 
15332
+ // src/routes/syncs.ts
15333
+ import { isOAuthConnectorDefinition as isOAuthConnectorDefinition3 } from "@sixb/core/internal/connector-connections";
15334
+
15116
15335
  // src/schemas/syncs.ts
15117
15336
  import {
15118
15337
  SYNC_RUN_FAILURE_CODES
@@ -15126,6 +15345,7 @@ var SyncRunStatusSchema = z38.enum(["queued", "running", "succeeded", "failed",
15126
15345
  var SyncModeSchema = z38.enum(["snapshot", "append", "merge"]);
15127
15346
  var SyncRunsQuerySchema = z38.object({
15128
15347
  syncId: z38.string().optional(),
15348
+ connectionId: z38.string().optional(),
15129
15349
  datasetId: z38.string().optional(),
15130
15350
  status: SyncRunStatusSchema.optional(),
15131
15351
  startedAfter: z38.string().optional(),
@@ -15135,6 +15355,7 @@ var SyncRunsQuerySchema = z38.object({
15135
15355
  order: z38.enum(["asc", "desc"]).optional()
15136
15356
  });
15137
15357
  var RequestSyncRunBodySchema = z38.object({
15358
+ connectionId: z38.string().optional(),
15138
15359
  expectedLatestVersionId: z38.string().optional(),
15139
15360
  commitMessage: z38.string().optional()
15140
15361
  });
@@ -15146,6 +15367,7 @@ var SyncRunSchema = z38.object({
15146
15367
  id: z38.string(),
15147
15368
  projectId: z38.string(),
15148
15369
  syncId: z38.string(),
15370
+ connectionId: z38.string().optional(),
15149
15371
  datasetId: z38.string(),
15150
15372
  mode: SyncModeSchema,
15151
15373
  status: SyncRunStatusSchema,
@@ -15162,8 +15384,36 @@ var SyncRunSchema = z38.object({
15162
15384
  commitMessage: z38.string().optional(),
15163
15385
  error: SyncRunFailureSchema.optional()
15164
15386
  });
15387
+ var SyncAccountConnectionSchema = z38.object({
15388
+ id: z38.string(),
15389
+ owner: z38.discriminatedUnion("type", [
15390
+ z38.object({ type: z38.literal("project") }),
15391
+ z38.object({ type: z38.literal("user"), id: z38.string() })
15392
+ ]),
15393
+ slot: z38.string(),
15394
+ account: z38.object({ id: z38.string(), label: z38.string() })
15395
+ });
15396
+ var ConnectorAccountSchema2 = z38.object({
15397
+ connection: SyncAccountConnectionSchema,
15398
+ latestRuns: z38.array(SyncRunSchema)
15399
+ });
15400
+ var ConnectorAccountListResponseSchema = z38.object({
15401
+ accounts: z38.array(ConnectorAccountSchema2)
15402
+ });
15403
+ var ConnectorAccountsParamsSchema = z38.object({
15404
+ connectorId: z38.string().min(1)
15405
+ });
15406
+ var SyncAccountSummarySchema = z38.object({
15407
+ total: z38.number(),
15408
+ running: z38.number(),
15409
+ needsReconnecting: z38.number(),
15410
+ failing: z38.number(),
15411
+ synced: z38.number(),
15412
+ lastSyncedAt: z38.string().optional()
15413
+ });
15165
15414
  var SyncSchema = z38.object({
15166
15415
  id: z38.string(),
15416
+ folder: DefinitionFolderSchema,
15167
15417
  mode: SyncModeSchema,
15168
15418
  connector: z38.object({
15169
15419
  id: z38.string(),
@@ -15174,19 +15424,31 @@ var SyncSchema = z38.object({
15174
15424
  dataset: DatasetDefinitionSchema
15175
15425
  }),
15176
15426
  triggers: z38.array(SyncTriggerSchema),
15177
- latestRun: SyncRunSchema.nullable()
15427
+ latestRun: SyncRunSchema.nullable(),
15428
+ accounts: SyncAccountSummarySchema.optional()
15429
+ });
15430
+ var ConnectionSyncRunsParamsSchema = z38.object({
15431
+ connectorId: z38.string().min(1),
15432
+ connectionId: z38.string().min(1)
15433
+ });
15434
+ var ConnectionSyncRunsResponseSchema = z38.object({
15435
+ runs: z38.array(SyncRunSchema)
15178
15436
  });
15179
15437
  var SyncRunListResponseSchema = z38.object({
15180
15438
  runs: z38.array(SyncRunSchema),
15181
15439
  hasMore: z38.boolean(),
15182
15440
  total: z38.number()
15183
15441
  });
15184
- var RequestSyncRunResponseSchema = z38.object({
15442
+ var RequestedSyncRunSchema = z38.object({
15185
15443
  runId: z38.string(),
15186
15444
  jobId: z38.string(),
15187
15445
  syncId: z38.string(),
15446
+ connectionId: z38.string().optional(),
15188
15447
  queuedAt: z38.string()
15189
15448
  });
15449
+ var RequestSyncRunResponseSchema = z38.object({
15450
+ runs: z38.array(RequestedSyncRunSchema)
15451
+ });
15190
15452
 
15191
15453
  // src/routes/syncs.ts
15192
15454
  function serializeSyncRun(run) {
@@ -15194,6 +15456,7 @@ function serializeSyncRun(run) {
15194
15456
  id: run.id,
15195
15457
  projectId: run.projectId,
15196
15458
  syncId: run.syncId,
15459
+ connectionId: run.connectionId,
15197
15460
  datasetId: run.datasetId,
15198
15461
  mode: run.mode,
15199
15462
  status: run.status,
@@ -15220,9 +15483,51 @@ async function getLatestSyncRuns(sixb, syncIds) {
15220
15483
  const result = await sixb.syncs.runs.listLatest(syncIds);
15221
15484
  return new Map(result.runs.map((run) => [run.syncId, serializeSyncRun(run)]));
15222
15485
  }
15223
- function serializeSync(sync, latestRun) {
15486
+ function serializeAccount(account) {
15487
+ const { id, owner, slot, account: candidate } = account.connection;
15488
+ return {
15489
+ connection: { id, owner, slot, account: { id: candidate.id, label: candidate.label } },
15490
+ latestRuns: account.latestRuns.map(serializeSyncRun)
15491
+ };
15492
+ }
15493
+ function connectorAccounts(sixb) {
15494
+ const byConnector = new Map;
15495
+ return (connectorId) => {
15496
+ let accounts = byConnector.get(connectorId);
15497
+ if (!accounts) {
15498
+ accounts = sixb.syncs.accounts.list(connectorId);
15499
+ byConnector.set(connectorId, accounts);
15500
+ }
15501
+ return accounts;
15502
+ };
15503
+ }
15504
+ async function summarizeAccounts(sync, accountsOf) {
15505
+ if (!isOAuthConnectorDefinition3(sync.connector))
15506
+ return;
15507
+ return summarizeSyncAccounts(sync.id, await accountsOf(sync.connector.id));
15508
+ }
15509
+ function summarizeSyncAccounts(syncId, accounts) {
15510
+ const latest = accounts.flatMap(({ latestRuns }) => latestRuns.filter((run) => run.syncId === syncId));
15511
+ const count = (matches) => latest.filter(matches).length;
15512
+ const reconnect = (run) => run.error?.code === "connector.authorization_required";
15513
+ const synced = latest.filter((run) => run.status === "succeeded");
15514
+ const lastSyncedAt = synced.reduce((last, run) => {
15515
+ const at = run.finishedAt ?? run.queuedAt;
15516
+ return last && last >= at ? last : at;
15517
+ }, undefined);
15518
+ return {
15519
+ total: accounts.length,
15520
+ running: count((run) => run.status === "queued" || run.status === "running"),
15521
+ needsReconnecting: count((run) => run.status === "failed" && reconnect(run)),
15522
+ failing: count((run) => run.status === "failed" && !reconnect(run)),
15523
+ synced: synced.length,
15524
+ ...lastSyncedAt === undefined ? {} : { lastSyncedAt: toIsoString(lastSyncedAt) }
15525
+ };
15526
+ }
15527
+ function serializeSync(sync, latestRun, folder, accounts) {
15224
15528
  return SyncSchema.parse({
15225
15529
  id: sync.id,
15530
+ folder,
15226
15531
  mode: sync.config.mode,
15227
15532
  connector: {
15228
15533
  id: sync.connector.id,
@@ -15233,7 +15538,8 @@ function serializeSync(sync, latestRun) {
15233
15538
  dataset: sync.target.dataset
15234
15539
  },
15235
15540
  triggers: sync.triggers,
15236
- latestRun
15541
+ latestRun,
15542
+ ...accounts === undefined ? {} : { accounts }
15237
15543
  });
15238
15544
  }
15239
15545
  function registerSyncRoutes(app, host) {
@@ -15241,7 +15547,8 @@ function registerSyncRoutes(app, host) {
15241
15547
  const sixb = requireRequestSixb(context);
15242
15548
  const syncs = sixb.syncs.list();
15243
15549
  const latestRuns = await getLatestSyncRuns(sixb, syncs.map((sync) => sync.id));
15244
- return syncs.map((sync) => serializeSync(sync, latestRuns.get(sync.id) ?? null));
15550
+ const accountsOf = connectorAccounts(sixb);
15551
+ return Promise.all(syncs.map(async (sync) => serializeSync(sync, latestRuns.get(sync.id) ?? null, host.definitions.folders.syncs?.get(sync.id), await summarizeAccounts(sync, accountsOf))));
15245
15552
  }, {
15246
15553
  response: { 200: SyncSchema.array() },
15247
15554
  detail: {
@@ -15258,7 +15565,7 @@ function registerSyncRoutes(app, host) {
15258
15565
  set.status = 404;
15259
15566
  return { error: "Sync not found" };
15260
15567
  }
15261
- return serializeSync(sync, await getLatestSyncRun(sixb, sync.id));
15568
+ return serializeSync(sync, await getLatestSyncRun(sixb, sync.id), host.definitions.folders.syncs?.get(sync.id), await summarizeAccounts(sync, connectorAccounts(sixb)));
15262
15569
  }, {
15263
15570
  params: SyncParamsSchema,
15264
15571
  response: { 200: SyncSchema, 404: ErrorResponseSchema },
@@ -15268,6 +15575,35 @@ function registerSyncRoutes(app, host) {
15268
15575
  operationId: "getSync",
15269
15576
  security: accessTokenSecurityRequirement("getSync")
15270
15577
  }
15578
+ }).get("/api/connectors/:connectorId/accounts", async (context) => {
15579
+ const { params } = context;
15580
+ const sixb = requireRequestSixb(context);
15581
+ const accounts = await sixb.syncs.accounts.list(params.connectorId);
15582
+ return { accounts: accounts.map(serializeAccount) };
15583
+ }, {
15584
+ params: ConnectorAccountsParamsSchema,
15585
+ response: { 200: ConnectorAccountListResponseSchema },
15586
+ detail: {
15587
+ summary: "List a connector's accounts and how they synced",
15588
+ 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.",
15589
+ tags: [OPENAPI_TAGS.connectorConnections.name],
15590
+ operationId: "listConnectorAccounts",
15591
+ security: accessTokenSecurityRequirement("listConnectorAccounts")
15592
+ }
15593
+ }).get("/api/connectors/:connectorId/connections/:connectionId/sync-runs", async (context) => {
15594
+ const { params } = context;
15595
+ const sixb = requireRequestSixb(context);
15596
+ const runs = await sixb.syncs.accounts.latestRuns(params.connectorId, params.connectionId);
15597
+ return { runs: runs.map(serializeSyncRun) };
15598
+ }, {
15599
+ params: ConnectionSyncRunsParamsSchema,
15600
+ response: { 200: ConnectionSyncRunsResponseSchema },
15601
+ detail: {
15602
+ summary: "Latest sync runs of a connection",
15603
+ 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.",
15604
+ tags: [OPENAPI_TAGS.connectorConnections.name],
15605
+ operationId: "listConnectorConnectionSyncRuns"
15606
+ }
15271
15607
  }).get("/api/sync-runs", async (context) => {
15272
15608
  const { query, set } = context;
15273
15609
  const sixb = requireRequestSixb(context);
@@ -15279,6 +15615,7 @@ function registerSyncRoutes(app, host) {
15279
15615
  }
15280
15616
  const result = await sixb.syncs.runs.list({
15281
15617
  syncId: parsed.syncId,
15618
+ ...parsed.connectionId === undefined ? {} : { connectionId: parsed.connectionId },
15282
15619
  datasetId: parsed.datasetId,
15283
15620
  statuses: parsed.status ? [parsed.status] : undefined,
15284
15621
  startedAfter: parseDate(parsed.startedAfter),
@@ -15316,10 +15653,13 @@ function registerSyncRoutes(app, host) {
15316
15653
  const result = await sixb.syncs.request({ syncId: params.syncId, ...parsedBody });
15317
15654
  set.status = 202;
15318
15655
  return {
15319
- runId: result.runId,
15320
- jobId: result.jobId ?? "",
15321
- syncId: result.syncId,
15322
- queuedAt: result.queuedAt
15656
+ runs: result.runs.map((run) => ({
15657
+ runId: run.runId,
15658
+ jobId: run.jobId ?? "",
15659
+ syncId: run.syncId,
15660
+ connectionId: run.connectionId,
15661
+ queuedAt: run.queuedAt
15662
+ }))
15323
15663
  };
15324
15664
  } catch (error) {
15325
15665
  return handleRouteError(error, set);
@@ -15902,9 +16242,10 @@ async function getLatestWorkflowRuns(sixb, workflowIds) {
15902
16242
  const result = await sixb.workflows.runs.listLatest(workflowIds);
15903
16243
  return new Map(result.runs.map((run) => [run.workflowId, serializeWorkflowRunSummary(run)]));
15904
16244
  }
15905
- function serializeWorkflow(workflow, latestRun) {
16245
+ function serializeWorkflow(workflow, latestRun, folder) {
15906
16246
  return WorkflowSchema.parse({
15907
16247
  id: workflow.id,
16248
+ folder,
15908
16249
  input: workflow.input,
15909
16250
  triggers: workflow.triggers,
15910
16251
  nodes: workflow.nodes.map((node) => {
@@ -16075,7 +16416,7 @@ function registerWorkflowRoutes(app, host) {
16075
16416
  const sixb = requireRequestSixb(context);
16076
16417
  const workflows = sixb.workflows.list();
16077
16418
  const latestRuns = await getLatestWorkflowRuns(sixb, workflows.map((workflow) => workflow.id));
16078
- return workflows.map((workflow) => serializeWorkflow(workflow, latestRuns.get(workflow.id) ?? null));
16419
+ return workflows.map((workflow) => serializeWorkflow(workflow, latestRuns.get(workflow.id) ?? null, host.definitions.folders.workflows?.get(workflow.id)));
16079
16420
  }, {
16080
16421
  response: { 200: WorkflowSchema.array() },
16081
16422
  detail: {
@@ -16092,7 +16433,7 @@ function registerWorkflowRoutes(app, host) {
16092
16433
  set.status = 404;
16093
16434
  return { error: "Workflow not found" };
16094
16435
  }
16095
- return serializeWorkflow(workflow, await getLatestWorkflowRun(sixb, workflow.id));
16436
+ return serializeWorkflow(workflow, await getLatestWorkflowRun(sixb, workflow.id), host.definitions.folders.workflows?.get(workflow.id));
16096
16437
  }, {
16097
16438
  params: WorkflowParamsSchema,
16098
16439
  response: { 200: WorkflowSchema, 404: ErrorResponseSchema },
@@ -16739,7 +17080,7 @@ function registerHttpRoutes(app, host, options) {
16739
17080
  registerModelCallRoutes(app, host);
16740
17081
  registerModelGenerationRoutes(app, host);
16741
17082
  registerProjectRoutes(app, host);
16742
- registerStatusRoutes(app, host);
17083
+ registerStatusRoutes(app, host, { isStopping: options.isStopping });
16743
17084
  registerConnectorRoutes(app, host);
16744
17085
  registerConnectorConnectionRoutes(app, host);
16745
17086
  registerConnectorConnectionRunRoutes(app, host, options.connectorConnections);
@@ -16758,6 +17099,7 @@ function registerHttpRoutes(app, host, options) {
16758
17099
  registerFileDownloadRoutes(app, host);
16759
17100
  registerActionRunRoutes(app, host);
16760
17101
  registerAgentRoutes(app, host);
17102
+ registerAgentThreadReadRoutes(app, host);
16761
17103
  registerAgentChildRoutes(app, host);
16762
17104
  registerAgentRunnerRoutes(app, host);
16763
17105
  registerAgentComputerRoutes(app, host);
@@ -19603,7 +19945,9 @@ import { BrokerCursorExpiredError } from "@sixb/core/broker";
19603
19945
  import {
19604
19946
  agentActivityStreamDefinition,
19605
19947
  agentRunStreamDefinition,
19606
- agentRunStreamId as agentRunStreamId3
19948
+ agentRunStreamId as agentRunStreamId3,
19949
+ coveredBySteps,
19950
+ readAgentRunSteps
19607
19951
  } from "@sixb/core/internal/agents/streams";
19608
19952
  import { z as z43 } from "zod";
19609
19953
 
@@ -19773,12 +20117,17 @@ async function subscribeAgentStream(states, server, ws, message) {
19773
20117
  states.set(wsStateKey(ws), state);
19774
20118
  const buffered = [];
19775
20119
  let live = false;
20120
+ let steps = null;
20121
+ const send = (records) => {
20122
+ const current = steps;
20123
+ sendRecords(ws, current ? records.filter((record) => !coveredBySteps(current, record.payload)) : records);
20124
+ };
19776
20125
  const receive = (records) => {
19777
20126
  if (!live) {
19778
20127
  buffered.push(...records);
19779
20128
  return;
19780
20129
  }
19781
- sendRecords(ws, records);
20130
+ send(records);
19782
20131
  };
19783
20132
  let resumedFromEarliest = false;
19784
20133
  try {
@@ -19816,13 +20165,34 @@ async function subscribeAgentStream(states, server, ws, message) {
19816
20165
  runId: message.runId,
19817
20166
  afterCursor: resumedFromEarliest ? null : message.afterCursor ?? null
19818
20167
  });
19819
- sendRecords(ws, buffered.splice(0));
20168
+ if (message.afterCursor === undefined || resumedFromEarliest) {
20169
+ steps = await readRunSteps(server, sixb, message.runId);
20170
+ if (steps)
20171
+ safeSend(ws, { type: "run.steps", event: steps });
20172
+ }
20173
+ send(buffered.splice(0));
19820
20174
  if (!await sendRunSnapshot(sixb, ws, message.runId)) {
19821
20175
  stopSubscription(state);
19822
20176
  return;
19823
20177
  }
19824
20178
  live = true;
19825
- sendRecords(ws, buffered.splice(0));
20179
+ send(buffered.splice(0));
20180
+ }
20181
+ async function readRunSteps(server, sixb, runId) {
20182
+ try {
20183
+ const run = await sixb.agent.runs.getById(runId);
20184
+ if (!run || run.status !== "queued" && run.status !== "running")
20185
+ return null;
20186
+ const host = server.getHost();
20187
+ return await readAgentRunSteps(host.broker, {
20188
+ projectId: host.id,
20189
+ runId,
20190
+ attempt: run.attempt
20191
+ });
20192
+ } catch (error) {
20193
+ console.error(`[SixbServer] Agent run '${runId}' finished steps could not be read:`, error);
20194
+ return null;
20195
+ }
19826
20196
  }
19827
20197
  async function subscribeAgentActivity(states, server, ws) {
19828
20198
  const host = server.getHost();
@@ -21732,6 +22102,7 @@ function registerWebSocketRoutes(app, server, sharedAccess) {
21732
22102
 
21733
22103
  // src/server.ts
21734
22104
  var MAX_WEBSOCKET_MESSAGE_BYTES = 64 * 1024;
22105
+ var SERVICE_RESTART_CLOSE_CODE = 1012;
21735
22106
  function createSixbServer(options) {
21736
22107
  return new SixbServer(options);
21737
22108
  }
@@ -21750,10 +22121,13 @@ class SixbServer {
21750
22121
  timing;
21751
22122
  app = null;
21752
22123
  bunServer = null;
22124
+ closeWebSockets = null;
22125
+ stopping = false;
21753
22126
  hostsOntologyMaintenance;
21754
22127
  flushesIngestion;
21755
22128
  maintenance = null;
21756
22129
  stopSweeper = null;
22130
+ inProgressStop = null;
21757
22131
  constructor(options) {
21758
22132
  this.hostRuntime = options.host;
21759
22133
  this.port = options.port ?? 3000;
@@ -21799,10 +22173,17 @@ class SixbServer {
21799
22173
  getSharedAccessOptions() {
21800
22174
  return this.sharedAccessOptions;
21801
22175
  }
22176
+ markStopping() {
22177
+ this.stopping = true;
22178
+ }
22179
+ isStopping() {
22180
+ return this.stopping;
22181
+ }
21802
22182
  async start() {
21803
22183
  if (this.app !== null || this.bunServer !== null || this.maintenance !== null) {
21804
22184
  throw new Error("[SixbServer] Server is already running.");
21805
22185
  }
22186
+ this.stopping = false;
21806
22187
  await checkPipelineMarkings({
21807
22188
  definitions: this.hostRuntime.definitions,
21808
22189
  lakeStorage: this.hostRuntime.lakeStorage
@@ -21814,15 +22195,18 @@ class SixbServer {
21814
22195
  this.maintenance = maintenance;
21815
22196
  try {
21816
22197
  this.app = createSixbApi(this);
21817
- this.bunServer = startApiServer(this.app, {
22198
+ const started = startApiServer(this.app, {
21818
22199
  host: this.hostname,
21819
22200
  port: this.port,
21820
22201
  resolveClientAddress: this.resolveClientAddress,
21821
22202
  timing: this.timing
21822
22203
  });
22204
+ this.bunServer = started.bunServer;
22205
+ this.closeWebSockets = started.closeWebSockets;
21823
22206
  } catch (error) {
21824
22207
  this.app = null;
21825
22208
  this.bunServer = null;
22209
+ this.closeWebSockets = null;
21826
22210
  this.maintenance = null;
21827
22211
  await maintenance?.stop();
21828
22212
  const message = error instanceof Error ? error.message : String(error);
@@ -21840,17 +22224,42 @@ class SixbServer {
21840
22224
  if (ingest)
21841
22225
  ingest.writesInline = inline;
21842
22226
  }
21843
- async stop() {
22227
+ async stop(options = {}) {
22228
+ const timeoutMs = resolveStopTimeoutMs(options.timeoutMs, ACTION_RUN_DRAIN_TIMEOUT_MS);
22229
+ if (this.inProgressStop) {
22230
+ this.inProgressStop.deadline.bringForward(timeoutMs);
22231
+ return this.inProgressStop.done;
22232
+ }
22233
+ const deadline = new StopDeadline(timeoutMs);
22234
+ const done = this.stopUntil(deadline).finally(() => {
22235
+ this.inProgressStop = null;
22236
+ });
22237
+ this.inProgressStop = { deadline, done };
22238
+ return done;
22239
+ }
22240
+ async stopUntil(deadline) {
22241
+ this.stopping = true;
21844
22242
  this.setIngestFlush(false);
21845
22243
  this.stopSweeper?.();
21846
22244
  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;
22245
+ const bunServer = this.bunServer;
22246
+ const closeWebSockets = this.closeWebSockets;
22247
+ const app = this.app;
22248
+ this.bunServer = null;
22249
+ this.closeWebSockets = null;
22250
+ this.app = null;
22251
+ const stopAppAndSockets = async () => {
22252
+ try {
22253
+ if (app)
22254
+ await stopElysiaHooks(app);
22255
+ } finally {
22256
+ closeWebSockets?.();
22257
+ }
22258
+ };
22259
+ if (bunServer) {
22260
+ await drainBunServer(bunServer, deadline, stopAppAndSockets);
22261
+ } else {
22262
+ await stopAppAndSockets();
21854
22263
  }
21855
22264
  const maintenance = this.maintenance;
21856
22265
  this.maintenance = null;
@@ -22055,6 +22464,7 @@ function createSixbApi(server) {
22055
22464
  registerHttpRoutes(app, host, {
22056
22465
  sharedAccess,
22057
22466
  browserPolicy: apiBrowserPolicy,
22467
+ isStopping: () => server.isStopping(),
22058
22468
  connectorConnections: {
22059
22469
  resolveReturnTo: (request, returnTo) => server.resolveAuthRedirectContext(request, { returnTo }).returnTo,
22060
22470
  resolveCallbackUrl: (request) => new URL("/auth/connectors/callback", server.resolveAuthRequestOrigin(request)).toString()
@@ -22110,6 +22520,7 @@ function rejectDisallowedBrowserOrigin(request, policy) {
22110
22520
  });
22111
22521
  }
22112
22522
  function startApiServer(app, options) {
22523
+ const openSockets = new Set;
22113
22524
  const bunServer = Bun.serve({
22114
22525
  port: options.port,
22115
22526
  hostname: options.host,
@@ -22123,26 +22534,119 @@ function startApiServer(app, options) {
22123
22534
  }
22124
22535
  return timeRequest(request, options.timing, () => app.fetch(request));
22125
22536
  },
22126
- websocket: getElysiaWsHandler(app)
22537
+ websocket: getElysiaWsHandler(app, openSockets)
22127
22538
  });
22128
22539
  attachBunServer(app, bunServer);
22129
- return bunServer;
22540
+ return {
22541
+ bunServer,
22542
+ closeWebSockets: () => {
22543
+ for (const ws of [...openSockets]) {
22544
+ try {
22545
+ ws.close(SERVICE_RESTART_CLOSE_CODE, "Service Restart");
22546
+ } catch {}
22547
+ }
22548
+ openSockets.clear();
22549
+ }
22550
+ };
22130
22551
  }
22131
- function getElysiaWsHandler(app) {
22552
+ function getElysiaWsHandler(app, openSockets) {
22132
22553
  const cfg = app.config;
22133
- return {
22554
+ const base = {
22134
22555
  ...elysiaWebSocket,
22135
- ...cfg?.websocket ?? {},
22136
- maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES
22556
+ ...cfg?.websocket ?? {}
22137
22557
  };
22558
+ return {
22559
+ ...base,
22560
+ maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES,
22561
+ open(ws) {
22562
+ openSockets.add(ws);
22563
+ return base.open?.(ws);
22564
+ },
22565
+ close(ws, code, reason) {
22566
+ openSockets.delete(ws);
22567
+ return base.close?.(ws, code, reason);
22568
+ }
22569
+ };
22570
+ }
22571
+ function resolveStopTimeoutMs(timeoutMs, fallbackMs) {
22572
+ const resolved = timeoutMs ?? fallbackMs;
22573
+ if (!Number.isFinite(resolved) || resolved < 0) {
22574
+ throw new Error("[SixbServer] Stop timeout must be a non-negative finite number.");
22575
+ }
22576
+ return resolved;
22577
+ }
22578
+
22579
+ class StopDeadline {
22580
+ at;
22581
+ constructor(timeoutMs) {
22582
+ this.at = Date.now() + timeoutMs;
22583
+ }
22584
+ remainingMs() {
22585
+ return this.at - Date.now();
22586
+ }
22587
+ bringForward(timeoutMs) {
22588
+ this.at = Math.min(this.at, Date.now() + timeoutMs);
22589
+ }
22590
+ }
22591
+ async function drainBunServer(server, deadline, beforeWait) {
22592
+ if (deadline.remainingMs() <= 0) {
22593
+ try {
22594
+ await beforeWait();
22595
+ } finally {
22596
+ await server.stop(true);
22597
+ }
22598
+ return;
22599
+ }
22600
+ const draining = server.stop(false);
22601
+ try {
22602
+ await beforeWait();
22603
+ } catch (error) {
22604
+ await server.stop(true);
22605
+ await draining;
22606
+ throw error;
22607
+ }
22608
+ await waitUntilIdleOrTimeout(server, draining, deadline);
22609
+ await server.stop(true);
22610
+ await draining;
22611
+ }
22612
+ async function waitUntilIdleOrTimeout(server, draining, deadline) {
22613
+ let settled = false;
22614
+ draining.then(() => {
22615
+ settled = true;
22616
+ }, () => {
22617
+ settled = true;
22618
+ });
22619
+ while (!settled && (server.pendingRequests > 0 || server.pendingWebSockets > 0)) {
22620
+ const remaining = deadline.remainingMs();
22621
+ if (remaining <= 0)
22622
+ return;
22623
+ let timer;
22624
+ try {
22625
+ await Promise.race([
22626
+ draining,
22627
+ new Promise((resolve) => {
22628
+ timer = setTimeout(resolve, Math.min(remaining, 25));
22629
+ })
22630
+ ]);
22631
+ } finally {
22632
+ if (timer !== undefined)
22633
+ clearTimeout(timer);
22634
+ }
22635
+ }
22138
22636
  }
22139
22637
  function attachBunServer(app, bunServer) {
22140
22638
  app.server = bunServer;
22141
22639
  }
22640
+ async function stopElysiaHooks(app) {
22641
+ const internal = app;
22642
+ const hooks = internal.event?.stop ?? [];
22643
+ internal.server = null;
22644
+ await Promise.all(hooks.map((hook) => Promise.resolve(hook.fn(app))));
22645
+ }
22142
22646
  export {
22143
22647
  SixbServer,
22144
22648
  createSixbServer,
22145
22649
  requestTimingOptionsFromEnv
22146
22650
  };
22147
22651
 
22148
- //# debugId=39E8C6B2A92C4BF064756E2164756E21
22652
+ //# debugId=0351BBB652D7396764756E2164756E21