@sixb/server 0.1.15 → 0.1.17

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 (59) hide show
  1. package/README.md +6 -0
  2. package/dist/auth/public-routes.d.ts.map +1 -1
  3. package/dist/auth/shared-access.d.ts.map +1 -1
  4. package/dist/index.js +408 -327
  5. package/dist/index.js.map +19 -18
  6. package/dist/registerRoutes.d.ts.map +1 -1
  7. package/dist/routes/agents.d.ts +8 -0
  8. package/dist/routes/agents.d.ts.map +1 -1
  9. package/dist/routes/ai-accounting.d.ts.map +1 -1
  10. package/dist/routes/auth.d.ts +1 -1
  11. package/dist/routes/file-downloads.d.ts +98 -0
  12. package/dist/routes/file-downloads.d.ts.map +1 -0
  13. package/dist/routes/objects.d.ts +3 -0
  14. package/dist/routes/objects.d.ts.map +1 -1
  15. package/dist/routes/ontology.d.ts +6 -4
  16. package/dist/routes/ontology.d.ts.map +1 -1
  17. package/dist/routes/status.d.ts +0 -4
  18. package/dist/routes/status.d.ts.map +1 -1
  19. package/dist/routes/workflows.d.ts +3 -0
  20. package/dist/routes/workflows.d.ts.map +1 -1
  21. package/dist/routes/ws/events.d.ts.map +1 -1
  22. package/dist/routes/ws/logs.d.ts +11 -0
  23. package/dist/routes/ws/logs.d.ts.map +1 -1
  24. package/dist/routes/ws/subscription-hub.d.ts +66 -0
  25. package/dist/routes/ws/subscription-hub.d.ts.map +1 -0
  26. package/dist/schemas/agents.d.ts +33 -0
  27. package/dist/schemas/agents.d.ts.map +1 -1
  28. package/dist/schemas/ai-accounting.d.ts +224 -100
  29. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  30. package/dist/schemas/ai-usage.d.ts +3 -0
  31. package/dist/schemas/ai-usage.d.ts.map +1 -1
  32. package/dist/schemas/auth.d.ts +2 -2
  33. package/dist/schemas/objects.d.ts.map +1 -1
  34. package/dist/schemas/ontology.d.ts +27 -18
  35. package/dist/schemas/ontology.d.ts.map +1 -1
  36. package/dist/schemas/status.d.ts +0 -26
  37. package/dist/schemas/status.d.ts.map +1 -1
  38. package/dist/schemas/workflows.d.ts +35 -0
  39. package/dist/schemas/workflows.d.ts.map +1 -1
  40. package/dist/server.d.ts.map +1 -1
  41. package/package.json +4 -4
  42. package/src/auth/public-routes.ts +10 -0
  43. package/src/auth/shared-access.ts +48 -6
  44. package/src/registerRoutes.ts +2 -0
  45. package/src/routes/ai-accounting.ts +1 -0
  46. package/src/routes/file-downloads.ts +48 -0
  47. package/src/routes/objects.ts +13 -3
  48. package/src/routes/ontology.ts +1 -0
  49. package/src/routes/ws/events.ts +96 -133
  50. package/src/routes/ws/logs.ts +67 -5
  51. package/src/routes/ws/{log-subscription-hub.ts → subscription-hub.ts} +137 -127
  52. package/src/schemas/ai-accounting.ts +5 -0
  53. package/src/schemas/ai-usage.ts +3 -0
  54. package/src/schemas/objects.ts +28 -2
  55. package/src/schemas/ontology.ts +1 -0
  56. package/src/schemas/status.ts +0 -6
  57. package/src/server.ts +5 -0
  58. package/dist/routes/ws/log-subscription-hub.d.ts +0 -50
  59. package/dist/routes/ws/log-subscription-hub.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { cors } from "@elysiajs/cors";
4
4
  import { openapi } from "@elysiajs/openapi";
5
5
  import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2, setRequestClientAddress } from "@sixb/core/internal/auth";
6
6
  import { bindRequestExecution } from "@sixb/core/internal/request-execution";
7
+ import { setApiPublicOrigin } from "@sixb/core/internal/runtime";
7
8
  import { Elysia } from "elysia";
8
9
  import { websocket as elysiaWebSocket } from "elysia/ws";
9
10
  import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
@@ -317,11 +318,13 @@ function isSessionTerminationRequest(request) {
317
318
 
318
319
  // src/auth/shared-access.ts
319
320
  var SHARED_ACCESS_GRANT_HEADER_NAME = "x-sixb-share-grant";
321
+ var SHARED_ACCESS_GRANT_QUERY_PARAM = "shareGrant";
320
322
  var SHARED_SESSION_COOKIE_PREFIX = "sixb_share_session_";
321
323
  var SHARED_CSRF_COOKIE_PREFIX = "sixb_share_csrf_";
322
324
  var SHARED_COOKIE_PATH = "/api";
323
325
  var STORED_IDENTIFIER_MAX_LENGTH = 128;
324
326
  var SHARED_SESSION_ROUTES = SIXB_API_ROUTES2.filter((route) => route.sharedSession);
327
+ var SHARED_FILE_CONTENT_ROUTES = SHARED_SESSION_ROUTES.filter((route) => (route.method === "GET" || route.method === "HEAD") && route.path.endsWith("/files/content"));
325
328
 
326
329
  class SharedAccessBoundary {
327
330
  host;
@@ -334,24 +337,28 @@ class SharedAccessBoundary {
334
337
  preflightResponse(request) {
335
338
  if (isSharedAccessPublicRoute(request))
336
339
  return;
337
- const selectedGrantId = request.headers.get(SHARED_ACCESS_GRANT_HEADER_NAME);
338
- if (selectedGrantId === null)
340
+ const selection = selectSharedAccessGrant(request);
341
+ if (selection.kind === "absent")
339
342
  return;
340
- if (request.headers.has("authorization") || !isSharedSessionRoute(request)) {
343
+ if (selection.kind === "conflict" || request.headers.has("authorization") || !isSharedSessionRoute(request)) {
341
344
  return sharedAccessForbiddenResponse();
342
345
  }
343
- if (!isStoredIdentifier(selectedGrantId))
346
+ if (!isStoredIdentifier(selection.grantId))
344
347
  return sharedAccessUnauthenticatedResponse();
345
348
  }
346
349
  async resolveRequest(request) {
347
350
  if (isSharedAccessPublicRoute(request))
348
351
  return { kind: "absent" };
349
- const selectedGrantId = request.headers.get(SHARED_ACCESS_GRANT_HEADER_NAME);
350
- if (selectedGrantId === null)
352
+ const selection = selectSharedAccessGrant(request);
353
+ if (selection.kind === "absent")
351
354
  return { kind: "absent" };
355
+ if (selection.kind === "conflict") {
356
+ return { kind: "deny", response: sharedAccessForbiddenResponse() };
357
+ }
352
358
  const preflight = this.preflightResponse(request);
353
359
  if (preflight)
354
360
  return { kind: "deny", response: preflight };
361
+ const selectedGrantId = selection.grantId;
355
362
  let resolved;
356
363
  try {
357
364
  resolved = await this.resolveSession(request, selectedGrantId);
@@ -510,6 +517,20 @@ function isSharedAccessPublicPath(pathname, requestMethod) {
510
517
  return false;
511
518
  return matchesPathPattern2(normalizedPathname, `/api/shared-access/:grantId/${suffix}`);
512
519
  }
520
+ function selectSharedAccessGrant(request) {
521
+ const header = request.headers.get(SHARED_ACCESS_GRANT_HEADER_NAME);
522
+ const url = new URL(request.url);
523
+ const method = request.method.toUpperCase();
524
+ const pathname = normalizeRoutePath2(url.pathname);
525
+ const queryValues = SHARED_FILE_CONTENT_ROUTES.some((route) => route.method === method && matchesPathPattern2(pathname, route.path)) ? url.searchParams.getAll(SHARED_ACCESS_GRANT_QUERY_PARAM) : [];
526
+ const [query, ...extra] = queryValues;
527
+ if (query === undefined) {
528
+ return header === null ? { kind: "absent" } : { kind: "selected", grantId: header };
529
+ }
530
+ if (extra.length > 0 || header !== null && header !== query)
531
+ return { kind: "conflict" };
532
+ return { kind: "selected", grantId: query };
533
+ }
513
534
  function isSharedSessionRoute(request) {
514
535
  const method = request.method.toUpperCase();
515
536
  const pathname = normalizeRoutePath2(new URL(request.url).pathname);
@@ -664,6 +685,7 @@ function sessionCanAccessApplication(host, session, audience) {
664
685
  // src/auth/public-routes.ts
665
686
  import { AGENT_API_GATEWAY_PREFIX } from "@sixb/core/internal/agents";
666
687
  import { isCsrfExemptMethod as isCsrfExemptMethod3 } from "@sixb/core/internal/auth";
688
+ import { FILE_DOWNLOAD_ROUTE_PREFIX } from "@sixb/core/internal/blob-storage";
667
689
  var CONNECTOR_OAUTH_CALLBACK_PATH = "/auth/connectors/callback";
668
690
  function classifyRoute(request) {
669
691
  const url = new URL(request.url);
@@ -702,6 +724,9 @@ function isPublicRoute(pathname, method) {
702
724
  if (pathname.startsWith(`${AGENT_API_GATEWAY_PREFIX}/`)) {
703
725
  return true;
704
726
  }
727
+ if (pathname.startsWith(FILE_DOWNLOAD_ROUTE_PREFIX) && (normalizedMethod === "GET" || normalizedMethod === "HEAD")) {
728
+ return true;
729
+ }
705
730
  if (pathname.startsWith("/api/webhooks/") && normalizedMethod === "POST") {
706
731
  return true;
707
732
  }
@@ -1603,6 +1628,7 @@ var ObjectTypeSchema = z2.object({
1603
1628
  providerId: z2.string(),
1604
1629
  modelId: z2.string(),
1605
1630
  dimensions: z2.number().int().positive(),
1631
+ inputMode: z2.enum(["symmetric", "asymmetric"]).optional(),
1606
1632
  representation: z2.object({ name: z2.string(), version: z2.string().optional() }).optional()
1607
1633
  })
1608
1634
  })).optional()
@@ -3037,6 +3063,7 @@ var AiUsageSummarySchema = z6.object({
3037
3063
  cacheWriteInputTokens: TokenCountSchema.optional(),
3038
3064
  textOutputTokens: TokenCountSchema.optional(),
3039
3065
  reasoningOutputTokens: TokenCountSchema.optional(),
3066
+ audioDurationMs: TokenCountSchema.optional().describe("Audio content duration in milliseconds; not billed duration."),
3040
3067
  reportingStatus: z6.enum(["complete", "partial", "unavailable"])
3041
3068
  });
3042
3069
 
@@ -3119,7 +3146,8 @@ var AiAccountingAggregateSchema = z8.object({
3119
3146
  cacheReadInputTokens: z8.number().int().nonnegative(),
3120
3147
  cacheWriteInputTokens: z8.number().int().nonnegative(),
3121
3148
  textOutputTokens: z8.number().int().nonnegative(),
3122
- reasoningOutputTokens: z8.number().int().nonnegative()
3149
+ reasoningOutputTokens: z8.number().int().nonnegative(),
3150
+ audioDurationMs: z8.number().int().nonnegative()
3123
3151
  })
3124
3152
  }),
3125
3153
  costs: AiCostSummarySchema
@@ -3170,7 +3198,8 @@ var AiCostComponentSchema = z8.object({
3170
3198
  "tokens.input.cacheWrite1h",
3171
3199
  "tokens.output.total",
3172
3200
  "tokens.output.text",
3173
- "tokens.output.reasoning"
3201
+ "tokens.output.reasoning",
3202
+ "audio.input.milliseconds"
3174
3203
  ]),
3175
3204
  quantity: IntegerStringSchema,
3176
3205
  rateAmountNanosPerMillion: IntegerStringSchema,
@@ -3238,6 +3267,7 @@ var AiModelCallUsageRecordSchema = z8.object({
3238
3267
  callId: z8.string(),
3239
3268
  providerId: z8.string(),
3240
3269
  requestedModelId: z8.string(),
3270
+ modelKind: z8.enum(["language", "image", "video", "embedding", "decision", "transcription", "reranking"]).optional(),
3241
3271
  requestedReasoning: ModelReasoningSchema.optional(),
3242
3272
  responseModelId: z8.string().optional(),
3243
3273
  responseId: z8.string(),
@@ -4346,6 +4376,7 @@ function serializeModelCall(item) {
4346
4376
  callId: item.usage.callId,
4347
4377
  providerId: item.usage.providerId,
4348
4378
  requestedModelId: item.usage.requestedModelId,
4379
+ modelKind: item.usage.modelKind,
4349
4380
  providerIds: item.usage.providerIds ?? null,
4350
4381
  requestedReasoning: item.usage.requestedReasoning,
4351
4382
  responseModelId: item.usage.responseModelId,
@@ -6020,6 +6051,31 @@ function registerEventRoutes(app, _host) {
6020
6051
  });
6021
6052
  }
6022
6053
 
6054
+ // src/routes/file-downloads.ts
6055
+ import { FILE_DOWNLOAD_ROUTE_PREFIX as FILE_DOWNLOAD_ROUTE_PREFIX2, resolveFileDownload } from "@sixb/core/internal/blob-storage";
6056
+ function registerFileDownloadRoutes(app, host) {
6057
+ const path = `${FILE_DOWNLOAD_ROUTE_PREFIX2}:token`;
6058
+ return app.get(path, (context) => fileDownloadResponse(host, context), { detail: { hide: true } }).head(path, (context) => fileDownloadResponse(host, context, { head: true }), {
6059
+ detail: { hide: true }
6060
+ });
6061
+ }
6062
+ async function fileDownloadResponse(host, { params, request, set }, options = {}) {
6063
+ const fileRef = await resolveFileDownload(host, params.token);
6064
+ const response = fileRef && await createFileContentResponse({
6065
+ blobStorage: host.blobStorage,
6066
+ fileRef,
6067
+ head: options.head,
6068
+ rangeHeader: request.headers.get("range"),
6069
+ ifNoneMatchHeader: request.headers.get("if-none-match"),
6070
+ ifRangeHeader: request.headers.get("if-range")
6071
+ });
6072
+ if (!response) {
6073
+ set.status = 404;
6074
+ return { error: "File not found" };
6075
+ }
6076
+ return response;
6077
+ }
6078
+
6023
6079
  // src/schemas/links.ts
6024
6080
  import { z as z16 } from "zod";
6025
6081
  var LinkSourceParamsSchema = z16.object({
@@ -6485,6 +6541,11 @@ var ObjectQuerySchema = z18.lazy(() => z18.discriminatedUnion("kind", [
6485
6541
  profile: z18.string().min(1),
6486
6542
  k: z18.number().int().positive()
6487
6543
  }).strict(),
6544
+ z18.object({
6545
+ kind: z18.literal("rerank"),
6546
+ input: ObjectQuerySchema,
6547
+ model: z18.object({ provider: z18.string().min(1), modelId: z18.string().min(1) }).strict()
6548
+ }).strict(),
6488
6549
  z18.object({
6489
6550
  kind: z18.literal("traverse"),
6490
6551
  input: ObjectQuerySchema,
@@ -6622,7 +6683,7 @@ var ObjectQueryOpenApiSchemas = {
6622
6683
  required: ["mode", "providerIssues", "fallbackIssues", "issues"],
6623
6684
  additionalProperties: false,
6624
6685
  properties: {
6625
- mode: { type: "string", enum: ["pushdown", "fallback", "rejected"] },
6686
+ mode: { type: "string", enum: ["pushdown", "fallback", "pipeline", "rejected"] },
6626
6687
  providerIssues: {
6627
6688
  type: "array",
6628
6689
  items: { $ref: "#/components/schemas/ObjectQueryIssue" }
@@ -6702,9 +6763,10 @@ var ObjectQueryOpenApiSchemas = {
6702
6763
  },
6703
6764
  ObjectQueryFacetsResponse: {
6704
6765
  type: "object",
6705
- required: ["facets", "plan"],
6766
+ required: ["total", "facets", "plan"],
6706
6767
  additionalProperties: false,
6707
6768
  properties: {
6769
+ total: { type: "number" },
6708
6770
  facets: {
6709
6771
  type: "array",
6710
6772
  items: { $ref: "#/components/schemas/ObjectQueryFacetResult" }
@@ -6897,6 +6959,24 @@ var ObjectQueryOpenApiSchemas = {
6897
6959
  k: { type: "integer", minimum: 1 }
6898
6960
  }
6899
6961
  },
6962
+ {
6963
+ type: "object",
6964
+ required: ["kind", "input", "model"],
6965
+ additionalProperties: false,
6966
+ properties: {
6967
+ kind: { type: "string", enum: ["rerank"] },
6968
+ input: objectQueryRef,
6969
+ model: {
6970
+ type: "object",
6971
+ required: ["provider", "modelId"],
6972
+ additionalProperties: false,
6973
+ properties: {
6974
+ provider: { type: "string", minLength: 1 },
6975
+ modelId: { type: "string", minLength: 1 }
6976
+ }
6977
+ }
6978
+ }
6979
+ },
6900
6980
  {
6901
6981
  type: "object",
6902
6982
  required: ["kind", "input", "linkId", "direction"],
@@ -7076,7 +7156,10 @@ var ObjectQueryOpenApiSchemas = {
7076
7156
  };
7077
7157
 
7078
7158
  // src/routes/objects.ts
7079
- var ObjectFileContentQuerySchema = FileContentQuerySchema.extend({
7159
+ var ObjectFileContentRouteQuerySchema = FileContentQuerySchema.extend({
7160
+ shareGrant: z19.string().optional().describe("Share grant selector for elements that cannot send the x-sixb-share-grant header")
7161
+ });
7162
+ var ObjectFileContentQuerySchema = ObjectFileContentRouteQuerySchema.extend({
7080
7163
  path: z19.string().min(1).regex(/^\/properties(?:\/|$)/, "Object file content paths must start with /properties/")
7081
7164
  });
7082
7165
  function serializeObject(row) {
@@ -7627,6 +7710,7 @@ function registerObjectRoutes(app, host) {
7627
7710
  facets: parsed.facets
7628
7711
  });
7629
7712
  return {
7713
+ total: result.total,
7630
7714
  facets: result.facets,
7631
7715
  plan: serializePlan(result.plan)
7632
7716
  };
@@ -7684,7 +7768,7 @@ function registerObjectRoutes(app, host) {
7684
7768
  }
7685
7769
  }).get("/api/objects/:objectTypeId/:objectId/files/content", (context) => objectFileContentResponse(host, context), {
7686
7770
  params: ObjectParamsSchema,
7687
- query: FileContentQuerySchema,
7771
+ query: ObjectFileContentRouteQuerySchema,
7688
7772
  detail: {
7689
7773
  summary: "Get object file content",
7690
7774
  tags: [OPENAPI_TAGS.objectFiles.name],
@@ -7694,7 +7778,7 @@ function registerObjectRoutes(app, host) {
7694
7778
  }
7695
7779
  }).head("/api/objects/:objectTypeId/:objectId/files/content", (context) => objectFileContentResponse(host, context, { head: true }), {
7696
7780
  params: ObjectParamsSchema,
7697
- query: FileContentQuerySchema,
7781
+ query: ObjectFileContentRouteQuerySchema,
7698
7782
  detail: {
7699
7783
  summary: "Head object file content",
7700
7784
  tags: [OPENAPI_TAGS.objectFiles.name],
@@ -7796,6 +7880,7 @@ function serializeSearch(search) {
7796
7880
  providerId: profile.model.providerId,
7797
7881
  modelId: profile.model.modelId,
7798
7882
  dimensions: profile.model.definition.dimensions,
7883
+ inputMode: profile.model.definition.inputMode,
7799
7884
  representation: profile.model.definition.representation
7800
7885
  }
7801
7886
  }
@@ -9136,10 +9221,6 @@ var MaintenanceSummarySchema = z26.object({
9136
9221
  retryingCount: z26.number().int().nonnegative(),
9137
9222
  maxAttempts: z26.number().int().nonnegative()
9138
9223
  }).nullable(),
9139
- terminalSources: z26.object({
9140
- count: z26.number().int().nonnegative(),
9141
- oldestTerminalAt: z26.string().nullable()
9142
- }).nullable(),
9143
9224
  cleanup: z26.object({
9144
9225
  publishedOutboxRowsDeleted: z26.number().int().nonnegative(),
9145
9226
  terminalSourceRowsDeleted: z26.number().int().nonnegative(),
@@ -10982,6 +11063,7 @@ function registerHttpRoutes(app, host, options) {
10982
11063
  registerObjectRoutes(app, host);
10983
11064
  registerActionRoutes(app, host);
10984
11065
  registerFileRoutes(app, host);
11066
+ registerFileDownloadRoutes(app, host);
10985
11067
  registerActionRunRoutes(app, host);
10986
11068
  registerAgentRoutes(app, host);
10987
11069
  registerModelRoutes(app, host);
@@ -13950,248 +14032,45 @@ function errorMessage(error) {
13950
14032
  // src/routes/ws/events.ts
13951
14033
  import { scopeKeysForEvent } from "@sixb/core/internal/event-scope";
13952
14034
  import { z as z34 } from "zod";
13953
- var SubscribeSchema2 = z34.object({
13954
- type: z34.literal("subscribe"),
13955
- topic: z34.enum(EVENT_TOPICS).optional(),
13956
- types: z34.array(z34.enum(EVENT_TYPES)).optional(),
13957
- objectTypeId: z34.string().optional(),
13958
- primaryId: z34.string().optional(),
13959
- actionId: z34.string().optional(),
13960
- runId: z34.string().optional(),
13961
- afterCursor: z34.string().optional(),
13962
- limit: z34.number().int().positive().max(500).optional()
13963
- });
13964
- var UnsubscribeSchema2 = z34.object({
13965
- type: z34.literal("unsubscribe")
13966
- });
13967
- var SubscriptionMessageSchema = z34.union([SubscribeSchema2, UnsubscribeSchema2]);
13968
- function parseSubscriptionMessage(payload) {
13969
- if (!payload || typeof payload !== "object") {
13970
- return { ok: false, error: "Message must be a JSON object." };
13971
- }
13972
- const parsed = SubscriptionMessageSchema.safeParse(payload);
13973
- if (!parsed.success) {
13974
- return {
13975
- ok: false,
13976
- error: parsed.error.issues[0]?.message ?? "Invalid websocket message."
13977
- };
13978
- }
13979
- return { ok: true, data: parsed.data };
13980
- }
13981
- async function resolveLatestCursor(server) {
13982
- return server.getHost().events.latestCursor();
13983
- }
13984
- function createDefaultState() {
13985
- return {
13986
- topics: undefined,
13987
- types: undefined,
13988
- objectTypeId: undefined,
13989
- primaryId: undefined,
13990
- actionId: undefined,
13991
- runId: undefined,
13992
- afterCursor: undefined,
13993
- limit: 200,
13994
- polling: false,
13995
- timer: null,
13996
- initialized: Promise.resolve(),
13997
- initializationFailureHandled: false
13998
- };
13999
- }
14000
- function registerEventStreamRoutes(app, server) {
14001
- const states = new WeakMap;
14002
- const awaitInitialization = async (ws, state) => {
14003
- try {
14004
- await state.initialized;
14005
- return true;
14006
- } catch (error) {
14007
- if (state.initializationFailureHandled)
14008
- return false;
14009
- state.initializationFailureHandled = true;
14010
- const message = error instanceof Error ? error.message : String(error);
14011
- safeSend(ws, {
14012
- type: "error",
14013
- message: `[SixbServer] Failed to initialize event websocket: ${message}`
14014
- });
14015
- ws.close();
14016
- return false;
14017
- }
14018
- };
14019
- const stopPolling = (ws) => {
14020
- const state = states.get(wsStateKey(ws));
14021
- if (!state) {
14022
- return;
14023
- }
14024
- if (state.timer) {
14025
- clearInterval(state.timer);
14026
- state.timer = null;
14027
- }
14028
- };
14029
- const startPolling = (ws) => {
14030
- const state = states.get(wsStateKey(ws));
14031
- if (!state || state.timer) {
14032
- return;
14033
- }
14034
- const sixb = wsRequestSixb(ws);
14035
- if (!sixb) {
14036
- safeSend(ws, { type: "error", message: "Execution scope is not available." });
14037
- return;
14038
- }
14039
- const tick = async () => {
14040
- if (state.polling) {
14041
- return;
14042
- }
14043
- state.polling = true;
14044
- try {
14045
- const p = server.getHost();
14046
- const events = await p.events.read({
14047
- afterCursor: state.afterCursor,
14048
- limit: state.limit,
14049
- topics: state.topics,
14050
- types: state.types
14051
- });
14052
- for (const event of events) {
14053
- if (!eventMatchesScope(event, state)) {
14054
- continue;
14055
- }
14056
- if (sixb.events.canRead(event)) {
14057
- safeSend(ws, { type: "event", event });
14058
- }
14059
- }
14060
- const last = events[events.length - 1];
14061
- if (last) {
14062
- state.afterCursor = last.cursor;
14063
- }
14064
- } catch (error) {
14065
- const message = error instanceof Error ? error.message : String(error);
14066
- safeSend(ws, { type: "error", message });
14067
- } finally {
14068
- state.polling = false;
14069
- }
14070
- };
14071
- state.timer = setInterval(() => {
14072
- tick();
14073
- }, 500);
14074
- tick();
14075
- };
14076
- return app.ws("/ws/events", {
14077
- async open(ws) {
14078
- const state = createDefaultState();
14079
- states.set(wsStateKey(ws), state);
14080
- state.initialized = resolveLatestCursor(server).then((cursor) => {
14081
- state.afterCursor = cursor;
14082
- });
14083
- if (!await awaitInitialization(ws, state))
14084
- return;
14085
- safeSend(ws, { type: "connected", channel: "events" });
14086
- },
14087
- async message(ws, message) {
14088
- const decoded = await decodeWsMessage(message);
14089
- const parsed = parseSubscriptionMessage(decoded);
14090
- if (!parsed.ok) {
14091
- safeSend(ws, { type: "error", message: parsed.error });
14092
- return;
14093
- }
14094
- const state = states.get(wsStateKey(ws));
14095
- if (!state) {
14096
- safeSend(ws, { type: "error", message: "Subscription state not found." });
14097
- return;
14098
- }
14099
- if (!await awaitInitialization(ws, state))
14100
- return;
14101
- if (parsed.data.type === "unsubscribe") {
14102
- stopPolling(ws);
14103
- state.topics = undefined;
14104
- state.types = undefined;
14105
- state.objectTypeId = undefined;
14106
- state.primaryId = undefined;
14107
- state.actionId = undefined;
14108
- state.runId = undefined;
14109
- state.afterCursor = await resolveLatestCursor(server);
14110
- safeSend(ws, { type: "unsubscribed" });
14111
- return;
14112
- }
14113
- state.topics = parsed.data.topic ? [parsed.data.topic] : undefined;
14114
- state.types = parsed.data.types;
14115
- state.objectTypeId = parsed.data.objectTypeId;
14116
- state.primaryId = parsed.data.primaryId;
14117
- state.actionId = parsed.data.actionId;
14118
- state.runId = parsed.data.runId;
14119
- state.limit = parsed.data.limit ?? state.limit;
14120
- state.afterCursor = parsed.data.afterCursor ?? state.afterCursor;
14121
- startPolling(ws);
14122
- safeSend(ws, {
14123
- type: "subscribed",
14124
- topic: state.topics?.[0] ?? null,
14125
- types: state.types ?? null,
14126
- afterCursor: state.afterCursor ?? null
14127
- });
14128
- },
14129
- close(ws) {
14130
- stopPolling(ws);
14131
- states.delete(wsStateKey(ws));
14132
- }
14133
- });
14134
- }
14135
- function eventMatchesScope(event, filter) {
14136
- const { objectTypeId, primaryId, actionId, runId } = filter;
14137
- if (objectTypeId === undefined && primaryId === undefined && actionId === undefined && runId === undefined) {
14138
- return true;
14139
- }
14140
- const scope = scopeKeysForEvent(event);
14141
- if (objectTypeId !== undefined && scope.objectTypeId !== objectTypeId) {
14142
- return false;
14143
- }
14144
- if (primaryId !== undefined && scope.primaryId !== primaryId) {
14145
- return false;
14146
- }
14147
- if (actionId !== undefined && scope.actionId !== actionId) {
14148
- return false;
14149
- }
14150
- if (runId !== undefined && scope.runId !== runId) {
14151
- return false;
14152
- }
14153
- return true;
14154
- }
14155
-
14156
- // src/routes/ws/logs.ts
14157
- import { z as z35 } from "zod";
14158
14035
 
14159
- // src/routes/ws/log-subscription-hub.ts
14036
+ // src/routes/ws/subscription-hub.ts
14160
14037
  import { BrokerCursorExpiredError as BrokerCursorExpiredError2 } from "@sixb/core/broker";
14161
14038
  var MAX_CLIENT_RECORDS = 1000;
14162
14039
  var MAX_CLIENT_BYTES = 1048576;
14163
14040
  var MAX_SOCKET_BUFFERED_BYTES = 1048576;
14164
14041
  var MAX_BATCH_RECORDS = 100;
14165
14042
  var FLUSH_DELAY_MS = 10;
14166
- var READ_PAGE_SIZE = 500;
14167
14043
 
14168
- class LogSubscriptionHub {
14169
- host;
14044
+ class SubscriptionHub {
14045
+ source;
14170
14046
  clients = new Map;
14171
14047
  subscriptionGenerations = new WeakMap;
14172
- startPromise = null;
14173
- unsubscribeBroker = null;
14048
+ started = null;
14174
14049
  closed = false;
14175
- constructor(host) {
14176
- this.host = host;
14050
+ constructor(source) {
14051
+ this.source = source;
14177
14052
  }
14178
- async subscribe(key, ws, filter, onSubscribed) {
14053
+ async subscribe(key, ws, subscription, onSubscribed) {
14179
14054
  if (this.closed)
14180
- throw new Error("Log subscription hub is closed");
14055
+ throw new Error("Subscription hub is closed");
14181
14056
  const generation = this.nextSubscriptionGeneration(key);
14182
14057
  this.removeClient(key);
14183
- try {
14184
- await this.ensureStarted();
14185
- } catch (error) {
14058
+ let started;
14059
+ do {
14060
+ started = this.start();
14061
+ try {
14062
+ await started;
14063
+ } catch (error) {
14064
+ if (this.closed || !this.isCurrentSubscription(key, generation))
14065
+ return;
14066
+ throw error;
14067
+ }
14186
14068
  if (this.closed || !this.isCurrentSubscription(key, generation))
14187
14069
  return;
14188
- throw error;
14189
- }
14190
- if (this.closed || !this.isCurrentSubscription(key, generation))
14191
- return;
14070
+ } while (started !== this.started);
14192
14071
  const state = {
14193
14072
  ws,
14194
- filter,
14073
+ subscription,
14195
14074
  queue: [],
14196
14075
  queuedCursors: new Set,
14197
14076
  pendingLive: [],
@@ -14201,13 +14080,13 @@ class LogSubscriptionHub {
14201
14080
  pendingBytes: 0,
14202
14081
  flushTimer: null,
14203
14082
  queueProgressWaiters: new Set,
14204
- catchingUp: filter.afterCursor !== undefined,
14083
+ catchingUp: subscription.replay !== undefined,
14205
14084
  closed: false
14206
14085
  };
14207
14086
  this.clients.set(key, state);
14208
14087
  onSubscribed();
14209
- if (state.catchingUp) {
14210
- this.catchUp(key, state);
14088
+ if (subscription.replay) {
14089
+ this.catchUp(key, state, subscription.replay);
14211
14090
  }
14212
14091
  }
14213
14092
  unsubscribe(key) {
@@ -14222,7 +14101,12 @@ class LogSubscriptionHub {
14222
14101
  if (state.flushTimer)
14223
14102
  clearTimeout(state.flushTimer);
14224
14103
  this.notifyQueueProgress(state);
14104
+ this.deleteClient(key);
14105
+ }
14106
+ deleteClient(key) {
14225
14107
  this.clients.delete(key);
14108
+ if (this.clients.size === 0)
14109
+ this.release();
14226
14110
  }
14227
14111
  nextSubscriptionGeneration(key) {
14228
14112
  const generation = (this.subscriptionGenerations.get(key) ?? 0) + 1;
@@ -14234,58 +14118,57 @@ class LogSubscriptionHub {
14234
14118
  }
14235
14119
  async close() {
14236
14120
  this.closed = true;
14237
- this.unsubscribeBroker?.();
14238
- this.unsubscribeBroker = null;
14239
14121
  for (const key of this.clients.keys())
14240
14122
  this.unsubscribe(key);
14123
+ this.release();
14241
14124
  }
14242
- async ensureStarted() {
14125
+ start() {
14243
14126
  if (this.closed)
14244
- throw new Error("Log subscription hub is closed");
14245
- if (!this.startPromise) {
14246
- this.startPromise = this.host.logging.subscribe({ from: "latest" }, (lines) => this.deliverLive(lines)).then((unsubscribe) => {
14247
- if (this.closed)
14248
- unsubscribe();
14249
- else
14250
- this.unsubscribeBroker = unsubscribe;
14251
- }).catch((error) => {
14252
- this.startPromise = null;
14253
- throw error;
14127
+ return Promise.reject(new Error("Subscription hub is closed"));
14128
+ if (!this.started) {
14129
+ const started = this.source.subscribe((records) => this.deliverLive(records));
14130
+ started.catch(() => {
14131
+ if (this.started === started)
14132
+ this.started = null;
14254
14133
  });
14134
+ this.started = started;
14255
14135
  }
14256
- await this.startPromise;
14136
+ return this.started;
14257
14137
  }
14258
- deliverLive(lines) {
14138
+ release() {
14139
+ const started = this.started;
14140
+ this.started = null;
14141
+ started?.then((unsubscribe) => unsubscribe(), () => {
14142
+ return;
14143
+ });
14144
+ }
14145
+ deliverLive(records) {
14259
14146
  for (const state of this.clients.values()) {
14260
- for (const line of lines) {
14261
- if (!matches(line, state.filter))
14147
+ for (const record of records) {
14148
+ if (!state.subscription.matches(record))
14262
14149
  continue;
14263
14150
  if (state.catchingUp)
14264
- this.enqueuePendingLive(state, line);
14151
+ this.enqueuePendingLive(state, record);
14265
14152
  else
14266
- this.enqueue(state, line);
14153
+ this.enqueue(state, record);
14267
14154
  }
14268
14155
  }
14269
14156
  }
14270
- async catchUp(key, state) {
14271
- let afterCursor = state.filter.afterCursor;
14157
+ async catchUp(key, state, replay) {
14158
+ let afterCursor = replay.afterCursor;
14272
14159
  try {
14273
14160
  let hasMore = true;
14274
14161
  while (hasMore) {
14275
- const page = await this.host.logging.read({
14276
- afterCursor,
14277
- limit: READ_PAGE_SIZE,
14278
- kinds: state.filter.kinds,
14279
- levels: state.filter.levels,
14280
- run: state.filter.run
14281
- });
14162
+ const page = await replay.read(afterCursor);
14282
14163
  if (state.closed || this.clients.get(key) !== state)
14283
14164
  return;
14284
- for (const line of page.lines) {
14285
- if (state.pendingCursors.has(line.cursor)) {
14286
- state.replayedPendingCursors.add(line.cursor);
14165
+ for (const record of page.records) {
14166
+ if (state.pendingCursors.has(record.cursor)) {
14167
+ state.replayedPendingCursors.add(record.cursor);
14287
14168
  }
14288
- if (!await this.enqueueReplay(state, line))
14169
+ if (!state.subscription.matches(record))
14170
+ continue;
14171
+ if (!await this.enqueueReplay(state, record))
14289
14172
  return;
14290
14173
  }
14291
14174
  if (state.closed)
@@ -14293,7 +14176,7 @@ class LogSubscriptionHub {
14293
14176
  afterCursor = page.cursor ?? afterCursor;
14294
14177
  hasMore = page.hasMore;
14295
14178
  if (hasMore && !page.cursor) {
14296
- throw new Error("Log broker returned hasMore without a cursor");
14179
+ throw new Error("Broker returned hasMore without a cursor");
14297
14180
  }
14298
14181
  }
14299
14182
  state.catchingUp = false;
@@ -14303,9 +14186,9 @@ class LogSubscriptionHub {
14303
14186
  state.pendingCursors.clear();
14304
14187
  state.replayedPendingCursors.clear();
14305
14188
  state.pendingBytes = 0;
14306
- for (const line of pendingLive) {
14307
- if (!replayedPendingCursors.has(line.cursor))
14308
- this.enqueue(state, line);
14189
+ for (const record of pendingLive) {
14190
+ if (!replayedPendingCursors.has(record.cursor))
14191
+ this.enqueue(state, record);
14309
14192
  }
14310
14193
  } catch (error) {
14311
14194
  if (state.closed || this.clients.get(key) !== state)
@@ -14317,12 +14200,7 @@ class LogSubscriptionHub {
14317
14200
  state.pendingBytes = 0;
14318
14201
  if (error instanceof BrokerCursorExpiredError2) {
14319
14202
  try {
14320
- const latest = await this.host.logging.tail({ limit: 1 });
14321
- this.send(state, {
14322
- type: "reset",
14323
- reason: "cursor_expired",
14324
- cursor: latest.lines.at(-1)?.cursor ?? latest.cursor
14325
- });
14203
+ this.send(state, await this.source.expired());
14326
14204
  } catch (resetError) {
14327
14205
  this.fail(state, resetError instanceof Error ? resetError.message : String(resetError), 1011);
14328
14206
  }
@@ -14331,25 +14209,25 @@ class LogSubscriptionHub {
14331
14209
  this.fail(state, error instanceof Error ? error.message : String(error), 1011);
14332
14210
  }
14333
14211
  }
14334
- enqueue(state, line) {
14335
- if (state.closed || state.queuedCursors.has(line.cursor))
14212
+ enqueue(state, record) {
14213
+ if (state.closed || state.queuedCursors.has(record.cursor))
14336
14214
  return;
14337
- const bytes = encodedBytes(line);
14215
+ const bytes = encodedBytes(record);
14338
14216
  if (!hasQueueCapacity(state, bytes)) {
14339
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013);
14217
+ this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013);
14340
14218
  return;
14341
14219
  }
14342
- this.pushQueuedLine(state, line, bytes);
14220
+ this.pushQueuedRecord(state, record, bytes);
14343
14221
  }
14344
- async enqueueReplay(state, line) {
14222
+ async enqueueReplay(state, record) {
14345
14223
  if (state.closed)
14346
14224
  return false;
14347
- if (state.queuedCursors.has(line.cursor))
14225
+ if (state.queuedCursors.has(record.cursor))
14348
14226
  return true;
14349
- const bytes = encodedBytes(line);
14227
+ const bytes = encodedBytes(record);
14350
14228
  while (!hasQueueCapacity(state, bytes)) {
14351
14229
  if (state.queue.length === 0 || socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
14352
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013);
14230
+ this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013);
14353
14231
  return false;
14354
14232
  }
14355
14233
  this.scheduleFlush(state);
@@ -14357,25 +14235,25 @@ class LogSubscriptionHub {
14357
14235
  if (state.closed)
14358
14236
  return false;
14359
14237
  }
14360
- this.pushQueuedLine(state, line, bytes);
14238
+ this.pushQueuedRecord(state, record, bytes);
14361
14239
  return !state.closed;
14362
14240
  }
14363
- pushQueuedLine(state, line, bytes) {
14364
- state.queue.push(line);
14365
- state.queuedCursors.add(line.cursor);
14241
+ pushQueuedRecord(state, record, bytes) {
14242
+ state.queue.push(record);
14243
+ state.queuedCursors.add(record.cursor);
14366
14244
  state.queuedBytes += bytes;
14367
14245
  this.scheduleFlush(state);
14368
14246
  }
14369
- enqueuePendingLive(state, line) {
14370
- if (state.closed || state.pendingCursors.has(line.cursor))
14247
+ enqueuePendingLive(state, record) {
14248
+ if (state.closed || state.pendingCursors.has(record.cursor))
14371
14249
  return;
14372
- const bytes = encodedBytes(line);
14250
+ const bytes = encodedBytes(record);
14373
14251
  if (!hasQueueCapacity(state, bytes)) {
14374
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013);
14252
+ this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013);
14375
14253
  return;
14376
14254
  }
14377
- state.pendingLive.push(line);
14378
- state.pendingCursors.add(line.cursor);
14255
+ state.pendingLive.push(record);
14256
+ state.pendingCursors.add(record.cursor);
14379
14257
  state.pendingBytes += bytes;
14380
14258
  }
14381
14259
  scheduleFlush(state) {
@@ -14393,13 +14271,14 @@ class LogSubscriptionHub {
14393
14271
  this.scheduleFlush(state);
14394
14272
  return;
14395
14273
  }
14396
- const lines = state.queue.splice(0, MAX_BATCH_RECORDS);
14397
- for (const line of lines) {
14398
- state.queuedCursors.delete(line.cursor);
14399
- state.queuedBytes -= encodedBytes(line);
14274
+ const records = state.queue.splice(0, MAX_BATCH_RECORDS);
14275
+ for (const record of records) {
14276
+ state.queuedCursors.delete(record.cursor);
14277
+ state.queuedBytes -= encodedBytes(record);
14400
14278
  }
14401
14279
  this.notifyQueueProgress(state);
14402
- this.send(state, { type: "logs", logs: lines });
14280
+ for (const frame of this.source.frames(records))
14281
+ this.send(state, frame);
14403
14282
  if (state.queue.length > 0)
14404
14283
  this.scheduleFlush(state);
14405
14284
  }
@@ -14433,28 +14312,16 @@ class LogSubscriptionHub {
14433
14312
  this.notifyQueueProgress(state);
14434
14313
  for (const [key, candidate] of this.clients) {
14435
14314
  if (candidate === state)
14436
- this.clients.delete(key);
14315
+ this.deleteClient(key);
14437
14316
  }
14438
14317
  try {
14439
- state.ws.close(closeCode, closeCode === 1013 ? "Log stream backpressure" : "Log stream failure");
14318
+ state.ws.close(closeCode, closeCode === 1013 ? "Stream backpressure" : "Stream failure");
14440
14319
  } catch {}
14441
14320
  }
14442
14321
  }
14443
14322
  function hasQueueCapacity(state, bytes) {
14444
14323
  return state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS && state.queuedBytes + state.pendingBytes + bytes <= MAX_CLIENT_BYTES;
14445
14324
  }
14446
- function matches(line, filter) {
14447
- if (filter.run) {
14448
- if (line.context.run.kind !== filter.run.kind || line.context.run.id !== filter.run.id) {
14449
- return false;
14450
- }
14451
- }
14452
- if (filter.kinds && !filter.kinds.includes(line.context.run.kind))
14453
- return false;
14454
- if (filter.levels && !filter.levels.includes(line.level))
14455
- return false;
14456
- return true;
14457
- }
14458
14325
  function encodedBytes(value) {
14459
14326
  return new TextEncoder().encode(JSON.stringify(value)).byteLength;
14460
14327
  }
@@ -14466,7 +14333,173 @@ function socketBufferedAmount(ws) {
14466
14333
  return typeof bufferedAmount === "number" ? bufferedAmount : 0;
14467
14334
  }
14468
14335
 
14336
+ // src/routes/ws/events.ts
14337
+ var DEFAULT_READ_LIMIT = 200;
14338
+ var SubscribeSchema2 = z34.object({
14339
+ type: z34.literal("subscribe"),
14340
+ topic: z34.enum(EVENT_TOPICS).optional(),
14341
+ types: z34.array(z34.enum(EVENT_TYPES)).optional(),
14342
+ objectTypeId: z34.string().optional(),
14343
+ primaryId: z34.string().optional(),
14344
+ actionId: z34.string().optional(),
14345
+ runId: z34.string().optional(),
14346
+ afterCursor: z34.string().optional(),
14347
+ limit: z34.number().int().positive().max(500).optional()
14348
+ });
14349
+ var UnsubscribeSchema2 = z34.object({
14350
+ type: z34.literal("unsubscribe")
14351
+ });
14352
+ var SubscriptionMessageSchema = z34.union([SubscribeSchema2, UnsubscribeSchema2]);
14353
+ function parseSubscriptionMessage(payload) {
14354
+ if (!payload || typeof payload !== "object") {
14355
+ return { ok: false, error: "Message must be a JSON object." };
14356
+ }
14357
+ const parsed = SubscriptionMessageSchema.safeParse(payload);
14358
+ if (!parsed.success) {
14359
+ return {
14360
+ ok: false,
14361
+ error: parsed.error.issues[0]?.message ?? "Invalid websocket message."
14362
+ };
14363
+ }
14364
+ return { ok: true, data: parsed.data };
14365
+ }
14366
+ function registerEventStreamRoutes(app, server) {
14367
+ const events = server.getHost().events;
14368
+ const states = new WeakMap;
14369
+ const hub = new SubscriptionHub({
14370
+ subscribe: (deliver) => events.subscribe({ from: "latest" }, deliver),
14371
+ frames: (batch) => batch.map((event) => ({ type: "event", event })),
14372
+ expired: async () => ({
14373
+ type: "error",
14374
+ message: "[SixbServer] Event cursor expired; refetch current state. Live events continue."
14375
+ })
14376
+ });
14377
+ const awaitInitialization = async (ws, state) => {
14378
+ try {
14379
+ await state.initialized;
14380
+ return true;
14381
+ } catch (error) {
14382
+ if (state.initializationFailureHandled)
14383
+ return false;
14384
+ state.initializationFailureHandled = true;
14385
+ const message = error instanceof Error ? error.message : String(error);
14386
+ safeSend(ws, {
14387
+ type: "error",
14388
+ message: `[SixbServer] Failed to initialize event websocket: ${message}`
14389
+ });
14390
+ ws.close();
14391
+ return false;
14392
+ }
14393
+ };
14394
+ app.onStop(() => hub.close());
14395
+ return app.ws("/ws/events", {
14396
+ async open(ws) {
14397
+ const state = {
14398
+ replayFrom: null,
14399
+ initialized: Promise.resolve(),
14400
+ initializationFailureHandled: false
14401
+ };
14402
+ states.set(wsStateKey(ws), state);
14403
+ state.initialized = events.latestCursor().then((afterCursor) => {
14404
+ state.replayFrom = { afterCursor };
14405
+ });
14406
+ if (!await awaitInitialization(ws, state))
14407
+ return;
14408
+ safeSend(ws, { type: "connected", channel: "events" });
14409
+ },
14410
+ async message(ws, message) {
14411
+ const decoded = await decodeWsMessage(message);
14412
+ const parsed = parseSubscriptionMessage(decoded);
14413
+ if (!parsed.ok) {
14414
+ safeSend(ws, { type: "error", message: parsed.error });
14415
+ return;
14416
+ }
14417
+ const key = wsStateKey(ws);
14418
+ const state = states.get(key);
14419
+ if (!state) {
14420
+ safeSend(ws, { type: "error", message: "Subscription state not found." });
14421
+ return;
14422
+ }
14423
+ if (!await awaitInitialization(ws, state))
14424
+ return;
14425
+ if (parsed.data.type === "unsubscribe") {
14426
+ hub.unsubscribe(key);
14427
+ safeSend(ws, { type: "unsubscribed" });
14428
+ return;
14429
+ }
14430
+ const sixb = wsRequestSixb(ws);
14431
+ if (!sixb) {
14432
+ safeSend(ws, { type: "error", message: "Execution scope is not available." });
14433
+ return;
14434
+ }
14435
+ const filter = parsed.data;
14436
+ const topics = filter.topic ? [filter.topic] : undefined;
14437
+ const limit = filter.limit ?? DEFAULT_READ_LIMIT;
14438
+ const replayFrom = filter.afterCursor === undefined ? state.replayFrom : { afterCursor: filter.afterCursor };
14439
+ state.replayFrom = null;
14440
+ try {
14441
+ await hub.subscribe(key, ws, {
14442
+ matches: (event) => (!filter.topic || event.topic === filter.topic) && (!filter.types?.length || filter.types.includes(event.type)) && eventMatchesScope(event, filter) && sixb.events.canRead(event),
14443
+ replay: replayFrom ? {
14444
+ afterCursor: replayFrom.afterCursor,
14445
+ read: async (afterCursor) => {
14446
+ const records = await events.read({
14447
+ afterCursor,
14448
+ limit,
14449
+ topics,
14450
+ types: filter.types
14451
+ });
14452
+ return {
14453
+ records,
14454
+ cursor: records.at(-1)?.cursor,
14455
+ hasMore: records.length === limit
14456
+ };
14457
+ }
14458
+ } : undefined
14459
+ }, () => safeSend(ws, {
14460
+ type: "subscribed",
14461
+ topic: filter.topic ?? null,
14462
+ types: filter.types ?? null,
14463
+ afterCursor: replayFrom?.afterCursor ?? null
14464
+ }));
14465
+ } catch (error) {
14466
+ safeSend(ws, {
14467
+ type: "error",
14468
+ message: error instanceof Error ? error.message : String(error)
14469
+ });
14470
+ ws.close(1011, "Event stream setup failed");
14471
+ }
14472
+ },
14473
+ close(ws) {
14474
+ hub.unsubscribe(wsStateKey(ws));
14475
+ states.delete(wsStateKey(ws));
14476
+ }
14477
+ });
14478
+ }
14479
+ function eventMatchesScope(event, filter) {
14480
+ const { objectTypeId, primaryId, actionId, runId } = filter;
14481
+ if (objectTypeId === undefined && primaryId === undefined && actionId === undefined && runId === undefined) {
14482
+ return true;
14483
+ }
14484
+ const scope = scopeKeysForEvent(event);
14485
+ if (objectTypeId !== undefined && scope.objectTypeId !== objectTypeId) {
14486
+ return false;
14487
+ }
14488
+ if (primaryId !== undefined && scope.primaryId !== primaryId) {
14489
+ return false;
14490
+ }
14491
+ if (actionId !== undefined && scope.actionId !== actionId) {
14492
+ return false;
14493
+ }
14494
+ if (runId !== undefined && scope.runId !== runId) {
14495
+ return false;
14496
+ }
14497
+ return true;
14498
+ }
14499
+
14469
14500
  // src/routes/ws/logs.ts
14501
+ import { z as z35 } from "zod";
14502
+ var READ_PAGE_SIZE = 500;
14470
14503
  var SubscribeSchema3 = z35.object({
14471
14504
  type: z35.literal("subscribe"),
14472
14505
  kinds: z35.array(z35.enum(SIXB_RUN_KINDS)).min(1).optional(),
@@ -14500,8 +14533,41 @@ function parseLogSubscriptionMessage(payload) {
14500
14533
  }
14501
14534
  return { ok: true, data: parsed.data };
14502
14535
  }
14536
+ function createLogSubscriptionHub(logging) {
14537
+ return new SubscriptionHub({
14538
+ subscribe: (deliver) => logging.subscribe({ from: "latest" }, deliver),
14539
+ frames: (logs) => [{ type: "logs", logs }],
14540
+ expired: async () => {
14541
+ const latest = await logging.tail({ limit: 1 });
14542
+ return {
14543
+ type: "reset",
14544
+ reason: "cursor_expired",
14545
+ cursor: latest.lines.at(-1)?.cursor ?? latest.cursor
14546
+ };
14547
+ }
14548
+ });
14549
+ }
14550
+ function logSubscription(logging, filter) {
14551
+ return {
14552
+ matches: (line) => matchesLogFilter(line, filter),
14553
+ replay: filter.afterCursor === undefined ? undefined : {
14554
+ afterCursor: filter.afterCursor,
14555
+ read: async (afterCursor) => {
14556
+ const page = await logging.read({
14557
+ afterCursor,
14558
+ limit: READ_PAGE_SIZE,
14559
+ kinds: filter.kinds,
14560
+ levels: filter.levels,
14561
+ run: filter.run
14562
+ });
14563
+ return { records: page.lines, cursor: page.cursor, hasMore: page.hasMore };
14564
+ }
14565
+ }
14566
+ };
14567
+ }
14503
14568
  function registerLogStreamRoutes(app, server) {
14504
- const hub = new LogSubscriptionHub(server.getHost());
14569
+ const logging = server.getHost().logging;
14570
+ const hub = createLogSubscriptionHub(logging);
14505
14571
  app.onStop(() => hub.close());
14506
14572
  return app.ws("/ws/logs", {
14507
14573
  open(ws) {
@@ -14540,12 +14606,12 @@ function registerLogStreamRoutes(app, server) {
14540
14606
  const subscription = parsed.data;
14541
14607
  const levels = subscription.levels;
14542
14608
  try {
14543
- await hub.subscribe(key, ws, {
14609
+ await hub.subscribe(key, ws, logSubscription(logging, {
14544
14610
  kinds: subscription.kinds,
14545
14611
  levels,
14546
14612
  run: subscription.run,
14547
14613
  afterCursor: subscription.afterCursor
14548
- }, () => safeSend(ws, {
14614
+ }), () => safeSend(ws, {
14549
14615
  type: "subscribed",
14550
14616
  kinds: subscription.kinds ?? null,
14551
14617
  levels: levels ?? null,
@@ -14565,6 +14631,18 @@ function registerLogStreamRoutes(app, server) {
14565
14631
  }
14566
14632
  });
14567
14633
  }
14634
+ function matchesLogFilter(line, filter) {
14635
+ if (filter.run) {
14636
+ if (line.context.run.kind !== filter.run.kind || line.context.run.id !== filter.run.id) {
14637
+ return false;
14638
+ }
14639
+ }
14640
+ if (filter.kinds && !filter.kinds.includes(line.context.run.kind))
14641
+ return false;
14642
+ if (filter.levels && !filter.levels.includes(line.level))
14643
+ return false;
14644
+ return true;
14645
+ }
14568
14646
 
14569
14647
  // src/routes/ws/index.ts
14570
14648
  function registerWebSocketRoutes(app, server) {
@@ -14599,6 +14677,9 @@ class SixbServer {
14599
14677
  this.hostname = options.hostname ?? "0.0.0.0";
14600
14678
  this.quiet = options.quiet ?? false;
14601
14679
  this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser);
14680
+ if (this.apiBrowserPolicy.publicOrigin) {
14681
+ setApiPublicOrigin(this.hostRuntime, this.apiBrowserPolicy.publicOrigin);
14682
+ }
14602
14683
  this.authContextResolver = createApiBrowserAuthContextResolver(this.apiBrowserPolicy);
14603
14684
  this.authRedirectContextResolver = createApiBrowserAuthRedirectContextResolver(this.apiBrowserPolicy);
14604
14685
  this.authExperience = options.authExperience;
@@ -14947,4 +15028,4 @@ export {
14947
15028
  createSixbServer
14948
15029
  };
14949
15030
 
14950
- //# debugId=EB0D514324A9872464756E2164756E21
15031
+ //# debugId=A2358A8A15C4EC4564756E2164756E21