@sixb/server 0.2.2 → 0.2.3

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 (147) hide show
  1. package/README.md +3 -3
  2. package/dist/artifacts/frame.d.ts.map +1 -1
  3. package/dist/auth/scope.d.ts +3 -0
  4. package/dist/auth/scope.d.ts.map +1 -1
  5. package/dist/auth/shared-access.d.ts +23 -0
  6. package/dist/auth/shared-access.d.ts.map +1 -1
  7. package/dist/connectors/http.d.ts +6 -1
  8. package/dist/connectors/http.d.ts.map +1 -1
  9. package/dist/index.js +2777 -683
  10. package/dist/index.js.map +41 -34
  11. package/dist/live/awareness.d.ts +48 -0
  12. package/dist/live/awareness.d.ts.map +1 -0
  13. package/dist/live/room.d.ts +198 -0
  14. package/dist/live/room.d.ts.map +1 -0
  15. package/dist/live/rooms.d.ts +67 -0
  16. package/dist/live/rooms.d.ts.map +1 -0
  17. package/dist/registerRoutes.d.ts.map +1 -1
  18. package/dist/routes/actions.d.ts +3 -3
  19. package/dist/routes/agent-approvals.d.ts +10 -10
  20. package/dist/routes/agent-children.d.ts +2 -2
  21. package/dist/routes/agent-computers.d.ts +32 -0
  22. package/dist/routes/agent-computers.d.ts.map +1 -1
  23. package/dist/routes/agent-runners.d.ts.map +1 -1
  24. package/dist/routes/agents.d.ts +48 -48
  25. package/dist/routes/artifact-frames.d.ts +2 -1
  26. package/dist/routes/artifact-frames.d.ts.map +1 -1
  27. package/dist/routes/artifacts.d.ts +1713 -178
  28. package/dist/routes/artifacts.d.ts.map +1 -1
  29. package/dist/routes/auth.d.ts +21 -21
  30. package/dist/routes/connector-connection-runs.d.ts +124 -5
  31. package/dist/routes/connector-connection-runs.d.ts.map +1 -1
  32. package/dist/routes/connector-connections.d.ts +9 -1
  33. package/dist/routes/connector-connections.d.ts.map +1 -1
  34. package/dist/routes/datasets.d.ts +5 -5
  35. package/dist/routes/events.d.ts +4 -4
  36. package/dist/routes/lake.d.ts +91 -0
  37. package/dist/routes/lake.d.ts.map +1 -0
  38. package/dist/routes/links.d.ts +6 -6
  39. package/dist/routes/logs.d.ts +2 -2
  40. package/dist/routes/model-generations.d.ts +2 -2
  41. package/dist/routes/objects.d.ts +6 -6
  42. package/dist/routes/objects.d.ts.map +1 -1
  43. package/dist/routes/observed-agent-threads.d.ts +7 -7
  44. package/dist/routes/ontology.d.ts +6 -6
  45. package/dist/routes/pipelines.d.ts +8 -4
  46. package/dist/routes/pipelines.d.ts.map +1 -1
  47. package/dist/routes/projections.d.ts +2 -2
  48. package/dist/routes/share-grants.d.ts +9 -9
  49. package/dist/routes/shared-access.d.ts +57 -2
  50. package/dist/routes/shared-access.d.ts.map +1 -1
  51. package/dist/routes/status.d.ts +11 -15
  52. package/dist/routes/status.d.ts.map +1 -1
  53. package/dist/routes/syncs.d.ts +5 -2
  54. package/dist/routes/syncs.d.ts.map +1 -1
  55. package/dist/routes/telemetry.d.ts +7 -7
  56. package/dist/routes/webhooks.d.ts.map +1 -1
  57. package/dist/routes/workflows.d.ts +3 -3
  58. package/dist/routes/ws/artifacts.d.ts +57 -0
  59. package/dist/routes/ws/artifacts.d.ts.map +1 -0
  60. package/dist/routes/ws/events.d.ts +8 -7
  61. package/dist/routes/ws/events.d.ts.map +1 -1
  62. package/dist/routes/ws/index.d.ts +2 -1
  63. package/dist/routes/ws/index.d.ts.map +1 -1
  64. package/dist/routes/ws/logs.d.ts +10 -10
  65. package/dist/routes/ws/shared-sockets.d.ts +52 -0
  66. package/dist/routes/ws/shared-sockets.d.ts.map +1 -0
  67. package/dist/schemas/actions.d.ts +7 -7
  68. package/dist/schemas/activity.d.ts +8 -8
  69. package/dist/schemas/agent-approvals.d.ts +27 -27
  70. package/dist/schemas/agents.d.ts +195 -154
  71. package/dist/schemas/agents.d.ts.map +1 -1
  72. package/dist/schemas/ai-accounting.d.ts +12 -12
  73. package/dist/schemas/artifacts.d.ts +2106 -127
  74. package/dist/schemas/artifacts.d.ts.map +1 -1
  75. package/dist/schemas/auth.d.ts +63 -63
  76. package/dist/schemas/connectors.d.ts +180 -20
  77. package/dist/schemas/connectors.d.ts.map +1 -1
  78. package/dist/schemas/datasets.d.ts +44 -44
  79. package/dist/schemas/event-payloads.d.ts +2 -2
  80. package/dist/schemas/events.d.ts +26 -26
  81. package/dist/schemas/events.d.ts.map +1 -1
  82. package/dist/schemas/files.d.ts +12 -0
  83. package/dist/schemas/files.d.ts.map +1 -1
  84. package/dist/schemas/lake.d.ts +251 -0
  85. package/dist/schemas/lake.d.ts.map +1 -0
  86. package/dist/schemas/lineage.d.ts +56 -56
  87. package/dist/schemas/logs.d.ts +18 -18
  88. package/dist/schemas/models.d.ts +4 -4
  89. package/dist/schemas/objects.d.ts.map +1 -1
  90. package/dist/schemas/ontology.d.ts +14 -14
  91. package/dist/schemas/pipelines.d.ts +70 -48
  92. package/dist/schemas/pipelines.d.ts.map +1 -1
  93. package/dist/schemas/projections.d.ts +14 -14
  94. package/dist/schemas/projections.d.ts.map +1 -1
  95. package/dist/schemas/share-grants.d.ts +30 -30
  96. package/dist/schemas/shared-access.d.ts +17 -4
  97. package/dist/schemas/shared-access.d.ts.map +1 -1
  98. package/dist/schemas/status.d.ts +59 -79
  99. package/dist/schemas/status.d.ts.map +1 -1
  100. package/dist/schemas/syncs.d.ts +26 -10
  101. package/dist/schemas/syncs.d.ts.map +1 -1
  102. package/dist/schemas/telemetry.d.ts +26 -26
  103. package/dist/schemas/workflows.d.ts +19 -19
  104. package/dist/server.d.ts +13 -0
  105. package/dist/server.d.ts.map +1 -1
  106. package/dist/utils/ws.d.ts +3 -0
  107. package/dist/utils/ws.d.ts.map +1 -1
  108. package/package.json +11 -7
  109. package/src/artifacts/frame.ts +4 -13
  110. package/src/auth/scope.ts +10 -1
  111. package/src/auth/shared-access.ts +108 -12
  112. package/src/connectors/http.ts +35 -1
  113. package/src/live/README.md +136 -0
  114. package/src/live/awareness.ts +141 -0
  115. package/src/live/room.ts +933 -0
  116. package/src/live/rooms.ts +288 -0
  117. package/src/registerRoutes.ts +2 -0
  118. package/src/routes/agent-computers.ts +59 -1
  119. package/src/routes/agent-runners.ts +1 -0
  120. package/src/routes/artifact-frames.ts +40 -12
  121. package/src/routes/artifacts.ts +713 -28
  122. package/src/routes/connector-connection-runs.ts +7 -12
  123. package/src/routes/connector-connections.ts +10 -7
  124. package/src/routes/lake.ts +73 -0
  125. package/src/routes/objects.ts +3 -9
  126. package/src/routes/pipelines.ts +1 -0
  127. package/src/routes/shared-access.ts +53 -1
  128. package/src/routes/status.ts +9 -4
  129. package/src/routes/syncs.ts +1 -0
  130. package/src/routes/webhooks.ts +44 -3
  131. package/src/routes/ws/artifacts.ts +138 -0
  132. package/src/routes/ws/events.ts +7 -2
  133. package/src/routes/ws/index.ts +13 -2
  134. package/src/routes/ws/shared-sockets.ts +152 -0
  135. package/src/schemas/agents.ts +11 -0
  136. package/src/schemas/artifacts.ts +255 -18
  137. package/src/schemas/connectors.ts +17 -2
  138. package/src/schemas/files.ts +12 -0
  139. package/src/schemas/lake.ts +53 -0
  140. package/src/schemas/objects.ts +1 -0
  141. package/src/schemas/pipelines.ts +2 -0
  142. package/src/schemas/projections.ts +2 -2
  143. package/src/schemas/shared-access.ts +16 -0
  144. package/src/schemas/status.ts +16 -22
  145. package/src/schemas/syncs.ts +2 -0
  146. package/src/server.ts +35 -4
  147. package/src/utils/ws.ts +7 -0
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { bindAgentRunRequestExecution as bindAgentRunRequestExecution2 } from "@
6
6
  import { ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX4 } from "@sixb/core/internal/artifacts/frames";
7
7
  import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2, setRequestClientAddress } from "@sixb/core/internal/auth";
8
8
  import { bindRequestExecution } from "@sixb/core/internal/request-execution";
9
- import { setApiPublicOrigin } from "@sixb/core/internal/runtime";
9
+ import { findDatasetIngestRuntime, setApiPublicOrigin } from "@sixb/core/internal/runtime";
10
10
  import { checkPipelineMarkings, warmAppliedMarkings } from "@sixb/core/internal/security";
11
11
  import { Elysia, ParseError } from "elysia";
12
12
  import { websocket as elysiaWebSocket } from "elysia/ws";
@@ -178,6 +178,7 @@ import { CSRF_HEADER_NAME } from "@sixb/core/internal/auth";
178
178
 
179
179
  // src/auth/shared-access.ts
180
180
  import { createHash } from "crypto";
181
+ import { ARTIFACT_LIVE_ROUTE } from "@sixb/core/artifacts/live";
181
182
  import {
182
183
  generateCsrfToken,
183
184
  getCookie,
@@ -185,7 +186,10 @@ import {
185
186
  verifyDoubleSubmitCsrf
186
187
  } from "@sixb/core/internal/auth";
187
188
  import { matchesPathPattern, normalizeRoutePath, SIXB_API_ROUTES } from "@sixb/core/internal/http";
188
- import { SharedSessionProtocol } from "@sixb/core/internal/shares";
189
+ import {
190
+ guestName,
191
+ SharedSessionProtocol
192
+ } from "@sixb/core/internal/shares";
189
193
 
190
194
  // src/auth/session-activity.ts
191
195
  var SESSION_ACTIVITY_HEADER_NAME = "x-sixb-session-activity";
@@ -206,15 +210,22 @@ var SHARED_ACCESS_GRANT_HEADER_NAME = "x-sixb-share-grant";
206
210
  var SHARED_ACCESS_GRANT_QUERY_PARAM = "shareGrant";
207
211
  var SHARED_SESSION_COOKIE_PREFIX = "sixb_share_session_";
208
212
  var SHARED_CSRF_COOKIE_PREFIX = "sixb_share_csrf_";
209
- var SHARED_COOKIE_PATH = "/api";
213
+ var SHARED_SESSION_COOKIE_PATH = "/";
214
+ var SHARED_CSRF_COOKIE_PATH = "/api";
215
+ var LEGACY_SHARED_SESSION_COOKIE_PATH = "/api";
210
216
  var STORED_IDENTIFIER_MAX_LENGTH = 128;
211
217
  var SHARED_SESSION_ROUTES = SIXB_API_ROUTES.filter((route) => route.sharedSession);
212
- var SHARED_FILE_CONTENT_ROUTES = SHARED_SESSION_ROUTES.filter((route) => (route.method === "GET" || route.method === "HEAD") && route.path.endsWith("/files/content"));
218
+ var SHARED_SESSION_SOCKETS = [ARTIFACT_LIVE_ROUTE, "/ws/events"];
219
+ var SHARED_QUERY_SELECTOR_ROUTES = [
220
+ ...SHARED_SESSION_ROUTES.filter((route) => (route.method === "GET" || route.method === "HEAD") && (route.path.endsWith("/content") || route.path.endsWith("/preview"))),
221
+ ...SHARED_SESSION_SOCKETS.map((path) => ({ method: "GET", path }))
222
+ ];
213
223
 
214
224
  class SharedAccessBoundary {
215
225
  host;
216
226
  options;
217
227
  protocol;
228
+ guestNamed = new Set;
218
229
  constructor(host, options = {}) {
219
230
  this.host = host;
220
231
  this.options = options;
@@ -307,6 +318,7 @@ class SharedAccessBoundary {
307
318
  serializeSharedCookie({
308
319
  request,
309
320
  name: names.csrf,
321
+ path: SHARED_CSRF_COOKIE_PATH,
310
322
  value: csrfToken,
311
323
  expiresAt: context.expiresAt,
312
324
  maxAge: cookieMaxAge(context.expiresAt)
@@ -332,6 +344,31 @@ class SharedAccessBoundary {
332
344
  await protocol.revoke(resolved.context);
333
345
  return { kind: "signedOut", setCookies: clearCookies };
334
346
  }
347
+ async setGuestName(request, grantId, name) {
348
+ if (!isStoredIdentifier(grantId))
349
+ return { kind: "invalid", setCookies: [] };
350
+ const resolved = await this.resolveSession(request, grantId);
351
+ if (!resolved)
352
+ return { kind: "invalid", setCookies: this.clearCookieHeaders(request, grantId) };
353
+ if (!verifyDoubleSubmitCsrf(request, { cookieName: sharedCookieNames(grantId).csrf })) {
354
+ return { kind: "csrf" };
355
+ }
356
+ const kept = guestName(name);
357
+ if (kept === null)
358
+ return { kind: "unnamed" };
359
+ const context = await this.getProtocol().setGuestName(resolved.context, kept);
360
+ if (!context)
361
+ return { kind: "invalid", setCookies: this.clearCookieHeaders(request, grantId) };
362
+ for (const listener of this.guestNamed)
363
+ listener(context.sessionId);
364
+ return { kind: "named", context, cookies: resolved.cookies };
365
+ }
366
+ onGuestNamed(listener) {
367
+ this.guestNamed.add(listener);
368
+ }
369
+ current(context) {
370
+ return this.getProtocol().current(context);
371
+ }
335
372
  clearCookieHeaders(request, grantId) {
336
373
  if (!isStoredIdentifier(grantId))
337
374
  return [];
@@ -340,6 +377,16 @@ class SharedAccessBoundary {
340
377
  serializeSharedCookie({
341
378
  request,
342
379
  name: names.session,
380
+ path: SHARED_SESSION_COOKIE_PATH,
381
+ value: "",
382
+ expiresAt: new Date(0),
383
+ maxAge: 0,
384
+ httpOnly: true
385
+ }),
386
+ serializeSharedCookie({
387
+ request,
388
+ name: names.session,
389
+ path: LEGACY_SHARED_SESSION_COOKIE_PATH,
343
390
  value: "",
344
391
  expiresAt: new Date(0),
345
392
  maxAge: 0,
@@ -348,6 +395,7 @@ class SharedAccessBoundary {
348
395
  serializeSharedCookie({
349
396
  request,
350
397
  name: names.csrf,
398
+ path: SHARED_CSRF_COOKIE_PATH,
351
399
  value: "",
352
400
  expiresAt: new Date(0),
353
401
  maxAge: 0
@@ -363,6 +411,7 @@ class SharedAccessBoundary {
363
411
  serializeSharedCookie({
364
412
  request: input.request,
365
413
  name: names.session,
414
+ path: SHARED_SESSION_COOKIE_PATH,
366
415
  value: input.sessionValue,
367
416
  expiresAt: input.expiresAt,
368
417
  maxAge,
@@ -371,6 +420,7 @@ class SharedAccessBoundary {
371
420
  serializeSharedCookie({
372
421
  request: input.request,
373
422
  name: names.csrf,
423
+ path: SHARED_CSRF_COOKIE_PATH,
374
424
  value: input.csrfToken,
375
425
  expiresAt: input.expiresAt,
376
426
  maxAge
@@ -397,7 +447,7 @@ function isSharedAccessPublicRoute(request) {
397
447
  function isSharedAccessPublicPath(pathname, requestMethod) {
398
448
  const method = requestMethod.toUpperCase();
399
449
  const normalizedPathname = normalizeRoutePath(pathname);
400
- const suffix = method === "POST" && normalizedPathname.endsWith("/exchange") ? "exchange" : method === "GET" && normalizedPathname.endsWith("/session") ? "session" : method === "POST" && normalizedPathname.endsWith("/sign-out") ? "sign-out" : null;
450
+ const suffix = method === "POST" && normalizedPathname.endsWith("/exchange") ? "exchange" : method === "GET" && normalizedPathname.endsWith("/session") ? "session" : method === "POST" && normalizedPathname.endsWith("/sign-out") ? "sign-out" : method === "PUT" && normalizedPathname.endsWith("/name") ? "name" : null;
401
451
  if (!suffix)
402
452
  return false;
403
453
  return matchesPathPattern(normalizedPathname, `/api/shared-access/:grantId/${suffix}`);
@@ -407,7 +457,7 @@ function selectSharedAccessGrant(request) {
407
457
  const url = new URL(request.url);
408
458
  const method = request.method.toUpperCase();
409
459
  const pathname = normalizeRoutePath(url.pathname);
410
- const queryValues = SHARED_FILE_CONTENT_ROUTES.some((route) => route.method === method && matchesPathPattern(pathname, route.path)) ? url.searchParams.getAll(SHARED_ACCESS_GRANT_QUERY_PARAM) : [];
460
+ const queryValues = SHARED_QUERY_SELECTOR_ROUTES.some((route) => route.method === method && matchesPathPattern(pathname, route.path)) ? url.searchParams.getAll(SHARED_ACCESS_GRANT_QUERY_PARAM) : [];
411
461
  const [query, ...extra] = queryValues;
412
462
  if (query === undefined) {
413
463
  return header === null ? { kind: "absent" } : { kind: "selected", grantId: header };
@@ -419,6 +469,8 @@ function selectSharedAccessGrant(request) {
419
469
  function isSharedSessionRoute(request) {
420
470
  const method = request.method.toUpperCase();
421
471
  const pathname = normalizeRoutePath(new URL(request.url).pathname);
472
+ if (method === "GET" && SHARED_SESSION_SOCKETS.includes(pathname))
473
+ return true;
422
474
  return SHARED_SESSION_ROUTES.some((route) => route.method === method && matchesPathPattern(pathname, route.path));
423
475
  }
424
476
  function sharedAccessUnauthenticatedResponse() {
@@ -456,7 +508,7 @@ function sharedCookieNames(grantId) {
456
508
  function serializeSharedCookie(input) {
457
509
  const parts = [
458
510
  `${input.name}=${input.value}`,
459
- `Path=${SHARED_COOKIE_PATH}`,
511
+ `Path=${input.path}`,
460
512
  "SameSite=Strict",
461
513
  `Max-Age=${Math.trunc(input.maxAge)}`,
462
514
  `Expires=${input.expiresAt.toUTCString()}`
@@ -1291,6 +1343,9 @@ var CompleteFileUploadBodySchema = z6.object({
1291
1343
  digest: BlobDigestSchema.optional(),
1292
1344
  parts: z6.array(FileUploadPartSchema).optional()
1293
1345
  });
1346
+ var ShareGrantQuerySchema = z6.object({
1347
+ shareGrant: z6.string().optional().describe("Share grant selector for elements that cannot send the x-sixb-share-grant header")
1348
+ });
1294
1349
  var FileContentQuerySchema = z6.object({
1295
1350
  path: z6.string().min(1),
1296
1351
  disposition: z6.enum(["inline", "attachment"]).optional(),
@@ -1938,6 +1993,14 @@ var StopAgentBackgroundCommandBodySchema = z9.object({
1938
1993
  var StopAgentBackgroundCommandResponseSchema = z9.object({
1939
1994
  command: AgentBackgroundCommandSchema.extend({ stopping: z9.boolean().optional() })
1940
1995
  });
1996
+ var AgentComputerSchema = z9.object({
1997
+ id: z9.string(),
1998
+ name: z9.string(),
1999
+ folders: z9.array(z9.string())
2000
+ });
2001
+ var AgentComputerListResponseSchema = z9.object({
2002
+ computers: z9.array(AgentComputerSchema)
2003
+ });
1941
2004
  var AddAgentThreadParticipantsBodySchema = z9.object({
1942
2005
  users: z9.array(z9.union([
1943
2006
  z9.object({ type: z9.literal("user"), id: z9.string().trim().min(1) }).strict(),
@@ -3285,9 +3348,15 @@ function serializeActionRunDetail(run) {
3285
3348
  import { SYSTEM_PRINCIPAL } from "@sixb/core";
3286
3349
  import { agentServiceAccountId } from "@sixb/core/internal/agents";
3287
3350
  function requestAuthState(context) {
3288
- const { sixb = null, agentRun, agentExecution } = context;
3351
+ const {
3352
+ sixb = null,
3353
+ sharedSession,
3354
+ agentRun,
3355
+ agentExecution
3356
+ } = context;
3289
3357
  return {
3290
3358
  sixb,
3359
+ ...sharedSession ? { sharedSession } : {},
3291
3360
  ...agentRun === undefined ? {} : { agentRun },
3292
3361
  ...agentExecution === undefined ? {} : { agentExecution }
3293
3362
  };
@@ -5671,7 +5740,35 @@ async function endLapsedComputerSessions(host) {
5671
5740
  await announceOffline(host, agents, lapsed);
5672
5741
  }
5673
5742
  function registerAgentComputerRoutes(app, host) {
5674
- return app.post("/api/agent-threads/:threadId/computer", async (context) => {
5743
+ return app.get("/api/agent-computers", async (context) => {
5744
+ const { set } = context;
5745
+ const sixb = requireRequestSixb(context);
5746
+ try {
5747
+ const agents = host.storage.agents;
5748
+ if (!agents)
5749
+ return unconfiguredStorageResponse(set, "Agent storage");
5750
+ const live = await agents.computers.listLive({
5751
+ projectId: host.id,
5752
+ ownerPrincipal: requestActor(sixb),
5753
+ now: new Date
5754
+ });
5755
+ return AgentComputerListResponseSchema.parse({ computers: computersOf(live) });
5756
+ } catch (error) {
5757
+ return handleAgentRouteError(error, set);
5758
+ }
5759
+ }, {
5760
+ response: {
5761
+ 200: AgentComputerListResponseSchema,
5762
+ 501: ErrorResponseSchema
5763
+ },
5764
+ detail: {
5765
+ summary: "List your computers with sixb open now",
5766
+ description: "Each of your computers with a live session, and the folders `sixb` is open in there: a thread created to run in one of them runs there now.",
5767
+ tags: [OPENAPI_TAGS.agentThreads.name],
5768
+ operationId: "listAgentComputers",
5769
+ security: SIXB_SESSION_SECURITY_REQUIREMENT
5770
+ }
5771
+ }).post("/api/agent-threads/:threadId/computer", async (context) => {
5675
5772
  const { params, body, set } = context;
5676
5773
  const sixb = requireRequestSixb(context);
5677
5774
  try {
@@ -5886,6 +5983,21 @@ function registerAgentComputerRoutes(app, host) {
5886
5983
  function sameCommands(before, now) {
5887
5984
  return stableJsonStringify(before) === stableJsonStringify(now);
5888
5985
  }
5986
+ function computersOf(sessions) {
5987
+ const byId = new Map;
5988
+ for (const { computer } of sessions) {
5989
+ const known = byId.get(computer.id);
5990
+ if (known)
5991
+ known.folders.add(computer.folder);
5992
+ else
5993
+ byId.set(computer.id, {
5994
+ id: computer.id,
5995
+ name: computer.name,
5996
+ folders: new Set([computer.folder])
5997
+ });
5998
+ }
5999
+ return [...byId.values()].map(({ id, name, folders }) => ({ id, name, folders: [...folders].sort() })).sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
6000
+ }
5889
6001
  async function waitingTurns(host, agents, ownerPrincipal, computer) {
5890
6002
  const { threads } = await agents.threads.list({
5891
6003
  projectId: host.id,
@@ -6178,6 +6290,7 @@ function agentRunSessionHost(host) {
6178
6290
  broker: host.broker,
6179
6291
  recoverAiModelCall: (input) => enqueueAiModelCallRecovery(host.queues.agents, input),
6180
6292
  events: isolateStreamSink(withAgentActivityStream(createBrokerStreamSink({ broker: host.broker, projectId: host.id }), host.broker)),
6293
+ domainEvents: host.events,
6181
6294
  security: host.definitions.security,
6182
6295
  sdk: host,
6183
6296
  definitions: host.definitions,
@@ -6904,9 +7017,11 @@ function registerAiAccountingRoutes(app, host) {
6904
7017
 
6905
7018
  // src/routes/artifact-frames.ts
6906
7019
  import { parseArtifactAddress } from "@sixb/core/artifacts";
7020
+ import { annotateBoard } from "@sixb/core/artifacts/live";
6907
7021
  import {
6908
7022
  ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX3,
6909
7023
  FRAME_ASSETS,
7024
+ FRAME_REFERENCE_PATH,
6910
7025
  FRAME_REFERENCE_PREFIX,
6911
7026
  frameEntries,
6912
7027
  frameLayout,
@@ -6917,14 +7032,10 @@ import {
6917
7032
  import { openFileRef } from "@sixb/core/internal/blob-storage";
6918
7033
 
6919
7034
  // src/artifacts/frame.ts
6920
- import { ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX2 } from "@sixb/core/internal/artifacts/frames";
6921
- var FRAME_CDN_ALLOWLIST = [
6922
- "https://cdn.jsdelivr.net",
6923
- "https://cdnjs.cloudflare.com",
6924
- "https://unpkg.com",
6925
- "https://fonts.googleapis.com",
6926
- "https://fonts.gstatic.com"
6927
- ];
7035
+ import {
7036
+ ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX2,
7037
+ FRAME_CDN_ALLOWLIST
7038
+ } from "@sixb/core/internal/artifacts/frames";
6928
7039
  function frameContentSecurityPolicy(input) {
6929
7040
  const origin = resolveApiBrowserPublicOrigin(input.policy, input.request);
6930
7041
  const base = `${origin}${ARTIFACT_FRAME_ROUTE_PREFIX2}${input.token}/`;
@@ -6985,13 +7096,9 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
6985
7096
  }
6986
7097
  let lent = false;
6987
7098
  if (path?.startsWith(FRAME_REFERENCE_PREFIX)) {
6988
- const match = /^([^/@]+)@(\d+)\/(.+)$/.exec(path.slice(FRAME_REFERENCE_PREFIX.length));
6989
- const target = frame.targets.find((candidate) => candidate.artifactId === match?.[1] && candidate.version === Number(match?.[2]) && parseArtifactAddress(candidate.address)?.path === match?.[3]);
6990
- const lender = target ? await storage.getVersion({
6991
- projectId: host.id,
6992
- artifactId: target.artifactId,
6993
- version: target.version
6994
- }) : null;
7099
+ const match = FRAME_REFERENCE_PATH.exec(path.slice(FRAME_REFERENCE_PREFIX.length));
7100
+ const target = frame.targets.find((candidate) => candidate.artifactId === match?.[1] && String(candidate.version) === match?.[2] && parseArtifactAddress(candidate.address)?.path === match?.[3]);
7101
+ const lender = target ? await lenderVersion(storage, host.id, target) : null;
6995
7102
  if (!lender || !match)
6996
7103
  return notFound();
6997
7104
  version = lender;
@@ -7011,7 +7118,9 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
7011
7118
  if (options.head)
7012
7119
  return new Response(null, { headers });
7013
7120
  const text = await new Response(opened.body).text();
7014
- return new Response(injectFrameAssets(rewriteFrameReferences(text, frame.targets, file.path), layout, file.path), { headers });
7121
+ const editing = version.outline.kind === "canvas" && new URL(request.url).searchParams.has("sixb-edit");
7122
+ const source = editing ? annotateBoard(text) : text;
7123
+ return new Response(injectFrameAssets(rewriteFrameReferences(source, frame.targets, file.path), layout, file.path), { headers });
7015
7124
  }
7016
7125
  const response = await createFileContentResponse({
7017
7126
  blobStorage: host.blobStorage,
@@ -7027,6 +7136,13 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
7027
7136
  response.headers.set("content-disposition", "inline");
7028
7137
  return response;
7029
7138
  }
7139
+ async function lenderVersion(storage, projectId, target) {
7140
+ const { artifactId } = target;
7141
+ const version = target.version === "latest" ? (await storage.get({ projectId, id: artifactId }))?.latestVersion : target.version;
7142
+ if (version === undefined)
7143
+ return null;
7144
+ return storage.getVersion({ projectId, artifactId, version });
7145
+ }
7030
7146
  function decodePath(raw) {
7031
7147
  try {
7032
7148
  return decodeURIComponent(raw ?? "");
@@ -7048,10 +7164,105 @@ import {
7048
7164
  createArtifactFrame,
7049
7165
  serializeArtifactQueryResult
7050
7166
  } from "@sixb/core/internal/artifacts/frames";
7167
+ import {
7168
+ boardPreview,
7169
+ boardPreviewStatuses,
7170
+ boardPreviews,
7171
+ boardsReadLiveData
7172
+ } from "@sixb/core/internal/artifacts/publish";
7051
7173
  import { ZodError as ZodError6 } from "zod";
7052
7174
 
7175
+ // src/live/awareness.ts
7176
+ import { createHash as createHash3 } from "crypto";
7177
+ import {
7178
+ AGENT_AWARENESS_FIELD,
7179
+ USER_AWARENESS_FIELD
7180
+ } from "@sixb/core/artifacts/live";
7181
+ import * as decoding from "lib0/decoding";
7182
+ import * as encoding from "lib0/encoding";
7183
+ var MAX_AWARENESS_CLIENTS = 4;
7184
+ var MAX_AWARENESS_STATE_BYTES = 4 * 1024;
7185
+ var COLORS = [
7186
+ "#e5484d",
7187
+ "#f76b15",
7188
+ "#ffc53d",
7189
+ "#46a758",
7190
+ "#12a594",
7191
+ "#0090ff",
7192
+ "#8e4ec6",
7193
+ "#d6409f"
7194
+ ];
7195
+ var PROJECT_NAME = "Project";
7196
+ async function principalName(storage, projectId, principal, options = {}) {
7197
+ if (principal.type === "system")
7198
+ return PROJECT_NAME;
7199
+ if (principal.type !== "user")
7200
+ return null;
7201
+ const record = await storage.auth?.users.getById({ projectId, id: principal.id });
7202
+ if (options.email === false)
7203
+ return record?.displayName ?? null;
7204
+ return record?.displayName ?? record?.email ?? null;
7205
+ }
7206
+ async function liveUserOf(storage, projectId, principal) {
7207
+ if (!principal)
7208
+ return { id: "system", name: PROJECT_NAME, color: colorOf("system") };
7209
+ const id = `${principal.type}:${principal.id}`;
7210
+ const name = await principalName(storage, projectId, principal, { email: false }) ?? "";
7211
+ return { id, name, color: colorOf(id) };
7212
+ }
7213
+ function guestLiveUser(sessionId, name) {
7214
+ const id = `guest:${sessionId}`;
7215
+ return { id, name: name ?? "", color: colorOf(id), guest: true };
7216
+ }
7217
+ function vouchedAwareness(update, input) {
7218
+ const entries = [];
7219
+ try {
7220
+ const decoder = decoding.createDecoder(update);
7221
+ const length = decoding.readVarUint(decoder);
7222
+ for (let index = 0;index < length; index += 1) {
7223
+ const clientID = decoding.readVarUint(decoder);
7224
+ const clock = decoding.readVarUint(decoder);
7225
+ const state = vouchedState(decoding.readVarString(decoder), input.user);
7226
+ if (state !== undefined && input.mayUse(clientID))
7227
+ entries.push({ clientID, clock, state });
7228
+ }
7229
+ } catch {
7230
+ return null;
7231
+ }
7232
+ if (entries.length === 0)
7233
+ return null;
7234
+ const encoder = encoding.createEncoder();
7235
+ encoding.writeVarUint(encoder, entries.length);
7236
+ for (const entry of entries) {
7237
+ encoding.writeVarUint(encoder, entry.clientID);
7238
+ encoding.writeVarUint(encoder, entry.clock);
7239
+ encoding.writeVarString(encoder, entry.state);
7240
+ }
7241
+ return encoding.toUint8Array(encoder);
7242
+ }
7243
+ function vouchedState(json, user) {
7244
+ if (json.length > MAX_AWARENESS_STATE_BYTES)
7245
+ return;
7246
+ const state = JSON.parse(json);
7247
+ if (state === null)
7248
+ return "null";
7249
+ if (typeof state !== "object" || Array.isArray(state))
7250
+ return;
7251
+ const {
7252
+ [AGENT_AWARENESS_FIELD]: _agent,
7253
+ [USER_AWARENESS_FIELD]: _user,
7254
+ ...own
7255
+ } = state;
7256
+ return JSON.stringify({ ...own, [USER_AWARENESS_FIELD]: user });
7257
+ }
7258
+ function colorOf(id) {
7259
+ const index = createHash3("sha256").update(id).digest()[0] ?? 0;
7260
+ return COLORS[index % COLORS.length];
7261
+ }
7262
+
7053
7263
  // src/schemas/artifacts.ts
7054
- import { ARTIFACT_KINDS, ARTIFACT_STATE_LIMITS } from "@sixb/core/artifacts";
7264
+ import { ARTIFACT_HOLDERS_LIMIT, ARTIFACT_KINDS, ARTIFACT_STATE_LIMITS } from "@sixb/core/artifacts";
7265
+ import { ARTIFACT_RESTORE_POINTS } from "@sixb/core/internal/storage";
7055
7266
  import { z as z18 } from "zod";
7056
7267
  var ArtifactKindSchema = z18.enum(ARTIFACT_KINDS);
7057
7268
  var ArtifactFileSchema = z18.object({
@@ -7077,6 +7288,7 @@ var SlidesOutlineSchema = z18.object({
7077
7288
  slides: z18.array(z18.object({ title: z18.string().optional() }))
7078
7289
  });
7079
7290
  var PageOutlineSchema = z18.object({ kind: z18.literal("page"), title: z18.string().optional() });
7291
+ var ArtifactThemeModeSchema = z18.enum(["light", "dark"]);
7080
7292
  var CanvasOutlineSchema = z18.object({
7081
7293
  kind: z18.literal("canvas"),
7082
7294
  items: z18.array(z18.discriminatedUnion("type", [
@@ -7086,10 +7298,12 @@ var CanvasOutlineSchema = z18.object({
7086
7298
  title: z18.string().optional(),
7087
7299
  file: z18.string(),
7088
7300
  w: z18.number(),
7089
- h: z18.number()
7301
+ h: z18.number(),
7302
+ renderKey: z18.string().optional().describe("What the board's preview is a picture of: a board kept as it was keeps it")
7090
7303
  }),
7091
7304
  z18.object({ id: z18.string(), type: z18.literal("section"), title: z18.string().optional() })
7092
- ]))
7305
+ ])),
7306
+ themes: z18.array(ArtifactThemeModeSchema).optional().describe("The modes each board has a preview in: both, or the one its theme.json pins")
7093
7307
  });
7094
7308
  var FileOutlineSchema = z18.object({ kind: z18.literal("file"), mediaType: z18.string() });
7095
7309
  var ArtifactOutlineSchema = z18.discriminatedUnion("kind", [
@@ -7111,6 +7325,7 @@ var ArtifactWarningSchema = z18.object({
7111
7325
  message: z18.string(),
7112
7326
  part: z18.string().optional()
7113
7327
  });
7328
+ var RevisionSchema = z18.number().int().positive().describe("Counts the artifact's changes: a write, a version created, a restore. It only grows, so content read at one revision is that revision's for good");
7114
7329
  var ArtifactSchema = z18.object({
7115
7330
  id: z18.string(),
7116
7331
  projectId: z18.string(),
@@ -7118,38 +7333,59 @@ var ArtifactSchema = z18.object({
7118
7333
  title: z18.string(),
7119
7334
  owner: PrincipalSchema,
7120
7335
  latestVersion: z18.number().int().positive(),
7336
+ revision: RevisionSchema,
7121
7337
  createdAt: z18.string(),
7122
- updatedAt: z18.string()
7338
+ updatedAt: z18.string().describe("When the artifact last changed")
7123
7339
  });
7124
7340
  var ArtifactOriginSchema = z18.object({ threadId: z18.string(), runId: z18.string() });
7125
7341
  var ArtifactVersionSchema = z18.object({
7126
7342
  artifactId: z18.string(),
7127
7343
  version: z18.number().int().positive(),
7344
+ revision: RevisionSchema.describe("The artifact's revision when this version last changed: the latest version's is the artifact's"),
7345
+ frozen: z18.boolean().describe("Someone created this version: it never changes again. The latest version is open until then, and each write replaces its content"),
7128
7346
  title: z18.string(),
7129
7347
  entry: z18.string(),
7130
7348
  files: z18.array(ArtifactFileSchema),
7131
7349
  outline: ArtifactOutlineSchema,
7132
7350
  references: z18.array(ArtifactReferenceSchema),
7133
- author: PrincipalSchema,
7134
- origin: ArtifactOriginSchema.optional(),
7135
- createdAt: z18.string()
7351
+ author: PrincipalSchema.describe("Who last wrote its content"),
7352
+ origin: ArtifactOriginSchema.optional().describe("The Agent turn and thread its content was last written from"),
7353
+ createdAt: z18.string().describe("When the version was opened"),
7354
+ updatedAt: z18.string().describe("When its content was last written"),
7355
+ frozenAt: z18.string().optional().describe("When it was created, which froze it"),
7356
+ frozenBy: PrincipalSchema.optional().describe("Who created it"),
7357
+ boardPreviews: z18.record(z18.string(), z18.enum(["ready", "pending", "none"])).optional().describe("A canvas's boards by id, as reading or publishing the version returns them: ready when its preview is, pending while it is rendered, none when none will come and the board shows its outline")
7136
7358
  });
7137
7359
  var ArtifactVersionSummarySchema = ArtifactVersionSchema.pick({
7138
7360
  version: true,
7361
+ revision: true,
7362
+ frozen: true,
7139
7363
  title: true,
7140
7364
  author: true,
7141
7365
  origin: true,
7142
- createdAt: true
7366
+ createdAt: true,
7367
+ updatedAt: true,
7368
+ frozenAt: true,
7369
+ frozenBy: true
7143
7370
  });
7144
7371
  var ArtifactParamsSchema = z18.object({ artifactId: z18.string().min(1) });
7145
7372
  var ArtifactVersionParamsSchema = ArtifactParamsSchema.extend({
7146
7373
  version: z18.string().regex(/^(?:latest|[1-9]\d*)$/).describe('A version number, or "latest"')
7147
7374
  });
7375
+ var ArtifactBoardPreviewParamsSchema = ArtifactVersionParamsSchema.extend({
7376
+ board: z18.string().min(1).describe("The board's id in the canvas")
7377
+ });
7378
+ var ArtifactBoardPreviewQuerySchema = z18.object({
7379
+ theme: ArtifactThemeModeSchema.optional().describe("The reader's mode; a canvas whose theme.json pins one is pictured only in it"),
7380
+ size: z18.enum(["full", "small"]).optional().describe("full, the default: a PNG of the board at its own size. small: a WebP at most 480 pixels wide, for a canvas that shows many boards at once"),
7381
+ revision: z18.coerce.number().int().min(1).optional().describe("The version's revision the picture is of. Another than the version's current one is 404 preview_not_found: the version changed, and says which pictures it has now. One that matches is cached for good"),
7382
+ key: z18.string().min(1).max(200).optional().describe("The board's render key the picture is of, as the version's outline names it, in place of revision: the picture stays the same while the board shows the same, however often the canvas around it changes. Another than the board's current one is 404 preview_not_found. One that matches is cached for good")
7383
+ }).extend(ShareGrantQuerySchema.shape).strict();
7148
7384
  var ArtifactQueryParamsSchema = ArtifactVersionParamsSchema.extend({
7149
7385
  name: z18.string().min(1).describe("The query's name: queries/<name>.json in the version")
7150
7386
  });
7151
7387
  var ArtifactListQuerySchema = z18.object({
7152
- thread: z18.string().min(1).optional().describe("Only artifacts with a version the Agent published in this thread"),
7388
+ thread: z18.string().min(1).optional().describe("Only artifacts this conversation shares: the Agent wrote them in it"),
7153
7389
  kind: ArtifactKindSchema.optional().describe("Only artifacts of this kind"),
7154
7390
  limit: z18.string().optional(),
7155
7391
  offset: z18.string().optional()
@@ -7162,15 +7398,57 @@ var ArtifactListResponseSchema = z18.object({
7162
7398
  var ArtifactResponseSchema = z18.object({
7163
7399
  artifact: ArtifactSchema,
7164
7400
  versions: z18.array(ArtifactVersionSummarySchema).describe("Newest first"),
7165
- access: z18.enum(["owner", "update", "read"]).describe("What the caller may do with it: everything as its owner, publish and keep page data as a participant of a conversation that shares it, or only read as an observer of one")
7401
+ access: z18.enum(["owner", "update", "read"]).describe("What the caller may do with it: everything as its owner, publish and keep page data as a participant of a conversation that shares it or an editor of an object that holds it, or only read as an observer of such a conversation or a reader of such an object")
7166
7402
  });
7167
7403
  var PublishArtifactBodySchema = z18.object({
7168
7404
  kind: ArtifactKindSchema,
7169
7405
  title: z18.string(),
7170
7406
  files: z18.array(ArtifactFileSchema).min(1).describe("Files stored with POST /api/files, at their paths in the artifact")
7171
7407
  }).strict();
7172
- var PublishArtifactVersionBodySchema = PublishArtifactBodySchema.extend({
7173
- baseVersion: z18.number().int().positive().optional().describe("The version this one was made from. When another was published since, the publish is refused with 409 artifact_moved, naming the latest version.")
7408
+ var BaseRevisionSchema = z18.number().int().positive().optional().describe("The revision this was made from. When the artifact changed since, it is refused with 409 artifact_moved, naming the revision and who last wrote the latest version.");
7409
+ var UpdateArtifactBodySchema = PublishArtifactBodySchema.extend({
7410
+ baseRevision: BaseRevisionSchema
7411
+ });
7412
+ var FreezeArtifactBodySchema = z18.object({ baseRevision: BaseRevisionSchema }).strict().default({});
7413
+ var RestoreArtifactBodySchema = z18.object({ baseRevision: BaseRevisionSchema }).strict().default({});
7414
+ var ArtifactRestorePointParamsSchema = ArtifactParamsSchema.extend({
7415
+ revision: z18.string().regex(/^[1-9]\d*$/).describe("The revision whose content the restore point holds")
7416
+ });
7417
+ var ArtifactRestorePointSummarySchema = z18.object({
7418
+ artifactId: z18.string(),
7419
+ revision: RevisionSchema.describe("The revision whose content it holds, which restores it"),
7420
+ version: z18.number().int().positive().describe("The version it was taken of"),
7421
+ frozen: z18.boolean().describe("Whether that version was already created, and so frozen, when the point was taken: its content is then that version's"),
7422
+ title: z18.string(),
7423
+ author: PrincipalSchema.describe("Who had last written that content"),
7424
+ origin: ArtifactOriginSchema.optional(),
7425
+ updatedAt: z18.string().describe("When that content was written"),
7426
+ reason: z18.enum(["turn", "restore"]).describe("Taken before an Agent turn's first write to the artifact, or before a restore"),
7427
+ turnRunId: z18.string().optional().describe("With turn: the turn's run"),
7428
+ createdAt: z18.string().describe("When it was taken")
7429
+ });
7430
+ var ArtifactRestorePointSchema = ArtifactRestorePointSummarySchema.extend({
7431
+ entry: z18.string(),
7432
+ files: z18.array(ArtifactFileSchema),
7433
+ outline: ArtifactOutlineSchema,
7434
+ references: z18.array(ArtifactReferenceSchema)
7435
+ });
7436
+ var ArtifactRestorePointListResponseSchema = z18.object({
7437
+ restorePoints: z18.array(ArtifactRestorePointSummarySchema).describe(`Newest first: an artifact keeps its last ${ARTIFACT_RESTORE_POINTS}`)
7438
+ });
7439
+ var ArtifactHolderSchema = z18.object({
7440
+ objectTypeId: z18.string(),
7441
+ primaryId: z18.string(),
7442
+ propertyId: z18.string().describe("The property whose value holds the artifact"),
7443
+ title: z18.string().optional().describe("The object's value of its type's search title, when it has one you read")
7444
+ });
7445
+ var ArtifactHolderListResponseSchema = z18.object({
7446
+ holders: z18.array(ArtifactHolderSchema).describe(`The first ${ARTIFACT_HOLDERS_LIMIT} objects you read that hold the artifact`),
7447
+ hasMore: z18.boolean().describe("More objects you read hold it")
7448
+ });
7449
+ var ArtifactChangeResponseSchema = z18.object({
7450
+ artifact: ArtifactSchema,
7451
+ version: ArtifactVersionSchema
7174
7452
  });
7175
7453
  var PublishedArtifactResponseSchema = z18.object({
7176
7454
  artifact: ArtifactSchema,
@@ -7202,9 +7480,53 @@ var ArtifactFrameResponseSchema = z18.object({
7202
7480
  expiresAt: z18.string().describe("When the frame stops serving; ask for a new one before then")
7203
7481
  });
7204
7482
  var ArtifactErrorResponseSchema = ErrorResponseSchema.extend({
7205
- code: z18.string().optional().describe("Stable machine-readable failure code: artifact_not_found, artifact_kind_mismatch, artifact_moved, invalid_artifact, invalid_state, state_full, not_allowed, not_shared (it exists but no conversation you read shares it), read_only (you observe the conversation that shares it), query_not_found, query_invalid (the ontology no longer admits the query), execution_lost (a run token's run ended or moved to another runner), or storage_unavailable."),
7206
- latest: z18.object({ version: z18.number().int(), author: PrincipalSchema }).optional().describe("With artifact_moved: the latest version and who published it")
7483
+ code: z18.string().optional().describe("Stable machine-readable failure code: artifact_not_found, artifact_kind_mismatch, artifact_moved, restore_point_not_found, comment_not_found, invalid_artifact, invalid_comment, invalid_state, name_required (a shared link's guest gives their name before commenting), state_full, comments_full, not_allowed, not_shared (it exists but neither a conversation nor an object you read shares it), read_only (you only read it), query_not_found, query_invalid (the ontology no longer admits the query), preview_not_found (the board has no preview yet, or will have none), execution_lost (a run token's run ended or moved to another runner), or storage_unavailable."),
7484
+ latest: z18.object({
7485
+ version: z18.number().int(),
7486
+ revision: z18.number().int(),
7487
+ author: PrincipalSchema,
7488
+ frozenBy: PrincipalSchema.optional()
7489
+ }).optional().describe("With artifact_moved: the artifact's latest version, its revision, who last wrote it, and who created it once it is frozen")
7490
+ });
7491
+ var ArtifactCommentAnchorSchema = z18.object({
7492
+ board: z18.string().max(200).optional().describe("The id of the canvas's board it is about"),
7493
+ element: z18.string().max(1024).optional().describe("The address of the board's element it is about, such as body>main:0>h1:0"),
7494
+ label: z18.string().max(1000).optional().describe("The element's first words, which name it once it is gone; kept to 120 characters"),
7495
+ point: z18.object({ x: z18.number().min(0).max(1), y: z18.number().min(0).max(1) }).optional().describe("Where on the board its pin is, as fractions of the board's width and height from its top left"),
7496
+ revision: RevisionSchema.describe("The artifact's revision its author saw")
7497
+ });
7498
+ var ArtifactCommentAuthorSchema = z18.object({
7499
+ type: z18.enum(["user", "serviceAccount", "system", "guest"]),
7500
+ id: z18.string().min(1)
7501
+ }).describe("Who wrote it: a principal, or a guest, someone without an account who opened a shared link, whose id is their link's session");
7502
+ var ArtifactCommentSchema = z18.object({
7503
+ artifactId: z18.string(),
7504
+ id: z18.string(),
7505
+ parentId: z18.string().optional().describe("The comment it replies to, for a reply"),
7506
+ anchor: ArtifactCommentAnchorSchema,
7507
+ body: z18.string().describe("Plain text"),
7508
+ author: ArtifactCommentAuthorSchema,
7509
+ authorName: z18.string().nullable().describe("Its author's name: a member's profile name or email, the project's for its own code, or the name a guest gave; null for anyone the project cannot name. A guest reading it never gets a member's email"),
7510
+ origin: z18.object({ threadId: z18.string(), runId: z18.string() }).optional().describe("The Agent's run that wrote it for its author, and that run's conversation"),
7511
+ createdAt: z18.string(),
7512
+ resolvedAt: z18.string().optional().describe("When someone marked it resolved"),
7513
+ resolvedBy: PrincipalSchema.optional().describe("Who marked it resolved")
7207
7514
  });
7515
+ var ArtifactCommentListResponseSchema = z18.object({
7516
+ comments: z18.array(ArtifactCommentSchema).describe("Comments and replies, oldest first")
7517
+ });
7518
+ var ArtifactCommentParamsSchema = ArtifactParamsSchema.extend({
7519
+ commentId: z18.string().min(1).max(64)
7520
+ });
7521
+ var AddArtifactCommentBodySchema = z18.object({
7522
+ body: z18.string().min(1).max(4000).describe("Plain text"),
7523
+ anchor: ArtifactCommentAnchorSchema.partial().optional().describe("What it is about: a board, an element of the board, or, without, the artifact; at the artifact's revision by default. A reply is about what it replies to."),
7524
+ parentId: z18.string().min(1).max(64).optional().describe("The comment it replies to")
7525
+ });
7526
+ var ResolveArtifactCommentBodySchema = z18.object({
7527
+ resolved: z18.boolean().default(true).describe("False opens it again")
7528
+ });
7529
+ var DeleteArtifactCommentResponseSchema = z18.object({ deleted: z18.literal(true) });
7208
7530
 
7209
7531
  // src/routes/objects.ts
7210
7532
  import {
@@ -8453,6 +8775,7 @@ var ObjectQueryOpenApiSchemas = {
8453
8775
  "uuid",
8454
8776
  "fileRef",
8455
8777
  "userRef",
8778
+ "artifactRef",
8456
8779
  "enum",
8457
8780
  "array",
8458
8781
  "object",
@@ -8942,9 +9265,7 @@ async function timeRequest(request, options, handle) {
8942
9265
  }
8943
9266
 
8944
9267
  // src/routes/objects.ts
8945
- var ObjectFileContentRouteQuerySchema = FileContentQuerySchema.extend({
8946
- shareGrant: z25.string().optional().describe("Share grant selector for elements that cannot send the x-sixb-share-grant header")
8947
- });
9268
+ var ObjectFileContentRouteQuerySchema = FileContentQuerySchema.extend(ShareGrantQuerySchema.shape);
8948
9269
  var ObjectFileContentQuerySchema = ObjectFileContentRouteQuerySchema.extend({
8949
9270
  path: z25.string().min(1).regex(/^\/properties(?:\/|$)/, "Object file content paths must start with /properties/")
8950
9271
  });
@@ -9650,6 +9971,7 @@ function registerObjectRoutes(app, host) {
9650
9971
  }
9651
9972
 
9652
9973
  // src/routes/artifacts.ts
9974
+ var ArtifactFileContentQuerySchema = FileContentQuerySchema.extend(ShareGrantQuerySchema.shape);
9653
9975
  function artifactBody(artifact) {
9654
9976
  return {
9655
9977
  id: artifact.id,
@@ -9658,6 +9980,7 @@ function artifactBody(artifact) {
9658
9980
  title: artifact.title,
9659
9981
  owner: artifact.owner,
9660
9982
  latestVersion: artifact.latestVersion,
9983
+ revision: artifact.revision,
9661
9984
  createdAt: toIsoString(artifact.createdAt),
9662
9985
  updatedAt: toIsoString(artifact.updatedAt)
9663
9986
  };
@@ -9666,6 +9989,8 @@ function versionBody(version) {
9666
9989
  return {
9667
9990
  artifactId: version.artifactId,
9668
9991
  version: version.version,
9992
+ revision: version.revision,
9993
+ frozen: version.frozenAt !== undefined,
9669
9994
  title: version.title,
9670
9995
  entry: version.entry,
9671
9996
  files: version.files,
@@ -9673,13 +9998,80 @@ function versionBody(version) {
9673
9998
  references: version.references,
9674
9999
  author: version.author,
9675
10000
  origin: version.origin,
9676
- createdAt: toIsoString(version.createdAt)
10001
+ createdAt: toIsoString(version.createdAt),
10002
+ updatedAt: toIsoString(version.updatedAt),
10003
+ ...version.frozenAt ? { frozenAt: toIsoString(version.frozenAt) } : {},
10004
+ ...version.frozenBy ? { frozenBy: version.frozenBy } : {}
10005
+ };
10006
+ }
10007
+ function commentAuthors(host, context) {
10008
+ const email = !requestAuthState(context).sharedSession;
10009
+ const names = new Map;
10010
+ return (comment) => {
10011
+ const { author } = comment;
10012
+ if (author.type === "guest")
10013
+ return Promise.resolve(author.name);
10014
+ const key = `${author.type}:${author.id}`;
10015
+ let name = names.get(key);
10016
+ if (!name) {
10017
+ name = principalName(host.storage, host.projectId, author, { email });
10018
+ names.set(key, name);
10019
+ }
10020
+ return name;
10021
+ };
10022
+ }
10023
+ async function commentBody(comment, nameOf) {
10024
+ return {
10025
+ authorName: await nameOf(comment),
10026
+ ...comment.origin ? { origin: comment.origin } : {},
10027
+ artifactId: comment.artifactId,
10028
+ id: comment.id,
10029
+ ...comment.parentId === undefined ? {} : { parentId: comment.parentId },
10030
+ anchor: comment.anchor,
10031
+ body: comment.body,
10032
+ author: { type: comment.author.type, id: comment.author.id },
10033
+ createdAt: toIsoString(comment.createdAt),
10034
+ ...comment.resolvedAt ? { resolvedAt: toIsoString(comment.resolvedAt) } : {},
10035
+ ...comment.resolvedBy ? { resolvedBy: comment.resolvedBy } : {}
10036
+ };
10037
+ }
10038
+ function restorePointSummary(point) {
10039
+ return {
10040
+ artifactId: point.artifactId,
10041
+ revision: point.revision,
10042
+ version: point.version,
10043
+ frozen: point.frozen,
10044
+ title: point.title,
10045
+ author: point.author,
10046
+ origin: point.origin,
10047
+ updatedAt: toIsoString(point.updatedAt),
10048
+ reason: point.reason,
10049
+ ...point.turnRunId === undefined ? {} : { turnRunId: point.turnRunId },
10050
+ createdAt: toIsoString(point.createdAt)
10051
+ };
10052
+ }
10053
+ async function versionResponse(host, version, options = {}) {
10054
+ const storage = host.storage.artifacts;
10055
+ const stored = storage && version.outline.kind === "canvas" ? await boardPreviewStatuses(storage, version, {
10056
+ renders: host.sandboxes !== undefined,
10057
+ now: new Date
10058
+ }) : undefined;
10059
+ const statuses = stored && options.previews === false ? new Map([...stored.keys()].map((board) => [board, "none"])) : stored;
10060
+ return {
10061
+ ...versionBody(version),
10062
+ ...statuses ? { boardPreviews: Object.fromEntries(statuses) } : {}
9677
10063
  };
9678
10064
  }
9679
- function serializePublished(published) {
10065
+ async function serializeChange(host, change) {
10066
+ return ArtifactChangeResponseSchema.parse({
10067
+ artifact: artifactBody(change.artifact),
10068
+ version: await versionResponse(host, change.version)
10069
+ });
10070
+ }
10071
+ async function serializePublished(host, published) {
9680
10072
  return PublishedArtifactResponseSchema.parse({
9681
10073
  artifact: artifactBody(published.artifact),
9682
- version: versionBody(published.version),
10074
+ version: await versionResponse(host, published.version),
9683
10075
  warnings: published.warnings
9684
10076
  });
9685
10077
  }
@@ -9706,7 +10098,17 @@ async function runTokenArtifacts(host, context) {
9706
10098
  const run = await host.storage.agents?.runs.getById({ projectId: host.id, id: runId });
9707
10099
  if (!run || !sixb)
9708
10100
  throw new AgentExecutionLostError(runId);
9709
- return agentRunArtifacts({ projectId: host.id, storage: host.storage }, run, executionToken, () => Promise.resolve(sixb));
10101
+ return agentRunArtifacts({ projectId: host.id, storage: host.storage, domainEvents: host.events, broker: host.broker }, run, executionToken, () => Promise.resolve(sixb));
10102
+ }
10103
+ async function runTokenOrigin(host, context) {
10104
+ const { agentExecution } = requestAuthState(context);
10105
+ if (!agentExecution || agentExecution.kind === "workflow")
10106
+ return;
10107
+ const run = await host.storage.agents?.runs.getById({
10108
+ projectId: host.id,
10109
+ id: agentExecution.runId
10110
+ });
10111
+ return run?.threadId ? { threadId: run.threadId, runId: run.id } : undefined;
9710
10112
  }
9711
10113
  function versionParam(value) {
9712
10114
  return value === "latest" ? "latest" : Number(value);
@@ -9718,12 +10120,19 @@ function notFound(set) {
9718
10120
  async function refusal2(context, artifactId, set) {
9719
10121
  return refusalFor(await requireRequestSixb(context).artifacts.access(artifactId), set);
9720
10122
  }
10123
+ async function restorePointRefusal(context, artifactId, set) {
10124
+ const access = await requireRequestSixb(context).artifacts.access(artifactId);
10125
+ if (access === null || access === "none")
10126
+ return refusalFor(access, set);
10127
+ set.status = 404;
10128
+ return { error: "Restore point not found", code: "restore_point_not_found" };
10129
+ }
9721
10130
  function refusalFor(access, set) {
9722
10131
  if (access !== "none")
9723
10132
  return notFound(set);
9724
10133
  set.status = 403;
9725
10134
  return {
9726
- error: "Artifact not shared in a conversation you read",
10135
+ error: "Artifact not shared with you",
9727
10136
  code: "not_shared"
9728
10137
  };
9729
10138
  }
@@ -9731,7 +10140,9 @@ function handleArtifactRouteError(error, set) {
9731
10140
  if (error instanceof ArtifactRequestError) {
9732
10141
  switch (error.code) {
9733
10142
  case "artifact_not_found":
10143
+ case "comment_not_found":
9734
10144
  case "query_not_found":
10145
+ case "restore_point_not_found":
9735
10146
  set.status = 404;
9736
10147
  break;
9737
10148
  case "artifact_kind_mismatch":
@@ -9740,9 +10151,12 @@ function handleArtifactRouteError(error, set) {
9740
10151
  set.status = 409;
9741
10152
  break;
9742
10153
  case "invalid_artifact":
10154
+ case "invalid_comment":
9743
10155
  case "invalid_state":
10156
+ case "name_required":
9744
10157
  set.status = 400;
9745
10158
  break;
10159
+ case "comments_full":
9746
10160
  case "state_full":
9747
10161
  set.status = 413;
9748
10162
  break;
@@ -9782,14 +10196,15 @@ function artifactErrorResponse(status) {
9782
10196
  }
9783
10197
  };
9784
10198
  }
9785
- var publishResponses = {
9786
- 201: PublishedArtifactResponseSchema,
10199
+ var writeRefusals = {
9787
10200
  400: ArtifactErrorResponseSchema,
9788
10201
  403: ArtifactErrorResponseSchema,
9789
10202
  404: ArtifactErrorResponseSchema,
9790
10203
  409: ArtifactErrorResponseSchema,
9791
10204
  501: ArtifactErrorResponseSchema
9792
10205
  };
10206
+ var createResponses = { 201: PublishedArtifactResponseSchema, ...writeRefusals };
10207
+ var updateResponses = { 200: PublishedArtifactResponseSchema, ...writeRefusals };
9793
10208
  async function artifactFileContentResponse(host, context, options = {}) {
9794
10209
  try {
9795
10210
  const query = FileContentQuerySchema.parse(context.query);
@@ -9817,6 +10232,76 @@ async function artifactFileContentResponse(host, context, options = {}) {
9817
10232
  return handleArtifactRouteError(error, context.set);
9818
10233
  }
9819
10234
  }
10235
+ async function restorePointFileContentResponse(host, context) {
10236
+ try {
10237
+ const query = FileContentQuerySchema.parse(context.query);
10238
+ const { artifactId } = context.params;
10239
+ const point = await requireRequestSixb(context).artifacts.getRestorePoint(artifactId, Number(context.params.revision));
10240
+ if (!point)
10241
+ return await restorePointRefusal(context, artifactId, context.set);
10242
+ const file = point.files.find((candidate) => candidate.path === query.path);
10243
+ const response = file && await createFileContentResponse({
10244
+ blobStorage: host.blobStorage,
10245
+ fileRef: file.file,
10246
+ disposition: query.disposition,
10247
+ request: context.request
10248
+ });
10249
+ if (!response) {
10250
+ context.set.status = 404;
10251
+ return { error: "File not found" };
10252
+ }
10253
+ return response;
10254
+ } catch (error) {
10255
+ if (error instanceof ZodError6) {
10256
+ context.set.status = 400;
10257
+ return { error: "Invalid file content query" };
10258
+ }
10259
+ return handleArtifactRouteError(error, context.set);
10260
+ }
10261
+ }
10262
+ async function artifactBoardPreviewResponse(host, context) {
10263
+ try {
10264
+ const query = ArtifactBoardPreviewQuerySchema.parse(context.query);
10265
+ const { artifactId, board } = context.params;
10266
+ const number = versionParam(context.params.version);
10267
+ const version = await requireRequestSixb(context).artifacts.getVersion(artifactId, number);
10268
+ if (!version)
10269
+ return await refusal2(context, artifactId, context.set);
10270
+ if (!seesBoardPreviews(context, version)) {
10271
+ context.set.status = 404;
10272
+ context.set.headers["cache-control"] = "no-store";
10273
+ return { error: "Board preview not found", code: "preview_not_found" };
10274
+ }
10275
+ const current = query.key !== undefined ? boardRenderKey(version, board) === query.key : query.revision === undefined || query.revision === version.revision;
10276
+ const themes = version.outline.kind === "canvas" ? version.outline.themes ?? [] : [];
10277
+ const theme = query.theme && themes.includes(query.theme) ? query.theme : themes[0];
10278
+ const storage = host.storage.artifacts;
10279
+ const preview = storage && theme && current ? boardPreview((await boardPreviews(storage, version)).get(board), theme, query.size ?? "full") : undefined;
10280
+ const response = preview && await createFileContentResponse({
10281
+ blobStorage: host.blobStorage,
10282
+ fileRef: preview.file,
10283
+ request: context.request
10284
+ });
10285
+ if (!response) {
10286
+ context.set.status = 404;
10287
+ context.set.headers["cache-control"] = "no-store";
10288
+ return { error: "Board preview not found", code: "preview_not_found" };
10289
+ }
10290
+ response.headers.set("cache-control", number !== "latest" && version.frozenAt || query.revision !== undefined || query.key !== undefined ? "private, max-age=31536000, immutable" : "private, no-cache");
10291
+ return response;
10292
+ } catch (error) {
10293
+ return handleArtifactRouteError(error, context.set);
10294
+ }
10295
+ }
10296
+ function seesBoardPreviews(context, version) {
10297
+ return !requestAuthState(context).sharedSession || !boardsReadLiveData(version);
10298
+ }
10299
+ function boardRenderKey(version, board) {
10300
+ if (version.outline.kind !== "canvas")
10301
+ return;
10302
+ const item = version.outline.items.find((candidate) => candidate.type === "board" && candidate.id === board);
10303
+ return item?.type === "board" ? item.renderKey : undefined;
10304
+ }
9820
10305
  function registerArtifactRoutes(app, host) {
9821
10306
  return app.get("/api/artifacts", async (context) => {
9822
10307
  try {
@@ -9857,13 +10342,13 @@ function registerArtifactRoutes(app, host) {
9857
10342
  const run = await runTokenArtifacts(host, context);
9858
10343
  const published = run ? await run.publish(contentInput(body)) : await requireRequestSixb(context).artifacts.create(contentInput(body));
9859
10344
  context.set.status = 201;
9860
- return serializePublished(published);
10345
+ return await serializePublished(host, published);
9861
10346
  } catch (error) {
9862
10347
  return handleArtifactRouteError(error, context.set);
9863
10348
  }
9864
10349
  }, {
9865
10350
  body: PublishArtifactBodySchema,
9866
- response: publishResponses,
10351
+ response: createResponses,
9867
10352
  detail: {
9868
10353
  summary: "Create an artifact",
9869
10354
  description: "Creates an artifact owned by the caller, with its first version. Store each file with POST /api/files first. With a run token, it is created in the run's conversation, owned by the conversation's owner and authored by the run's requester.",
@@ -9908,6 +10393,31 @@ function registerArtifactRoutes(app, host) {
9908
10393
  operationId: "getArtifact",
9909
10394
  security: accessTokenSecurityRequirement("getArtifact")
9910
10395
  }
10396
+ }).get("/api/artifacts/:artifactId/holders", async (context) => {
10397
+ try {
10398
+ const { artifactId } = context.params;
10399
+ const holders = await requireRequestSixb(context).artifacts.holders(artifactId);
10400
+ if (!holders)
10401
+ return await refusal2(context, artifactId, context.set);
10402
+ return ArtifactHolderListResponseSchema.parse(holders);
10403
+ } catch (error) {
10404
+ return handleArtifactRouteError(error, context.set);
10405
+ }
10406
+ }, {
10407
+ params: ArtifactParamsSchema,
10408
+ response: {
10409
+ 200: ArtifactHolderListResponseSchema,
10410
+ 403: ArtifactErrorResponseSchema,
10411
+ 404: ArtifactErrorResponseSchema,
10412
+ 501: ArtifactErrorResponseSchema
10413
+ },
10414
+ detail: {
10415
+ summary: "List the objects that hold an artifact",
10416
+ description: "The objects whose property holds the artifact, among those you read with that property, in a stable order. Whoever reads such an object reads the artifact.",
10417
+ tags: [OPENAPI_TAGS.artifacts.name],
10418
+ operationId: "listArtifactHolders",
10419
+ security: accessTokenSecurityRequirement("listArtifactHolders")
10420
+ }
9911
10421
  }).delete("/api/artifacts/:artifactId", async (context) => {
9912
10422
  try {
9913
10423
  const artifacts = requireRequestSixb(context).artifacts;
@@ -10042,129 +10552,383 @@ function registerArtifactRoutes(app, host) {
10042
10552
  operationId: "clearArtifactState",
10043
10553
  security: accessTokenSecurityRequirement("clearArtifactState")
10044
10554
  }
10045
- }).post("/api/artifacts/:artifactId/versions", async (context) => {
10555
+ }).put("/api/artifacts/:artifactId/content", async (context) => {
10046
10556
  try {
10047
- const body = PublishArtifactVersionBodySchema.parse(context.body);
10557
+ const body = UpdateArtifactBodySchema.parse(context.body);
10048
10558
  const { artifactId } = context.params;
10049
10559
  const content = {
10050
10560
  ...contentInput(body),
10051
- ...body.baseVersion === undefined ? {} : { baseVersion: body.baseVersion }
10561
+ ...body.baseRevision === undefined ? {} : { baseRevision: body.baseRevision }
10052
10562
  };
10053
10563
  const run = await runTokenArtifacts(host, context);
10054
- const published = run ? await run.publish({ ...content, artifactId }) : await requireRequestSixb(context).artifacts.publish(artifactId, content);
10055
- context.set.status = 201;
10056
- return serializePublished(published);
10564
+ const published = run ? await run.publish({ ...content, artifactId }) : await requireRequestSixb(context).artifacts.update(artifactId, content);
10565
+ return await serializePublished(host, published);
10057
10566
  } catch (error) {
10058
10567
  return handleArtifactRouteError(error, context.set);
10059
10568
  }
10060
10569
  }, {
10061
10570
  params: ArtifactParamsSchema,
10062
- body: PublishArtifactVersionBodySchema,
10063
- response: publishResponses,
10571
+ body: UpdateArtifactBodySchema,
10572
+ response: updateResponses,
10064
10573
  detail: {
10065
- summary: "Publish an artifact's next version",
10066
- description: "The kind must be the artifact's. The new version becomes the latest. With baseVersion, it is refused with 409 artifact_moved when another version was published since. With a run token, only an artifact the run's conversation shares or its requester owns; the version is shared in that conversation. A run that lost its execution gets 409 execution_lost.",
10574
+ summary: "Update an artifact",
10575
+ description: "Writes the artifact's latest version: its content is replaced while the version is open, and the next version opens when it is frozen. Either way the revision grows. The kind must be the artifact's. With baseRevision, it is refused with 409 artifact_moved when the artifact changed since. With a run token, only an artifact the run's conversation shares, its requester owns, or an object its requester edits holds; it is shared in that conversation, and the turn's first write to it keeps a restore point. A run that lost its execution gets 409 execution_lost.",
10067
10576
  tags: [OPENAPI_TAGS.artifacts.name],
10068
- operationId: "publishArtifactVersion",
10069
- security: accessTokenSecurityRequirement("publishArtifactVersion")
10577
+ operationId: "updateArtifact",
10578
+ security: accessTokenSecurityRequirement("updateArtifact")
10070
10579
  }
10071
- }).post("/api/artifacts/:artifactId/versions/:version/frame", async (context) => {
10580
+ }).post("/api/artifacts/:artifactId/freeze", async (context) => {
10072
10581
  try {
10073
- const storage = host.storage.artifacts;
10074
- const artifacts = requireRequestSixb(context).artifacts;
10075
- const version = await artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
10076
- if (!storage)
10077
- return notFound(context.set);
10078
- if (!version)
10079
- return await refusal2(context, context.params.artifactId, context.set);
10080
- const frame = await createArtifactFrame({
10081
- projectId: host.id,
10082
- storage,
10083
- version,
10084
- read: (id, number) => artifacts.getVersion(id, number)
10085
- });
10086
- return ArtifactFrameResponseSchema.parse({
10087
- path: frame.path,
10088
- expiresAt: frame.expiresAt.toISOString()
10089
- });
10582
+ const body = FreezeArtifactBodySchema.parse(context.body ?? {});
10583
+ const frozen = await requireRequestSixb(context).artifacts.freeze(context.params.artifactId, body.baseRevision === undefined ? {} : { baseRevision: body.baseRevision });
10584
+ return await serializeChange(host, frozen);
10090
10585
  } catch (error) {
10091
10586
  return handleArtifactRouteError(error, context.set);
10092
10587
  }
10093
10588
  }, {
10094
- params: ArtifactVersionParamsSchema,
10589
+ params: ArtifactParamsSchema,
10590
+ body: FreezeArtifactBodySchema,
10095
10591
  response: {
10096
- 200: ArtifactFrameResponseSchema,
10592
+ 200: ArtifactChangeResponseSchema,
10593
+ 400: ArtifactErrorResponseSchema,
10097
10594
  403: ArtifactErrorResponseSchema,
10098
10595
  404: ArtifactErrorResponseSchema,
10099
10596
  409: ArtifactErrorResponseSchema,
10100
10597
  501: ArtifactErrorResponseSchema
10101
10598
  },
10102
10599
  detail: {
10103
- summary: "Open a version in a frame",
10104
- description: "A short-lived path that serves the files of a version that opens in a sandboxed frame, as slides do. It expires within an hour. A kind that does not open in a frame is refused with 409 artifact_kind_mismatch.",
10600
+ summary: "Create a version",
10601
+ description: "Freezes the artifact's open latest version: it never changes again, and the next write opens the next version. A latest version already frozen is returned as it is. Whoever may update the artifact may create a version. With baseRevision, it is refused with 409 artifact_moved when the open version changed since.",
10105
10602
  tags: [OPENAPI_TAGS.artifacts.name],
10106
- operationId: "createArtifactFrame",
10107
- security: accessTokenSecurityRequirement("createArtifactFrame")
10603
+ operationId: "freezeArtifactVersion",
10604
+ security: accessTokenSecurityRequirement("freezeArtifactVersion")
10108
10605
  }
10109
- }).get("/api/artifacts/:artifactId/versions/:version", async (context) => {
10606
+ }).get("/api/artifacts/:artifactId/comments", async (context) => {
10110
10607
  try {
10111
- const version = await requireRequestSixb(context).artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
10112
- if (!version)
10113
- return await refusal2(context, context.params.artifactId, context.set);
10114
- return ArtifactVersionSchema.parse(versionBody(version));
10608
+ const { artifactId } = context.params;
10609
+ const comments = await requireRequestSixb(context).artifacts.listComments(artifactId);
10610
+ if (!comments)
10611
+ return await refusal2(context, artifactId, context.set);
10612
+ const nameOf = commentAuthors(host, context);
10613
+ return ArtifactCommentListResponseSchema.parse({
10614
+ comments: await Promise.all(comments.map((comment) => commentBody(comment, nameOf)))
10615
+ });
10115
10616
  } catch (error) {
10116
10617
  return handleArtifactRouteError(error, context.set);
10117
10618
  }
10118
10619
  }, {
10119
- params: ArtifactVersionParamsSchema,
10620
+ params: ArtifactParamsSchema,
10120
10621
  response: {
10121
- 200: ArtifactVersionSchema,
10622
+ 200: ArtifactCommentListResponseSchema,
10122
10623
  403: ArtifactErrorResponseSchema,
10123
10624
  404: ArtifactErrorResponseSchema,
10124
10625
  501: ArtifactErrorResponseSchema
10125
10626
  },
10126
10627
  detail: {
10127
- summary: "Get an artifact version",
10128
- description: 'Its files, outline, and references. Use "latest" for the newest version.',
10628
+ summary: "List an artifact's comments",
10629
+ description: "Every comment and reply, oldest first, resolved ones included. Whoever reads the artifact reads them.",
10129
10630
  tags: [OPENAPI_TAGS.artifacts.name],
10130
- operationId: "getArtifactVersion",
10131
- security: accessTokenSecurityRequirement("getArtifactVersion")
10631
+ operationId: "listArtifactComments",
10632
+ security: accessTokenSecurityRequirement("listArtifactComments")
10132
10633
  }
10133
- }).get("/api/artifacts/:artifactId/versions/:version/queries/:name", async (context) => {
10634
+ }).post("/api/artifacts/:artifactId/comments", async (context) => {
10134
10635
  try {
10135
- const { artifactId, version, name } = context.params;
10136
- const result = await requireRequestSixb(context).artifacts.query(artifactId, name, {
10137
- version: versionParam(version)
10636
+ const body = AddArtifactCommentBodySchema.parse(context.body);
10637
+ const origin = await runTokenOrigin(host, context);
10638
+ const comment = await requireRequestSixb(context).artifacts.addComment(context.params.artifactId, {
10639
+ body: body.body,
10640
+ ...body.anchor ? { anchor: body.anchor } : {},
10641
+ ...body.parentId ? { parentId: body.parentId } : {},
10642
+ ...origin ? { origin } : {}
10138
10643
  });
10139
- if (!result)
10140
- return await refusal2(context, artifactId, context.set);
10141
- return serializeArtifactQueryResult(result);
10644
+ context.set.status = 201;
10645
+ return ArtifactCommentSchema.parse(await commentBody(comment, commentAuthors(host, context)));
10142
10646
  } catch (error) {
10143
- return error instanceof ArtifactRequestError || error instanceof ZodError6 ? handleArtifactRouteError(error, context.set) : handleObjectQueryError(error, context.set);
10647
+ return handleArtifactRouteError(error, context.set);
10144
10648
  }
10145
10649
  }, {
10146
- params: ArtifactQueryParamsSchema,
10650
+ params: ArtifactParamsSchema,
10651
+ body: AddArtifactCommentBodySchema,
10652
+ response: {
10653
+ 201: ArtifactCommentSchema,
10654
+ 400: ArtifactErrorResponseSchema,
10655
+ 403: ArtifactErrorResponseSchema,
10656
+ 404: ArtifactErrorResponseSchema,
10657
+ 413: ArtifactErrorResponseSchema,
10658
+ 501: ArtifactErrorResponseSchema
10659
+ },
10147
10660
  detail: {
10148
- summary: "Run an artifact's query",
10149
- description: `Runs the version's queries/<name>.json as the caller, with their rights: a type they cannot view is refused with 403, and a marked property they are not cleared for is left out of each row. Rows are serialized as POST /api/objects/query returns them, beside the schema of what they hold as the caller may view it. Use "latest" for the newest version. A query the ontology no longer admits is refused with 409 query_invalid.`,
10661
+ summary: "Comment on an artifact",
10662
+ description: "Adds a comment, or a reply with parentId, as the caller. Whoever reads the artifact may, a shared link's guest included, under the name they gave its session (400 name_required until they give one). A canvas's comment can be about one of its boards, or an element of a board by its address. Readers receive artifact.commented.",
10150
10663
  tags: [OPENAPI_TAGS.artifacts.name],
10151
- operationId: "getArtifactQuery",
10152
- security: accessTokenSecurityRequirement("getArtifactQuery"),
10153
- responses: {
10154
- 200: {
10155
- description: "Response for status 200",
10156
- content: {
10157
- "application/json": {
10158
- schema: { $ref: "#/components/schemas/ArtifactQueryResponse" }
10159
- }
10160
- }
10161
- },
10162
- 400: {
10163
- description: "Response for status 400",
10164
- content: {
10165
- "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } }
10166
- }
10167
- },
10664
+ operationId: "addArtifactComment",
10665
+ security: accessTokenSecurityRequirement("addArtifactComment")
10666
+ }
10667
+ }).post("/api/artifacts/:artifactId/comments/:commentId/resolve", async (context) => {
10668
+ try {
10669
+ const body = ResolveArtifactCommentBodySchema.parse(context.body ?? {});
10670
+ const comment = await requireRequestSixb(context).artifacts.resolveComment(context.params.artifactId, context.params.commentId, body.resolved);
10671
+ return ArtifactCommentSchema.parse(await commentBody(comment, commentAuthors(host, context)));
10672
+ } catch (error) {
10673
+ return handleArtifactRouteError(error, context.set);
10674
+ }
10675
+ }, {
10676
+ params: ArtifactCommentParamsSchema,
10677
+ body: ResolveArtifactCommentBodySchema,
10678
+ response: {
10679
+ 200: ArtifactCommentSchema,
10680
+ 400: ArtifactErrorResponseSchema,
10681
+ 403: ArtifactErrorResponseSchema,
10682
+ 404: ArtifactErrorResponseSchema,
10683
+ 501: ArtifactErrorResponseSchema
10684
+ },
10685
+ detail: {
10686
+ summary: "Resolve an artifact's comment",
10687
+ description: "Marks the comment resolved, or, with resolved false, opens it again. Its author, or whoever may update the artifact, may; anyone else is refused with 403 not_allowed. A guest's comment is resolved only by whoever may update the artifact.",
10688
+ tags: [OPENAPI_TAGS.artifacts.name],
10689
+ operationId: "resolveArtifactComment",
10690
+ security: accessTokenSecurityRequirement("resolveArtifactComment")
10691
+ }
10692
+ }).delete("/api/artifacts/:artifactId/comments/:commentId", async (context) => {
10693
+ try {
10694
+ await requireRequestSixb(context).artifacts.deleteComment(context.params.artifactId, context.params.commentId);
10695
+ return DeleteArtifactCommentResponseSchema.parse({ deleted: true });
10696
+ } catch (error) {
10697
+ return handleArtifactRouteError(error, context.set);
10698
+ }
10699
+ }, {
10700
+ params: ArtifactCommentParamsSchema,
10701
+ response: {
10702
+ 200: DeleteArtifactCommentResponseSchema,
10703
+ 403: ArtifactErrorResponseSchema,
10704
+ 404: ArtifactErrorResponseSchema,
10705
+ 501: ArtifactErrorResponseSchema
10706
+ },
10707
+ detail: {
10708
+ summary: "Delete an artifact's comment",
10709
+ description: "Deletes the comment and its replies. Its author, or whoever may update the artifact, may.",
10710
+ tags: [OPENAPI_TAGS.artifacts.name],
10711
+ operationId: "deleteArtifactComment",
10712
+ security: accessTokenSecurityRequirement("deleteArtifactComment")
10713
+ }
10714
+ }).get("/api/artifacts/:artifactId/restore-points", async (context) => {
10715
+ try {
10716
+ const { artifactId } = context.params;
10717
+ const points = await requireRequestSixb(context).artifacts.listRestorePoints(artifactId);
10718
+ if (!points)
10719
+ return await refusal2(context, artifactId, context.set);
10720
+ return ArtifactRestorePointListResponseSchema.parse({
10721
+ restorePoints: points.map(restorePointSummary)
10722
+ });
10723
+ } catch (error) {
10724
+ return handleArtifactRouteError(error, context.set);
10725
+ }
10726
+ }, {
10727
+ params: ArtifactParamsSchema,
10728
+ response: {
10729
+ 200: ArtifactRestorePointListResponseSchema,
10730
+ 403: ArtifactErrorResponseSchema,
10731
+ 404: ArtifactErrorResponseSchema,
10732
+ 501: ArtifactErrorResponseSchema
10733
+ },
10734
+ detail: {
10735
+ summary: "List an artifact's restore points",
10736
+ description: "What the artifact's latest version held before each Agent turn's first write to it, and before each restore, newest first. They are not versions: restoring one puts its content back in the latest version.",
10737
+ tags: [OPENAPI_TAGS.artifacts.name],
10738
+ operationId: "listArtifactRestorePoints",
10739
+ security: accessTokenSecurityRequirement("listArtifactRestorePoints")
10740
+ }
10741
+ }).get("/api/artifacts/:artifactId/restore-points/:revision", async (context) => {
10742
+ try {
10743
+ const { artifactId, revision } = context.params;
10744
+ const point = await requireRequestSixb(context).artifacts.getRestorePoint(artifactId, Number(revision));
10745
+ if (!point)
10746
+ return await restorePointRefusal(context, artifactId, context.set);
10747
+ return ArtifactRestorePointSchema.parse({
10748
+ ...restorePointSummary(point),
10749
+ entry: point.entry,
10750
+ files: point.files,
10751
+ outline: point.outline,
10752
+ references: point.references
10753
+ });
10754
+ } catch (error) {
10755
+ return handleArtifactRouteError(error, context.set);
10756
+ }
10757
+ }, {
10758
+ params: ArtifactRestorePointParamsSchema,
10759
+ response: {
10760
+ 200: ArtifactRestorePointSchema,
10761
+ 403: ArtifactErrorResponseSchema,
10762
+ 404: ArtifactErrorResponseSchema,
10763
+ 501: ArtifactErrorResponseSchema
10764
+ },
10765
+ detail: {
10766
+ summary: "Get an artifact's restore point",
10767
+ description: "Its files, outline, and references, as the latest version held them. Read a file's bytes with GET /api/artifacts/{artifactId}/restore-points/{revision}/content.",
10768
+ tags: [OPENAPI_TAGS.artifacts.name],
10769
+ operationId: "getArtifactRestorePoint",
10770
+ security: accessTokenSecurityRequirement("getArtifactRestorePoint")
10771
+ }
10772
+ }).get("/api/artifacts/:artifactId/restore-points/:revision/content", async (context) => restorePointFileContentResponse(host, context), {
10773
+ params: ArtifactRestorePointParamsSchema,
10774
+ query: FileContentQuerySchema,
10775
+ detail: {
10776
+ summary: "Get a file of an artifact's restore point",
10777
+ tags: [OPENAPI_TAGS.artifacts.name],
10778
+ operationId: "getArtifactRestorePointFileContent",
10779
+ security: accessTokenSecurityRequirement("getArtifactRestorePointFileContent"),
10780
+ responses: fileContentGetResponses({ optionalStorage: true })
10781
+ }
10782
+ }).post("/api/artifacts/:artifactId/restore-points/:revision/restore", async (context) => {
10783
+ try {
10784
+ const body = RestoreArtifactBodySchema.parse(context.body ?? {});
10785
+ const { artifactId, revision } = context.params;
10786
+ const restored = await requireRequestSixb(context).artifacts.restore(artifactId, Number(revision), body.baseRevision === undefined ? {} : { baseRevision: body.baseRevision });
10787
+ return await serializeChange(host, restored);
10788
+ } catch (error) {
10789
+ return handleArtifactRouteError(error, context.set);
10790
+ }
10791
+ }, {
10792
+ params: ArtifactRestorePointParamsSchema,
10793
+ body: RestoreArtifactBodySchema,
10794
+ response: {
10795
+ 200: ArtifactChangeResponseSchema,
10796
+ 400: ArtifactErrorResponseSchema,
10797
+ 403: ArtifactErrorResponseSchema,
10798
+ 404: ArtifactErrorResponseSchema,
10799
+ 409: ArtifactErrorResponseSchema,
10800
+ 501: ArtifactErrorResponseSchema
10801
+ },
10802
+ detail: {
10803
+ summary: "Restore an artifact",
10804
+ description: "Puts a restore point's content back in the latest version, as an update writes it: in place while it is open, as the next version when it is frozen. What it replaces becomes a restore point, so the restore can be undone. Whoever may update the artifact may restore it. With baseRevision, it is refused with 409 artifact_moved when the artifact changed since.",
10805
+ tags: [OPENAPI_TAGS.artifacts.name],
10806
+ operationId: "restoreArtifact",
10807
+ security: accessTokenSecurityRequirement("restoreArtifact")
10808
+ }
10809
+ }).post("/api/artifacts/:artifactId/versions/:version/frame", async (context) => {
10810
+ try {
10811
+ const storage = host.storage.artifacts;
10812
+ const artifacts = requireRequestSixb(context).artifacts;
10813
+ const version = await artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
10814
+ if (!storage)
10815
+ return notFound(context.set);
10816
+ if (!version)
10817
+ return await refusal2(context, context.params.artifactId, context.set);
10818
+ const frame = await createArtifactFrame({
10819
+ projectId: host.id,
10820
+ storage,
10821
+ version,
10822
+ read: (id, number) => artifacts.getVersion(id, number)
10823
+ });
10824
+ return ArtifactFrameResponseSchema.parse({
10825
+ path: frame.path,
10826
+ expiresAt: frame.expiresAt.toISOString()
10827
+ });
10828
+ } catch (error) {
10829
+ return handleArtifactRouteError(error, context.set);
10830
+ }
10831
+ }, {
10832
+ params: ArtifactVersionParamsSchema,
10833
+ response: {
10834
+ 200: ArtifactFrameResponseSchema,
10835
+ 403: ArtifactErrorResponseSchema,
10836
+ 404: ArtifactErrorResponseSchema,
10837
+ 409: ArtifactErrorResponseSchema,
10838
+ 501: ArtifactErrorResponseSchema
10839
+ },
10840
+ detail: {
10841
+ summary: "Open a version in a frame",
10842
+ description: "A short-lived path that serves the files of a version that opens in a sandboxed frame, as slides do, at the revision it has now: once the version is written again, the path serves nothing and a new one is needed. It expires within an hour. A kind that does not open in a frame is refused with 409 artifact_kind_mismatch.",
10843
+ tags: [OPENAPI_TAGS.artifacts.name],
10844
+ operationId: "createArtifactFrame",
10845
+ security: accessTokenSecurityRequirement("createArtifactFrame")
10846
+ }
10847
+ }).get("/api/artifacts/:artifactId/versions/:version", async (context) => {
10848
+ try {
10849
+ const version = await requireRequestSixb(context).artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
10850
+ if (!version)
10851
+ return await refusal2(context, context.params.artifactId, context.set);
10852
+ return ArtifactVersionSchema.parse(await versionResponse(host, version, {
10853
+ previews: seesBoardPreviews(context, version)
10854
+ }));
10855
+ } catch (error) {
10856
+ return handleArtifactRouteError(error, context.set);
10857
+ }
10858
+ }, {
10859
+ params: ArtifactVersionParamsSchema,
10860
+ response: {
10861
+ 200: ArtifactVersionSchema,
10862
+ 403: ArtifactErrorResponseSchema,
10863
+ 404: ArtifactErrorResponseSchema,
10864
+ 501: ArtifactErrorResponseSchema
10865
+ },
10866
+ detail: {
10867
+ summary: "Get an artifact version",
10868
+ description: 'Its files, outline, and references. Use "latest" for the newest version.',
10869
+ tags: [OPENAPI_TAGS.artifacts.name],
10870
+ operationId: "getArtifactVersion",
10871
+ security: accessTokenSecurityRequirement("getArtifactVersion")
10872
+ }
10873
+ }).get("/api/artifacts/:artifactId/versions/:version/boards/:board/preview", async (context) => artifactBoardPreviewResponse(host, context), {
10874
+ params: ArtifactBoardPreviewParamsSchema,
10875
+ query: ArtifactBoardPreviewQuerySchema,
10876
+ detail: {
10877
+ summary: "Get the preview of a canvas's board",
10878
+ description: `A picture of the board as its version shows it, in the reader's mode: a PNG at its own size, or with size=small a WebP at most 480 pixels wide, which a viewer shows until the board is opened. It shows the data the version's author can see. A frozen version's preview never changes, and is cached as such, as is one asked for at a revision; an open version's otherwise, and "latest", are revalidated. 404 preview_not_found until it is rendered, when it never will be, or when revision is not the version's current one: the version says which.`,
10879
+ tags: [OPENAPI_TAGS.artifacts.name],
10880
+ operationId: "getArtifactBoardPreview",
10881
+ security: accessTokenSecurityRequirement("getArtifactBoardPreview"),
10882
+ responses: {
10883
+ 200: {
10884
+ description: "The board's preview",
10885
+ content: {
10886
+ "image/png": { schema: { type: "string", format: "binary" } },
10887
+ "image/webp": { schema: { type: "string", format: "binary" } }
10888
+ }
10889
+ },
10890
+ 304: { description: "The preview is unchanged; reuse the privately cached one" },
10891
+ 400: artifactErrorResponse(400),
10892
+ 403: artifactErrorResponse(403),
10893
+ 404: artifactErrorResponse(404),
10894
+ 501: artifactErrorResponse(501)
10895
+ }
10896
+ }
10897
+ }).get("/api/artifacts/:artifactId/versions/:version/queries/:name", async (context) => {
10898
+ try {
10899
+ const { artifactId, version, name } = context.params;
10900
+ const result = await requireRequestSixb(context).artifacts.query(artifactId, name, {
10901
+ version: versionParam(version)
10902
+ });
10903
+ if (!result)
10904
+ return await refusal2(context, artifactId, context.set);
10905
+ return serializeArtifactQueryResult(result);
10906
+ } catch (error) {
10907
+ return error instanceof ArtifactRequestError || error instanceof ZodError6 ? handleArtifactRouteError(error, context.set) : handleObjectQueryError(error, context.set);
10908
+ }
10909
+ }, {
10910
+ params: ArtifactQueryParamsSchema,
10911
+ detail: {
10912
+ summary: "Run an artifact's query",
10913
+ description: `Runs the version's queries/<name>.json as the caller, with their rights: a type they cannot view is refused with 403, and a marked property they are not cleared for is left out of each row. Rows are serialized as POST /api/objects/query returns them, beside the schema of what they hold as the caller may view it. Use "latest" for the newest version. A query the ontology no longer admits is refused with 409 query_invalid.`,
10914
+ tags: [OPENAPI_TAGS.artifacts.name],
10915
+ operationId: "getArtifactQuery",
10916
+ security: accessTokenSecurityRequirement("getArtifactQuery"),
10917
+ responses: {
10918
+ 200: {
10919
+ description: "Response for status 200",
10920
+ content: {
10921
+ "application/json": {
10922
+ schema: { $ref: "#/components/schemas/ArtifactQueryResponse" }
10923
+ }
10924
+ }
10925
+ },
10926
+ 400: {
10927
+ description: "Response for status 400",
10928
+ content: {
10929
+ "application/json": { schema: { $ref: "#/components/schemas/ErrorResponse" } }
10930
+ }
10931
+ },
10168
10932
  403: artifactErrorResponse(403),
10169
10933
  404: artifactErrorResponse(404),
10170
10934
  409: artifactErrorResponse(409),
@@ -10173,7 +10937,7 @@ function registerArtifactRoutes(app, host) {
10173
10937
  }
10174
10938
  }).get("/api/artifacts/:artifactId/versions/:version/content", async (context) => artifactFileContentResponse(host, context), {
10175
10939
  params: ArtifactVersionParamsSchema,
10176
- query: FileContentQuerySchema,
10940
+ query: ArtifactFileContentQuerySchema,
10177
10941
  detail: {
10178
10942
  summary: "Get a file of an artifact version",
10179
10943
  tags: [OPENAPI_TAGS.artifacts.name],
@@ -10183,7 +10947,7 @@ function registerArtifactRoutes(app, host) {
10183
10947
  }
10184
10948
  }).head("/api/artifacts/:artifactId/versions/:version/content", async (context) => artifactFileContentResponse(host, context, { head: true }), {
10185
10949
  params: ArtifactVersionParamsSchema,
10186
- query: FileContentQuerySchema,
10950
+ query: ArtifactFileContentQuerySchema,
10187
10951
  detail: {
10188
10952
  summary: "Head a file of an artifact version",
10189
10953
  tags: [OPENAPI_TAGS.artifacts.name],
@@ -10263,6 +11027,7 @@ function validDate(value) {
10263
11027
  }
10264
11028
 
10265
11029
  // src/connectors/http.ts
11030
+ import { AuthorizationError as AuthorizationError4 } from "@sixb/core";
10266
11031
  import {
10267
11032
  getConnectorConnectionsRuntime,
10268
11033
  isOAuthConnectorDefinition
@@ -10344,10 +11109,14 @@ var ConnectorAccountSchema = z26.object({
10344
11109
  description: z26.string().optional(),
10345
11110
  avatarUrl: z26.string().url().optional()
10346
11111
  });
11112
+ var ConnectorConnectionOwnerSchema = z26.discriminatedUnion("type", [
11113
+ z26.object({ type: z26.literal("project") }),
11114
+ z26.object({ type: z26.literal("user"), id: z26.string() })
11115
+ ]);
10347
11116
  var ConnectorConnectionSchema = z26.object({
10348
11117
  id: z26.string(),
10349
11118
  connectorId: z26.string(),
10350
- owner: z26.object({ type: z26.literal("project") }),
11119
+ owner: ConnectorConnectionOwnerSchema,
10351
11120
  slot: z26.string(),
10352
11121
  account: ConnectorAccountSchema,
10353
11122
  status: z26.enum(["connected", "needs_reauthorization", "disconnected"])
@@ -10357,7 +11126,7 @@ var ConnectorConnectionRunBaseSchema = z26.object({
10357
11126
  id: z26.string(),
10358
11127
  connectorId: z26.string(),
10359
11128
  kind: z26.enum(["connect", "reauthorize"]),
10360
- owner: z26.object({ type: z26.literal("project") }),
11129
+ owner: ConnectorConnectionOwnerSchema,
10361
11130
  slot: z26.string(),
10362
11131
  createdAt: z26.string().datetime(),
10363
11132
  updatedAt: z26.string().datetime()
@@ -10391,11 +11160,17 @@ var ConnectorConnectionRunSchema = z26.union([
10391
11160
  finishedAt: z26.string().datetime()
10392
11161
  })
10393
11162
  ]);
11163
+ var ConnectorConnectionOwnerChoiceSchema = z26.enum(["project", "me"]);
11164
+ var ListConnectorConnectionsQuerySchema = z26.object({
11165
+ owner: ConnectorConnectionOwnerChoiceSchema.optional()
11166
+ });
10394
11167
  var StartConnectorConnectionRunBodySchema = z26.object({
11168
+ owner: ConnectorConnectionOwnerChoiceSchema.default("project"),
10395
11169
  slot: z26.string().trim().min(1),
10396
11170
  returnTo: z26.string().url()
10397
11171
  });
10398
11172
  var AddConnectorConnectionBodySchema = z26.object({
11173
+ owner: ConnectorConnectionOwnerChoiceSchema.default("project"),
10399
11174
  slot: z26.string().trim().min(1)
10400
11175
  });
10401
11176
  var StartConnectorReauthorizationBodySchema = z26.object({
@@ -10437,6 +11212,23 @@ function connectorRouteRuntime(host, owner, connectorId) {
10437
11212
  }
10438
11213
  return getConnectorConnectionsRuntime(owner);
10439
11214
  }
11215
+ function connectorConnectionOwner(sixb, connectorId, choice) {
11216
+ if (choice === "project")
11217
+ return { type: "project" };
11218
+ const requester = sixb.execution.requestedBy;
11219
+ if (requester?.type !== "user") {
11220
+ throw new AuthorizationError4(`connection:connector:${connectorId}`, "[Sixb] Only a signed-in user can connect their own account.");
11221
+ }
11222
+ return { type: "user", id: requester.id };
11223
+ }
11224
+ function matchesConnectorConnectionOwner(sixb, connection, choice) {
11225
+ if (choice === undefined)
11226
+ return true;
11227
+ if (choice === "project")
11228
+ return connection.owner.type === "project";
11229
+ const requester = sixb.execution.requestedBy;
11230
+ return connection.owner.type === "user" && requester?.type === "user" && connection.owner.id === requester.id;
11231
+ }
10440
11232
  function serializeConnectorConnection(connection) {
10441
11233
  return {
10442
11234
  id: connection.id,
@@ -10528,10 +11320,11 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
10528
11320
  }).post("/api/connectors/:connectorId/connection-runs", async (context) => {
10529
11321
  const { params, body, request, set } = context;
10530
11322
  try {
10531
- const runtime = connectorRouteRuntime(host, requireRequestSixb(context), params.connectorId);
11323
+ const sixb = requireRequestSixb(context);
11324
+ const runtime = connectorRouteRuntime(host, sixb, params.connectorId);
10532
11325
  const parsed = StartConnectorConnectionRunBodySchema.parse(body);
10533
11326
  const started = await runtime.startConnectionRun(params.connectorId, {
10534
- owner: { type: "project" },
11327
+ owner: connectorConnectionOwner(sixb, params.connectorId, parsed.owner),
10535
11328
  slot: parsed.slot,
10536
11329
  returnTo: options.resolveReturnTo(request, parsed.returnTo),
10537
11330
  redirectUri: options.resolveCallbackUrl(request)
@@ -10600,11 +11393,12 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
10600
11393
  }).post("/api/connectors/:connectorId/connections/:connectionId/connection-runs", async (context) => {
10601
11394
  const { params, body, set } = context;
10602
11395
  try {
10603
- const runtime = connectorRouteRuntime(host, requireRequestSixb(context), params.connectorId);
11396
+ const sixb = requireRequestSixb(context);
11397
+ const runtime = connectorRouteRuntime(host, sixb, params.connectorId);
10604
11398
  const parsed = AddConnectorConnectionBodySchema.parse(body);
10605
11399
  const run = await runtime.addConnection(params.connectorId, {
10606
11400
  fromConnectionId: params.connectionId,
10607
- owner: { type: "project" },
11401
+ owner: connectorConnectionOwner(sixb, params.connectorId, parsed.owner),
10608
11402
  slot: parsed.slot
10609
11403
  });
10610
11404
  set.status = 201;
@@ -10757,16 +11551,19 @@ function setResponseHeader(set, name, value) {
10757
11551
  // src/routes/connector-connections.ts
10758
11552
  function registerConnectorConnectionRoutes(app, host) {
10759
11553
  return app.get("/api/connectors/:connectorId/connections", async (context) => {
10760
- const { params, set } = context;
11554
+ const { params, query, set } = context;
10761
11555
  try {
10762
- const runtime = connectorRouteRuntime(host, requireRequestSixb(context), params.connectorId);
11556
+ const sixb = requireRequestSixb(context);
11557
+ const runtime = connectorRouteRuntime(host, sixb, params.connectorId);
11558
+ const { owner } = ListConnectorConnectionsQuerySchema.parse(query);
10763
11559
  const connections = await runtime.listConnections(params.connectorId);
10764
- return connections.map(serializeConnectorConnection);
11560
+ return connections.filter((connection) => matchesConnectorConnectionOwner(sixb, connection, owner)).map(serializeConnectorConnection);
10765
11561
  } catch (error) {
10766
11562
  return handleConnectorRouteError(error, set);
10767
11563
  }
10768
11564
  }, {
10769
11565
  params: ConnectorParamsSchema,
11566
+ query: ListConnectorConnectionsQuerySchema,
10770
11567
  response: {
10771
11568
  200: ConnectorConnectionSchema.array(),
10772
11569
  400: ConnectorBadRequestResponseSchema,
@@ -11206,7 +12003,7 @@ function registerDatasetRoutes(app, host) {
11206
12003
  }
11207
12004
 
11208
12005
  // src/routes/events.ts
11209
- import { AuthorizationError as AuthorizationError4 } from "@sixb/core";
12006
+ import { AuthorizationError as AuthorizationError5 } from "@sixb/core";
11210
12007
  function registerEventRoutes(app, _host) {
11211
12008
  return app.get("/api/events", async (context) => {
11212
12009
  const { query, set } = context;
@@ -11225,7 +12022,7 @@ function registerEventRoutes(app, _host) {
11225
12022
  events: [...events]
11226
12023
  };
11227
12024
  } catch (error) {
11228
- if (error instanceof AuthorizationError4) {
12025
+ if (error instanceof AuthorizationError5) {
11229
12026
  set.status = 403;
11230
12027
  return { error: error.message };
11231
12028
  }
@@ -11727,16 +12524,111 @@ function expectedContentLengthError(session, request) {
11727
12524
  return expectedSizeBytesError(session, sizeBytes);
11728
12525
  }
11729
12526
 
11730
- // src/schemas/links.ts
12527
+ // src/routes/lake.ts
12528
+ import { getLakeRetentionRuntime } from "@sixb/core/internal/runtime";
12529
+
12530
+ // src/schemas/lake.ts
11731
12531
  import { z as z27 } from "zod";
11732
- var LinkParamsSchema = z27.object({
11733
- objectTypeId: z27.string().min(1),
11734
- objectId: z27.string().min(1),
11735
- linkId: z27.string().min(1)
12532
+ var DatasetStorageWarningSchema = z27.object({
12533
+ code: z27.enum(["partitioned-small-dataset"]),
12534
+ message: z27.string()
12535
+ });
12536
+ var DatasetStorageHealthSchema = z27.object({
12537
+ datasetId: z27.string(),
12538
+ materialized: z27.boolean().describe("Whether the dataset has a table in the lake"),
12539
+ rowCount: z27.number().int(),
12540
+ dataFiles: z27.number().int().describe("Data files its current rows are read from"),
12541
+ smallDataFiles: z27.number().int().describe("Data files small enough that compaction merges them"),
12542
+ dataBytes: z27.number().int(),
12543
+ deleteFiles: z27.number().int().describe("Files listing deleted rows, until compaction"),
12544
+ inlinedRows: z27.number().int().describe("Rows kept in the catalog rather than in files"),
12545
+ retainedSnapshots: z27.number().int().describe("Commits still in the dataset's history"),
12546
+ partitionBy: z27.array(z27.string()),
12547
+ warnings: z27.array(DatasetStorageWarningSchema),
12548
+ ingest: z27.object({
12549
+ pendingDeliveries: z27.number().int(),
12550
+ pendingChanges: z27.number().int(),
12551
+ oldestReceivedAt: z27.string().datetime().nullable().describe("When the oldest waiting delivery arrived"),
12552
+ rejectedDeliveries: z27.number().int().describe("Deliveries refused when written, kept for a week to read and send again")
12553
+ }).nullable().describe("Ingested changes waiting or refused; null when there are none")
12554
+ });
12555
+ var LakeHealthResponseSchema = z27.object({
12556
+ available: z27.boolean().describe("Whether the lake storage provider supports maintenance"),
12557
+ cleanup: z27.object({
12558
+ state: z27.enum(["off", "idle", "not-requested", "no-worker", "failing", "cleaning", "ok"]).describe("What actually happens: `not-requested` when no orchestrator asks, `no-worker` when no lake worker runs what it asks"),
12559
+ lastRequestedAt: z27.string().nullable().describe("When the orchestrator last asked for cleanup"),
12560
+ lastRunAt: z27.string().nullable().describe("When a lake worker last started a cleanup"),
12561
+ keepVersionsFor: z27.string(),
12562
+ deleteFilesAfter: z27.string(),
12563
+ cleanupEvery: z27.string()
12564
+ }),
12565
+ datasets: z27.array(DatasetStorageHealthSchema)
12566
+ });
12567
+
12568
+ // src/routes/lake.ts
12569
+ function registerLakeRoutes(app, host) {
12570
+ return app.get("/api/lake/health", async (context) => {
12571
+ const { set } = context;
12572
+ const sixb = requireRequestSixb(context);
12573
+ try {
12574
+ const retention = getLakeRetentionRuntime(host);
12575
+ const { settings, maintenance } = retention;
12576
+ const cleanup = {
12577
+ ...await retention.status(),
12578
+ keepVersionsFor: settings.keepVersionsFor,
12579
+ deleteFilesAfter: settings.deleteFilesAfter,
12580
+ cleanupEvery: settings.cleanupEvery
12581
+ };
12582
+ if (maintenance === null)
12583
+ return { available: false, cleanup, datasets: [] };
12584
+ const datasetIds = sixb.datasets.list().map((dataset) => dataset.id);
12585
+ if (datasetIds.length === 0) {
12586
+ return LakeHealthResponseSchema.parse({ available: true, cleanup, datasets: [] });
12587
+ }
12588
+ const [storage, waiting] = await Promise.all([
12589
+ maintenance.describeStorage(datasetIds),
12590
+ host.storage.datasetIngest?.summarize({ projectId: host.id, datasetIds }) ?? []
12591
+ ]);
12592
+ const waitingById = new Map(waiting.map((summary) => [summary.datasetId, summary]));
12593
+ const datasets = storage.map((dataset) => ({
12594
+ ...dataset,
12595
+ ingest: ingestWaiting(waitingById.get(dataset.datasetId))
12596
+ }));
12597
+ return LakeHealthResponseSchema.parse({ available: true, cleanup, datasets });
12598
+ } catch (error) {
12599
+ return handleRouteError(error, set);
12600
+ }
12601
+ }, {
12602
+ response: { 200: LakeHealthResponseSchema, 400: ErrorResponseSchema },
12603
+ detail: {
12604
+ summary: "Describe how the lake stores each dataset, and what its retention does",
12605
+ tags: [OPENAPI_TAGS.datasets.name],
12606
+ operationId: "getLakeHealth",
12607
+ security: accessTokenSecurityRequirement("getLakeHealth")
12608
+ }
12609
+ });
12610
+ }
12611
+ function ingestWaiting(summary) {
12612
+ if (!summary || summary.pendingDeliveries === 0 && summary.rejectedDeliveries === 0)
12613
+ return null;
12614
+ return {
12615
+ pendingDeliveries: summary.pendingDeliveries,
12616
+ pendingChanges: summary.pendingChanges,
12617
+ oldestReceivedAt: summary.oldestReceivedAt?.toISOString() ?? null,
12618
+ rejectedDeliveries: summary.rejectedDeliveries
12619
+ };
12620
+ }
12621
+
12622
+ // src/schemas/links.ts
12623
+ import { z as z28 } from "zod";
12624
+ var LinkParamsSchema = z28.object({
12625
+ objectTypeId: z28.string().min(1),
12626
+ objectId: z28.string().min(1),
12627
+ linkId: z28.string().min(1)
11736
12628
  });
11737
- var LinkLineageQuerySchema = z27.object({
11738
- targetTypeId: z27.string().min(1),
11739
- targetId: z27.string().min(1)
12629
+ var LinkLineageQuerySchema = z28.object({
12630
+ targetTypeId: z28.string().min(1),
12631
+ targetId: z28.string().min(1)
11740
12632
  });
11741
12633
 
11742
12634
  // src/routes/links.ts
@@ -11784,71 +12676,71 @@ import { logLevelsAtOrAbove } from "@sixb/core";
11784
12676
 
11785
12677
  // src/schemas/logs.ts
11786
12678
  import { LOG_LEVELS, SIXB_RUN_KINDS } from "@sixb/core";
11787
- import { z as z28 } from "zod";
11788
- var SixbRunKindSchema = z28.enum(SIXB_RUN_KINDS);
11789
- var LogLevelSchema = z28.enum(LOG_LEVELS);
11790
- var LogRunIdSchema = z28.string().regex(/\S/, "run id must not be blank");
12679
+ import { z as z29 } from "zod";
12680
+ var SixbRunKindSchema = z29.enum(SIXB_RUN_KINDS);
12681
+ var LogLevelSchema = z29.enum(LOG_LEVELS);
12682
+ var LogRunIdSchema = z29.string().regex(/\S/, "run id must not be blank");
11791
12683
  var DEFAULT_LOGS_PAGE_LIMIT = 200;
11792
12684
  var MAX_LOGS_PAGE_LIMIT = 1000;
11793
- var LogsLimitSchema = z28.coerce.number().int().positive().max(MAX_LOGS_PAGE_LIMIT);
11794
- var LogsQuerySchema = z28.object({
12685
+ var LogsLimitSchema = z29.coerce.number().int().positive().max(MAX_LOGS_PAGE_LIMIT);
12686
+ var LogsQuerySchema = z29.object({
11795
12687
  kind: SixbRunKindSchema.optional(),
11796
12688
  runId: LogRunIdSchema.optional(),
11797
12689
  level: LogLevelSchema.optional(),
11798
- direction: z28.enum(["forward", "backward"]).optional(),
11799
- afterCursor: z28.string().optional(),
11800
- beforeCursor: z28.string().optional(),
12690
+ direction: z29.enum(["forward", "backward"]).optional(),
12691
+ afterCursor: z29.string().optional(),
12692
+ beforeCursor: z29.string().optional(),
11801
12693
  limit: LogsLimitSchema.optional()
11802
12694
  }).superRefine((query, context) => {
11803
12695
  if (query.runId !== undefined && query.kind === undefined) {
11804
12696
  context.addIssue({
11805
- code: z28.ZodIssueCode.custom,
12697
+ code: z29.ZodIssueCode.custom,
11806
12698
  path: ["runId"],
11807
12699
  message: "kind is required when runId is provided"
11808
12700
  });
11809
12701
  }
11810
12702
  if (query.afterCursor && query.beforeCursor) {
11811
12703
  context.addIssue({
11812
- code: z28.ZodIssueCode.custom,
12704
+ code: z29.ZodIssueCode.custom,
11813
12705
  message: "afterCursor and beforeCursor are mutually exclusive"
11814
12706
  });
11815
12707
  }
11816
12708
  if (query.direction === "backward" && query.afterCursor) {
11817
12709
  context.addIssue({
11818
- code: z28.ZodIssueCode.custom,
12710
+ code: z29.ZodIssueCode.custom,
11819
12711
  path: ["afterCursor"],
11820
12712
  message: "afterCursor cannot be used with backward reads"
11821
12713
  });
11822
12714
  }
11823
12715
  if (query.direction !== "backward" && query.beforeCursor) {
11824
12716
  context.addIssue({
11825
- code: z28.ZodIssueCode.custom,
12717
+ code: z29.ZodIssueCode.custom,
11826
12718
  path: ["beforeCursor"],
11827
12719
  message: "beforeCursor requires direction=backward"
11828
12720
  });
11829
12721
  }
11830
12722
  });
11831
- var LogLineSchema = z28.object({
12723
+ var LogLineSchema = z29.object({
11832
12724
  level: LogLevelSchema,
11833
- message: z28.string(),
11834
- fields: z28.record(z28.unknown()).optional(),
11835
- at: z28.string(),
11836
- context: z28.object({
11837
- run: z28.object({
12725
+ message: z29.string(),
12726
+ fields: z29.record(z29.unknown()).optional(),
12727
+ at: z29.string(),
12728
+ context: z29.object({
12729
+ run: z29.object({
11838
12730
  kind: SixbRunKindSchema,
11839
- id: z28.string()
12731
+ id: z29.string()
11840
12732
  }),
11841
- stepId: z28.string().optional(),
11842
- phase: z28.string().optional(),
11843
- attempt: z28.number().optional()
12733
+ stepId: z29.string().optional(),
12734
+ phase: z29.string().optional(),
12735
+ attempt: z29.number().optional()
11844
12736
  }),
11845
- cursor: z28.string()
12737
+ cursor: z29.string()
11846
12738
  });
11847
- var LogsResponseSchema = z28.object({
11848
- count: z28.number(),
11849
- lines: z28.array(LogLineSchema),
11850
- cursor: z28.string().optional(),
11851
- hasMore: z28.boolean()
12739
+ var LogsResponseSchema = z29.object({
12740
+ count: z29.number(),
12741
+ lines: z29.array(LogLineSchema),
12742
+ cursor: z29.string().optional(),
12743
+ hasMore: z29.boolean()
11852
12744
  });
11853
12745
 
11854
12746
  // src/routes/logs.ts
@@ -11893,9 +12785,9 @@ function registerLogRoutes(app, _host) {
11893
12785
  }
11894
12786
 
11895
12787
  // src/routes/model-calls.ts
11896
- import { z as z29 } from "zod";
12788
+ import { z as z30 } from "zod";
11897
12789
  var ModelCallFileContentQuerySchema = FileContentQuerySchema.extend({
11898
- path: z29.string().min(1).regex(/^\/files(?:\/|$)/, "Model call file content paths must start with /files/")
12790
+ path: z30.string().min(1).regex(/^\/files(?:\/|$)/, "Model call file content paths must start with /files/")
11899
12791
  });
11900
12792
  function serializeModelCallFiles(call) {
11901
12793
  return ModelCallFilesSchema.parse({
@@ -12532,111 +13424,112 @@ function registerOntologyRoutes(app, host) {
12532
13424
  import {
12533
13425
  PIPELINE_RUN_FAILURE_CODES
12534
13426
  } from "@sixb/core/storage";
12535
- import { z as z30 } from "zod";
13427
+ import { z as z31 } from "zod";
12536
13428
  var PipelineRunFailureSchema = sixbFailureSchema(PIPELINE_RUN_FAILURE_CODES);
12537
- var PipelineParamsSchema = z30.object({
12538
- pipelineId: z30.string().min(1)
13429
+ var PipelineParamsSchema = z31.object({
13430
+ pipelineId: z31.string().min(1)
12539
13431
  });
12540
- var PipelineRunParamsSchema = z30.object({
12541
- runId: z30.string().min(1)
13432
+ var PipelineRunParamsSchema = z31.object({
13433
+ runId: z31.string().min(1)
12542
13434
  });
12543
- var PipelineRunStatusSchema = z30.enum([
13435
+ var PipelineRunStatusSchema = z31.enum([
12544
13436
  "queued",
12545
13437
  "running",
12546
13438
  "succeeded",
12547
13439
  "failed",
12548
13440
  "cancelled"
12549
13441
  ]);
12550
- var PipelineStepRunStatusSchema = z30.enum(["running", "succeeded", "failed", "cancelled"]);
12551
- var PipelineRunsQuerySchema = z30.object({
12552
- pipelineId: z30.string().optional(),
13442
+ var PipelineStepRunStatusSchema = z31.enum(["running", "succeeded", "failed", "cancelled"]);
13443
+ var PipelineRunsQuerySchema = z31.object({
13444
+ pipelineId: z31.string().optional(),
12553
13445
  status: PipelineRunStatusSchema.optional(),
12554
- startedAfter: z30.string().optional(),
12555
- startedBefore: z30.string().optional(),
12556
- limit: z30.string().optional(),
12557
- offset: z30.string().optional(),
12558
- order: z30.enum(["asc", "desc"]).optional()
12559
- });
12560
- var DatasetVersionRefSchema2 = z30.object({
12561
- datasetId: z30.string(),
12562
- versionId: z30.string()
12563
- });
12564
- var PipelineTriggerSchema = z30.object({
12565
- type: z30.literal("schedule"),
12566
- scheduleId: z30.string()
12567
- });
12568
- var PipelineStepExecutorSchema = z30.union([
12569
- z30.object({
12570
- kind: z30.literal("sql"),
12571
- dialect: z30.literal("duckdb")
13446
+ startedAfter: z31.string().optional(),
13447
+ startedBefore: z31.string().optional(),
13448
+ limit: z31.string().optional(),
13449
+ offset: z31.string().optional(),
13450
+ order: z31.enum(["asc", "desc"]).optional()
13451
+ });
13452
+ var DatasetVersionRefSchema2 = z31.object({
13453
+ datasetId: z31.string(),
13454
+ versionId: z31.string()
13455
+ });
13456
+ var PipelineTriggerSchema = z31.object({
13457
+ type: z31.literal("schedule"),
13458
+ scheduleId: z31.string()
13459
+ });
13460
+ var PipelineStepExecutorSchema = z31.union([
13461
+ z31.object({
13462
+ kind: z31.literal("sql"),
13463
+ dialect: z31.literal("duckdb")
12572
13464
  }),
12573
- z30.object({
12574
- kind: z30.literal("run")
13465
+ z31.object({
13466
+ kind: z31.literal("run")
12575
13467
  })
12576
13468
  ]);
12577
- var PipelineRunSchema = z30.object({
12578
- id: z30.string(),
12579
- projectId: z30.string(),
12580
- pipelineId: z30.string(),
13469
+ var PipelineRunSchema = z31.object({
13470
+ id: z31.string(),
13471
+ projectId: z31.string(),
13472
+ pipelineId: z31.string(),
12581
13473
  status: PipelineRunStatusSchema,
12582
- queuedAt: z30.string(),
12583
- startedAt: z30.string().optional(),
12584
- finishedAt: z30.string().optional(),
13474
+ attempt: z31.number(),
13475
+ queuedAt: z31.string(),
13476
+ startedAt: z31.string().optional(),
13477
+ finishedAt: z31.string().optional(),
12585
13478
  output: DatasetVersionRefSchema2.optional(),
12586
13479
  error: PipelineRunFailureSchema.optional()
12587
13480
  });
12588
- var PipelineStepRunSchema = z30.object({
12589
- id: z30.string(),
12590
- projectId: z30.string(),
12591
- pipelineRunId: z30.string(),
12592
- pipelineId: z30.string(),
12593
- stepId: z30.string(),
12594
- datasetId: z30.string(),
12595
- mode: z30.enum(["snapshot", "append"]),
13481
+ var PipelineStepRunSchema = z31.object({
13482
+ id: z31.string(),
13483
+ projectId: z31.string(),
13484
+ pipelineRunId: z31.string(),
13485
+ pipelineId: z31.string(),
13486
+ stepId: z31.string(),
13487
+ datasetId: z31.string(),
13488
+ mode: z31.enum(["snapshot", "append"]),
12596
13489
  status: PipelineStepRunStatusSchema,
12597
- startedAt: z30.string(),
12598
- finishedAt: z30.string().optional(),
12599
- inputs: z30.array(DatasetVersionRefSchema2),
13490
+ startedAt: z31.string(),
13491
+ finishedAt: z31.string().optional(),
13492
+ inputs: z31.array(DatasetVersionRefSchema2),
12600
13493
  output: DatasetVersionRefSchema2.optional(),
12601
- rowsWritten: z30.number().optional(),
13494
+ rowsWritten: z31.number().optional(),
12602
13495
  error: PipelineRunFailureSchema.optional()
12603
13496
  });
12604
- var PipelineStepSchema = z30.object({
12605
- id: z30.string(),
12606
- mode: z30.enum(["snapshot", "append"]),
13497
+ var PipelineStepSchema = z31.object({
13498
+ id: z31.string(),
13499
+ mode: z31.enum(["snapshot", "append"]),
12607
13500
  executor: PipelineStepExecutorSchema,
12608
- inputs: z30.array(z30.object({
12609
- name: z30.string(),
13501
+ inputs: z31.array(z31.object({
13502
+ name: z31.string(),
12610
13503
  dataset: DatasetDefinitionSchema
12611
13504
  })),
12612
13505
  output: DatasetDefinitionSchema
12613
13506
  });
12614
- var PipelineSchema = z30.object({
12615
- id: z30.string(),
12616
- triggers: z30.array(PipelineTriggerSchema),
12617
- graph: z30.object({
12618
- kind: z30.literal("sequence"),
12619
- nodes: z30.array(z30.object({
12620
- kind: z30.literal("step"),
13507
+ var PipelineSchema = z31.object({
13508
+ id: z31.string(),
13509
+ triggers: z31.array(PipelineTriggerSchema),
13510
+ graph: z31.object({
13511
+ kind: z31.literal("sequence"),
13512
+ nodes: z31.array(z31.object({
13513
+ kind: z31.literal("step"),
12621
13514
  step: PipelineStepSchema
12622
13515
  }))
12623
13516
  }),
12624
13517
  latestRun: PipelineRunSchema.nullable()
12625
13518
  });
12626
- var PipelineRunListResponseSchema = z30.object({
12627
- runs: z30.array(PipelineRunSchema),
12628
- hasMore: z30.boolean(),
12629
- total: z30.number()
13519
+ var PipelineRunListResponseSchema = z31.object({
13520
+ runs: z31.array(PipelineRunSchema),
13521
+ hasMore: z31.boolean(),
13522
+ total: z31.number()
12630
13523
  });
12631
- var PipelineRunDetailResponseSchema = z30.object({
13524
+ var PipelineRunDetailResponseSchema = z31.object({
12632
13525
  run: PipelineRunSchema,
12633
- steps: z30.array(PipelineStepRunSchema)
13526
+ steps: z31.array(PipelineStepRunSchema)
12634
13527
  });
12635
- var RequestPipelineRunResponseSchema = z30.object({
12636
- runId: z30.string(),
12637
- jobId: z30.string(),
12638
- pipelineId: z30.string(),
12639
- queuedAt: z30.string()
13528
+ var RequestPipelineRunResponseSchema = z31.object({
13529
+ runId: z31.string(),
13530
+ jobId: z31.string(),
13531
+ pipelineId: z31.string(),
13532
+ queuedAt: z31.string()
12640
13533
  });
12641
13534
 
12642
13535
  // src/routes/pipelines.ts
@@ -12646,6 +13539,7 @@ function serializePipelineRun(run) {
12646
13539
  projectId: run.projectId,
12647
13540
  pipelineId: run.pipelineId,
12648
13541
  status: run.status,
13542
+ attempt: run.attempt,
12649
13543
  queuedAt: toIsoString(run.queuedAt),
12650
13544
  startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
12651
13545
  finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
@@ -12862,11 +13756,11 @@ function registerPipelineRoutes(app, host) {
12862
13756
  }
12863
13757
 
12864
13758
  // src/schemas/project.ts
12865
- import { z as z31 } from "zod";
12866
- var ProjectInfoResponseSchema = z31.object({
12867
- id: z31.string(),
12868
- locale: z31.string(),
12869
- timeZone: z31.string()
13759
+ import { z as z32 } from "zod";
13760
+ var ProjectInfoResponseSchema = z32.object({
13761
+ id: z32.string(),
13762
+ locale: z32.string(),
13763
+ timeZone: z32.string()
12870
13764
  });
12871
13765
 
12872
13766
  // src/routes/project.ts
@@ -12885,10 +13779,10 @@ function registerProjectRoutes(app, host) {
12885
13779
 
12886
13780
  // src/schemas/projections.ts
12887
13781
  import { PROJECTION_RUN_FAILURE_CODES } from "@sixb/core/storage";
12888
- import { z as z32 } from "zod";
13782
+ import { z as z33 } from "zod";
12889
13783
  var ProjectionRunFailureSchema = sixbFailureSchema(PROJECTION_RUN_FAILURE_CODES);
12890
- var ProjectionKindSchema = z32.enum(["object", "link", "telemetry"]);
12891
- var ProjectionRunStatusSchema = z32.enum([
13784
+ var ProjectionKindSchema = z33.enum(["object", "link", "telemetry"]);
13785
+ var ProjectionRunStatusSchema = z33.enum([
12892
13786
  "queued",
12893
13787
  "running",
12894
13788
  "succeeded",
@@ -12896,139 +13790,139 @@ var ProjectionRunStatusSchema = z32.enum([
12896
13790
  "cancelled",
12897
13791
  "superseded"
12898
13792
  ]);
12899
- var ProjectionRunIdentityBaseSchema = z32.object({
12900
- projectionId: z32.string(),
12901
- datasetVersion: z32.object({
12902
- datasetId: z32.string(),
12903
- versionId: z32.string(),
12904
- createdAt: z32.string()
13793
+ var ProjectionRunIdentityBaseSchema = z33.object({
13794
+ projectionId: z33.string(),
13795
+ datasetVersion: z33.object({
13796
+ datasetId: z33.string(),
13797
+ versionId: z33.string(),
13798
+ createdAt: z33.string()
12905
13799
  }),
12906
- ontologyRevision: z32.string(),
12907
- projectionRevision: z32.string(),
12908
- ownershipHash: z32.string()
13800
+ ontologyRevision: z33.string(),
13801
+ projectionRevision: z33.string(),
13802
+ ownershipHash: z33.string()
12909
13803
  });
12910
- var ProjectionRunBaseSchema = z32.object({
12911
- id: z32.string(),
12912
- projectId: z32.string(),
12913
- executionId: z32.string(),
13804
+ var ProjectionRunBaseSchema = z33.object({
13805
+ id: z33.string(),
13806
+ projectId: z33.string(),
13807
+ executionId: z33.string(),
12914
13808
  status: ProjectionRunStatusSchema,
12915
- attempt: z32.number(),
12916
- progress: z32.object({
12917
- sourceRowsRead: z32.number(),
12918
- sourceRowsSkipped: z32.number(),
12919
- sourceChangesRead: z32.number().optional()
13809
+ attempt: z33.number(),
13810
+ progress: z33.object({
13811
+ sourceRowsRead: z33.number(),
13812
+ sourceRowsSkipped: z33.number(),
13813
+ sourceChangesRead: z33.number().optional()
12920
13814
  }),
12921
- queuedAt: z32.string(),
12922
- startedAt: z32.string().optional(),
12923
- finishedAt: z32.string().optional(),
13815
+ queuedAt: z33.string(),
13816
+ startedAt: z33.string().optional(),
13817
+ finishedAt: z33.string().optional(),
12924
13818
  error: ProjectionRunFailureSchema.optional()
12925
13819
  });
12926
13820
  var ObjectProjectionRunSchema = ProjectionRunBaseSchema.extend({
12927
13821
  identity: ProjectionRunIdentityBaseSchema.extend({
12928
- projectionKind: z32.literal("object"),
12929
- protocol: z32.literal("replacement")
13822
+ projectionKind: z33.literal("object"),
13823
+ protocol: z33.literal("replacement")
12930
13824
  }),
12931
- target: z32.object({ objectTypeId: z32.string() })
13825
+ target: z33.object({ objectTypeId: z33.string() })
12932
13826
  });
12933
13827
  var LinkProjectionRunSchema = ProjectionRunBaseSchema.extend({
12934
13828
  identity: ProjectionRunIdentityBaseSchema.extend({
12935
- projectionKind: z32.literal("link"),
12936
- protocol: z32.literal("replacement")
13829
+ projectionKind: z33.literal("link"),
13830
+ protocol: z33.literal("replacement")
12937
13831
  }),
12938
- target: z32.object({
12939
- sourceObjectTypeId: z32.string(),
12940
- targetObjectTypeId: z32.string()
13832
+ target: z33.object({
13833
+ sourceObjectTypeId: z33.string(),
13834
+ targetObjectTypeId: z33.string()
12941
13835
  })
12942
13836
  });
12943
13837
  var TelemetryProjectionRunSchema = ProjectionRunBaseSchema.extend({
12944
13838
  identity: ProjectionRunIdentityBaseSchema.extend({
12945
- projectionKind: z32.literal("telemetry"),
12946
- protocol: z32.literal("telemetry")
13839
+ projectionKind: z33.literal("telemetry"),
13840
+ protocol: z33.literal("telemetry")
12947
13841
  }),
12948
- target: z32.object({ objectTypeId: z32.string() })
13842
+ target: z33.object({ objectTypeId: z33.string() })
12949
13843
  });
12950
- var ProjectionRunSchema = z32.union([
13844
+ var ProjectionRunSchema = z33.union([
12951
13845
  ObjectProjectionRunSchema,
12952
13846
  LinkProjectionRunSchema,
12953
13847
  TelemetryProjectionRunSchema
12954
13848
  ]);
12955
- var ForeignKeyDescriptorSchema = z32.object({
12956
- linkId: z32.string(),
12957
- sourcePropertyId: z32.string().optional(),
12958
- sourceField: z32.string().optional(),
12959
- targetObjectTypeId: z32.string()
12960
- });
12961
- var SourceEditConflictResolutionSchema = z32.union([
12962
- z32.object({ strategy: z32.literal("editsWin") }),
12963
- z32.object({ strategy: z32.literal("mostRecent"), sourceTimestamp: z32.string() })
13849
+ var ForeignKeyDescriptorSchema = z33.object({
13850
+ linkId: z33.string(),
13851
+ sourcePropertyId: z33.string().optional(),
13852
+ sourceField: z33.string().optional(),
13853
+ targetObjectTypeId: z33.string()
13854
+ });
13855
+ var SourceEditConflictResolutionSchema = z33.union([
13856
+ z33.object({ strategy: z33.literal("editsWin") }),
13857
+ z33.object({ strategy: z33.literal("mostRecent"), sourceTimestamp: z33.string() })
12964
13858
  ]);
12965
- var ObjectProjectionSchema = z32.object({
12966
- _tag: z32.literal("ObjectProjectionDefinition"),
12967
- id: z32.string(),
12968
- objectTypeId: z32.string(),
12969
- datasetId: z32.string(),
12970
- properties: z32.record(z32.string()),
12971
- users: z32.record(z32.literal("email")).optional(),
12972
- links: z32.record(ForeignKeyDescriptorSchema),
13859
+ var ObjectProjectionSchema = z33.object({
13860
+ _tag: z33.literal("ObjectProjectionDefinition"),
13861
+ id: z33.string(),
13862
+ objectTypeId: z33.string(),
13863
+ datasetId: z33.string(),
13864
+ properties: z33.record(z33.string()),
13865
+ users: z33.record(z33.enum(["email", "id"])).optional(),
13866
+ links: z33.record(ForeignKeyDescriptorSchema),
12973
13867
  conflictResolution: SourceEditConflictResolutionSchema,
12974
13868
  latestRun: ProjectionRunSchema.nullable()
12975
13869
  });
12976
- var LinkProjectionSchema = z32.object({
12977
- _tag: z32.literal("LinkProjectionDefinition"),
12978
- id: z32.string(),
12979
- linkId: z32.string(),
12980
- sourceObjectTypeId: z32.string(),
12981
- targetObjectTypeId: z32.string(),
12982
- datasetId: z32.string(),
12983
- sourceField: z32.string(),
12984
- targetField: z32.string(),
13870
+ var LinkProjectionSchema = z33.object({
13871
+ _tag: z33.literal("LinkProjectionDefinition"),
13872
+ id: z33.string(),
13873
+ linkId: z33.string(),
13874
+ sourceObjectTypeId: z33.string(),
13875
+ targetObjectTypeId: z33.string(),
13876
+ datasetId: z33.string(),
13877
+ sourceField: z33.string(),
13878
+ targetField: z33.string(),
12985
13879
  latestRun: ProjectionRunSchema.nullable()
12986
13880
  });
12987
- var TelemetryProjectionSchema = z32.object({
12988
- _tag: z32.literal("TelemetryProjectionDefinition"),
12989
- id: z32.string(),
12990
- objectTypeId: z32.string(),
12991
- datasetId: z32.string(),
12992
- objectIdField: z32.string(),
12993
- atField: z32.string(),
12994
- properties: z32.record(z32.object({
12995
- valueField: z32.string(),
12996
- unitField: z32.string().optional()
13881
+ var TelemetryProjectionSchema = z33.object({
13882
+ _tag: z33.literal("TelemetryProjectionDefinition"),
13883
+ id: z33.string(),
13884
+ objectTypeId: z33.string(),
13885
+ datasetId: z33.string(),
13886
+ objectIdField: z33.string(),
13887
+ atField: z33.string(),
13888
+ properties: z33.record(z33.object({
13889
+ valueField: z33.string(),
13890
+ unitField: z33.string().optional()
12997
13891
  })),
12998
13892
  latestRun: ProjectionRunSchema.nullable()
12999
13893
  });
13000
- var ProjectionListResponseSchema = z32.object({
13001
- objectProjections: z32.array(ObjectProjectionSchema),
13002
- linkProjections: z32.array(LinkProjectionSchema),
13003
- telemetryProjections: z32.array(TelemetryProjectionSchema)
13894
+ var ProjectionListResponseSchema = z33.object({
13895
+ objectProjections: z33.array(ObjectProjectionSchema),
13896
+ linkProjections: z33.array(LinkProjectionSchema),
13897
+ telemetryProjections: z33.array(TelemetryProjectionSchema)
13004
13898
  });
13005
- var ProjectionParamsSchema = z32.object({
13006
- projectionId: z32.string().min(1)
13899
+ var ProjectionParamsSchema = z33.object({
13900
+ projectionId: z33.string().min(1)
13007
13901
  });
13008
- var ProjectionResponseSchema = z32.union([
13902
+ var ProjectionResponseSchema = z33.union([
13009
13903
  ObjectProjectionSchema,
13010
13904
  LinkProjectionSchema,
13011
13905
  TelemetryProjectionSchema
13012
13906
  ]);
13013
- var ProjectionRunParamsSchema = z32.object({
13014
- runId: z32.string().min(1)
13907
+ var ProjectionRunParamsSchema = z33.object({
13908
+ runId: z33.string().min(1)
13015
13909
  });
13016
- var ProjectionRunsQuerySchema = z32.object({
13017
- projectionId: z32.string().optional(),
13910
+ var ProjectionRunsQuerySchema = z33.object({
13911
+ projectionId: z33.string().optional(),
13018
13912
  projectionKind: ProjectionKindSchema.optional(),
13019
- datasetId: z32.string().optional(),
13020
- datasetVersionId: z32.string().optional(),
13913
+ datasetId: z33.string().optional(),
13914
+ datasetVersionId: z33.string().optional(),
13021
13915
  status: ProjectionRunStatusSchema.optional(),
13022
- startedAfter: z32.string().optional(),
13023
- startedBefore: z32.string().optional(),
13024
- limit: z32.string().optional(),
13025
- offset: z32.string().optional(),
13026
- order: z32.enum(["asc", "desc"]).optional()
13916
+ startedAfter: z33.string().optional(),
13917
+ startedBefore: z33.string().optional(),
13918
+ limit: z33.string().optional(),
13919
+ offset: z33.string().optional(),
13920
+ order: z33.enum(["asc", "desc"]).optional()
13027
13921
  });
13028
- var ProjectionRunListResponseSchema = z32.object({
13029
- runs: z32.array(ProjectionRunSchema),
13030
- hasMore: z32.boolean(),
13031
- total: z32.number()
13922
+ var ProjectionRunListResponseSchema = z33.object({
13923
+ runs: z33.array(ProjectionRunSchema),
13924
+ hasMore: z33.boolean(),
13925
+ total: z33.number()
13032
13926
  });
13033
13927
 
13034
13928
  // src/routes/projections.ts
@@ -13196,88 +14090,88 @@ function registerProjectionRoutes(app, host) {
13196
14090
  import { deriveRuleEventDependencies } from "@sixb/core/internal/rules";
13197
14091
 
13198
14092
  // src/schemas/rules.ts
13199
- import { z as z33 } from "zod";
13200
- var RuleParamsSchema = z33.object({
13201
- ruleId: z33.string().min(1)
13202
- });
13203
- var RuleStatesQuerySchema = z33.object({
13204
- ruleId: z33.string().optional(),
13205
- objectTypeId: z33.string().optional(),
13206
- primaryId: z33.string().optional(),
13207
- limit: z33.string().optional(),
13208
- offset: z33.string().optional(),
13209
- order: z33.enum(["asc", "desc"]).optional()
13210
- });
13211
- var RuleValueSchema = z33.union([z33.string(), z33.number(), z33.boolean()]).nullable();
13212
- var RuleSubjectSchema = z33.object({
13213
- kind: z33.literal("object"),
13214
- objectTypeId: z33.string()
13215
- });
13216
- var RuleEventSubjectSchema = z33.object({
13217
- kind: z33.literal("object"),
13218
- objectTypeId: z33.string(),
13219
- primaryId: z33.string()
13220
- });
13221
- var RulePropertyPredicateSchema = z33.object({
13222
- kind: z33.literal("property"),
13223
- propertyId: z33.string(),
13224
- op: z33.enum(["eq", "notEq", "gt", "gte", "lt", "lte", "isPresent", "isMissing"]),
14093
+ import { z as z34 } from "zod";
14094
+ var RuleParamsSchema = z34.object({
14095
+ ruleId: z34.string().min(1)
14096
+ });
14097
+ var RuleStatesQuerySchema = z34.object({
14098
+ ruleId: z34.string().optional(),
14099
+ objectTypeId: z34.string().optional(),
14100
+ primaryId: z34.string().optional(),
14101
+ limit: z34.string().optional(),
14102
+ offset: z34.string().optional(),
14103
+ order: z34.enum(["asc", "desc"]).optional()
14104
+ });
14105
+ var RuleValueSchema = z34.union([z34.string(), z34.number(), z34.boolean()]).nullable();
14106
+ var RuleSubjectSchema = z34.object({
14107
+ kind: z34.literal("object"),
14108
+ objectTypeId: z34.string()
14109
+ });
14110
+ var RuleEventSubjectSchema = z34.object({
14111
+ kind: z34.literal("object"),
14112
+ objectTypeId: z34.string(),
14113
+ primaryId: z34.string()
14114
+ });
14115
+ var RulePropertyPredicateSchema = z34.object({
14116
+ kind: z34.literal("property"),
14117
+ propertyId: z34.string(),
14118
+ op: z34.enum(["eq", "notEq", "gt", "gte", "lt", "lte", "isPresent", "isMissing"]),
13225
14119
  value: RuleValueSchema.optional()
13226
14120
  });
13227
- var RuleLinkPredicateSchema = z33.object({
13228
- kind: z33.literal("link"),
13229
- linkId: z33.string(),
13230
- op: z33.enum(["exists", "isMissing"])
14121
+ var RuleLinkPredicateSchema = z34.object({
14122
+ kind: z34.literal("link"),
14123
+ linkId: z34.string(),
14124
+ op: z34.enum(["exists", "isMissing"])
13231
14125
  });
13232
14126
  function createRulePredicateSchema(childPredicateSchema) {
13233
- return z33.union([
13234
- z33.object({
13235
- kind: z33.literal("all"),
13236
- predicates: z33.array(childPredicateSchema)
14127
+ return z34.union([
14128
+ z34.object({
14129
+ kind: z34.literal("all"),
14130
+ predicates: z34.array(childPredicateSchema)
13237
14131
  }),
13238
- z33.object({
13239
- kind: z33.literal("any"),
13240
- predicates: z33.array(childPredicateSchema)
14132
+ z34.object({
14133
+ kind: z34.literal("any"),
14134
+ predicates: z34.array(childPredicateSchema)
13241
14135
  }),
13242
- z33.object({
13243
- kind: z33.literal("not"),
14136
+ z34.object({
14137
+ kind: z34.literal("not"),
13244
14138
  predicate: childPredicateSchema
13245
14139
  }),
13246
14140
  RulePropertyPredicateSchema,
13247
14141
  RuleLinkPredicateSchema
13248
14142
  ]);
13249
14143
  }
13250
- var DeepRulePredicateSchema = createRulePredicateSchema(z33.unknown());
14144
+ var DeepRulePredicateSchema = createRulePredicateSchema(z34.unknown());
13251
14145
  var NestedRulePredicateSchema = createRulePredicateSchema(DeepRulePredicateSchema);
13252
14146
  var RulePredicateSchema = NestedRulePredicateSchema;
13253
- var RuleEventDependencySchema = z33.union([
13254
- z33.object({
13255
- type: z33.enum(["object.created", "object.updated", "object.deleted"]),
13256
- objectTypeId: z33.string()
14147
+ var RuleEventDependencySchema = z34.union([
14148
+ z34.object({
14149
+ type: z34.enum(["object.created", "object.updated", "object.deleted"]),
14150
+ objectTypeId: z34.string()
13257
14151
  }),
13258
- z33.object({
13259
- type: z33.enum(["link.created", "link.updated", "link.deleted"]),
13260
- sourceTypeId: z33.string(),
13261
- linkId: z33.string()
14152
+ z34.object({
14153
+ type: z34.enum(["link.created", "link.updated", "link.deleted"]),
14154
+ sourceTypeId: z34.string(),
14155
+ linkId: z34.string()
13262
14156
  })
13263
14157
  ]);
13264
- var RuleSchema = z33.object({
13265
- kind: z33.literal("rule"),
13266
- id: z33.string(),
14158
+ var RuleSchema = z34.object({
14159
+ kind: z34.literal("rule"),
14160
+ id: z34.string(),
13267
14161
  subject: RuleSubjectSchema,
13268
14162
  predicate: RulePredicateSchema,
13269
- dependencies: z33.array(RuleEventDependencySchema)
14163
+ dependencies: z34.array(RuleEventDependencySchema)
13270
14164
  });
13271
- var RuleStateSchema = z33.object({
13272
- projectId: z33.string(),
13273
- ruleId: z33.string(),
14165
+ var RuleStateSchema = z34.object({
14166
+ projectId: z34.string(),
14167
+ ruleId: z34.string(),
13274
14168
  subject: RuleEventSubjectSchema,
13275
- triggeredAt: z33.string()
14169
+ triggeredAt: z34.string()
13276
14170
  });
13277
- var RuleStateListResponseSchema = z33.object({
13278
- states: z33.array(RuleStateSchema),
13279
- hasMore: z33.boolean(),
13280
- total: z33.number()
14171
+ var RuleStateListResponseSchema = z34.object({
14172
+ states: z34.array(RuleStateSchema),
14173
+ hasMore: z34.boolean(),
14174
+ total: z34.number()
13281
14175
  });
13282
14176
 
13283
14177
  // src/routes/rules.ts
@@ -13358,52 +14252,52 @@ function registerRuleRoutes(app, host) {
13358
14252
 
13359
14253
  // src/routes/share-grants.ts
13360
14254
  import {
13361
- AuthorizationError as AuthorizationError5,
14255
+ AuthorizationError as AuthorizationError6,
13362
14256
  ShareError
13363
14257
  } from "@sixb/core";
13364
14258
  import { ObjectNotFoundError as ObjectNotFoundError2 } from "@sixb/core/storage";
13365
14259
 
13366
14260
  // src/schemas/share-grants.ts
13367
- import { z as z34 } from "zod";
13368
- var StoredIdentifierSchema = z34.string().min(1).refine(isStoredIdentifier2, {
14261
+ import { z as z35 } from "zod";
14262
+ var StoredIdentifierSchema = z35.string().min(1).refine(isStoredIdentifier2, {
13369
14263
  message: "stored identifier must not be blank or contain NUL bytes"
13370
14264
  });
13371
- var Rfc3339DateSchema2 = z34.string().datetime({ offset: true });
13372
- var DestinationPathSchema = z34.string().min(1).max(4096);
13373
- var QueryBooleanSchema = z34.preprocess((value) => {
14265
+ var Rfc3339DateSchema2 = z35.string().datetime({ offset: true });
14266
+ var DestinationPathSchema = z35.string().min(1).max(4096);
14267
+ var QueryBooleanSchema = z35.preprocess((value) => {
13374
14268
  if (value === "true" || value === true)
13375
14269
  return true;
13376
14270
  if (value === "false" || value === false)
13377
14271
  return false;
13378
14272
  return value;
13379
- }, z34.boolean());
13380
- var ShareGrantListLimitSchema = z34.preprocess(parseUnsignedQueryInteger, z34.number().int().min(1).max(200));
13381
- var ShareGrantListOffsetSchema = z34.preprocess(parseUnsignedQueryInteger, z34.number().int().min(0).max(Number.MAX_SAFE_INTEGER));
14273
+ }, z35.boolean());
14274
+ var ShareGrantListLimitSchema = z35.preprocess(parseUnsignedQueryInteger, z35.number().int().min(1).max(200));
14275
+ var ShareGrantListOffsetSchema = z35.preprocess(parseUnsignedQueryInteger, z35.number().int().min(0).max(Number.MAX_SAFE_INTEGER));
13382
14276
  function parseUnsignedQueryInteger(value) {
13383
14277
  if (typeof value !== "string" || !/^\d+$/.test(value))
13384
14278
  return value;
13385
14279
  const parsed = Number(value);
13386
14280
  return Number.isSafeInteger(parsed) ? parsed : value;
13387
14281
  }
13388
- var ShareGrantTargetSchema = z34.object({
14282
+ var ShareGrantTargetSchema = z35.object({
13389
14283
  objectTypeId: StoredIdentifierSchema,
13390
14284
  primaryId: StoredIdentifierSchema
13391
14285
  });
13392
- var ShareGrantTargetInputSchema = z34.object({
14286
+ var ShareGrantTargetInputSchema = z35.object({
13393
14287
  objectTypeId: StoredIdentifierSchema,
13394
- primaryId: z34.string().min(1).refine(isStoredIdentifier2, {
14288
+ primaryId: z35.string().min(1).refine(isStoredIdentifier2, {
13395
14289
  message: "primaryId must not be blank or contain NUL bytes"
13396
14290
  })
13397
14291
  });
13398
- var AuthorizablePrincipalSchema = z34.object({
13399
- type: z34.enum(["user", "serviceAccount"]),
14292
+ var AuthorizablePrincipalSchema = z35.object({
14293
+ type: z35.enum(["user", "serviceAccount"]),
13400
14294
  id: StoredIdentifierSchema
13401
14295
  });
13402
- var PrincipalSchema2 = z34.object({
13403
- type: z34.enum(["user", "serviceAccount", "system"]),
14296
+ var PrincipalSchema2 = z35.object({
14297
+ type: z35.enum(["user", "serviceAccount", "system"]),
13404
14298
  id: StoredIdentifierSchema
13405
14299
  });
13406
- var SharedAccessGrantSchema = z34.object({
14300
+ var SharedAccessGrantSchema = z35.object({
13407
14301
  id: StoredIdentifierSchema,
13408
14302
  definitionId: StoredIdentifierSchema,
13409
14303
  target: ShareGrantTargetSchema,
@@ -13414,19 +14308,19 @@ var SharedAccessGrantSchema = z34.object({
13414
14308
  revokedAt: Rfc3339DateSchema2.optional(),
13415
14309
  revokedBy: PrincipalSchema2.optional()
13416
14310
  });
13417
- var IssueSharedAccessGrantBodySchema = z34.object({
14311
+ var IssueSharedAccessGrantBodySchema = z35.object({
13418
14312
  definitionId: StoredIdentifierSchema,
13419
14313
  target: ShareGrantTargetInputSchema,
13420
14314
  destinationPath: DestinationPathSchema,
13421
14315
  expiresAt: Rfc3339DateSchema2
13422
14316
  });
13423
- var IssueSharedAccessGrantResponseSchema = z34.object({
14317
+ var IssueSharedAccessGrantResponseSchema = z35.object({
13424
14318
  grant: SharedAccessGrantSchema,
13425
- url: z34.string().startsWith("/shared/")
14319
+ url: z35.string().startsWith("/shared/")
13426
14320
  });
13427
- var ListSharedAccessGrantsQuerySchema = z34.object({
14321
+ var ListSharedAccessGrantsQuerySchema = z35.object({
13428
14322
  definitionId: StoredIdentifierSchema,
13429
- primaryId: z34.string().min(1).refine(isStoredIdentifier2, {
14323
+ primaryId: z35.string().min(1).refine(isStoredIdentifier2, {
13430
14324
  message: "primaryId must not be blank or contain NUL bytes"
13431
14325
  }).optional(),
13432
14326
  includeRevoked: QueryBooleanSchema.optional(),
@@ -13434,15 +14328,15 @@ var ListSharedAccessGrantsQuerySchema = z34.object({
13434
14328
  limit: ShareGrantListLimitSchema.optional(),
13435
14329
  offset: ShareGrantListOffsetSchema.optional()
13436
14330
  });
13437
- var ListSharedAccessGrantsResponseSchema = z34.object({
13438
- grants: z34.array(SharedAccessGrantSchema),
13439
- hasMore: z34.boolean(),
13440
- total: z34.number().int().nonnegative()
14331
+ var ListSharedAccessGrantsResponseSchema = z35.object({
14332
+ grants: z35.array(SharedAccessGrantSchema),
14333
+ hasMore: z35.boolean(),
14334
+ total: z35.number().int().nonnegative()
13441
14335
  });
13442
- var SharedAccessGrantIdParamsSchema = z34.object({
14336
+ var SharedAccessGrantIdParamsSchema = z35.object({
13443
14337
  grantId: StoredIdentifierSchema
13444
14338
  });
13445
- var RevokeSharedAccessGrantResponseSchema = z34.object({
14339
+ var RevokeSharedAccessGrantResponseSchema = z35.object({
13446
14340
  grant: SharedAccessGrantSchema
13447
14341
  });
13448
14342
  function isStoredIdentifier2(value) {
@@ -13590,7 +14484,7 @@ function handleShareGrantRouteError(error, set) {
13590
14484
  return { error: "Authentication required." };
13591
14485
  return { error: error.message };
13592
14486
  }
13593
- if (error instanceof AuthorizationError5) {
14487
+ if (error instanceof AuthorizationError6) {
13594
14488
  set.status = 403;
13595
14489
  return { error: error.message };
13596
14490
  }
@@ -13638,27 +14532,35 @@ function setNoStore(set) {
13638
14532
  set.headers["cache-control"] = "no-store";
13639
14533
  }
13640
14534
 
14535
+ // src/routes/shared-access.ts
14536
+ import { GUEST_NAME_MAX_LENGTH } from "@sixb/core/internal/shares";
14537
+
13641
14538
  // src/schemas/shared-access.ts
13642
- import { z as z35 } from "zod";
13643
- var StoredIdentifierSchema2 = z35.string().min(1).max(128).refine((value) => value.trim() === value && !value.includes("\x00"), {
14539
+ import { z as z36 } from "zod";
14540
+ var StoredIdentifierSchema2 = z36.string().min(1).max(128).refine((value) => value.trim() === value && !value.includes("\x00"), {
13644
14541
  message: "stored identifier must not be blank or contain NUL bytes"
13645
14542
  });
13646
- var Rfc3339DateSchema3 = z35.string().datetime({ offset: true });
13647
- var SharedAccessGrantParamsSchema = z35.object({
14543
+ var Rfc3339DateSchema3 = z36.string().datetime({ offset: true });
14544
+ var SharedAccessGrantParamsSchema = z36.object({
13648
14545
  grantId: StoredIdentifierSchema2
13649
14546
  });
13650
- var ExchangeSharedAccessBodySchema = z35.object({
13651
- secret: z35.string().regex(/^[A-Za-z0-9_-]{43}$/)
14547
+ var ExchangeSharedAccessBodySchema = z36.object({
14548
+ secret: z36.string().regex(/^[A-Za-z0-9_-]{43}$/)
13652
14549
  });
13653
- var SharedAccessSessionResponseSchema = z35.object({
14550
+ var SharedAccessSessionResponseSchema = z36.object({
13654
14551
  grantId: StoredIdentifierSchema2,
13655
- destinationPath: z35.string().min(1).max(4096),
14552
+ destinationPath: z36.string().min(1).max(4096),
13656
14553
  expiresAt: Rfc3339DateSchema3,
13657
14554
  absoluteExpiresAt: Rfc3339DateSchema3,
13658
- csrfToken: z35.string().regex(/^[A-Za-z0-9_-]{43}$/)
14555
+ csrfToken: z36.string().regex(/^[A-Za-z0-9_-]{43}$/),
14556
+ guestId: StoredIdentifierSchema2.describe("Who the visitor is in this session: the author id of the comments they write as a guest"),
14557
+ guestName: z36.string().optional().describe("The name the visitor gave, which their comments and live presence carry")
14558
+ });
14559
+ var SetSharedAccessGuestNameBodySchema = z36.object({
14560
+ name: z36.string().max(1000).describe("The visitor's name, on one line: 1 to 60 characters once its spaces are collapsed, without control or direction marks")
13659
14561
  });
13660
- var SharedAccessSignOutResponseSchema = z35.object({
13661
- signedOut: z35.literal(true)
14562
+ var SharedAccessSignOutResponseSchema = z36.object({
14563
+ signedOut: z36.literal(true)
13662
14564
  });
13663
14565
 
13664
14566
  // src/routes/shared-access.ts
@@ -13711,6 +14613,43 @@ function registerSharedAccessRoutes(app, boundary) {
13711
14613
  operationId: "getSharedAccessSession",
13712
14614
  security: []
13713
14615
  }
14616
+ }).put("/api/shared-access/:grantId/name", async ({ body, params, request }) => {
14617
+ try {
14618
+ const result = await boundary.setGuestName(request, params.grantId, body.name);
14619
+ switch (result.kind) {
14620
+ case "csrf":
14621
+ return sharedAccessForbiddenResponse();
14622
+ case "invalid":
14623
+ return withSetCookies(sharedAccessUnauthenticatedResponse(), result.setCookies);
14624
+ case "unnamed":
14625
+ return sharedBoundaryJsonResponse({
14626
+ error: `A name holds 1 to ${GUEST_NAME_MAX_LENGTH} characters on one line.`,
14627
+ code: "invalid_name"
14628
+ }, 400);
14629
+ case "named":
14630
+ return sharedSessionResponse(result.context, result.cookies);
14631
+ }
14632
+ } catch {
14633
+ return sharedAccessUnavailableResponse();
14634
+ }
14635
+ }, {
14636
+ params: SharedAccessGrantParamsSchema,
14637
+ body: SetSharedAccessGuestNameBodySchema,
14638
+ response: {
14639
+ 200: SharedAccessSessionResponseSchema,
14640
+ 400: ErrorResponseSchema,
14641
+ 401: ErrorResponseSchema,
14642
+ 403: ErrorResponseSchema,
14643
+ 503: ErrorResponseSchema
14644
+ },
14645
+ error: sharedAccessRouteError,
14646
+ detail: {
14647
+ summary: "Name a shared-access session's visitor",
14648
+ description: "The visitor of a shared link has no account: they give their name once, and their comments and live presence carry it, marked as a guest's. Giving it again replaces it for what comes next; comments keep the name they were written under.",
14649
+ tags: [OPENAPI_TAGS.sharedAccess.name],
14650
+ operationId: "setSharedAccessGuestName",
14651
+ security: [{ [SIXB_CSRF_SECURITY_SCHEME_ID]: [] }, {}]
14652
+ }
13714
14653
  }).post("/api/shared-access/:grantId/sign-out", async ({ params, request }) => {
13715
14654
  try {
13716
14655
  const result = await boundary.signOut(request, params.grantId);
@@ -13754,7 +14693,9 @@ function sharedSessionResponse(context, cookies) {
13754
14693
  destinationPath: context.destinationPath,
13755
14694
  expiresAt: context.expiresAt.toISOString(),
13756
14695
  absoluteExpiresAt: context.absoluteExpiresAt.toISOString(),
13757
- csrfToken: cookies.csrfToken
14696
+ csrfToken: cookies.csrfToken,
14697
+ guestId: context.sessionId,
14698
+ ...context.guestName === undefined ? {} : { guestName: context.guestName }
13758
14699
  }), { status: 200, headers });
13759
14700
  }
13760
14701
  function withSetCookies(response, setCookies) {
@@ -13778,40 +14719,36 @@ function isRecord(value) {
13778
14719
  }
13779
14720
 
13780
14721
  // src/schemas/status.ts
13781
- import { z as z36 } from "zod";
13782
- var HealthResponseSchema = z36.object({ status: z36.literal("ok") });
13783
- var StorageReadinessSchema = z36.object({
13784
- reachable: z36.boolean(),
13785
- schemaValid: z36.boolean()
14722
+ import { z as z37 } from "zod";
14723
+ var HealthResponseSchema = z37.object({ status: z37.literal("ok") });
14724
+ var StorageReadinessSchema = z37.object({
14725
+ reachable: z37.boolean(),
14726
+ schemaValid: z37.boolean()
13786
14727
  });
13787
- var ReadinessResponseSchema = z36.object({
13788
- status: z36.enum(["ready", "unready"]),
14728
+ var ReadinessResponseSchema = z37.object({
14729
+ status: z37.enum(["ready", "unready"]),
13789
14730
  storage: StorageReadinessSchema,
13790
- reason: z36.string().optional()
13791
- });
13792
- var MaintenanceSummarySchema = z36.object({
13793
- running: z36.boolean(),
13794
- intervalMs: z36.number().int().positive(),
13795
- lastStartedAt: z36.string().nullable(),
13796
- lastCompletedAt: z36.string().nullable(),
13797
- lastDurationMs: z36.number().nonnegative().nullable(),
13798
- consecutiveFailures: z36.number().int().nonnegative(),
13799
- lastError: z36.string().nullable(),
13800
- outbox: z36.object({
13801
- pendingCount: z36.number().int().nonnegative(),
13802
- oldestPendingAt: z36.string().nullable(),
13803
- retryingCount: z36.number().int().nonnegative(),
13804
- maxAttempts: z36.number().int().nonnegative()
13805
- }).nullable(),
13806
- cleanup: z36.object({
13807
- publishedOutboxRowsDeleted: z36.number().int().nonnegative(),
13808
- terminalSourceRowsDeleted: z36.number().int().nonnegative(),
13809
- terminalSourceMaterializationsDeleted: z36.number().int().nonnegative()
13810
- }).nullable()
13811
- });
13812
- var StatusResponseSchema = z36.object({
13813
- status: z36.enum(["ok", "degraded"]),
13814
- objectTypes: z36.number().int().nonnegative(),
14731
+ reason: z37.string().optional()
14732
+ });
14733
+ var MaintenanceSummarySchema = z37.object({
14734
+ owner: z37.enum(["orchestrator", "embedded"]).nullable(),
14735
+ beatAt: z37.string().nullable(),
14736
+ stale: z37.boolean(),
14737
+ passes: z37.array(z37.object({
14738
+ id: z37.string(),
14739
+ lastSucceededAt: z37.string().nullable(),
14740
+ consecutiveFailures: z37.number().int().nonnegative()
14741
+ })),
14742
+ outbox: z37.object({
14743
+ pendingCount: z37.number().int().nonnegative(),
14744
+ oldestPendingAt: z37.string().nullable(),
14745
+ retryingCount: z37.number().int().nonnegative(),
14746
+ maxAttempts: z37.number().int().nonnegative()
14747
+ })
14748
+ });
14749
+ var StatusResponseSchema = z37.object({
14750
+ status: z37.enum(["ok", "degraded", "unknown"]),
14751
+ objectTypes: z37.number().int().nonnegative(),
13815
14752
  maintenance: MaintenanceSummarySchema
13816
14753
  });
13817
14754
 
@@ -13840,10 +14777,14 @@ function registerStatusRoutes(app, host) {
13840
14777
  operationId: "getReadiness"
13841
14778
  }
13842
14779
  });
13843
- return app.get("/api/status", async () => ({
13844
- ...host.getOntologyOperationalStatus(),
13845
- objectTypes: host.definitions.ontology.listObjectTypes().length
13846
- }), {
14780
+ return app.get("/api/status", async () => {
14781
+ const { status, maintenance } = await host.getOntologyOperationalStatus();
14782
+ return {
14783
+ status,
14784
+ objectTypes: host.definitions.ontology.listObjectTypes().length,
14785
+ maintenance: { ...maintenance, passes: [...maintenance.passes] }
14786
+ };
14787
+ }, {
13847
14788
  response: { 200: StatusResponseSchema },
13848
14789
  detail: {
13849
14790
  summary: "Get runtime status",
@@ -13857,74 +14798,75 @@ function registerStatusRoutes(app, host) {
13857
14798
  import {
13858
14799
  SYNC_RUN_FAILURE_CODES
13859
14800
  } from "@sixb/core/storage";
13860
- import { z as z37 } from "zod";
14801
+ import { z as z38 } from "zod";
13861
14802
  var SyncRunFailureSchema = sixbFailureSchema(SYNC_RUN_FAILURE_CODES);
13862
- var SyncParamsSchema = z37.object({
13863
- syncId: z37.string().min(1)
13864
- });
13865
- var SyncRunStatusSchema = z37.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
13866
- var SyncModeSchema = z37.enum(["snapshot", "append", "merge"]);
13867
- var SyncRunsQuerySchema = z37.object({
13868
- syncId: z37.string().optional(),
13869
- datasetId: z37.string().optional(),
14803
+ var SyncParamsSchema = z38.object({
14804
+ syncId: z38.string().min(1)
14805
+ });
14806
+ var SyncRunStatusSchema = z38.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
14807
+ var SyncModeSchema = z38.enum(["snapshot", "append", "merge"]);
14808
+ var SyncRunsQuerySchema = z38.object({
14809
+ syncId: z38.string().optional(),
14810
+ datasetId: z38.string().optional(),
13870
14811
  status: SyncRunStatusSchema.optional(),
13871
- startedAfter: z37.string().optional(),
13872
- startedBefore: z37.string().optional(),
13873
- limit: z37.string().optional(),
13874
- offset: z37.string().optional(),
13875
- order: z37.enum(["asc", "desc"]).optional()
13876
- });
13877
- var RequestSyncRunBodySchema = z37.object({
13878
- expectedLatestVersionId: z37.string().optional(),
13879
- commitMessage: z37.string().optional()
13880
- });
13881
- var SyncTriggerSchema = z37.object({
13882
- type: z37.literal("schedule"),
13883
- scheduleId: z37.string()
13884
- });
13885
- var SyncRunSchema = z37.object({
13886
- id: z37.string(),
13887
- projectId: z37.string(),
13888
- syncId: z37.string(),
13889
- datasetId: z37.string(),
14812
+ startedAfter: z38.string().optional(),
14813
+ startedBefore: z38.string().optional(),
14814
+ limit: z38.string().optional(),
14815
+ offset: z38.string().optional(),
14816
+ order: z38.enum(["asc", "desc"]).optional()
14817
+ });
14818
+ var RequestSyncRunBodySchema = z38.object({
14819
+ expectedLatestVersionId: z38.string().optional(),
14820
+ commitMessage: z38.string().optional()
14821
+ });
14822
+ var SyncTriggerSchema = z38.object({
14823
+ type: z38.literal("schedule"),
14824
+ scheduleId: z38.string()
14825
+ });
14826
+ var SyncRunSchema = z38.object({
14827
+ id: z38.string(),
14828
+ projectId: z38.string(),
14829
+ syncId: z38.string(),
14830
+ datasetId: z38.string(),
13890
14831
  mode: SyncModeSchema,
13891
14832
  status: SyncRunStatusSchema,
13892
- queuedAt: z37.string(),
13893
- startedAt: z37.string().optional(),
13894
- finishedAt: z37.string().optional(),
13895
- rowsRead: z37.number().optional(),
13896
- output: z37.object({
13897
- datasetId: z37.string(),
13898
- versionId: z37.string()
14833
+ attempt: z38.number(),
14834
+ queuedAt: z38.string(),
14835
+ startedAt: z38.string().optional(),
14836
+ finishedAt: z38.string().optional(),
14837
+ rowsRead: z38.number().optional(),
14838
+ output: z38.object({
14839
+ datasetId: z38.string(),
14840
+ versionId: z38.string()
13899
14841
  }).optional(),
13900
- expectedLatestVersionId: z37.string().optional(),
13901
- commitMessage: z37.string().optional(),
14842
+ expectedLatestVersionId: z38.string().optional(),
14843
+ commitMessage: z38.string().optional(),
13902
14844
  error: SyncRunFailureSchema.optional()
13903
14845
  });
13904
- var SyncSchema = z37.object({
13905
- id: z37.string(),
14846
+ var SyncSchema = z38.object({
14847
+ id: z38.string(),
13906
14848
  mode: SyncModeSchema,
13907
- connector: z37.object({
13908
- id: z37.string(),
13909
- type: z37.string()
14849
+ connector: z38.object({
14850
+ id: z38.string(),
14851
+ type: z38.string()
13910
14852
  }),
13911
- target: z37.object({
13912
- kind: z37.literal("dataset"),
14853
+ target: z38.object({
14854
+ kind: z38.literal("dataset"),
13913
14855
  dataset: DatasetDefinitionSchema
13914
14856
  }),
13915
- triggers: z37.array(SyncTriggerSchema),
14857
+ triggers: z38.array(SyncTriggerSchema),
13916
14858
  latestRun: SyncRunSchema.nullable()
13917
14859
  });
13918
- var SyncRunListResponseSchema = z37.object({
13919
- runs: z37.array(SyncRunSchema),
13920
- hasMore: z37.boolean(),
13921
- total: z37.number()
14860
+ var SyncRunListResponseSchema = z38.object({
14861
+ runs: z38.array(SyncRunSchema),
14862
+ hasMore: z38.boolean(),
14863
+ total: z38.number()
13922
14864
  });
13923
- var RequestSyncRunResponseSchema = z37.object({
13924
- runId: z37.string(),
13925
- jobId: z37.string(),
13926
- syncId: z37.string(),
13927
- queuedAt: z37.string()
14865
+ var RequestSyncRunResponseSchema = z38.object({
14866
+ runId: z38.string(),
14867
+ jobId: z38.string(),
14868
+ syncId: z38.string(),
14869
+ queuedAt: z38.string()
13928
14870
  });
13929
14871
 
13930
14872
  // src/routes/syncs.ts
@@ -13936,6 +14878,7 @@ function serializeSyncRun(run) {
13936
14878
  datasetId: run.datasetId,
13937
14879
  mode: run.mode,
13938
14880
  status: run.status,
14881
+ attempt: run.attempt,
13939
14882
  queuedAt: toIsoString(run.queuedAt),
13940
14883
  startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
13941
14884
  finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
@@ -14081,47 +15024,47 @@ function registerSyncRoutes(app, host) {
14081
15024
  }
14082
15025
 
14083
15026
  // src/schemas/telemetry.ts
14084
- import { z as z38 } from "zod";
14085
- var TelemetryParamsSchema = z38.object({
14086
- objectTypeId: z38.string().min(1),
14087
- objectId: z38.string().min(1),
14088
- propertyId: z38.string().min(1)
14089
- });
14090
- var TelemetryHistoryQuerySchema = z38.object({
14091
- from: z38.string().optional(),
14092
- to: z38.string().optional(),
14093
- limit: z38.string().optional(),
14094
- order: z38.enum(["asc", "desc"]).optional()
14095
- });
14096
- var BulkTelemetryHistorySeriesInputSchema = z38.object({
14097
- objectTypeId: z38.string().min(1),
14098
- objectId: z38.string().min(1),
14099
- propertyId: z38.string().min(1)
15027
+ import { z as z39 } from "zod";
15028
+ var TelemetryParamsSchema = z39.object({
15029
+ objectTypeId: z39.string().min(1),
15030
+ objectId: z39.string().min(1),
15031
+ propertyId: z39.string().min(1)
15032
+ });
15033
+ var TelemetryHistoryQuerySchema = z39.object({
15034
+ from: z39.string().optional(),
15035
+ to: z39.string().optional(),
15036
+ limit: z39.string().optional(),
15037
+ order: z39.enum(["asc", "desc"]).optional()
15038
+ });
15039
+ var BulkTelemetryHistorySeriesInputSchema = z39.object({
15040
+ objectTypeId: z39.string().min(1),
15041
+ objectId: z39.string().min(1),
15042
+ propertyId: z39.string().min(1)
14100
15043
  }).strict();
14101
- var BulkTelemetryHistoryBodySchema = z38.object({
14102
- series: z38.array(BulkTelemetryHistorySeriesInputSchema).min(1),
14103
- from: z38.string().optional(),
14104
- to: z38.string().optional(),
14105
- limitPerSeries: z38.number().int().nonnegative().optional(),
14106
- order: z38.enum(["asc", "desc"]).optional()
15044
+ var BulkTelemetryHistoryBodySchema = z39.object({
15045
+ series: z39.array(BulkTelemetryHistorySeriesInputSchema).min(1),
15046
+ from: z39.string().optional(),
15047
+ to: z39.string().optional(),
15048
+ limitPerSeries: z39.number().int().nonnegative().optional(),
15049
+ order: z39.enum(["asc", "desc"]).optional()
14107
15050
  }).strict();
14108
- var TelemetryPointSchema = z38.object({
14109
- projectId: z38.string(),
14110
- objectTypeId: z38.string(),
14111
- objectId: z38.string(),
14112
- propertyId: z38.string(),
14113
- value: z38.unknown(),
14114
- unit: z38.string().optional(),
14115
- at: z38.string()
14116
- });
14117
- var BulkTelemetryHistorySeriesSchema = z38.object({
14118
- objectTypeId: z38.string(),
14119
- objectId: z38.string(),
14120
- propertyId: z38.string(),
14121
- points: z38.array(TelemetryPointSchema)
14122
- });
14123
- var BulkTelemetryHistoryResponseSchema = z38.object({
14124
- series: z38.array(BulkTelemetryHistorySeriesSchema)
15051
+ var TelemetryPointSchema = z39.object({
15052
+ projectId: z39.string(),
15053
+ objectTypeId: z39.string(),
15054
+ objectId: z39.string(),
15055
+ propertyId: z39.string(),
15056
+ value: z39.unknown(),
15057
+ unit: z39.string().optional(),
15058
+ at: z39.string()
15059
+ });
15060
+ var BulkTelemetryHistorySeriesSchema = z39.object({
15061
+ objectTypeId: z39.string(),
15062
+ objectId: z39.string(),
15063
+ propertyId: z39.string(),
15064
+ points: z39.array(TelemetryPointSchema)
15065
+ });
15066
+ var BulkTelemetryHistoryResponseSchema = z39.object({
15067
+ series: z39.array(BulkTelemetryHistorySeriesSchema)
14125
15068
  });
14126
15069
 
14127
15070
  // src/routes/telemetry.ts
@@ -14249,24 +15192,24 @@ function registerTelemetryRoutes(app, _host) {
14249
15192
  import { userRef } from "@sixb/core";
14250
15193
 
14251
15194
  // src/schemas/users.ts
14252
- import { z as z39 } from "zod";
15195
+ import { z as z40 } from "zod";
14253
15196
  var MAX_USERS_PAGE_LIMIT = 200;
14254
15197
  var MAX_USERS_SEARCH_LENGTH = 200;
14255
15198
  var MAX_USER_EMAIL_LENGTH = 320;
14256
- var ListUsersQuerySchema = z39.object({
14257
- status: z39.enum(["active", "suspended", "all"]).optional(),
14258
- search: z39.string().max(MAX_USERS_SEARCH_LENGTH).optional(),
14259
- limit: z39.coerce.number().int().min(1).max(MAX_USERS_PAGE_LIMIT).optional(),
14260
- offset: z39.coerce.number().int().min(0).optional(),
14261
- email: z39.string().min(1).max(MAX_USER_EMAIL_LENGTH).optional()
14262
- });
14263
- var ListUsersResponseSchema = z39.object({
14264
- users: z39.array(UserProfileSchema),
14265
- hasMore: z39.boolean(),
14266
- total: z39.number()
15199
+ var ListUsersQuerySchema = z40.object({
15200
+ status: z40.enum(["active", "suspended", "all"]).optional(),
15201
+ search: z40.string().max(MAX_USERS_SEARCH_LENGTH).optional(),
15202
+ limit: z40.coerce.number().int().min(1).max(MAX_USERS_PAGE_LIMIT).optional(),
15203
+ offset: z40.coerce.number().int().min(0).optional(),
15204
+ email: z40.string().min(1).max(MAX_USER_EMAIL_LENGTH).optional()
15205
+ });
15206
+ var ListUsersResponseSchema = z40.object({
15207
+ users: z40.array(UserProfileSchema),
15208
+ hasMore: z40.boolean(),
15209
+ total: z40.number()
14267
15210
  });
14268
- var UserParamsSchema = z39.object({
14269
- userId: z39.string().min(1)
15211
+ var UserParamsSchema = z40.object({
15212
+ userId: z40.string().min(1)
14270
15213
  });
14271
15214
 
14272
15215
  // src/routes/users.ts
@@ -14335,40 +15278,40 @@ function registerUserRoutes(app, _host) {
14335
15278
 
14336
15279
  // src/schemas/webhook-runs.ts
14337
15280
  import { WEBHOOK_RUN_FAILURE_CODES } from "@sixb/core/storage";
14338
- import { z as z40 } from "zod";
15281
+ import { z as z41 } from "zod";
14339
15282
  var WebhookRunFailureSchema = sixbFailureSchema(WEBHOOK_RUN_FAILURE_CODES);
14340
- var WebhookRunStatusSchema = z40.enum(["running", "succeeded", "failed"]);
14341
- var WebhookRunsQuerySchema = z40.object({
14342
- connectorId: z40.string().optional(),
14343
- webhookId: z40.string().optional(),
15283
+ var WebhookRunStatusSchema = z41.enum(["running", "succeeded", "failed"]);
15284
+ var WebhookRunsQuerySchema = z41.object({
15285
+ connectorId: z41.string().optional(),
15286
+ webhookId: z41.string().optional(),
14344
15287
  status: WebhookRunStatusSchema.optional(),
14345
- idempotencyKey: z40.string().optional(),
14346
- startedAfter: z40.string().optional(),
14347
- startedBefore: z40.string().optional(),
14348
- limit: z40.string().optional(),
14349
- offset: z40.string().optional(),
14350
- order: z40.enum(["asc", "desc"]).optional()
14351
- });
14352
- var WebhookRunSchema = z40.object({
14353
- id: z40.string(),
14354
- projectId: z40.string(),
14355
- executionId: z40.string(),
14356
- connectorId: z40.string(),
14357
- webhookId: z40.string(),
15288
+ idempotencyKey: z41.string().optional(),
15289
+ startedAfter: z41.string().optional(),
15290
+ startedBefore: z41.string().optional(),
15291
+ limit: z41.string().optional(),
15292
+ offset: z41.string().optional(),
15293
+ order: z41.enum(["asc", "desc"]).optional()
15294
+ });
15295
+ var WebhookRunSchema = z41.object({
15296
+ id: z41.string(),
15297
+ projectId: z41.string(),
15298
+ executionId: z41.string(),
15299
+ connectorId: z41.string(),
15300
+ webhookId: z41.string(),
14358
15301
  status: WebhookRunStatusSchema,
14359
- method: z40.string(),
14360
- route: z40.string(),
14361
- startedAt: z40.string(),
14362
- finishedAt: z40.string().optional(),
14363
- requestBodyBytes: z40.number(),
14364
- responseStatus: z40.number().optional(),
14365
- idempotencyKey: z40.string().optional(),
15302
+ method: z41.string(),
15303
+ route: z41.string(),
15304
+ startedAt: z41.string(),
15305
+ finishedAt: z41.string().optional(),
15306
+ requestBodyBytes: z41.number(),
15307
+ responseStatus: z41.number().optional(),
15308
+ idempotencyKey: z41.string().optional(),
14366
15309
  error: WebhookRunFailureSchema.optional()
14367
15310
  });
14368
- var WebhookRunListResponseSchema = z40.object({
14369
- runs: z40.array(WebhookRunSchema),
14370
- hasMore: z40.boolean(),
14371
- total: z40.number()
15311
+ var WebhookRunListResponseSchema = z41.object({
15312
+ runs: z41.array(WebhookRunSchema),
15313
+ hasMore: z41.boolean(),
15314
+ total: z41.number()
14372
15315
  });
14373
15316
 
14374
15317
  // src/routes/webhook-runs.ts
@@ -14444,15 +15387,15 @@ import {
14444
15387
  snapshotWorkflowInterventionResponse
14445
15388
  } from "@sixb/core/internal/workflows";
14446
15389
  import { AGENT_RUN_FAILURE_CODES as AGENT_RUN_FAILURE_CODES2, WORKFLOW_RUN_FAILURE_CODES as WORKFLOW_RUN_FAILURE_CODES2 } from "@sixb/core/storage";
14447
- import { z as z41 } from "zod";
15390
+ import { z as z42 } from "zod";
14448
15391
  var WorkflowRunFileContentQuerySchema = FileContentQuerySchema.extend({
14449
- path: z41.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow run file content paths must start with /input/ or /output/")
15392
+ path: z42.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow run file content paths must start with /input/ or /output/")
14450
15393
  });
14451
15394
  var WorkflowNodeFileContentQuerySchema = FileContentQuerySchema.extend({
14452
- path: z41.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow node file content paths must start with /input/ or /output/")
15395
+ path: z42.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow node file content paths must start with /input/ or /output/")
14453
15396
  });
14454
15397
  var WorkflowNodeFileContentParamsSchema = WorkflowRunParamsSchema.extend({
14455
- nodeKey: z41.string().min(1)
15398
+ nodeKey: z42.string().min(1)
14456
15399
  });
14457
15400
  function serializeWorkflowRunSummary(run) {
14458
15401
  return {
@@ -15482,6 +16425,7 @@ function registerHttpRoutes(app, host, options) {
15482
16425
  registerConnectorConnectionRoutes(app, host);
15483
16426
  registerConnectorConnectionRunRoutes(app, host, options.connectorConnections);
15484
16427
  registerDatasetRoutes(app, host);
16428
+ registerLakeRoutes(app, host);
15485
16429
  registerSyncRoutes(app, host);
15486
16430
  registerPipelineRoutes(app, host);
15487
16431
  registerWorkflowRoutes(app, host);
@@ -15516,7 +16460,7 @@ function registerHttpRoutes(app, host, options) {
15516
16460
  }
15517
16461
 
15518
16462
  // src/routes/auth.ts
15519
- import { createHash as createHash3, randomBytes, randomUUID, timingSafeEqual } from "crypto";
16463
+ import { createHash as createHash4, randomBytes, randomUUID, timingSafeEqual } from "crypto";
15520
16464
  import {
15521
16465
  AuthRuntimeError,
15522
16466
  clearCsrfCookieHeader,
@@ -16956,7 +17900,7 @@ var DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10;
16956
17900
  var DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2;
16957
17901
  var DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789";
16958
17902
  function hashDeviceCode(deviceCode) {
16959
- return createHash3("sha256").update(deviceCode).digest("base64url");
17903
+ return createHash4("sha256").update(deviceCode).digest("base64url");
16960
17904
  }
16961
17905
  function parseDeviceAuthorizationId(deviceCode) {
16962
17906
  const separator = deviceCode.indexOf(".");
@@ -17087,7 +18031,7 @@ function createMagicLinkPendingCredential() {
17087
18031
  return { secret, hash: hashMagicLinkPendingSecret(secret) };
17088
18032
  }
17089
18033
  function hashMagicLinkPendingSecret(secret) {
17090
- return createHash3("sha256").update(secret).digest("base64url");
18034
+ return createHash4("sha256").update(secret).digest("base64url");
17091
18035
  }
17092
18036
  function matchesMagicLinkRequester(pendingSecret, requesterHash) {
17093
18037
  const expected = Buffer.from(hashMagicLinkPendingSecret(pendingSecret));
@@ -17147,7 +18091,7 @@ async function completeMagicLinkCallback(input) {
17147
18091
  }
17148
18092
  }
17149
18093
  function oidcStateCookieName(state) {
17150
- return `sixb_oidc_${createHash3("sha256").update(state).digest("base64url").slice(0, 22)}`;
18094
+ return `sixb_oidc_${createHash4("sha256").update(state).digest("base64url").slice(0, 22)}`;
17151
18095
  }
17152
18096
  function oidcSignInRedirect(request, host, result) {
17153
18097
  const response = redirectResponse(result.redirectTo);
@@ -18012,13 +18956,14 @@ function jsonResponse2(body, status, headersInit) {
18012
18956
  }
18013
18957
 
18014
18958
  // src/routes/webhooks.ts
18015
- import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
18959
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "crypto";
18016
18960
  import { reportRunFailure } from "@sixb/core/internal/error-reporting";
18017
18961
  import { captureSixbFailure, createSixbError as createSixbError6, toSixbFailure as toSixbFailure2 } from "@sixb/core/internal/errors";
18018
18962
  import { bindDurablePrimitiveExecution } from "@sixb/core/internal/primitive-execution";
18019
18963
  import {
18020
18964
  admitWebhookRun,
18021
18965
  createWebhookConnections,
18966
+ holdWebhookRun,
18022
18967
  isStaticConnectorDefinition
18023
18968
  } from "@sixb/core/internal/webhooks";
18024
18969
  import { WEBHOOK_RUN_FAILURE_CODES as WEBHOOK_RUN_FAILURE_CODES2, WebhookRunError } from "@sixb/core/storage";
@@ -18041,15 +18986,25 @@ async function dispatchWebhook(options) {
18041
18986
  const admission = await admitPreparedWebhook(options, candidateRunId, prepared.request);
18042
18987
  if (admission.status === "responded")
18043
18988
  return admission.response;
18989
+ if (admission.status === "in_progress")
18990
+ return retryLater(options.set, admission.run);
18044
18991
  if (admission.status !== "admitted")
18045
18992
  return accepted(options.set);
18993
+ const execution = requireWebhookExecution(admission.run);
18994
+ const stopHolding = holdWebhookRun({
18995
+ storage: options.host.storage,
18996
+ projectId: options.host.id,
18997
+ runId: admission.run.id,
18998
+ execution
18999
+ });
18046
19000
  const executionLogs = options.host.logging.startExecution({
18047
19001
  kind: "webhook",
18048
19002
  id: admission.run.id
18049
19003
  });
18050
19004
  try {
18051
- return await executeWebhookHandler(options, prepared.request, admission, executionLogs.withContext({ phase: "handle" }));
19005
+ return await executeWebhookHandler(options, prepared.request, admission, execution, executionLogs.withContext({ phase: "handle" }));
18052
19006
  } finally {
19007
+ stopHolding();
18053
19008
  await executionLogs.flush();
18054
19009
  }
18055
19010
  }
@@ -18125,7 +19080,7 @@ async function admitPreparedWebhook(options, runId, prepared) {
18125
19080
  method: options.request.method.toUpperCase(),
18126
19081
  route: options.registered.route,
18127
19082
  requestBodyBytes: prepared.rawBody.byteLength,
18128
- requestBodySha256: createHash4("sha256").update(prepared.rawBody).digest("hex"),
19083
+ requestBodySha256: createHash5("sha256").update(prepared.rawBody).digest("hex"),
18129
19084
  idempotencyKey: prepared.idempotencyKey
18130
19085
  });
18131
19086
  } catch (error) {
@@ -18137,7 +19092,7 @@ async function admitPreparedWebhook(options, runId, prepared) {
18137
19092
  return { status: "responded", response: { error: "Webhook admission failed" } };
18138
19093
  }
18139
19094
  }
18140
- async function executeWebhookHandler(options, prepared, admission, logger) {
19095
+ async function executeWebhookHandler(options, prepared, admission, { token: executionToken }, logger) {
18141
19096
  const { host, registered, request, set } = options;
18142
19097
  const { connector, webhook } = registered;
18143
19098
  const runId = admission.run.id;
@@ -18172,6 +19127,7 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18172
19127
  try {
18173
19128
  await finishWebhookRun(host, {
18174
19129
  runId,
19130
+ executionToken,
18175
19131
  status: "failed",
18176
19132
  responseStatus: 500,
18177
19133
  failure: failed.failure
@@ -18190,7 +19146,7 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18190
19146
  message: `Webhook handler returned HTTP ${responseStatus}`
18191
19147
  });
18192
19148
  try {
18193
- await finishWebhookRun(host, failed ? { runId, status: "failed", responseStatus, failure: failed.failure } : { runId, status: "succeeded", responseStatus });
19149
+ await finishWebhookRun(host, failed ? { runId, executionToken, status: "failed", responseStatus, failure: failed.failure } : { runId, executionToken, status: "succeeded", responseStatus });
18194
19150
  } catch (error) {
18195
19151
  const failure = captureSixbFailure(error, {
18196
19152
  allowedCodes: WEBHOOK_RUN_FAILURE_CODES2,
@@ -18211,6 +19167,17 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18211
19167
  }
18212
19168
  return applyWebhookResponse(set, response);
18213
19169
  }
19170
+ function retryLater(set, run) {
19171
+ const untilLeaseEnds = (run.execution?.leaseExpiresAt.getTime() ?? 0) - Date.now();
19172
+ set.status = 503;
19173
+ setHeader(set, "retry-after", String(Math.max(1, Math.ceil(untilLeaseEnds / 1000))));
19174
+ return { error: "Webhook delivery in progress" };
19175
+ }
19176
+ function requireWebhookExecution(run) {
19177
+ if (run.execution)
19178
+ return run.execution;
19179
+ throw createSixbError6("internal.unexpected", `[SixbServer] Admitted webhook run '${run.id}' has no execution.`);
19180
+ }
18214
19181
  function createFailureReporter(host, registered, runId) {
18215
19182
  let reported = false;
18216
19183
  return (error, failure) => {
@@ -18237,6 +19204,7 @@ async function finishWebhookRun(host, input) {
18237
19204
  const terminal = {
18238
19205
  id: input.runId,
18239
19206
  projectId: host.id,
19207
+ executionToken: input.executionToken,
18240
19208
  responseStatus: input.responseStatus
18241
19209
  };
18242
19210
  await storage.finish(input.status === "failed" ? {
@@ -18318,7 +19286,7 @@ import {
18318
19286
  agentRunStreamDefinition,
18319
19287
  agentRunStreamId as agentRunStreamId3
18320
19288
  } from "@sixb/core/internal/agents/streams";
18321
- import { z as z42 } from "zod";
19289
+ import { z as z43 } from "zod";
18322
19290
 
18323
19291
  // src/utils/ws.ts
18324
19292
  function safeSend(target, payload) {
@@ -18334,6 +19302,10 @@ function wsRequestSixb(ws) {
18334
19302
  const data = ws.data;
18335
19303
  return data?.sixb ?? null;
18336
19304
  }
19305
+ function wsSharedSession(ws) {
19306
+ const data = ws.data;
19307
+ return data?.sharedSession ?? null;
19308
+ }
18337
19309
  function parseJson(text) {
18338
19310
  try {
18339
19311
  return JSON.parse(text);
@@ -18366,25 +19338,25 @@ async function decodeWsMessage(message) {
18366
19338
  }
18367
19339
 
18368
19340
  // src/routes/ws/agents.ts
18369
- var SubscribeSchema = z42.object({
18370
- type: z42.literal("subscribe"),
18371
- runId: z42.string().min(1),
18372
- afterCursor: z42.string().min(1).optional()
19341
+ var SubscribeSchema = z43.object({
19342
+ type: z43.literal("subscribe"),
19343
+ runId: z43.string().min(1),
19344
+ afterCursor: z43.string().min(1).optional()
18373
19345
  });
18374
- var SubscribeActivitySchema = z42.object({
18375
- type: z42.literal("subscribe.activity")
19346
+ var SubscribeActivitySchema = z43.object({
19347
+ type: z43.literal("subscribe.activity")
18376
19348
  });
18377
- var ReplaySchema = z42.object({
18378
- type: z42.literal("replay"),
18379
- runId: z42.string().min(1),
18380
- afterCursor: z42.string().min(1).optional(),
18381
- limit: z42.number().int().positive().max(500).optional()
19349
+ var ReplaySchema = z43.object({
19350
+ type: z43.literal("replay"),
19351
+ runId: z43.string().min(1),
19352
+ afterCursor: z43.string().min(1).optional(),
19353
+ limit: z43.number().int().positive().max(500).optional()
18382
19354
  });
18383
- var UnsubscribeSchema = z42.object({
18384
- type: z42.literal("unsubscribe"),
18385
- runId: z42.string().min(1).optional()
19355
+ var UnsubscribeSchema = z43.object({
19356
+ type: z43.literal("unsubscribe"),
19357
+ runId: z43.string().min(1).optional()
18386
19358
  });
18387
- var AgentStreamMessageSchema = z42.union([
19359
+ var AgentStreamMessageSchema = z43.union([
18388
19360
  SubscribeSchema,
18389
19361
  SubscribeActivitySchema,
18390
19362
  ReplaySchema,
@@ -18682,9 +19654,1018 @@ function errorMessage(error) {
18682
19654
  return error instanceof Error ? error.message : String(error);
18683
19655
  }
18684
19656
 
19657
+ // src/routes/ws/artifacts.ts
19658
+ import { randomUUID as randomUUID3 } from "crypto";
19659
+ import { ARTIFACT_LIVE_ROUTE as ARTIFACT_LIVE_ROUTE2 } from "@sixb/core/artifacts/live";
19660
+ import { z as z44 } from "zod";
19661
+
19662
+ // src/live/rooms.ts
19663
+ import {
19664
+ decodeLiveData as decodeLiveData2
19665
+ } from "@sixb/core/artifacts/live";
19666
+
19667
+ // src/live/room.ts
19668
+ import { ArtifactRequestError as ArtifactRequestError2 } from "@sixb/core";
19669
+ import {
19670
+ AGENT_AWARENESS_FIELD as AGENT_AWARENESS_FIELD2,
19671
+ decodeLiveData,
19672
+ documentFiles,
19673
+ encodeLiveData,
19674
+ USER_AWARENESS_FIELD as USER_AWARENESS_FIELD2
19675
+ } from "@sixb/core/artifacts/live";
19676
+ import {
19677
+ AGENT_PRESENCE_MS,
19678
+ artifactLiveStream,
19679
+ artifactPresenceStream,
19680
+ loadArtifactDocument,
19681
+ mergeIntoDocument,
19682
+ parseArtifactLiveRecord,
19683
+ readDocumentState,
19684
+ readLiveFiles,
19685
+ sameArtifactFiles,
19686
+ storeLiveFiles,
19687
+ writeLiveArtifact
19688
+ } from "@sixb/core/internal/artifacts/live";
19689
+ import { reportArtifactLiveWriteFailure } from "@sixb/core/internal/error-reporting";
19690
+ import * as decoding2 from "lib0/decoding";
19691
+ import * as encoding2 from "lib0/encoding";
19692
+ import * as awarenessProtocol from "y-protocols/awareness";
19693
+ import * as syncProtocol from "y-protocols/sync";
19694
+ import * as Y from "yjs";
19695
+ var SAVE_IDLE_MS = 1500;
19696
+ var SAVE_MAX_MS = 1e4;
19697
+ var ACCESS_RECHECK_MS = 2000;
19698
+ var RETRY_MS = 2000;
19699
+ var RETRY_MAX_MS = 30000;
19700
+ var AWARENESS_REPLAY_MS = awarenessProtocol.outdatedTimeout;
19701
+ var HEARD_SAVE_MS = 3 * SAVE_MAX_MS;
19702
+ var MEMBERS_RECHECK_MS = 60000;
19703
+ var AWARENESS_SHARE_MS = 100;
19704
+ var MERGED = Symbol("merged");
19705
+ var REMOTE = Symbol("remote");
19706
+ var LEFT = Symbol("left");
19707
+
19708
+ class LiveRoom {
19709
+ host;
19710
+ artifactId;
19711
+ onClose;
19712
+ doc;
19713
+ awareness;
19714
+ members = new Map;
19715
+ synced;
19716
+ savedSnapshot;
19717
+ dirty = false;
19718
+ unwritten = false;
19719
+ author;
19720
+ lastEditor;
19721
+ shadow;
19722
+ state = "saved";
19723
+ error;
19724
+ failure;
19725
+ attempts = 0;
19726
+ idle;
19727
+ deadline;
19728
+ retry;
19729
+ heardSave;
19730
+ recheck;
19731
+ unshared = new Set;
19732
+ sharing;
19733
+ queue = Promise.resolve();
19734
+ agents = new Map;
19735
+ remoteClients = new Set;
19736
+ unsubscribe;
19737
+ closed = false;
19738
+ constructor(host, artifactId, doc, synced, onClose) {
19739
+ this.host = host;
19740
+ this.artifactId = artifactId;
19741
+ this.onClose = onClose;
19742
+ this.synced = synced;
19743
+ this.savedSnapshot = Y.encodeSnapshot(Y.snapshot(doc));
19744
+ this.doc = doc;
19745
+ this.shadow = copyOf(doc);
19746
+ this.awareness = new awarenessProtocol.Awareness(this.doc);
19747
+ this.awareness.setLocalState(null);
19748
+ this.doc.on("update", (update, origin) => this.updated(update, origin));
19749
+ this.awareness.on("update", (changes, origin) => this.presenceChanged(changes, origin));
19750
+ }
19751
+ static async open(host, artifactId, onClose) {
19752
+ const storage = requireArtifacts(host);
19753
+ const artifact = await storage.get({ projectId: host.projectId, id: artifactId });
19754
+ if (!artifact)
19755
+ return "not_found";
19756
+ if (artifact.kind !== "canvas")
19757
+ return "not_live";
19758
+ const version = await storage.getVersion({
19759
+ projectId: host.projectId,
19760
+ artifactId,
19761
+ version: artifact.latestVersion
19762
+ });
19763
+ if (!version)
19764
+ return "not_found";
19765
+ const doc = await loadArtifactDocument(host.blobStorage, artifact, version.files);
19766
+ const room = new LiveRoom(host, artifactId, doc, { revision: version.revision, title: version.title, files: version.files }, onClose);
19767
+ try {
19768
+ await room.follow();
19769
+ } catch (error) {
19770
+ room.close();
19771
+ throw error;
19772
+ }
19773
+ return room;
19774
+ }
19775
+ get isClosed() {
19776
+ return this.closed;
19777
+ }
19778
+ get revision() {
19779
+ return this.synced.revision;
19780
+ }
19781
+ join(connection, access, user) {
19782
+ if (access === "edit")
19783
+ this.lastEditor = connection;
19784
+ this.recheck ??= setInterval(() => this.enqueue(() => this.recheckAccess()), MEMBERS_RECHECK_MS);
19785
+ this.members.set(connection.id, {
19786
+ connection,
19787
+ user,
19788
+ access,
19789
+ checkedAt: Date.now(),
19790
+ clients: new Set
19791
+ });
19792
+ connection.send({
19793
+ type: "joined",
19794
+ artifactId: this.artifactId,
19795
+ access,
19796
+ revision: this.synced.revision,
19797
+ user
19798
+ });
19799
+ const encoder = encoding2.createEncoder();
19800
+ syncProtocol.writeSyncStep1(encoder, this.doc);
19801
+ this.sendSync(connection, encoding2.toUint8Array(encoder));
19802
+ const clients = [...this.awareness.getStates().keys()];
19803
+ if (clients.length > 0) {
19804
+ connection.send({
19805
+ type: "awareness",
19806
+ artifactId: this.artifactId,
19807
+ data: encodeLiveData(awarenessProtocol.encodeAwarenessUpdate(this.awareness, clients))
19808
+ });
19809
+ }
19810
+ connection.send(this.status());
19811
+ }
19812
+ leave(connectionId) {
19813
+ const member = this.members.get(connectionId);
19814
+ if (!member)
19815
+ return;
19816
+ this.members.delete(connectionId);
19817
+ awarenessProtocol.removeAwarenessStates(this.awareness, [...member.clients], LEFT);
19818
+ if (![...this.members.values()].some((each) => each.access === "edit"))
19819
+ this.save();
19820
+ this.closeWhenDone();
19821
+ }
19822
+ async sync(connectionId, bytes) {
19823
+ const member = this.members.get(connectionId);
19824
+ if (!member)
19825
+ return;
19826
+ const type = decoding2.readVarUint(decoding2.createDecoder(bytes));
19827
+ if (type !== syncProtocol.messageYjsSyncStep1 && !await this.mayEdit(member)) {
19828
+ member.connection.send({
19829
+ type: "error",
19830
+ artifactId: this.artifactId,
19831
+ message: "[SixbServer] You watch this artifact: your changes are not kept."
19832
+ });
19833
+ return;
19834
+ }
19835
+ if (type !== syncProtocol.messageYjsSyncStep1 && !this.readable(bytes)) {
19836
+ member.connection.send({
19837
+ type: "error",
19838
+ artifactId: this.artifactId,
19839
+ message: "[SixbServer] That change leaves the artifact unreadable: it is not kept. Load the artifact again."
19840
+ });
19841
+ return;
19842
+ }
19843
+ const encoder = encoding2.createEncoder();
19844
+ syncProtocol.readSyncMessage(decoding2.createDecoder(bytes), encoder, this.doc, member);
19845
+ if (encoding2.length(encoder) > 0)
19846
+ this.sendSync(member.connection, encoding2.toUint8Array(encoder));
19847
+ if (type === syncProtocol.messageYjsSyncStep1 && member.access === "edit") {
19848
+ const ask = encoding2.createEncoder();
19849
+ syncProtocol.writeSyncStep1(ask, this.doc);
19850
+ this.sendSync(member.connection, encoding2.toUint8Array(ask));
19851
+ }
19852
+ }
19853
+ presence(connectionId, data) {
19854
+ const member = this.members.get(connectionId);
19855
+ const bytes = decodeLiveData(data);
19856
+ if (!member || !bytes)
19857
+ return;
19858
+ const vouched = vouchedAwareness(bytes, {
19859
+ user: member.user,
19860
+ mayUse: (client) => this.mayUse(member, client)
19861
+ });
19862
+ if (vouched)
19863
+ awarenessProtocol.applyAwarenessUpdate(this.awareness, vouched, member);
19864
+ }
19865
+ rename(connectionId, user) {
19866
+ const member = this.members.get(connectionId);
19867
+ if (!member)
19868
+ return;
19869
+ member.user = user;
19870
+ const states = this.awareness.getStates();
19871
+ const clients = [...member.clients].filter((client) => states.get(client));
19872
+ if (clients.length === 0)
19873
+ return;
19874
+ const encoder = encoding2.createEncoder();
19875
+ encoding2.writeVarUint(encoder, clients.length);
19876
+ for (const client of clients) {
19877
+ const clock = this.awareness.meta.get(client)?.clock ?? 0;
19878
+ encoding2.writeVarUint(encoder, client);
19879
+ encoding2.writeVarUint(encoder, clock + 1);
19880
+ encoding2.writeVarString(encoder, JSON.stringify({ ...states.get(client), [USER_AWARENESS_FIELD2]: user }));
19881
+ }
19882
+ awarenessProtocol.applyAwarenessUpdate(this.awareness, encoding2.toUint8Array(encoder), member);
19883
+ }
19884
+ written(revision) {
19885
+ this.enqueue(() => this.recheckAccess());
19886
+ if (revision <= this.synced.revision)
19887
+ return;
19888
+ this.enqueue(() => this.reconcile(revision));
19889
+ }
19890
+ closeIfUnheld() {
19891
+ this.closeWhenDone();
19892
+ }
19893
+ save() {
19894
+ this.clearTimers();
19895
+ this.enqueue(() => this.flush());
19896
+ }
19897
+ settled() {
19898
+ return this.queue;
19899
+ }
19900
+ close() {
19901
+ if (this.closed)
19902
+ return;
19903
+ const lost = this.dirty;
19904
+ this.closed = true;
19905
+ if (lost)
19906
+ this.lose();
19907
+ this.clearTimers();
19908
+ if (this.recheck)
19909
+ clearInterval(this.recheck);
19910
+ if (this.sharing)
19911
+ clearTimeout(this.sharing);
19912
+ for (const agent of this.agents.values())
19913
+ clearTimeout(agent.expiry);
19914
+ this.unsubscribe?.();
19915
+ this.awareness.destroy();
19916
+ this.doc.destroy();
19917
+ this.shadow.destroy();
19918
+ this.onClose(this);
19919
+ }
19920
+ updated(update, origin) {
19921
+ Y.applyUpdate(this.shadow, update);
19922
+ const message = encoding2.createEncoder();
19923
+ syncProtocol.writeUpdate(message, update);
19924
+ const data = encoding2.toUint8Array(message);
19925
+ for (const member of this.members.values()) {
19926
+ if (member !== origin)
19927
+ this.sendSync(member.connection, data);
19928
+ }
19929
+ if (origin === REMOTE) {
19930
+ this.heard();
19931
+ return;
19932
+ }
19933
+ if (!(origin instanceof Object && this.isMember(origin)))
19934
+ return;
19935
+ this.changed(origin);
19936
+ this.share("update", update);
19937
+ }
19938
+ heard() {
19939
+ this.unwritten = true;
19940
+ this.heardSave ??= setTimeout(() => {
19941
+ this.heardSave = undefined;
19942
+ this.save();
19943
+ }, HEARD_SAVE_MS);
19944
+ }
19945
+ changed(member) {
19946
+ this.dirty = true;
19947
+ this.author = member.connection;
19948
+ this.setState("unsaved");
19949
+ if (this.idle)
19950
+ clearTimeout(this.idle);
19951
+ this.idle = setTimeout(() => this.save(), SAVE_IDLE_MS);
19952
+ this.deadline ??= setTimeout(() => this.save(), SAVE_MAX_MS);
19953
+ }
19954
+ async flush() {
19955
+ if (this.closed || !(this.dirty || this.unwritten))
19956
+ return this.closeWhenDone();
19957
+ const author = this.author ?? [...this.members.values()].find((each) => each.access === "edit")?.connection ?? this.lastEditor;
19958
+ if (!author) {
19959
+ if (this.unwritten && !this.dirty) {
19960
+ console.warn(`[SixbServer] Nobody here may write back what another server heard of '${this.artifactId}'; that server writes it.`);
19961
+ this.unwritten = false;
19962
+ }
19963
+ return this.closeWhenDone();
19964
+ }
19965
+ const wasDirty = this.dirty;
19966
+ this.dirty = false;
19967
+ this.unwritten = false;
19968
+ if (wasDirty)
19969
+ this.setState("saving");
19970
+ try {
19971
+ const update = Y.encodeStateAsUpdate(this.doc);
19972
+ const written = Y.encodeSnapshot(Y.snapshot(this.doc));
19973
+ const snapshot2 = documentFiles(this.doc);
19974
+ const files = await storeLiveFiles(this.host.blobStorage, snapshot2, this.synced.files);
19975
+ if (sameArtifactFiles(files, this.synced.files)) {
19976
+ this.saved(this.synced, written);
19977
+ return this.closeWhenDone();
19978
+ }
19979
+ const published = await writeLiveArtifact(author.sixb.artifacts, this.artifactId, {
19980
+ title: this.synced.title,
19981
+ baseTitle: this.synced.title,
19982
+ files,
19983
+ baseRevision: this.synced.revision,
19984
+ update
19985
+ });
19986
+ const stored = published.artifact.document;
19987
+ if (published.merged && stored) {
19988
+ Y.applyUpdate(this.doc, await readDocumentState(this.host.blobStorage, stored.file), MERGED);
19989
+ }
19990
+ this.saved({
19991
+ revision: published.version.revision,
19992
+ title: published.version.title,
19993
+ files: published.version.files
19994
+ }, written);
19995
+ } catch (error) {
19996
+ this.failed(author, error);
19997
+ }
19998
+ this.closeWhenDone();
19999
+ }
20000
+ saved(synced, written) {
20001
+ this.synced = synced;
20002
+ this.savedSnapshot = written;
20003
+ this.attempts = 0;
20004
+ this.error = undefined;
20005
+ this.failure = undefined;
20006
+ this.setState(this.dirty ? "unsaved" : "saved", true);
20007
+ if (this.dirty && !this.idle)
20008
+ this.idle = setTimeout(() => this.save(), SAVE_IDLE_MS);
20009
+ }
20010
+ failed(author, error) {
20011
+ this.dirty = true;
20012
+ this.attempts += 1;
20013
+ this.error = error instanceof Error ? error.message : String(error);
20014
+ this.failure = error;
20015
+ this.setState("failed", true);
20016
+ const code = error instanceof ArtifactRequestError2 ? error.code : undefined;
20017
+ if (code === "artifact_not_found") {
20018
+ for (const member of [...this.members.values()]) {
20019
+ member.connection.send({ type: "left", artifactId: this.artifactId, reason: "not_found" });
20020
+ }
20021
+ this.members.clear();
20022
+ this.dirty = false;
20023
+ this.close();
20024
+ return;
20025
+ }
20026
+ if (code === "not_shared" || code === "read_only" || code === "not_allowed") {
20027
+ const member = this.members.get(author.id);
20028
+ if (member)
20029
+ this.demote(member);
20030
+ this.author = [...this.members.values()].find((each) => each.access === "edit")?.connection;
20031
+ if (this.author)
20032
+ this.scheduleRetry(0);
20033
+ else if (this.members.size === 0)
20034
+ this.lose();
20035
+ return;
20036
+ }
20037
+ if (code === "invalid_artifact") {
20038
+ if (this.members.size === 0)
20039
+ this.lose();
20040
+ return;
20041
+ }
20042
+ if (this.members.size === 0) {
20043
+ console.warn(`[SixbServer] Could not write back the live changes to artifact '${this.artifactId}' (attempt ${this.attempts}); trying again:`, error);
20044
+ }
20045
+ this.scheduleRetry(Math.min(RETRY_MS * 2 ** (this.attempts - 1), RETRY_MAX_MS));
20046
+ }
20047
+ lose() {
20048
+ reportArtifactLiveWriteFailure(this.host.errorReporterHost, this.failure, {
20049
+ projectId: this.host.projectId,
20050
+ artifactId: this.artifactId,
20051
+ revision: this.synced.revision,
20052
+ attempts: this.attempts
20053
+ });
20054
+ this.dirty = false;
20055
+ this.closeWhenDone();
20056
+ }
20057
+ scheduleRetry(delayMs) {
20058
+ if (this.retry)
20059
+ clearTimeout(this.retry);
20060
+ this.retry = setTimeout(() => {
20061
+ this.retry = undefined;
20062
+ this.save();
20063
+ }, delayMs);
20064
+ }
20065
+ async reconcile(revision) {
20066
+ if (this.closed || revision <= this.synced.revision)
20067
+ return;
20068
+ const storage = requireArtifacts(this.host);
20069
+ const artifact = await storage.get({ projectId: this.host.projectId, id: this.artifactId });
20070
+ const version = artifact && await storage.getVersion({
20071
+ projectId: this.host.projectId,
20072
+ artifactId: this.artifactId,
20073
+ version: artifact.latestVersion
20074
+ });
20075
+ if (!version) {
20076
+ for (const member of this.members.values()) {
20077
+ member.connection.send({ type: "left", artifactId: this.artifactId, reason: "not_found" });
20078
+ }
20079
+ this.members.clear();
20080
+ this.close();
20081
+ return;
20082
+ }
20083
+ if (version.revision <= this.synced.revision)
20084
+ return;
20085
+ const { blobStorage } = this.host;
20086
+ if (artifact.document) {
20087
+ const stored = await loadArtifactDocument(blobStorage, artifact, version.files);
20088
+ Y.applyUpdate(this.doc, Y.encodeStateAsUpdate(stored), MERGED);
20089
+ stored.destroy();
20090
+ } else {
20091
+ const [base, next] = await Promise.all([
20092
+ readLiveFiles(blobStorage, this.synced.files),
20093
+ readLiveFiles(blobStorage, version.files)
20094
+ ]);
20095
+ mergeIntoDocument(this.doc, base, next, MERGED);
20096
+ }
20097
+ this.synced = { revision: version.revision, title: version.title, files: version.files };
20098
+ if (!this.dirty)
20099
+ this.savedSnapshot = Y.encodeSnapshot(Y.snapshot(this.doc));
20100
+ this.setState(this.dirty ? this.state : "saved", true);
20101
+ }
20102
+ enqueue(task) {
20103
+ this.queue = this.queue.then(task).catch((error) => {
20104
+ console.error(`[SixbServer] Live artifact '${this.artifactId}' failed:`, error);
20105
+ });
20106
+ }
20107
+ closeWhenDone() {
20108
+ if (this.members.size === 0 && !this.dirty && !this.unwritten && !this.retry)
20109
+ this.close();
20110
+ }
20111
+ clearTimers() {
20112
+ for (const timer of [this.idle, this.deadline, this.retry, this.heardSave]) {
20113
+ if (timer)
20114
+ clearTimeout(timer);
20115
+ }
20116
+ this.idle = undefined;
20117
+ this.deadline = undefined;
20118
+ this.retry = undefined;
20119
+ this.heardSave = undefined;
20120
+ }
20121
+ readable(bytes) {
20122
+ try {
20123
+ syncProtocol.readSyncMessage(decoding2.createDecoder(bytes), encoding2.createEncoder(), this.shadow, null);
20124
+ documentFiles(this.shadow);
20125
+ return true;
20126
+ } catch {
20127
+ this.shadow.destroy();
20128
+ this.shadow = copyOf(this.doc);
20129
+ return false;
20130
+ }
20131
+ }
20132
+ async mayEdit(member) {
20133
+ if (member.access !== "edit")
20134
+ return false;
20135
+ if (Date.now() - member.checkedAt < ACCESS_RECHECK_MS)
20136
+ return true;
20137
+ const access = await member.connection.sixb.artifacts.access(this.artifactId);
20138
+ member.checkedAt = Date.now();
20139
+ if (access === "owner" || access === "update")
20140
+ return true;
20141
+ if (access === "read")
20142
+ this.demote(member);
20143
+ else {
20144
+ this.members.delete(member.connection.id);
20145
+ member.connection.send({ type: "left", artifactId: this.artifactId, reason: "not_shared" });
20146
+ this.closeWhenDone();
20147
+ }
20148
+ return false;
20149
+ }
20150
+ demote(member) {
20151
+ if (member.access === "watch")
20152
+ return;
20153
+ member.access = "watch";
20154
+ member.connection.send({ type: "access", artifactId: this.artifactId, access: "watch" });
20155
+ }
20156
+ async recheckAccess() {
20157
+ for (const member of [...this.members.values()]) {
20158
+ if (this.closed)
20159
+ return;
20160
+ const access = await member.connection.sixb.artifacts.access(this.artifactId);
20161
+ if (this.members.get(member.connection.id) !== member)
20162
+ continue;
20163
+ member.checkedAt = Date.now();
20164
+ if (access === null || access === "none") {
20165
+ this.members.delete(member.connection.id);
20166
+ awarenessProtocol.removeAwarenessStates(this.awareness, [...member.clients], LEFT);
20167
+ member.connection.send({ type: "left", artifactId: this.artifactId, reason: "not_shared" });
20168
+ } else if (access === "read") {
20169
+ this.demote(member);
20170
+ } else if (member.access === "watch") {
20171
+ member.access = "edit";
20172
+ this.lastEditor = member.connection;
20173
+ member.connection.send({ type: "access", artifactId: this.artifactId, access: "edit" });
20174
+ }
20175
+ }
20176
+ this.closeWhenDone();
20177
+ }
20178
+ isMember(value) {
20179
+ return [...this.members.values()].includes(value);
20180
+ }
20181
+ mayUse(member, client) {
20182
+ if (member.clients.has(client))
20183
+ return true;
20184
+ if (client === this.doc.clientID || this.remoteClients.has(client))
20185
+ return false;
20186
+ if (member.clients.size >= MAX_AWARENESS_CLIENTS)
20187
+ return false;
20188
+ return ![...this.members.values()].some((each) => each.clients.has(client));
20189
+ }
20190
+ presenceChanged(changes, origin) {
20191
+ const speaker = origin === REMOTE ? this.remoteClients : origin instanceof Object && this.isMember(origin) ? origin.clients : null;
20192
+ for (const client of changes.added)
20193
+ speaker?.add(client);
20194
+ for (const client of changes.removed) {
20195
+ speaker?.delete(client);
20196
+ this.remoteClients.delete(client);
20197
+ }
20198
+ const changed = [...changes.added, ...changes.updated, ...changes.removed];
20199
+ const data = encodeLiveData(awarenessProtocol.encodeAwarenessUpdate(this.awareness, changed));
20200
+ for (const member of this.members.values()) {
20201
+ member.connection.send({ type: "awareness", artifactId: this.artifactId, data });
20202
+ }
20203
+ if (origin === REMOTE)
20204
+ return;
20205
+ for (const client of changed)
20206
+ if (client !== this.doc.clientID)
20207
+ this.unshared.add(client);
20208
+ if (this.unshared.size === 0 || this.sharing)
20209
+ return;
20210
+ this.sharing = setTimeout(() => {
20211
+ this.sharing = undefined;
20212
+ const clients = [...this.unshared];
20213
+ this.unshared.clear();
20214
+ this.share("awareness", awarenessProtocol.encodeAwarenessUpdate(this.awareness, clients));
20215
+ }, AWARENESS_SHARE_MS);
20216
+ }
20217
+ share(name, update) {
20218
+ if (this.closed)
20219
+ return;
20220
+ const payload = { instance: this.host.instance, update: encodeLiveData(update) };
20221
+ const stream = name === "update" ? artifactLiveStream : artifactPresenceStream;
20222
+ this.host.broker.append({
20223
+ projectId: this.host.projectId,
20224
+ streamId: stream(this.artifactId).id,
20225
+ records: [{ name, payload }]
20226
+ }).catch((error) => {
20227
+ console.warn(`[SixbServer] Could not share a live ${name} of '${this.artifactId}':`, error);
20228
+ });
20229
+ }
20230
+ async follow() {
20231
+ const { broker, projectId } = this.host;
20232
+ const unsubscribes = [];
20233
+ this.unsubscribe = () => {
20234
+ for (const unsubscribe of unsubscribes)
20235
+ unsubscribe();
20236
+ };
20237
+ for (const stream of [
20238
+ artifactLiveStream(this.artifactId),
20239
+ artifactPresenceStream(this.artifactId)
20240
+ ]) {
20241
+ await broker.ensureStream({ projectId, stream });
20242
+ unsubscribes.push(await broker.subscribe({ projectId, streamId: stream.id, from: "earliest" }, (records) => {
20243
+ for (const record of records)
20244
+ this.heardRecord(record);
20245
+ }));
20246
+ }
20247
+ }
20248
+ heardRecord(record) {
20249
+ if (this.closed)
20250
+ return;
20251
+ const live = parseArtifactLiveRecord(record);
20252
+ if (!live)
20253
+ return;
20254
+ const age = Date.now() - Date.parse(record.publishedAt);
20255
+ switch (live.name) {
20256
+ case "update": {
20257
+ const update = decodeLiveData(live.payload.update);
20258
+ if (live.payload.instance === this.host.instance || !update)
20259
+ return;
20260
+ try {
20261
+ Y.applyUpdate(this.doc, update, REMOTE);
20262
+ } catch (error) {
20263
+ console.warn(`[SixbServer] Skipped an unreadable live update of '${this.artifactId}':`, error);
20264
+ }
20265
+ return;
20266
+ }
20267
+ case "awareness": {
20268
+ const update = decodeLiveData(live.payload.update);
20269
+ if (live.payload.instance === this.host.instance || !update || age > AWARENESS_REPLAY_MS) {
20270
+ return;
20271
+ }
20272
+ awarenessProtocol.applyAwarenessUpdate(this.awareness, update, REMOTE);
20273
+ return;
20274
+ }
20275
+ case "agent": {
20276
+ if (age > AGENT_PRESENCE_MS)
20277
+ return;
20278
+ const agent = this.agents.get(live.payload.runId);
20279
+ if (agent)
20280
+ clearTimeout(agent.expiry);
20281
+ const boards = new Set([...agent?.boards ?? [], ...live.payload.boards]);
20282
+ const expiry = setTimeout(() => this.agentEnded(live.payload.runId), AGENT_PRESENCE_MS - age);
20283
+ this.agents.set(live.payload.runId, { boards, expiry });
20284
+ this.showAgents();
20285
+ return;
20286
+ }
20287
+ case "agent-ended":
20288
+ this.agentEnded(live.payload.runId);
20289
+ return;
20290
+ }
20291
+ }
20292
+ agentEnded(runId) {
20293
+ const agent = this.agents.get(runId);
20294
+ if (!agent)
20295
+ return;
20296
+ clearTimeout(agent.expiry);
20297
+ this.agents.delete(runId);
20298
+ this.showAgents();
20299
+ }
20300
+ showAgents() {
20301
+ if (this.closed)
20302
+ return;
20303
+ const turns = [...this.agents].map(([runId, agent]) => ({
20304
+ runId,
20305
+ boards: [...agent.boards]
20306
+ }));
20307
+ this.awareness.setLocalState(turns.length === 0 ? null : { [AGENT_AWARENESS_FIELD2]: turns });
20308
+ }
20309
+ sendSync(connection, bytes) {
20310
+ connection.send({ type: "sync", artifactId: this.artifactId, data: encodeLiveData(bytes) });
20311
+ }
20312
+ status() {
20313
+ return {
20314
+ type: "status",
20315
+ artifactId: this.artifactId,
20316
+ state: this.state,
20317
+ revision: this.synced.revision,
20318
+ snapshot: encodeLiveData(this.savedSnapshot),
20319
+ ...this.state === "failed" && this.error ? { error: this.error } : {}
20320
+ };
20321
+ }
20322
+ setState(state, announce = false) {
20323
+ if (state === this.state && !announce)
20324
+ return;
20325
+ this.state = state;
20326
+ const status = this.status();
20327
+ for (const member of this.members.values())
20328
+ member.connection.send(status);
20329
+ }
20330
+ }
20331
+ function copyOf(doc) {
20332
+ const copy = new Y.Doc;
20333
+ Y.applyUpdate(copy, Y.encodeStateAsUpdate(doc));
20334
+ return copy;
20335
+ }
20336
+ function requireArtifacts(host) {
20337
+ const storage = host.storage.artifacts;
20338
+ if (!storage)
20339
+ throw new Error("[SixbServer] Live artifacts need storage that holds artifacts.");
20340
+ return storage;
20341
+ }
20342
+
20343
+ // src/live/rooms.ts
20344
+ var MAX_LIVE_ARTIFACTS_PER_CONNECTION = 16;
20345
+ var MAX_LIVE_SYNC_BYTES = 8 * 1024 * 1024;
20346
+
20347
+ class LiveRooms {
20348
+ host;
20349
+ rooms = new Map;
20350
+ joined = new Map;
20351
+ users = new Map;
20352
+ parts = new Map;
20353
+ events;
20354
+ closed = false;
20355
+ constructor(host) {
20356
+ this.host = host;
20357
+ }
20358
+ async receive(connection, message) {
20359
+ switch (message.type) {
20360
+ case "join":
20361
+ return this.join(connection, message.artifactId);
20362
+ case "leave":
20363
+ return this.leave(connection, message.artifactId);
20364
+ case "sync": {
20365
+ const room = await this.held(connection, message.artifactId);
20366
+ const bytes = room && this.assemble(connection, message);
20367
+ if (bytes)
20368
+ await room.sync(connection.id, bytes);
20369
+ return;
20370
+ }
20371
+ case "awareness": {
20372
+ const room = await this.held(connection, message.artifactId);
20373
+ room?.presence(connection.id, message.data);
20374
+ return;
20375
+ }
20376
+ }
20377
+ }
20378
+ async disconnect(connection) {
20379
+ for (const artifactId of [...this.joined.get(connection.id)?.keys() ?? []]) {
20380
+ await this.leave(connection, artifactId);
20381
+ }
20382
+ this.joined.delete(connection.id);
20383
+ this.users.delete(connection.id);
20384
+ }
20385
+ async close() {
20386
+ this.closed = true;
20387
+ for (const opening of this.rooms.values()) {
20388
+ const room = await opening.catch(() => null);
20389
+ if (!(room instanceof LiveRoom))
20390
+ continue;
20391
+ room.save();
20392
+ await room.settled();
20393
+ room.close();
20394
+ }
20395
+ this.rooms.clear();
20396
+ const unsubscribe = await this.events?.catch(() => {
20397
+ return;
20398
+ });
20399
+ unsubscribe?.();
20400
+ }
20401
+ async settled() {
20402
+ for (const opening of [...this.rooms.values()]) {
20403
+ const room = await opening.catch(() => null);
20404
+ if (room instanceof LiveRoom)
20405
+ await room.settled();
20406
+ }
20407
+ }
20408
+ async join(connection, artifactId) {
20409
+ const send = (message) => connection.send(message);
20410
+ const held = this.joined.get(connection.id) ?? new Map;
20411
+ if (held.has(artifactId))
20412
+ return;
20413
+ if (held.size >= MAX_LIVE_ARTIFACTS_PER_CONNECTION) {
20414
+ send({
20415
+ type: "error",
20416
+ artifactId,
20417
+ message: `[SixbServer] A connection holds at most ${MAX_LIVE_ARTIFACTS_PER_CONNECTION} artifacts live: leave one first.`
20418
+ });
20419
+ return;
20420
+ }
20421
+ const ticket = Symbol(artifactId);
20422
+ held.set(artifactId, ticket);
20423
+ this.joined.set(connection.id, held);
20424
+ const current = () => this.joined.get(connection.id)?.get(artifactId) === ticket;
20425
+ const release = () => {
20426
+ if (current())
20427
+ this.joined.get(connection.id)?.delete(artifactId);
20428
+ };
20429
+ try {
20430
+ const access = await connection.sixb.artifacts.access(artifactId);
20431
+ if (access === null || access === "none") {
20432
+ release();
20433
+ send({ type: "left", artifactId, reason: access === null ? "not_found" : "not_shared" });
20434
+ return;
20435
+ }
20436
+ const user = await this.userOf(connection);
20437
+ const room = await this.open(artifactId);
20438
+ if (!(room instanceof LiveRoom)) {
20439
+ release();
20440
+ send({ type: "left", artifactId, reason: room });
20441
+ return;
20442
+ }
20443
+ if (!current()) {
20444
+ room.closeIfUnheld();
20445
+ return;
20446
+ }
20447
+ room.join(connection, access === "read" ? "watch" : "edit", user);
20448
+ } catch (error) {
20449
+ release();
20450
+ throw error;
20451
+ }
20452
+ }
20453
+ userOf(connection) {
20454
+ if (connection.user)
20455
+ return connection.user();
20456
+ const known = this.users.get(connection.id);
20457
+ if (known)
20458
+ return known;
20459
+ const user = liveUserOf(this.host.storage, this.host.projectId, connection.sixb.execution.requestedBy);
20460
+ this.users.set(connection.id, user);
20461
+ return user;
20462
+ }
20463
+ async refreshUser(connection) {
20464
+ this.users.delete(connection.id);
20465
+ const user = await this.userOf(connection);
20466
+ for (const artifactId of this.joined.get(connection.id)?.keys() ?? []) {
20467
+ const room = await this.rooms.get(artifactId);
20468
+ if (room instanceof LiveRoom)
20469
+ room.rename(connection.id, user);
20470
+ }
20471
+ }
20472
+ async leave(connection, artifactId) {
20473
+ this.parts.delete(partsKey(connection, artifactId));
20474
+ const held = this.joined.get(connection.id);
20475
+ if (!held?.delete(artifactId))
20476
+ return;
20477
+ const room = await this.rooms.get(artifactId);
20478
+ if (room instanceof LiveRoom)
20479
+ room.leave(connection.id);
20480
+ connection.send({ type: "left", artifactId, reason: "left" });
20481
+ }
20482
+ assemble(connection, message) {
20483
+ const key = partsKey(connection, message.artifactId);
20484
+ const bytes = decodeLiveData2(message.data);
20485
+ const parts = this.parts.get(key);
20486
+ const size = (parts?.bytes ?? 0) + (bytes?.length ?? 0);
20487
+ if (!bytes || size > MAX_LIVE_SYNC_BYTES) {
20488
+ this.parts.delete(key);
20489
+ connection.send({
20490
+ type: "error",
20491
+ artifactId: message.artifactId,
20492
+ message: bytes ? `[SixbServer] A sync message holds at most ${MAX_LIVE_SYNC_BYTES} bytes.` : "[SixbServer] A sync message's data is base64."
20493
+ });
20494
+ return null;
20495
+ }
20496
+ if (message.more) {
20497
+ this.parts.set(key, { chunks: [...parts?.chunks ?? [], bytes], bytes: size });
20498
+ return null;
20499
+ }
20500
+ if (!parts)
20501
+ return bytes;
20502
+ this.parts.delete(key);
20503
+ const whole = new Uint8Array(size);
20504
+ let offset = 0;
20505
+ for (const chunk of [...parts.chunks, bytes]) {
20506
+ whole.set(chunk, offset);
20507
+ offset += chunk.length;
20508
+ }
20509
+ return whole;
20510
+ }
20511
+ async held(connection, artifactId) {
20512
+ if (!this.joined.get(connection.id)?.has(artifactId)) {
20513
+ connection.send({
20514
+ type: "error",
20515
+ artifactId,
20516
+ message: "[SixbServer] Join the artifact before sending it changes."
20517
+ });
20518
+ return null;
20519
+ }
20520
+ const room = await this.rooms.get(artifactId);
20521
+ return room instanceof LiveRoom ? room : null;
20522
+ }
20523
+ async open(artifactId) {
20524
+ const existing = await this.rooms.get(artifactId);
20525
+ if (existing instanceof LiveRoom && !existing.isClosed)
20526
+ return existing;
20527
+ this.followEvents();
20528
+ const opening = LiveRoom.open(this.host, artifactId, () => {
20529
+ if (this.rooms.get(artifactId) === opening)
20530
+ this.rooms.delete(artifactId);
20531
+ });
20532
+ this.rooms.set(artifactId, opening);
20533
+ const room = await opening.catch((error) => {
20534
+ this.rooms.delete(artifactId);
20535
+ throw error;
20536
+ });
20537
+ if (!(room instanceof LiveRoom))
20538
+ this.rooms.delete(artifactId);
20539
+ return room;
20540
+ }
20541
+ followEvents() {
20542
+ if (this.events || this.closed)
20543
+ return;
20544
+ const following = this.host.events.subscribe({ from: "latest", types: ["artifact.updated"] }, async (events) => {
20545
+ for (const event of events) {
20546
+ if (event.type !== "artifact.updated")
20547
+ continue;
20548
+ const room = await this.rooms.get(event.payload.artifactId);
20549
+ if (room instanceof LiveRoom)
20550
+ room.written(event.payload.revision);
20551
+ }
20552
+ });
20553
+ this.events = following;
20554
+ following.catch((error) => {
20555
+ if (this.events === following)
20556
+ this.events = undefined;
20557
+ console.error("[SixbServer] Could not follow the artifacts' writes:", error);
20558
+ });
20559
+ }
20560
+ }
20561
+ function partsKey(connection, artifactId) {
20562
+ return `${connection.id}
20563
+ ${artifactId}`;
20564
+ }
20565
+
20566
+ // src/routes/ws/artifacts.ts
20567
+ var ArtifactId = z44.string().min(1).max(200);
20568
+ var LiveMessageSchema = z44.discriminatedUnion("type", [
20569
+ z44.object({ type: z44.literal("join"), artifactId: ArtifactId }),
20570
+ z44.object({ type: z44.literal("leave"), artifactId: ArtifactId }),
20571
+ z44.object({
20572
+ type: z44.literal("sync"),
20573
+ artifactId: ArtifactId,
20574
+ data: z44.string().min(1),
20575
+ more: z44.literal(true).optional()
20576
+ }),
20577
+ z44.object({ type: z44.literal("awareness"), artifactId: ArtifactId, data: z44.string().min(1) })
20578
+ ]);
20579
+ async function decodeLiveMessage(message) {
20580
+ if (typeof message === "object" && message !== null && "type" in message)
20581
+ return message;
20582
+ return decodeWsMessage(message);
20583
+ }
20584
+ function parseArtifactLiveMessage(payload) {
20585
+ const parsed = LiveMessageSchema.safeParse(payload);
20586
+ if (!parsed.success) {
20587
+ return { ok: false, error: parsed.error.issues[0]?.message ?? "Invalid websocket message." };
20588
+ }
20589
+ return { ok: true, data: parsed.data };
20590
+ }
20591
+ function registerArtifactLiveRoutes(app, server, shared) {
20592
+ const host = server.getHost();
20593
+ const rooms = new LiveRooms({
20594
+ projectId: host.id,
20595
+ storage: host.storage,
20596
+ blobStorage: host.blobStorage,
20597
+ broker: host.broker,
20598
+ events: host.events,
20599
+ instance: randomUUID3(),
20600
+ errorReporterHost: host
20601
+ });
20602
+ const connections = new WeakMap;
20603
+ const connectionOf = (ws) => {
20604
+ const known = connections.get(wsStateKey(ws));
20605
+ if (known)
20606
+ return known;
20607
+ const sixb = wsRequestSixb(ws);
20608
+ if (!sixb)
20609
+ return null;
20610
+ const guest = wsSharedSession(ws);
20611
+ const connection = {
20612
+ id: randomUUID3(),
20613
+ sixb,
20614
+ send: (message) => safeSend(ws, message),
20615
+ ...guest ? {
20616
+ user: async () => guestLiveUser(guest.sessionId, (await shared.session(ws))?.guestName)
20617
+ } : {}
20618
+ };
20619
+ connections.set(wsStateKey(ws), connection);
20620
+ return connection;
20621
+ };
20622
+ app.onStop(() => rooms.close());
20623
+ return app.ws(ARTIFACT_LIVE_ROUTE2, {
20624
+ open(ws) {
20625
+ shared.open(ws, () => {
20626
+ const connection = connections.get(wsStateKey(ws));
20627
+ if (connection)
20628
+ rooms.refreshUser(connection);
20629
+ });
20630
+ safeSend(ws, { type: "connected", channel: "artifacts" });
20631
+ },
20632
+ async message(ws, message) {
20633
+ if (!await shared.holds(ws))
20634
+ return;
20635
+ const connection = connectionOf(ws);
20636
+ if (!connection) {
20637
+ safeSend(ws, { type: "error", message: "Execution scope is not available." });
20638
+ return;
20639
+ }
20640
+ const parsed = parseArtifactLiveMessage(await decodeLiveMessage(message));
20641
+ if (!parsed.ok) {
20642
+ safeSend(ws, { type: "error", message: parsed.error });
20643
+ return;
20644
+ }
20645
+ try {
20646
+ await rooms.receive(connection, parsed.data);
20647
+ } catch (error) {
20648
+ console.error("[SixbServer] A live artifact message failed:", error);
20649
+ safeSend(ws, {
20650
+ type: "error",
20651
+ artifactId: parsed.data.artifactId,
20652
+ message: "[SixbServer] The live artifact could not handle that message."
20653
+ });
20654
+ }
20655
+ },
20656
+ async close(ws) {
20657
+ shared.close(ws);
20658
+ const connection = connections.get(wsStateKey(ws));
20659
+ connections.delete(wsStateKey(ws));
20660
+ if (connection)
20661
+ await rooms.disconnect(connection);
20662
+ }
20663
+ });
20664
+ }
20665
+
18685
20666
  // src/routes/ws/events.ts
18686
20667
  import { scopeKeysForEvent } from "@sixb/core/internal/event-scope";
18687
- import { z as z43 } from "zod";
20668
+ import { z as z45 } from "zod";
18688
20669
 
18689
20670
  // src/routes/ws/subscription-hub.ts
18690
20671
  import { BrokerCursorExpiredError as BrokerCursorExpiredError2 } from "@sixb/core/broker";
@@ -19015,20 +20996,20 @@ function socketBufferedAmount(ws) {
19015
20996
 
19016
20997
  // src/routes/ws/events.ts
19017
20998
  var DEFAULT_READ_LIMIT = 200;
19018
- var SubscribeSchema2 = z43.object({
19019
- type: z43.literal("subscribe"),
19020
- topic: z43.enum(EVENT_TOPICS).optional(),
19021
- types: z43.array(z43.enum(EVENT_TYPES)).optional(),
19022
- objectTypeId: z43.string().optional(),
19023
- primaryId: z43.string().optional(),
19024
- runId: z43.string().optional(),
19025
- afterCursor: z43.string().optional(),
19026
- limit: z43.number().int().positive().max(500).optional()
19027
- });
19028
- var UnsubscribeSchema2 = z43.object({
19029
- type: z43.literal("unsubscribe")
19030
- });
19031
- var SubscriptionMessageSchema = z43.union([SubscribeSchema2, UnsubscribeSchema2]);
20999
+ var SubscribeSchema2 = z45.object({
21000
+ type: z45.literal("subscribe"),
21001
+ topic: z45.enum(EVENT_TOPICS).optional(),
21002
+ types: z45.array(z45.enum(EVENT_TYPES)).optional(),
21003
+ objectTypeId: z45.string().optional(),
21004
+ primaryId: z45.string().optional(),
21005
+ runId: z45.string().optional(),
21006
+ afterCursor: z45.string().optional(),
21007
+ limit: z45.number().int().positive().max(500).optional()
21008
+ });
21009
+ var UnsubscribeSchema2 = z45.object({
21010
+ type: z45.literal("unsubscribe")
21011
+ });
21012
+ var SubscriptionMessageSchema = z45.union([SubscribeSchema2, UnsubscribeSchema2]);
19032
21013
  function parseSubscriptionMessage(payload) {
19033
21014
  if (!payload || typeof payload !== "object") {
19034
21015
  return { ok: false, error: "Message must be a JSON object." };
@@ -19042,7 +21023,7 @@ function parseSubscriptionMessage(payload) {
19042
21023
  }
19043
21024
  return { ok: true, data: parsed.data };
19044
21025
  }
19045
- function registerEventStreamRoutes(app, server) {
21026
+ function registerEventStreamRoutes(app, server, shared) {
19046
21027
  const events = server.getHost().events;
19047
21028
  const states = new WeakMap;
19048
21029
  const hub = new SubscriptionHub({
@@ -19073,6 +21054,7 @@ function registerEventStreamRoutes(app, server) {
19073
21054
  app.onStop(() => hub.close());
19074
21055
  return app.ws("/ws/events", {
19075
21056
  async open(ws) {
21057
+ shared.open(ws);
19076
21058
  const state = {
19077
21059
  replayFrom: null,
19078
21060
  initialized: Promise.resolve(),
@@ -19087,6 +21069,8 @@ function registerEventStreamRoutes(app, server) {
19087
21069
  safeSend(ws, { type: "connected", channel: "events" });
19088
21070
  },
19089
21071
  async message(ws, message) {
21072
+ if (!await shared.holds(ws))
21073
+ return;
19090
21074
  const decoded = await decodeWsMessage(message);
19091
21075
  const parsed = parseSubscriptionMessage(decoded);
19092
21076
  if (!parsed.ok) {
@@ -19151,6 +21135,7 @@ function registerEventStreamRoutes(app, server) {
19151
21135
  }
19152
21136
  },
19153
21137
  close(ws) {
21138
+ shared.close(ws);
19154
21139
  hub.unsubscribe(wsStateKey(ws));
19155
21140
  states.delete(wsStateKey(ws));
19156
21141
  }
@@ -19175,28 +21160,28 @@ function eventMatchesScope(event, filter) {
19175
21160
  }
19176
21161
 
19177
21162
  // src/routes/ws/logs.ts
19178
- import { z as z44 } from "zod";
21163
+ import { z as z46 } from "zod";
19179
21164
  var READ_PAGE_SIZE = 500;
19180
- var SubscribeSchema3 = z44.object({
19181
- type: z44.literal("subscribe"),
19182
- kinds: z44.array(z44.enum(SIXB_RUN_KINDS)).min(1).optional(),
19183
- levels: z44.array(z44.enum(LOG_LEVELS)).min(1).optional(),
19184
- run: z44.object({
19185
- kind: z44.enum(SIXB_RUN_KINDS),
21165
+ var SubscribeSchema3 = z46.object({
21166
+ type: z46.literal("subscribe"),
21167
+ kinds: z46.array(z46.enum(SIXB_RUN_KINDS)).min(1).optional(),
21168
+ levels: z46.array(z46.enum(LOG_LEVELS)).min(1).optional(),
21169
+ run: z46.object({
21170
+ kind: z46.enum(SIXB_RUN_KINDS),
19186
21171
  id: LogRunIdSchema
19187
21172
  }).optional(),
19188
- afterCursor: z44.string().optional()
21173
+ afterCursor: z46.string().optional()
19189
21174
  }).superRefine((value, context) => {
19190
21175
  if (value.run && value.kinds && !value.kinds.includes(value.run.kind)) {
19191
21176
  context.addIssue({
19192
- code: z44.ZodIssueCode.custom,
21177
+ code: z46.ZodIssueCode.custom,
19193
21178
  path: ["run"],
19194
21179
  message: "run.kind must be included in kinds"
19195
21180
  });
19196
21181
  }
19197
21182
  });
19198
- var UnsubscribeSchema3 = z44.object({ type: z44.literal("unsubscribe") });
19199
- var SubscriptionMessageSchema2 = z44.union([SubscribeSchema3, UnsubscribeSchema3]);
21183
+ var UnsubscribeSchema3 = z46.object({ type: z46.literal("unsubscribe") });
21184
+ var SubscriptionMessageSchema2 = z46.union([SubscribeSchema3, UnsubscribeSchema3]);
19200
21185
  function parseLogSubscriptionMessage(payload) {
19201
21186
  if (!payload || typeof payload !== "object") {
19202
21187
  return { ok: false, error: "Message must be a JSON object." };
@@ -19321,11 +21306,103 @@ function matchesLogFilter(line, filter) {
19321
21306
  return true;
19322
21307
  }
19323
21308
 
21309
+ // src/routes/ws/shared-sockets.ts
21310
+ var SHARED_SOCKET_RECHECK_MS = 1e4;
21311
+ var SHARED_ACCESS_ENDED_CLOSE_CODE = 4401;
21312
+ var UNREADABLE_SESSION_CLOSE_CODE = 1011;
21313
+
21314
+ class SharedSockets {
21315
+ boundary;
21316
+ watches = new WeakMap;
21317
+ sockets = new Map;
21318
+ constructor(boundary) {
21319
+ this.boundary = boundary;
21320
+ boundary.onGuestNamed((sessionId) => {
21321
+ for (const ws of this.sockets.get(sessionId)?.values() ?? []) {
21322
+ const watch = this.watches.get(wsStateKey(ws));
21323
+ const session = wsSharedSession(ws);
21324
+ if (watch && session)
21325
+ this.read(ws, watch, session);
21326
+ }
21327
+ });
21328
+ }
21329
+ open(ws, onRenamed) {
21330
+ const session = wsSharedSession(ws);
21331
+ if (!session)
21332
+ return;
21333
+ const watch = {
21334
+ current: Promise.resolve(session),
21335
+ checkedAt: Date.now(),
21336
+ name: session.guestName,
21337
+ timer: setInterval(() => void this.read(ws, watch, session), SHARED_SOCKET_RECHECK_MS),
21338
+ onRenamed
21339
+ };
21340
+ this.watches.set(wsStateKey(ws), watch);
21341
+ const open = this.sockets.get(session.sessionId) ?? new Map;
21342
+ this.sockets.set(session.sessionId, open.set(wsStateKey(ws), ws));
21343
+ }
21344
+ async holds(ws) {
21345
+ const watch = this.watches.get(wsStateKey(ws));
21346
+ const session = wsSharedSession(ws);
21347
+ if (!watch || !session)
21348
+ return true;
21349
+ if (Date.now() - watch.checkedAt >= SHARED_SOCKET_RECHECK_MS)
21350
+ this.read(ws, watch, session);
21351
+ return await watch.current !== null;
21352
+ }
21353
+ async session(ws) {
21354
+ const watch = this.watches.get(wsStateKey(ws));
21355
+ const session = wsSharedSession(ws);
21356
+ if (!watch || !session)
21357
+ return null;
21358
+ this.read(ws, watch, session);
21359
+ return watch.current;
21360
+ }
21361
+ close(ws) {
21362
+ const key = wsStateKey(ws);
21363
+ const watch = this.watches.get(key);
21364
+ if (watch)
21365
+ clearInterval(watch.timer);
21366
+ this.watches.delete(key);
21367
+ const session = wsSharedSession(ws);
21368
+ const open = session ? this.sockets.get(session.sessionId) : undefined;
21369
+ open?.delete(key);
21370
+ if (session && open?.size === 0)
21371
+ this.sockets.delete(session.sessionId);
21372
+ }
21373
+ read(ws, watch, session) {
21374
+ watch.checkedAt = Date.now();
21375
+ watch.current = this.boundary.current(session).then((current) => {
21376
+ if (!current) {
21377
+ this.end(ws, SHARED_ACCESS_ENDED_CLOSE_CODE, "Shared access ended");
21378
+ return current;
21379
+ }
21380
+ if (current.guestName !== watch.name) {
21381
+ watch.name = current.guestName;
21382
+ watch.onRenamed?.();
21383
+ }
21384
+ return current;
21385
+ }, (error) => {
21386
+ console.error("[SixbServer] A shared link's socket could not read its session:", error);
21387
+ this.end(ws, UNREADABLE_SESSION_CLOSE_CODE, "Shared access could not be checked");
21388
+ return null;
21389
+ });
21390
+ }
21391
+ end(ws, code, reason) {
21392
+ this.close(ws);
21393
+ try {
21394
+ ws.close(code, reason);
21395
+ } catch {}
21396
+ }
21397
+ }
21398
+
19324
21399
  // src/routes/ws/index.ts
19325
- function registerWebSocketRoutes(app, server) {
19326
- registerEventStreamRoutes(app, server);
21400
+ function registerWebSocketRoutes(app, server, sharedAccess) {
21401
+ const shared = new SharedSockets(sharedAccess);
21402
+ registerEventStreamRoutes(app, server, shared);
19327
21403
  registerLogStreamRoutes(app, server);
19328
21404
  registerAgentStreamRoutes(app, server);
21405
+ registerArtifactLiveRoutes(app, server, shared);
19329
21406
  return app;
19330
21407
  }
19331
21408
 
@@ -19349,6 +21426,8 @@ class SixbServer {
19349
21426
  timing;
19350
21427
  app = null;
19351
21428
  bunServer = null;
21429
+ hostsOntologyMaintenance;
21430
+ flushesIngestion;
19352
21431
  maintenance = null;
19353
21432
  stopSweeper = null;
19354
21433
  constructor(options) {
@@ -19357,6 +21436,8 @@ class SixbServer {
19357
21436
  this.hostname = options.hostname ?? "0.0.0.0";
19358
21437
  this.quiet = options.quiet ?? false;
19359
21438
  this.timing = options.timing ?? {};
21439
+ this.hostsOntologyMaintenance = options.ontologyMaintenance ?? true;
21440
+ this.flushesIngestion = options.ingestFlush ?? true;
19360
21441
  this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser);
19361
21442
  if (this.apiBrowserPolicy.publicOrigin) {
19362
21443
  setApiPublicOrigin(this.hostRuntime, this.apiBrowserPolicy.publicOrigin);
@@ -19403,7 +21484,9 @@ class SixbServer {
19403
21484
  lakeStorage: this.hostRuntime.lakeStorage
19404
21485
  });
19405
21486
  warmAppliedMarkings(this.hostRuntime);
19406
- const maintenance = await this.hostRuntime.startOntologyMaintenance();
21487
+ this.hostRuntime.prepareReadiness();
21488
+ this.setIngestFlush(this.flushesIngestion);
21489
+ const maintenance = this.hostsOntologyMaintenance ? await this.hostRuntime.startOntologyMaintenance() : null;
19407
21490
  this.maintenance = maintenance;
19408
21491
  try {
19409
21492
  this.app = createSixbApi(this);
@@ -19417,7 +21500,7 @@ class SixbServer {
19417
21500
  this.app = null;
19418
21501
  this.bunServer = null;
19419
21502
  this.maintenance = null;
19420
- await maintenance.stop();
21503
+ await maintenance?.stop();
19421
21504
  const message = error instanceof Error ? error.message : String(error);
19422
21505
  throw new Error(`[SixbServer] Failed to listen on ${this.hostname}:${this.port}: ${message}`);
19423
21506
  }
@@ -19428,7 +21511,13 @@ class SixbServer {
19428
21511
  console.log(`OpenAPI docs at ${base}/docs`);
19429
21512
  }
19430
21513
  }
21514
+ setIngestFlush(inline) {
21515
+ const ingest = findDatasetIngestRuntime(this.hostRuntime);
21516
+ if (ingest)
21517
+ ingest.writesInline = inline;
21518
+ }
19431
21519
  async stop() {
21520
+ this.setIngestFlush(false);
19432
21521
  this.stopSweeper?.();
19433
21522
  this.stopSweeper = null;
19434
21523
  if (this.bunServer) {
@@ -19510,6 +21599,7 @@ function createSixbApi(server) {
19510
21599
  return {
19511
21600
  auth: { kind: "allow", session: null },
19512
21601
  sharedAccessCookies: null,
21602
+ sharedSession: null,
19513
21603
  ...agentState,
19514
21604
  sixb: bindAgentRunRequestExecution2(host, { signal: request.signal, ...runExecution })
19515
21605
  };
@@ -19520,6 +21610,7 @@ function createSixbApi(server) {
19520
21610
  return {
19521
21611
  auth: { kind: "deny", response: shared.response },
19522
21612
  sharedAccessCookies: null,
21613
+ sharedSession: null,
19523
21614
  sixb: null
19524
21615
  };
19525
21616
  }
@@ -19527,6 +21618,7 @@ function createSixbApi(server) {
19527
21618
  return {
19528
21619
  auth: { kind: "allow", session: null },
19529
21620
  sharedAccessCookies: shared.cookies,
21621
+ sharedSession: shared.context,
19530
21622
  sixb: bindRequestExecution(host, {
19531
21623
  request,
19532
21624
  authorization: {
@@ -19546,6 +21638,7 @@ function createSixbApi(server) {
19546
21638
  return {
19547
21639
  auth,
19548
21640
  sharedAccessCookies: null,
21641
+ sharedSession: null,
19549
21642
  sixb: auth.kind === "allow" && !guard.isAuthEnabled() ? bindRequestExecution(host, {
19550
21643
  request,
19551
21644
  authorization: { type: "disabled" }
@@ -19557,6 +21650,7 @@ function createSixbApi(server) {
19557
21650
  return {
19558
21651
  auth,
19559
21652
  sharedAccessCookies: null,
21653
+ sharedSession: null,
19560
21654
  sixb: bindRequestExecution(host, {
19561
21655
  request,
19562
21656
  authorization: { type: "principal", context: authz, credential }
@@ -19643,7 +21737,7 @@ function createSixbApi(server) {
19643
21737
  }
19644
21738
  });
19645
21739
  registerWebhookRoutes(app, host);
19646
- registerWebSocketRoutes(app, server);
21740
+ registerWebSocketRoutes(app, server, sharedAccess);
19647
21741
  return app;
19648
21742
  }
19649
21743
  function appendSetCookieHeaders(set, values) {
@@ -19727,4 +21821,4 @@ export {
19727
21821
  requestTimingOptionsFromEnv
19728
21822
  };
19729
21823
 
19730
- //# debugId=BFDF3ADA46380F7264756E2164756E21
21824
+ //# debugId=B5AFC4B93CECC31464756E2164756E21