@sixb/server 0.2.1 → 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 (153) 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 +2876 -667
  10. package/dist/index.js.map +43 -36
  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 +21 -11
  20. package/dist/routes/agent-approvals.d.ts.map +1 -1
  21. package/dist/routes/agent-children.d.ts +4 -4
  22. package/dist/routes/agent-computers.d.ts +146 -1
  23. package/dist/routes/agent-computers.d.ts.map +1 -1
  24. package/dist/routes/agent-runners.d.ts.map +1 -1
  25. package/dist/routes/agents.d.ts +152 -60
  26. package/dist/routes/agents.d.ts.map +1 -1
  27. package/dist/routes/artifact-frames.d.ts +2 -1
  28. package/dist/routes/artifact-frames.d.ts.map +1 -1
  29. package/dist/routes/artifacts.d.ts +1713 -178
  30. package/dist/routes/artifacts.d.ts.map +1 -1
  31. package/dist/routes/auth.d.ts +21 -21
  32. package/dist/routes/connector-connection-runs.d.ts +124 -5
  33. package/dist/routes/connector-connection-runs.d.ts.map +1 -1
  34. package/dist/routes/connector-connections.d.ts +9 -1
  35. package/dist/routes/connector-connections.d.ts.map +1 -1
  36. package/dist/routes/datasets.d.ts +5 -5
  37. package/dist/routes/events.d.ts +4 -4
  38. package/dist/routes/lake.d.ts +91 -0
  39. package/dist/routes/lake.d.ts.map +1 -0
  40. package/dist/routes/links.d.ts +6 -6
  41. package/dist/routes/logs.d.ts +2 -2
  42. package/dist/routes/model-generations.d.ts +2 -2
  43. package/dist/routes/objects.d.ts +6 -6
  44. package/dist/routes/objects.d.ts.map +1 -1
  45. package/dist/routes/observed-agent-threads.d.ts +21 -11
  46. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  47. package/dist/routes/ontology.d.ts +6 -6
  48. package/dist/routes/pipelines.d.ts +13 -9
  49. package/dist/routes/pipelines.d.ts.map +1 -1
  50. package/dist/routes/projections.d.ts +27 -27
  51. package/dist/routes/share-grants.d.ts +9 -9
  52. package/dist/routes/shared-access.d.ts +57 -2
  53. package/dist/routes/shared-access.d.ts.map +1 -1
  54. package/dist/routes/status.d.ts +11 -15
  55. package/dist/routes/status.d.ts.map +1 -1
  56. package/dist/routes/syncs.d.ts +9 -6
  57. package/dist/routes/syncs.d.ts.map +1 -1
  58. package/dist/routes/telemetry.d.ts +7 -7
  59. package/dist/routes/webhooks.d.ts.map +1 -1
  60. package/dist/routes/workflows.d.ts +14 -14
  61. package/dist/routes/ws/artifacts.d.ts +57 -0
  62. package/dist/routes/ws/artifacts.d.ts.map +1 -0
  63. package/dist/routes/ws/events.d.ts +8 -7
  64. package/dist/routes/ws/events.d.ts.map +1 -1
  65. package/dist/routes/ws/index.d.ts +2 -1
  66. package/dist/routes/ws/index.d.ts.map +1 -1
  67. package/dist/routes/ws/logs.d.ts +10 -10
  68. package/dist/routes/ws/shared-sockets.d.ts +52 -0
  69. package/dist/routes/ws/shared-sockets.d.ts.map +1 -0
  70. package/dist/schemas/actions.d.ts +7 -7
  71. package/dist/schemas/activity.d.ts +16 -16
  72. package/dist/schemas/agent-approvals.d.ts +27 -27
  73. package/dist/schemas/agents.d.ts +642 -196
  74. package/dist/schemas/agents.d.ts.map +1 -1
  75. package/dist/schemas/ai-accounting.d.ts +41 -41
  76. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  77. package/dist/schemas/artifacts.d.ts +2106 -127
  78. package/dist/schemas/artifacts.d.ts.map +1 -1
  79. package/dist/schemas/auth.d.ts +63 -63
  80. package/dist/schemas/connectors.d.ts +180 -20
  81. package/dist/schemas/connectors.d.ts.map +1 -1
  82. package/dist/schemas/datasets.d.ts +44 -44
  83. package/dist/schemas/event-payloads.d.ts +2 -2
  84. package/dist/schemas/events.d.ts +26 -26
  85. package/dist/schemas/events.d.ts.map +1 -1
  86. package/dist/schemas/files.d.ts +12 -0
  87. package/dist/schemas/files.d.ts.map +1 -1
  88. package/dist/schemas/lake.d.ts +251 -0
  89. package/dist/schemas/lake.d.ts.map +1 -0
  90. package/dist/schemas/lineage.d.ts +56 -56
  91. package/dist/schemas/logs.d.ts +18 -18
  92. package/dist/schemas/models.d.ts +4 -4
  93. package/dist/schemas/objects.d.ts.map +1 -1
  94. package/dist/schemas/ontology.d.ts +14 -14
  95. package/dist/schemas/pipelines.d.ts +86 -64
  96. package/dist/schemas/pipelines.d.ts.map +1 -1
  97. package/dist/schemas/projections.d.ts +160 -160
  98. package/dist/schemas/projections.d.ts.map +1 -1
  99. package/dist/schemas/share-grants.d.ts +30 -30
  100. package/dist/schemas/shared-access.d.ts +17 -4
  101. package/dist/schemas/shared-access.d.ts.map +1 -1
  102. package/dist/schemas/status.d.ts +59 -79
  103. package/dist/schemas/status.d.ts.map +1 -1
  104. package/dist/schemas/syncs.d.ts +38 -22
  105. package/dist/schemas/syncs.d.ts.map +1 -1
  106. package/dist/schemas/telemetry.d.ts +26 -26
  107. package/dist/schemas/workflows.d.ts +71 -71
  108. package/dist/server.d.ts +13 -0
  109. package/dist/server.d.ts.map +1 -1
  110. package/dist/utils/ws.d.ts +3 -0
  111. package/dist/utils/ws.d.ts.map +1 -1
  112. package/package.json +11 -7
  113. package/src/artifacts/frame.ts +4 -13
  114. package/src/auth/scope.ts +10 -1
  115. package/src/auth/shared-access.ts +108 -12
  116. package/src/connectors/http.ts +35 -1
  117. package/src/live/README.md +136 -0
  118. package/src/live/awareness.ts +141 -0
  119. package/src/live/room.ts +933 -0
  120. package/src/live/rooms.ts +288 -0
  121. package/src/registerRoutes.ts +2 -0
  122. package/src/routes/agent-computers.ts +208 -14
  123. package/src/routes/agent-runners.ts +1 -0
  124. package/src/routes/agents.ts +52 -7
  125. package/src/routes/artifact-frames.ts +40 -12
  126. package/src/routes/artifacts.ts +713 -28
  127. package/src/routes/connector-connection-runs.ts +7 -12
  128. package/src/routes/connector-connections.ts +10 -7
  129. package/src/routes/lake.ts +73 -0
  130. package/src/routes/objects.ts +3 -9
  131. package/src/routes/pipelines.ts +1 -0
  132. package/src/routes/shared-access.ts +53 -1
  133. package/src/routes/status.ts +9 -4
  134. package/src/routes/syncs.ts +1 -0
  135. package/src/routes/webhooks.ts +44 -3
  136. package/src/routes/ws/artifacts.ts +138 -0
  137. package/src/routes/ws/events.ts +7 -2
  138. package/src/routes/ws/index.ts +13 -2
  139. package/src/routes/ws/shared-sockets.ts +152 -0
  140. package/src/schemas/agents.ts +71 -1
  141. package/src/schemas/ai-accounting.ts +1 -0
  142. package/src/schemas/artifacts.ts +255 -18
  143. package/src/schemas/connectors.ts +17 -2
  144. package/src/schemas/files.ts +12 -0
  145. package/src/schemas/lake.ts +53 -0
  146. package/src/schemas/objects.ts +1 -0
  147. package/src/schemas/pipelines.ts +2 -0
  148. package/src/schemas/projections.ts +2 -2
  149. package/src/schemas/shared-access.ts +16 -0
  150. package/src/schemas/status.ts +16 -22
  151. package/src/schemas/syncs.ts +2 -0
  152. package/src/server.ts +35 -4
  153. 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(),
@@ -1511,7 +1566,8 @@ var ModelKindSchema = z8.enum([
1511
1566
  "decision",
1512
1567
  "transcription",
1513
1568
  "speech",
1514
- "reranking"
1569
+ "reranking",
1570
+ "web-search"
1515
1571
  ]);
1516
1572
  var AiAccountingRangeQuerySchema = z8.object({
1517
1573
  from: IsoDateSchema,
@@ -1840,6 +1896,15 @@ var AgentThreadComputerInputSchema = z9.object({
1840
1896
  name: plainText(z9.string().trim().min(1).max(120)),
1841
1897
  folder: plainText(z9.string().min(1).max(4096))
1842
1898
  }).strict();
1899
+ var AgentBackgroundCommandSchema = z9.object({
1900
+ threadId: z9.string().min(1).max(200),
1901
+ id: z9.string().min(1).max(200),
1902
+ command: z9.string().max(1000),
1903
+ status: z9.enum(["running", "exited", "stopped"]),
1904
+ exitCode: z9.number().int().optional(),
1905
+ startedAt: z9.string().min(1).max(200),
1906
+ endedAt: z9.string().max(200).optional()
1907
+ }).strict();
1843
1908
  var CreateAgentThreadBodySchema = z9.object({
1844
1909
  title: z9.string().trim().min(1).optional(),
1845
1910
  threadId: z9.string().trim().min(1).optional(),
@@ -1881,6 +1946,7 @@ var AgentThreadSchema = z9.object({
1881
1946
  folder: z9.string(),
1882
1947
  online: z9.boolean()
1883
1948
  }).optional(),
1949
+ backgroundCommands: z9.array(AgentBackgroundCommandSchema.extend({ stopping: z9.boolean().optional() })).optional(),
1884
1950
  movedAt: z9.string().optional(),
1885
1951
  status: AgentThreadStatusSchema,
1886
1952
  activeRunId: z9.string().nullable(),
@@ -1903,10 +1969,37 @@ var MoveAgentThreadToComputerBodySchema = z9.object({ computer: AgentThreadCompu
1903
1969
  var AgentComputerSessionParamsSchema = z9.object({
1904
1970
  sessionId: z9.string().trim().min(1).max(200)
1905
1971
  });
1906
- var HoldAgentComputerSessionBodySchema = z9.object({ computer: AgentThreadComputerInputSchema }).strict();
1972
+ var HoldAgentComputerSessionBodySchema = z9.object({
1973
+ computer: AgentThreadComputerInputSchema,
1974
+ backgroundCommands: z9.array(AgentBackgroundCommandSchema).max(64).optional()
1975
+ }).strict();
1976
+ var AgentBackgroundCommandRefSchema = z9.object({
1977
+ threadId: z9.string(),
1978
+ id: z9.string(),
1979
+ startedAt: z9.string()
1980
+ });
1907
1981
  var HoldAgentComputerSessionResponseSchema = z9.object({
1908
1982
  expiresAt: z9.string(),
1909
- waiting: z9.array(z9.string())
1983
+ waiting: z9.array(z9.string()),
1984
+ stop: z9.array(AgentBackgroundCommandRefSchema).optional()
1985
+ });
1986
+ var AgentBackgroundCommandParamsSchema = z9.object({
1987
+ threadId: z9.string().trim().min(1),
1988
+ commandId: z9.string().trim().min(1).max(200)
1989
+ });
1990
+ var StopAgentBackgroundCommandBodySchema = z9.object({
1991
+ startedAt: z9.string().trim().min(1).max(200)
1992
+ }).strict();
1993
+ var StopAgentBackgroundCommandResponseSchema = z9.object({
1994
+ command: AgentBackgroundCommandSchema.extend({ stopping: z9.boolean().optional() })
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)
1910
2003
  });
1911
2004
  var AddAgentThreadParticipantsBodySchema = z9.object({
1912
2005
  users: z9.array(z9.union([
@@ -3255,9 +3348,15 @@ function serializeActionRunDetail(run) {
3255
3348
  import { SYSTEM_PRINCIPAL } from "@sixb/core";
3256
3349
  import { agentServiceAccountId } from "@sixb/core/internal/agents";
3257
3350
  function requestAuthState(context) {
3258
- const { sixb = null, agentRun, agentExecution } = context;
3351
+ const {
3352
+ sixb = null,
3353
+ sharedSession,
3354
+ agentRun,
3355
+ agentExecution
3356
+ } = context;
3259
3357
  return {
3260
3358
  sixb,
3359
+ ...sharedSession ? { sharedSession } : {},
3261
3360
  ...agentRun === undefined ? {} : { agentRun },
3262
3361
  ...agentExecution === undefined ? {} : { agentExecution }
3263
3362
  };
@@ -4358,7 +4457,7 @@ async function serializeThreads(host, threads, viewer) {
4358
4457
  title: thread.title,
4359
4458
  sandboxParams: thread.sandboxParams,
4360
4459
  runsOn: thread.runsOn,
4361
- computer: placeOf(thread),
4460
+ ...placeOf(thread),
4362
4461
  movedAt: thread.movedAt ? toIsoString(thread.movedAt) : undefined,
4363
4462
  sandboxState: thread.sandboxState && {
4364
4463
  name: thread.sandboxState.name,
@@ -4380,20 +4479,30 @@ async function serializeThread(host, thread, viewer) {
4380
4479
  return serialized;
4381
4480
  }
4382
4481
  async function computerPlaces(host, threads, viewer) {
4383
- const owned = (thread) => thread.computer !== undefined && principalsEqual(thread.ownerPrincipal, viewer);
4482
+ const owned = (thread) => (thread.computer !== undefined || thread.movedAt !== undefined) && principalsEqual(thread.ownerPrincipal, viewer);
4384
4483
  const live = host.storage.agents && threads.some(owned) ? await host.storage.agents.computers.listLive({
4385
4484
  projectId: host.id,
4386
4485
  ownerPrincipal: viewer,
4387
4486
  now: new Date
4388
4487
  }) : [];
4389
4488
  return (thread) => {
4489
+ if (!owned(thread))
4490
+ return {};
4491
+ const backgroundCommands = live.flatMap((session) => (session.backgroundCommands ?? []).filter((command) => command.threadId === thread.id).map((command) => {
4492
+ const stopping = command.status === "running" && (session.stopRequests ?? []).some((ref) => sameBackgroundCommand(command, ref));
4493
+ return stopping ? { ...command, stopping } : command;
4494
+ }));
4390
4495
  const computer = thread.computer;
4391
- if (!computer || !owned(thread))
4392
- return;
4393
- const online = live.some((session) => sameComputerPlace(session.computer, computer));
4394
- return { ...computer, online };
4496
+ const online = computer !== undefined && live.some((session) => sameComputerPlace(session.computer, computer));
4497
+ return {
4498
+ ...computer ? { computer: { ...computer, online } } : {},
4499
+ ...backgroundCommands.length > 0 ? { backgroundCommands } : {}
4500
+ };
4395
4501
  };
4396
4502
  }
4503
+ function sameBackgroundCommand(command, ref) {
4504
+ return command.threadId === ref.threadId && command.id === ref.id && command.startedAt === ref.startedAt;
4505
+ }
4397
4506
  function serializeMessage(message, annotations = [], checkpoint) {
4398
4507
  return AgentMessageSchema.parse({
4399
4508
  id: message.id,
@@ -5583,11 +5692,16 @@ function registerAgentChildRoutes(app, host) {
5583
5692
  }
5584
5693
 
5585
5694
  // src/routes/agent-computers.ts
5695
+ import {
5696
+ AgentRequestError as AgentRequestError2,
5697
+ principalsEqual as principalsEqual2,
5698
+ stableJsonStringify
5699
+ } from "@sixb/core";
5586
5700
  import { sameComputerPlace as sameComputerPlace2 } from "@sixb/core/internal/agent-run-storage-provider";
5587
5701
  import { publishAgentComputerActivity } from "@sixb/core/internal/agents/streams";
5588
5702
  import { z as z15 } from "zod";
5589
5703
  var SESSION_MS = 60000;
5590
- var MAX_SESSIONS = 20;
5704
+ var MAX_SESSIONS = 200;
5591
5705
  async function computerClaiming(sessions, run, body) {
5592
5706
  const claimed = AgentThreadComputerInputSchema.safeParse(body?.computer);
5593
5707
  if (!claimed.success) {
@@ -5626,7 +5740,35 @@ async function endLapsedComputerSessions(host) {
5626
5740
  await announceOffline(host, agents, lapsed);
5627
5741
  }
5628
5742
  function registerAgentComputerRoutes(app, host) {
5629
- 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) => {
5630
5772
  const { params, body, set } = context;
5631
5773
  const sixb = requireRequestSixb(context);
5632
5774
  try {
@@ -5691,7 +5833,7 @@ function registerAgentComputerRoutes(app, host) {
5691
5833
  const agents = host.storage.agents;
5692
5834
  if (!agents)
5693
5835
  return unconfiguredStorageResponse(set, "Agent storage");
5694
- const { computer } = HoldAgentComputerSessionBodySchema.parse(body);
5836
+ const { computer, backgroundCommands = [] } = HoldAgentComputerSessionBodySchema.parse(body);
5695
5837
  const ownerPrincipal = requestActor(sixb);
5696
5838
  const now = new Date;
5697
5839
  const before = await agents.computers.listLive({
@@ -5702,7 +5844,7 @@ function registerAgentComputerRoutes(app, host) {
5702
5844
  if (before.length >= MAX_SESSIONS && !before.some((session) => session.id === params.sessionId)) {
5703
5845
  set.status = 429;
5704
5846
  return {
5705
- error: `[SixbServer] You have ${MAX_SESSIONS} sixb sessions open: quit one to open another.`
5847
+ error: `[SixbServer] You have ${MAX_SESSIONS} folders connected: forget one to connect another.`
5706
5848
  };
5707
5849
  }
5708
5850
  const expiresAt = new Date(now.getTime() + SESSION_MS);
@@ -5711,14 +5853,19 @@ function registerAgentComputerRoutes(app, host) {
5711
5853
  id: params.sessionId,
5712
5854
  ownerPrincipal,
5713
5855
  computer,
5714
- expiresAt
5856
+ expiresAt,
5857
+ ...backgroundCommands.length > 0 ? { backgroundCommands } : {}
5715
5858
  });
5716
- if (!before.some((session) => sameComputerPlace2(session.computer, computer))) {
5859
+ const held = before.find((session) => session.id === params.sessionId);
5860
+ const reported = !sameCommands(held?.backgroundCommands ?? [], backgroundCommands);
5861
+ if (reported || !before.some((session) => sameComputerPlace2(session.computer, computer))) {
5717
5862
  await announce(host, ownerPrincipal, computer, true);
5718
5863
  }
5864
+ const stop = (held?.stopRequests ?? []).filter((ref) => backgroundCommands.some((command) => command.status === "running" && sameBackgroundCommand(command, ref)));
5719
5865
  return HoldAgentComputerSessionResponseSchema.parse({
5720
5866
  expiresAt: expiresAt.toISOString(),
5721
- waiting: await waitingTurns(host, agents, ownerPrincipal, computer)
5867
+ waiting: await waitingTurns(host, agents, ownerPrincipal, computer),
5868
+ ...stop.length > 0 ? { stop } : {}
5722
5869
  });
5723
5870
  } catch (error) {
5724
5871
  return handleAgentRouteError(error, set);
@@ -5734,11 +5881,71 @@ function registerAgentComputerRoutes(app, host) {
5734
5881
  },
5735
5882
  detail: {
5736
5883
  summary: "Open or renew a computer session",
5737
- description: "`sixb` holds one while it is open: your threads on this computer, in this folder, read as online, and you can continue them from anywhere. It lapses a minute after its last renewal. The answer lists the turns waiting for it.",
5884
+ description: "`sixb` holds one while it is open: your threads on this computer, in this folder, read as online, and you can continue them from anywhere. It lapses a minute after its last renewal. It reports the background commands it runs for your threads; the answer lists the turns waiting for it, and the commands someone asked to stop.",
5738
5885
  tags: [OPENAPI_TAGS.agentThreads.name],
5739
5886
  operationId: "holdAgentComputerSession",
5740
5887
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5741
5888
  }
5889
+ }).post("/api/agent-threads/:threadId/background-commands/:commandId/stop", async (context) => {
5890
+ const { params, body, set } = context;
5891
+ const sixb = requireRequestSixb(context);
5892
+ try {
5893
+ const agents = host.storage.agents;
5894
+ if (!agents)
5895
+ return unconfiguredStorageResponse(set, "Agent storage");
5896
+ const { startedAt } = StopAgentBackgroundCommandBodySchema.parse(body);
5897
+ const thread = await sixb.agent.threads.getById(params.threadId);
5898
+ if (!thread) {
5899
+ throw new AgentRequestError2("thread_not_found", "[SixbServer] Agent thread not found.");
5900
+ }
5901
+ const ownerPrincipal = requestActor(sixb);
5902
+ if (!principalsEqual2(thread.ownerPrincipal, ownerPrincipal)) {
5903
+ throw new AgentRequestError2("not_thread_owner", `[SixbServer] Only the owner of Agent thread '${thread.id}' stops its background commands, which run on their computer.`);
5904
+ }
5905
+ const ref = { threadId: thread.id, id: params.commandId, startedAt };
5906
+ const live = await agents.computers.listLive({
5907
+ projectId: host.id,
5908
+ ownerPrincipal,
5909
+ now: new Date
5910
+ });
5911
+ const running = live.flatMap((session) => (session.backgroundCommands ?? []).map((command) => ({ session, command }))).find(({ command }) => command.status === "running" && sameBackgroundCommand(command, ref));
5912
+ const asked = running && await agents.computers.requestStop({
5913
+ projectId: host.id,
5914
+ id: running.session.id,
5915
+ ownerPrincipal,
5916
+ command: ref
5917
+ });
5918
+ if (!running || !asked) {
5919
+ set.status = 404;
5920
+ return {
5921
+ error: `[SixbServer] Background command '${params.commandId}' does not run on an open sixb: it ended, or sixb closed.`
5922
+ };
5923
+ }
5924
+ await announce(host, ownerPrincipal, running.session.computer, true);
5925
+ set.status = 202;
5926
+ return StopAgentBackgroundCommandResponseSchema.parse({
5927
+ command: { ...running.command, stopping: true }
5928
+ });
5929
+ } catch (error) {
5930
+ return handleAgentRouteError(error, set);
5931
+ }
5932
+ }, {
5933
+ params: AgentBackgroundCommandParamsSchema,
5934
+ body: StopAgentBackgroundCommandBodySchema,
5935
+ response: {
5936
+ 202: StopAgentBackgroundCommandResponseSchema,
5937
+ 400: AgentRequestErrorResponseSchema,
5938
+ 403: AgentRequestErrorResponseSchema,
5939
+ 404: AgentRequestErrorResponseSchema,
5940
+ 501: ErrorResponseSchema
5941
+ },
5942
+ detail: {
5943
+ summary: "Stop a background command on your computer",
5944
+ description: "A command the agent ran in the background on your computer keeps running after its turn. `sixb` there stops it, and everything it started, at its next renewal, which this asks for at once. The thread's owner alone stops it.",
5945
+ tags: [OPENAPI_TAGS.agentThreads.name],
5946
+ operationId: "stopAgentBackgroundCommand",
5947
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5948
+ }
5742
5949
  }).delete("/api/agent-computers/sessions/:sessionId", async (context) => {
5743
5950
  const { params, set } = context;
5744
5951
  const sixb = requireRequestSixb(context);
@@ -5773,6 +5980,24 @@ function registerAgentComputerRoutes(app, host) {
5773
5980
  }
5774
5981
  });
5775
5982
  }
5983
+ function sameCommands(before, now) {
5984
+ return stableJsonStringify(before) === stableJsonStringify(now);
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
+ }
5776
6001
  async function waitingTurns(host, agents, ownerPrincipal, computer) {
5777
6002
  const { threads } = await agents.threads.list({
5778
6003
  projectId: host.id,
@@ -5803,12 +6028,14 @@ async function announceOffline(host, agents, ended) {
5803
6028
  const { ownerPrincipal } = first;
5804
6029
  const live = await agents.computers.listLive({ projectId: host.id, ownerPrincipal, now });
5805
6030
  const announced = [];
5806
- for (const { computer } of [first, ...rest]) {
5807
- const stillHeld = [...live.map((other) => other.computer), ...announced];
5808
- if (stillHeld.some((other) => sameComputerPlace2(other, computer)))
6031
+ for (const { computer, backgroundCommands = [] } of [first, ...rest]) {
6032
+ if (announced.some((other) => sameComputerPlace2(other, computer)))
6033
+ continue;
6034
+ const online = live.some((other) => sameComputerPlace2(other.computer, computer));
6035
+ if (online && backgroundCommands.length === 0)
5809
6036
  continue;
5810
6037
  announced.push(computer);
5811
- await announce(host, ownerPrincipal, computer, false);
6038
+ await announce(host, ownerPrincipal, computer, online);
5812
6039
  }
5813
6040
  }
5814
6041
  }
@@ -6038,7 +6265,7 @@ function registerAgentMemoryRoutes(app) {
6038
6265
  }
6039
6266
 
6040
6267
  // src/routes/agent-runners.ts
6041
- import { principalsEqual as principalsEqual2, SYSTEM_PRINCIPAL as SYSTEM_PRINCIPAL2 } from "@sixb/core";
6268
+ import { principalsEqual as principalsEqual3, SYSTEM_PRINCIPAL as SYSTEM_PRINCIPAL2 } from "@sixb/core";
6042
6269
  import {
6043
6270
  AgentRunRefusedError,
6044
6271
  afterAgentRunFinished,
@@ -6063,6 +6290,7 @@ function agentRunSessionHost(host) {
6063
6290
  broker: host.broker,
6064
6291
  recoverAiModelCall: (input) => enqueueAiModelCallRecovery(host.queues.agents, input),
6065
6292
  events: isolateStreamSink(withAgentActivityStream(createBrokerStreamSink({ broker: host.broker, projectId: host.id }), host.broker)),
6293
+ domainEvents: host.events,
6066
6294
  security: host.definitions.security,
6067
6295
  sdk: host,
6068
6296
  definitions: host.definitions,
@@ -6128,7 +6356,7 @@ function registerAgentRunnerRoutes(app, host) {
6128
6356
  const visible = await sixb.agent.runs.getById(runId);
6129
6357
  const run = visible ? await sessions.storage.agents.runs.getById({ projectId: host.id, id: runId }) : null;
6130
6358
  const execution = run && await sessions.storage.executions.getById({ projectId: host.id, id: run.executionId });
6131
- if (run?.kind !== "conversation" || !execution || !principalsEqual2(execution.requestedBy ?? SYSTEM_PRINCIPAL2, requestActor(sixb))) {
6359
+ if (run?.kind !== "conversation" || !execution || !principalsEqual3(execution.requestedBy ?? SYSTEM_PRINCIPAL2, requestActor(sixb))) {
6132
6360
  return answer({
6133
6361
  error: {
6134
6362
  kind: "AgentRunRefusedError",
@@ -6789,9 +7017,11 @@ function registerAiAccountingRoutes(app, host) {
6789
7017
 
6790
7018
  // src/routes/artifact-frames.ts
6791
7019
  import { parseArtifactAddress } from "@sixb/core/artifacts";
7020
+ import { annotateBoard } from "@sixb/core/artifacts/live";
6792
7021
  import {
6793
7022
  ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX3,
6794
7023
  FRAME_ASSETS,
7024
+ FRAME_REFERENCE_PATH,
6795
7025
  FRAME_REFERENCE_PREFIX,
6796
7026
  frameEntries,
6797
7027
  frameLayout,
@@ -6802,14 +7032,10 @@ import {
6802
7032
  import { openFileRef } from "@sixb/core/internal/blob-storage";
6803
7033
 
6804
7034
  // src/artifacts/frame.ts
6805
- import { ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX2 } from "@sixb/core/internal/artifacts/frames";
6806
- var FRAME_CDN_ALLOWLIST = [
6807
- "https://cdn.jsdelivr.net",
6808
- "https://cdnjs.cloudflare.com",
6809
- "https://unpkg.com",
6810
- "https://fonts.googleapis.com",
6811
- "https://fonts.gstatic.com"
6812
- ];
7035
+ import {
7036
+ ARTIFACT_FRAME_ROUTE_PREFIX as ARTIFACT_FRAME_ROUTE_PREFIX2,
7037
+ FRAME_CDN_ALLOWLIST
7038
+ } from "@sixb/core/internal/artifacts/frames";
6813
7039
  function frameContentSecurityPolicy(input) {
6814
7040
  const origin = resolveApiBrowserPublicOrigin(input.policy, input.request);
6815
7041
  const base = `${origin}${ARTIFACT_FRAME_ROUTE_PREFIX2}${input.token}/`;
@@ -6870,13 +7096,9 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
6870
7096
  }
6871
7097
  let lent = false;
6872
7098
  if (path?.startsWith(FRAME_REFERENCE_PREFIX)) {
6873
- const match = /^([^/@]+)@(\d+)\/(.+)$/.exec(path.slice(FRAME_REFERENCE_PREFIX.length));
6874
- const target = frame.targets.find((candidate) => candidate.artifactId === match?.[1] && candidate.version === Number(match?.[2]) && parseArtifactAddress(candidate.address)?.path === match?.[3]);
6875
- const lender = target ? await storage.getVersion({
6876
- projectId: host.id,
6877
- artifactId: target.artifactId,
6878
- version: target.version
6879
- }) : 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;
6880
7102
  if (!lender || !match)
6881
7103
  return notFound();
6882
7104
  version = lender;
@@ -6896,7 +7118,9 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
6896
7118
  if (options.head)
6897
7119
  return new Response(null, { headers });
6898
7120
  const text = await new Response(opened.body).text();
6899
- 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 });
6900
7124
  }
6901
7125
  const response = await createFileContentResponse({
6902
7126
  blobStorage: host.blobStorage,
@@ -6912,6 +7136,13 @@ async function frameResponse(host, policy, { params, request }, options = {}) {
6912
7136
  response.headers.set("content-disposition", "inline");
6913
7137
  return response;
6914
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
+ }
6915
7146
  function decodePath(raw) {
6916
7147
  try {
6917
7148
  return decodeURIComponent(raw ?? "");
@@ -6933,10 +7164,105 @@ import {
6933
7164
  createArtifactFrame,
6934
7165
  serializeArtifactQueryResult
6935
7166
  } from "@sixb/core/internal/artifacts/frames";
7167
+ import {
7168
+ boardPreview,
7169
+ boardPreviewStatuses,
7170
+ boardPreviews,
7171
+ boardsReadLiveData
7172
+ } from "@sixb/core/internal/artifacts/publish";
6936
7173
  import { ZodError as ZodError6 } from "zod";
6937
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
+
6938
7263
  // src/schemas/artifacts.ts
6939
- 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";
6940
7266
  import { z as z18 } from "zod";
6941
7267
  var ArtifactKindSchema = z18.enum(ARTIFACT_KINDS);
6942
7268
  var ArtifactFileSchema = z18.object({
@@ -6962,6 +7288,7 @@ var SlidesOutlineSchema = z18.object({
6962
7288
  slides: z18.array(z18.object({ title: z18.string().optional() }))
6963
7289
  });
6964
7290
  var PageOutlineSchema = z18.object({ kind: z18.literal("page"), title: z18.string().optional() });
7291
+ var ArtifactThemeModeSchema = z18.enum(["light", "dark"]);
6965
7292
  var CanvasOutlineSchema = z18.object({
6966
7293
  kind: z18.literal("canvas"),
6967
7294
  items: z18.array(z18.discriminatedUnion("type", [
@@ -6971,10 +7298,12 @@ var CanvasOutlineSchema = z18.object({
6971
7298
  title: z18.string().optional(),
6972
7299
  file: z18.string(),
6973
7300
  w: z18.number(),
6974
- 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")
6975
7303
  }),
6976
7304
  z18.object({ id: z18.string(), type: z18.literal("section"), title: z18.string().optional() })
6977
- ]))
7305
+ ])),
7306
+ themes: z18.array(ArtifactThemeModeSchema).optional().describe("The modes each board has a preview in: both, or the one its theme.json pins")
6978
7307
  });
6979
7308
  var FileOutlineSchema = z18.object({ kind: z18.literal("file"), mediaType: z18.string() });
6980
7309
  var ArtifactOutlineSchema = z18.discriminatedUnion("kind", [
@@ -6996,6 +7325,7 @@ var ArtifactWarningSchema = z18.object({
6996
7325
  message: z18.string(),
6997
7326
  part: z18.string().optional()
6998
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");
6999
7329
  var ArtifactSchema = z18.object({
7000
7330
  id: z18.string(),
7001
7331
  projectId: z18.string(),
@@ -7003,38 +7333,59 @@ var ArtifactSchema = z18.object({
7003
7333
  title: z18.string(),
7004
7334
  owner: PrincipalSchema,
7005
7335
  latestVersion: z18.number().int().positive(),
7336
+ revision: RevisionSchema,
7006
7337
  createdAt: z18.string(),
7007
- updatedAt: z18.string()
7338
+ updatedAt: z18.string().describe("When the artifact last changed")
7008
7339
  });
7009
7340
  var ArtifactOriginSchema = z18.object({ threadId: z18.string(), runId: z18.string() });
7010
7341
  var ArtifactVersionSchema = z18.object({
7011
7342
  artifactId: z18.string(),
7012
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"),
7013
7346
  title: z18.string(),
7014
7347
  entry: z18.string(),
7015
7348
  files: z18.array(ArtifactFileSchema),
7016
7349
  outline: ArtifactOutlineSchema,
7017
7350
  references: z18.array(ArtifactReferenceSchema),
7018
- author: PrincipalSchema,
7019
- origin: ArtifactOriginSchema.optional(),
7020
- 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")
7021
7358
  });
7022
7359
  var ArtifactVersionSummarySchema = ArtifactVersionSchema.pick({
7023
7360
  version: true,
7361
+ revision: true,
7362
+ frozen: true,
7024
7363
  title: true,
7025
7364
  author: true,
7026
7365
  origin: true,
7027
- createdAt: true
7366
+ createdAt: true,
7367
+ updatedAt: true,
7368
+ frozenAt: true,
7369
+ frozenBy: true
7028
7370
  });
7029
7371
  var ArtifactParamsSchema = z18.object({ artifactId: z18.string().min(1) });
7030
7372
  var ArtifactVersionParamsSchema = ArtifactParamsSchema.extend({
7031
7373
  version: z18.string().regex(/^(?:latest|[1-9]\d*)$/).describe('A version number, or "latest"')
7032
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();
7033
7384
  var ArtifactQueryParamsSchema = ArtifactVersionParamsSchema.extend({
7034
7385
  name: z18.string().min(1).describe("The query's name: queries/<name>.json in the version")
7035
7386
  });
7036
7387
  var ArtifactListQuerySchema = z18.object({
7037
- 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"),
7038
7389
  kind: ArtifactKindSchema.optional().describe("Only artifacts of this kind"),
7039
7390
  limit: z18.string().optional(),
7040
7391
  offset: z18.string().optional()
@@ -7047,15 +7398,57 @@ var ArtifactListResponseSchema = z18.object({
7047
7398
  var ArtifactResponseSchema = z18.object({
7048
7399
  artifact: ArtifactSchema,
7049
7400
  versions: z18.array(ArtifactVersionSummarySchema).describe("Newest first"),
7050
- 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")
7051
7402
  });
7052
7403
  var PublishArtifactBodySchema = z18.object({
7053
7404
  kind: ArtifactKindSchema,
7054
7405
  title: z18.string(),
7055
7406
  files: z18.array(ArtifactFileSchema).min(1).describe("Files stored with POST /api/files, at their paths in the artifact")
7056
7407
  }).strict();
7057
- var PublishArtifactVersionBodySchema = PublishArtifactBodySchema.extend({
7058
- 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
7059
7452
  });
7060
7453
  var PublishedArtifactResponseSchema = z18.object({
7061
7454
  artifact: ArtifactSchema,
@@ -7087,9 +7480,53 @@ var ArtifactFrameResponseSchema = z18.object({
7087
7480
  expiresAt: z18.string().describe("When the frame stops serving; ask for a new one before then")
7088
7481
  });
7089
7482
  var ArtifactErrorResponseSchema = ErrorResponseSchema.extend({
7090
- 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."),
7091
- 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")
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)
7092
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) });
7093
7530
 
7094
7531
  // src/routes/objects.ts
7095
7532
  import {
@@ -8338,6 +8775,7 @@ var ObjectQueryOpenApiSchemas = {
8338
8775
  "uuid",
8339
8776
  "fileRef",
8340
8777
  "userRef",
8778
+ "artifactRef",
8341
8779
  "enum",
8342
8780
  "array",
8343
8781
  "object",
@@ -8827,9 +9265,7 @@ async function timeRequest(request, options, handle) {
8827
9265
  }
8828
9266
 
8829
9267
  // src/routes/objects.ts
8830
- var ObjectFileContentRouteQuerySchema = FileContentQuerySchema.extend({
8831
- shareGrant: z25.string().optional().describe("Share grant selector for elements that cannot send the x-sixb-share-grant header")
8832
- });
9268
+ var ObjectFileContentRouteQuerySchema = FileContentQuerySchema.extend(ShareGrantQuerySchema.shape);
8833
9269
  var ObjectFileContentQuerySchema = ObjectFileContentRouteQuerySchema.extend({
8834
9270
  path: z25.string().min(1).regex(/^\/properties(?:\/|$)/, "Object file content paths must start with /properties/")
8835
9271
  });
@@ -9535,6 +9971,7 @@ function registerObjectRoutes(app, host) {
9535
9971
  }
9536
9972
 
9537
9973
  // src/routes/artifacts.ts
9974
+ var ArtifactFileContentQuerySchema = FileContentQuerySchema.extend(ShareGrantQuerySchema.shape);
9538
9975
  function artifactBody(artifact) {
9539
9976
  return {
9540
9977
  id: artifact.id,
@@ -9543,6 +9980,7 @@ function artifactBody(artifact) {
9543
9980
  title: artifact.title,
9544
9981
  owner: artifact.owner,
9545
9982
  latestVersion: artifact.latestVersion,
9983
+ revision: artifact.revision,
9546
9984
  createdAt: toIsoString(artifact.createdAt),
9547
9985
  updatedAt: toIsoString(artifact.updatedAt)
9548
9986
  };
@@ -9551,6 +9989,8 @@ function versionBody(version) {
9551
9989
  return {
9552
9990
  artifactId: version.artifactId,
9553
9991
  version: version.version,
9992
+ revision: version.revision,
9993
+ frozen: version.frozenAt !== undefined,
9554
9994
  title: version.title,
9555
9995
  entry: version.entry,
9556
9996
  files: version.files,
@@ -9558,13 +9998,80 @@ function versionBody(version) {
9558
9998
  references: version.references,
9559
9999
  author: version.author,
9560
10000
  origin: version.origin,
9561
- 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) } : {}
9562
10063
  };
9563
10064
  }
9564
- 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) {
9565
10072
  return PublishedArtifactResponseSchema.parse({
9566
10073
  artifact: artifactBody(published.artifact),
9567
- version: versionBody(published.version),
10074
+ version: await versionResponse(host, published.version),
9568
10075
  warnings: published.warnings
9569
10076
  });
9570
10077
  }
@@ -9591,7 +10098,17 @@ async function runTokenArtifacts(host, context) {
9591
10098
  const run = await host.storage.agents?.runs.getById({ projectId: host.id, id: runId });
9592
10099
  if (!run || !sixb)
9593
10100
  throw new AgentExecutionLostError(runId);
9594
- 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;
9595
10112
  }
9596
10113
  function versionParam(value) {
9597
10114
  return value === "latest" ? "latest" : Number(value);
@@ -9603,12 +10120,19 @@ function notFound(set) {
9603
10120
  async function refusal2(context, artifactId, set) {
9604
10121
  return refusalFor(await requireRequestSixb(context).artifacts.access(artifactId), set);
9605
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
+ }
9606
10130
  function refusalFor(access, set) {
9607
10131
  if (access !== "none")
9608
10132
  return notFound(set);
9609
10133
  set.status = 403;
9610
10134
  return {
9611
- error: "Artifact not shared in a conversation you read",
10135
+ error: "Artifact not shared with you",
9612
10136
  code: "not_shared"
9613
10137
  };
9614
10138
  }
@@ -9616,7 +10140,9 @@ function handleArtifactRouteError(error, set) {
9616
10140
  if (error instanceof ArtifactRequestError) {
9617
10141
  switch (error.code) {
9618
10142
  case "artifact_not_found":
10143
+ case "comment_not_found":
9619
10144
  case "query_not_found":
10145
+ case "restore_point_not_found":
9620
10146
  set.status = 404;
9621
10147
  break;
9622
10148
  case "artifact_kind_mismatch":
@@ -9625,9 +10151,12 @@ function handleArtifactRouteError(error, set) {
9625
10151
  set.status = 409;
9626
10152
  break;
9627
10153
  case "invalid_artifact":
10154
+ case "invalid_comment":
9628
10155
  case "invalid_state":
10156
+ case "name_required":
9629
10157
  set.status = 400;
9630
10158
  break;
10159
+ case "comments_full":
9631
10160
  case "state_full":
9632
10161
  set.status = 413;
9633
10162
  break;
@@ -9667,14 +10196,15 @@ function artifactErrorResponse(status) {
9667
10196
  }
9668
10197
  };
9669
10198
  }
9670
- var publishResponses = {
9671
- 201: PublishedArtifactResponseSchema,
10199
+ var writeRefusals = {
9672
10200
  400: ArtifactErrorResponseSchema,
9673
10201
  403: ArtifactErrorResponseSchema,
9674
10202
  404: ArtifactErrorResponseSchema,
9675
10203
  409: ArtifactErrorResponseSchema,
9676
10204
  501: ArtifactErrorResponseSchema
9677
10205
  };
10206
+ var createResponses = { 201: PublishedArtifactResponseSchema, ...writeRefusals };
10207
+ var updateResponses = { 200: PublishedArtifactResponseSchema, ...writeRefusals };
9678
10208
  async function artifactFileContentResponse(host, context, options = {}) {
9679
10209
  try {
9680
10210
  const query = FileContentQuerySchema.parse(context.query);
@@ -9702,6 +10232,76 @@ async function artifactFileContentResponse(host, context, options = {}) {
9702
10232
  return handleArtifactRouteError(error, context.set);
9703
10233
  }
9704
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
+ }
9705
10305
  function registerArtifactRoutes(app, host) {
9706
10306
  return app.get("/api/artifacts", async (context) => {
9707
10307
  try {
@@ -9742,13 +10342,13 @@ function registerArtifactRoutes(app, host) {
9742
10342
  const run = await runTokenArtifacts(host, context);
9743
10343
  const published = run ? await run.publish(contentInput(body)) : await requireRequestSixb(context).artifacts.create(contentInput(body));
9744
10344
  context.set.status = 201;
9745
- return serializePublished(published);
10345
+ return await serializePublished(host, published);
9746
10346
  } catch (error) {
9747
10347
  return handleArtifactRouteError(error, context.set);
9748
10348
  }
9749
10349
  }, {
9750
10350
  body: PublishArtifactBodySchema,
9751
- response: publishResponses,
10351
+ response: createResponses,
9752
10352
  detail: {
9753
10353
  summary: "Create an artifact",
9754
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.",
@@ -9793,6 +10393,31 @@ function registerArtifactRoutes(app, host) {
9793
10393
  operationId: "getArtifact",
9794
10394
  security: accessTokenSecurityRequirement("getArtifact")
9795
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
+ }
9796
10421
  }).delete("/api/artifacts/:artifactId", async (context) => {
9797
10422
  try {
9798
10423
  const artifacts = requireRequestSixb(context).artifacts;
@@ -9927,66 +10552,294 @@ function registerArtifactRoutes(app, host) {
9927
10552
  operationId: "clearArtifactState",
9928
10553
  security: accessTokenSecurityRequirement("clearArtifactState")
9929
10554
  }
9930
- }).post("/api/artifacts/:artifactId/versions", async (context) => {
10555
+ }).put("/api/artifacts/:artifactId/content", async (context) => {
9931
10556
  try {
9932
- const body = PublishArtifactVersionBodySchema.parse(context.body);
10557
+ const body = UpdateArtifactBodySchema.parse(context.body);
9933
10558
  const { artifactId } = context.params;
9934
10559
  const content = {
9935
10560
  ...contentInput(body),
9936
- ...body.baseVersion === undefined ? {} : { baseVersion: body.baseVersion }
10561
+ ...body.baseRevision === undefined ? {} : { baseRevision: body.baseRevision }
9937
10562
  };
9938
10563
  const run = await runTokenArtifacts(host, context);
9939
- const published = run ? await run.publish({ ...content, artifactId }) : await requireRequestSixb(context).artifacts.publish(artifactId, content);
9940
- context.set.status = 201;
9941
- 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);
9942
10566
  } catch (error) {
9943
10567
  return handleArtifactRouteError(error, context.set);
9944
10568
  }
9945
10569
  }, {
9946
10570
  params: ArtifactParamsSchema,
9947
- body: PublishArtifactVersionBodySchema,
9948
- response: publishResponses,
10571
+ body: UpdateArtifactBodySchema,
10572
+ response: updateResponses,
9949
10573
  detail: {
9950
- summary: "Publish an artifact's next version",
9951
- 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.",
9952
10576
  tags: [OPENAPI_TAGS.artifacts.name],
9953
- operationId: "publishArtifactVersion",
9954
- security: accessTokenSecurityRequirement("publishArtifactVersion")
10577
+ operationId: "updateArtifact",
10578
+ security: accessTokenSecurityRequirement("updateArtifact")
9955
10579
  }
9956
- }).post("/api/artifacts/:artifactId/versions/:version/frame", async (context) => {
10580
+ }).post("/api/artifacts/:artifactId/freeze", async (context) => {
9957
10581
  try {
9958
- const storage = host.storage.artifacts;
9959
- const artifacts = requireRequestSixb(context).artifacts;
9960
- const version = await artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
9961
- if (!storage)
9962
- return notFound(context.set);
9963
- if (!version)
9964
- return await refusal2(context, context.params.artifactId, context.set);
9965
- const frame = await createArtifactFrame({
9966
- projectId: host.id,
9967
- storage,
9968
- version,
9969
- read: (id, number) => artifacts.getVersion(id, number)
9970
- });
9971
- return ArtifactFrameResponseSchema.parse({
9972
- path: frame.path,
9973
- expiresAt: frame.expiresAt.toISOString()
9974
- });
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);
9975
10585
  } catch (error) {
9976
10586
  return handleArtifactRouteError(error, context.set);
9977
10587
  }
9978
10588
  }, {
9979
- params: ArtifactVersionParamsSchema,
10589
+ params: ArtifactParamsSchema,
10590
+ body: FreezeArtifactBodySchema,
9980
10591
  response: {
9981
- 200: ArtifactFrameResponseSchema,
10592
+ 200: ArtifactChangeResponseSchema,
10593
+ 400: ArtifactErrorResponseSchema,
9982
10594
  403: ArtifactErrorResponseSchema,
9983
10595
  404: ArtifactErrorResponseSchema,
9984
10596
  409: ArtifactErrorResponseSchema,
9985
10597
  501: ArtifactErrorResponseSchema
9986
10598
  },
9987
10599
  detail: {
9988
- summary: "Open a version in a frame",
9989
- 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.",
10602
+ tags: [OPENAPI_TAGS.artifacts.name],
10603
+ operationId: "freezeArtifactVersion",
10604
+ security: accessTokenSecurityRequirement("freezeArtifactVersion")
10605
+ }
10606
+ }).get("/api/artifacts/:artifactId/comments", async (context) => {
10607
+ try {
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
+ });
10616
+ } catch (error) {
10617
+ return handleArtifactRouteError(error, context.set);
10618
+ }
10619
+ }, {
10620
+ params: ArtifactParamsSchema,
10621
+ response: {
10622
+ 200: ArtifactCommentListResponseSchema,
10623
+ 403: ArtifactErrorResponseSchema,
10624
+ 404: ArtifactErrorResponseSchema,
10625
+ 501: ArtifactErrorResponseSchema
10626
+ },
10627
+ detail: {
10628
+ summary: "List an artifact's comments",
10629
+ description: "Every comment and reply, oldest first, resolved ones included. Whoever reads the artifact reads them.",
10630
+ tags: [OPENAPI_TAGS.artifacts.name],
10631
+ operationId: "listArtifactComments",
10632
+ security: accessTokenSecurityRequirement("listArtifactComments")
10633
+ }
10634
+ }).post("/api/artifacts/:artifactId/comments", async (context) => {
10635
+ try {
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 } : {}
10643
+ });
10644
+ context.set.status = 201;
10645
+ return ArtifactCommentSchema.parse(await commentBody(comment, commentAuthors(host, context)));
10646
+ } catch (error) {
10647
+ return handleArtifactRouteError(error, context.set);
10648
+ }
10649
+ }, {
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
+ },
10660
+ detail: {
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.",
10663
+ tags: [OPENAPI_TAGS.artifacts.name],
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.",
9990
10843
  tags: [OPENAPI_TAGS.artifacts.name],
9991
10844
  operationId: "createArtifactFrame",
9992
10845
  security: accessTokenSecurityRequirement("createArtifactFrame")
@@ -9996,7 +10849,9 @@ function registerArtifactRoutes(app, host) {
9996
10849
  const version = await requireRequestSixb(context).artifacts.getVersion(context.params.artifactId, versionParam(context.params.version));
9997
10850
  if (!version)
9998
10851
  return await refusal2(context, context.params.artifactId, context.set);
9999
- return ArtifactVersionSchema.parse(versionBody(version));
10852
+ return ArtifactVersionSchema.parse(await versionResponse(host, version, {
10853
+ previews: seesBoardPreviews(context, version)
10854
+ }));
10000
10855
  } catch (error) {
10001
10856
  return handleArtifactRouteError(error, context.set);
10002
10857
  }
@@ -10015,6 +10870,30 @@ function registerArtifactRoutes(app, host) {
10015
10870
  operationId: "getArtifactVersion",
10016
10871
  security: accessTokenSecurityRequirement("getArtifactVersion")
10017
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
+ }
10018
10897
  }).get("/api/artifacts/:artifactId/versions/:version/queries/:name", async (context) => {
10019
10898
  try {
10020
10899
  const { artifactId, version, name } = context.params;
@@ -10058,7 +10937,7 @@ function registerArtifactRoutes(app, host) {
10058
10937
  }
10059
10938
  }).get("/api/artifacts/:artifactId/versions/:version/content", async (context) => artifactFileContentResponse(host, context), {
10060
10939
  params: ArtifactVersionParamsSchema,
10061
- query: FileContentQuerySchema,
10940
+ query: ArtifactFileContentQuerySchema,
10062
10941
  detail: {
10063
10942
  summary: "Get a file of an artifact version",
10064
10943
  tags: [OPENAPI_TAGS.artifacts.name],
@@ -10068,7 +10947,7 @@ function registerArtifactRoutes(app, host) {
10068
10947
  }
10069
10948
  }).head("/api/artifacts/:artifactId/versions/:version/content", async (context) => artifactFileContentResponse(host, context, { head: true }), {
10070
10949
  params: ArtifactVersionParamsSchema,
10071
- query: FileContentQuerySchema,
10950
+ query: ArtifactFileContentQuerySchema,
10072
10951
  detail: {
10073
10952
  summary: "Head a file of an artifact version",
10074
10953
  tags: [OPENAPI_TAGS.artifacts.name],
@@ -10148,6 +11027,7 @@ function validDate(value) {
10148
11027
  }
10149
11028
 
10150
11029
  // src/connectors/http.ts
11030
+ import { AuthorizationError as AuthorizationError4 } from "@sixb/core";
10151
11031
  import {
10152
11032
  getConnectorConnectionsRuntime,
10153
11033
  isOAuthConnectorDefinition
@@ -10229,10 +11109,14 @@ var ConnectorAccountSchema = z26.object({
10229
11109
  description: z26.string().optional(),
10230
11110
  avatarUrl: z26.string().url().optional()
10231
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
+ ]);
10232
11116
  var ConnectorConnectionSchema = z26.object({
10233
11117
  id: z26.string(),
10234
11118
  connectorId: z26.string(),
10235
- owner: z26.object({ type: z26.literal("project") }),
11119
+ owner: ConnectorConnectionOwnerSchema,
10236
11120
  slot: z26.string(),
10237
11121
  account: ConnectorAccountSchema,
10238
11122
  status: z26.enum(["connected", "needs_reauthorization", "disconnected"])
@@ -10242,7 +11126,7 @@ var ConnectorConnectionRunBaseSchema = z26.object({
10242
11126
  id: z26.string(),
10243
11127
  connectorId: z26.string(),
10244
11128
  kind: z26.enum(["connect", "reauthorize"]),
10245
- owner: z26.object({ type: z26.literal("project") }),
11129
+ owner: ConnectorConnectionOwnerSchema,
10246
11130
  slot: z26.string(),
10247
11131
  createdAt: z26.string().datetime(),
10248
11132
  updatedAt: z26.string().datetime()
@@ -10276,11 +11160,17 @@ var ConnectorConnectionRunSchema = z26.union([
10276
11160
  finishedAt: z26.string().datetime()
10277
11161
  })
10278
11162
  ]);
11163
+ var ConnectorConnectionOwnerChoiceSchema = z26.enum(["project", "me"]);
11164
+ var ListConnectorConnectionsQuerySchema = z26.object({
11165
+ owner: ConnectorConnectionOwnerChoiceSchema.optional()
11166
+ });
10279
11167
  var StartConnectorConnectionRunBodySchema = z26.object({
11168
+ owner: ConnectorConnectionOwnerChoiceSchema.default("project"),
10280
11169
  slot: z26.string().trim().min(1),
10281
11170
  returnTo: z26.string().url()
10282
11171
  });
10283
11172
  var AddConnectorConnectionBodySchema = z26.object({
11173
+ owner: ConnectorConnectionOwnerChoiceSchema.default("project"),
10284
11174
  slot: z26.string().trim().min(1)
10285
11175
  });
10286
11176
  var StartConnectorReauthorizationBodySchema = z26.object({
@@ -10322,6 +11212,23 @@ function connectorRouteRuntime(host, owner, connectorId) {
10322
11212
  }
10323
11213
  return getConnectorConnectionsRuntime(owner);
10324
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
+ }
10325
11232
  function serializeConnectorConnection(connection) {
10326
11233
  return {
10327
11234
  id: connection.id,
@@ -10413,10 +11320,11 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
10413
11320
  }).post("/api/connectors/:connectorId/connection-runs", async (context) => {
10414
11321
  const { params, body, request, set } = context;
10415
11322
  try {
10416
- const runtime = connectorRouteRuntime(host, requireRequestSixb(context), params.connectorId);
11323
+ const sixb = requireRequestSixb(context);
11324
+ const runtime = connectorRouteRuntime(host, sixb, params.connectorId);
10417
11325
  const parsed = StartConnectorConnectionRunBodySchema.parse(body);
10418
11326
  const started = await runtime.startConnectionRun(params.connectorId, {
10419
- owner: { type: "project" },
11327
+ owner: connectorConnectionOwner(sixb, params.connectorId, parsed.owner),
10420
11328
  slot: parsed.slot,
10421
11329
  returnTo: options.resolveReturnTo(request, parsed.returnTo),
10422
11330
  redirectUri: options.resolveCallbackUrl(request)
@@ -10485,11 +11393,12 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
10485
11393
  }).post("/api/connectors/:connectorId/connections/:connectionId/connection-runs", async (context) => {
10486
11394
  const { params, body, set } = context;
10487
11395
  try {
10488
- const runtime = connectorRouteRuntime(host, requireRequestSixb(context), params.connectorId);
11396
+ const sixb = requireRequestSixb(context);
11397
+ const runtime = connectorRouteRuntime(host, sixb, params.connectorId);
10489
11398
  const parsed = AddConnectorConnectionBodySchema.parse(body);
10490
11399
  const run = await runtime.addConnection(params.connectorId, {
10491
11400
  fromConnectionId: params.connectionId,
10492
- owner: { type: "project" },
11401
+ owner: connectorConnectionOwner(sixb, params.connectorId, parsed.owner),
10493
11402
  slot: parsed.slot
10494
11403
  });
10495
11404
  set.status = 201;
@@ -10642,16 +11551,19 @@ function setResponseHeader(set, name, value) {
10642
11551
  // src/routes/connector-connections.ts
10643
11552
  function registerConnectorConnectionRoutes(app, host) {
10644
11553
  return app.get("/api/connectors/:connectorId/connections", async (context) => {
10645
- const { params, set } = context;
11554
+ const { params, query, set } = context;
10646
11555
  try {
10647
- 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);
10648
11559
  const connections = await runtime.listConnections(params.connectorId);
10649
- return connections.map(serializeConnectorConnection);
11560
+ return connections.filter((connection) => matchesConnectorConnectionOwner(sixb, connection, owner)).map(serializeConnectorConnection);
10650
11561
  } catch (error) {
10651
11562
  return handleConnectorRouteError(error, set);
10652
11563
  }
10653
11564
  }, {
10654
11565
  params: ConnectorParamsSchema,
11566
+ query: ListConnectorConnectionsQuerySchema,
10655
11567
  response: {
10656
11568
  200: ConnectorConnectionSchema.array(),
10657
11569
  400: ConnectorBadRequestResponseSchema,
@@ -11091,7 +12003,7 @@ function registerDatasetRoutes(app, host) {
11091
12003
  }
11092
12004
 
11093
12005
  // src/routes/events.ts
11094
- import { AuthorizationError as AuthorizationError4 } from "@sixb/core";
12006
+ import { AuthorizationError as AuthorizationError5 } from "@sixb/core";
11095
12007
  function registerEventRoutes(app, _host) {
11096
12008
  return app.get("/api/events", async (context) => {
11097
12009
  const { query, set } = context;
@@ -11110,7 +12022,7 @@ function registerEventRoutes(app, _host) {
11110
12022
  events: [...events]
11111
12023
  };
11112
12024
  } catch (error) {
11113
- if (error instanceof AuthorizationError4) {
12025
+ if (error instanceof AuthorizationError5) {
11114
12026
  set.status = 403;
11115
12027
  return { error: error.message };
11116
12028
  }
@@ -11612,16 +12524,111 @@ function expectedContentLengthError(session, request) {
11612
12524
  return expectedSizeBytesError(session, sizeBytes);
11613
12525
  }
11614
12526
 
11615
- // src/schemas/links.ts
12527
+ // src/routes/lake.ts
12528
+ import { getLakeRetentionRuntime } from "@sixb/core/internal/runtime";
12529
+
12530
+ // src/schemas/lake.ts
11616
12531
  import { z as z27 } from "zod";
11617
- var LinkParamsSchema = z27.object({
11618
- objectTypeId: z27.string().min(1),
11619
- objectId: z27.string().min(1),
11620
- 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)
11621
12628
  });
11622
- var LinkLineageQuerySchema = z27.object({
11623
- targetTypeId: z27.string().min(1),
11624
- targetId: z27.string().min(1)
12629
+ var LinkLineageQuerySchema = z28.object({
12630
+ targetTypeId: z28.string().min(1),
12631
+ targetId: z28.string().min(1)
11625
12632
  });
11626
12633
 
11627
12634
  // src/routes/links.ts
@@ -11669,71 +12676,71 @@ import { logLevelsAtOrAbove } from "@sixb/core";
11669
12676
 
11670
12677
  // src/schemas/logs.ts
11671
12678
  import { LOG_LEVELS, SIXB_RUN_KINDS } from "@sixb/core";
11672
- import { z as z28 } from "zod";
11673
- var SixbRunKindSchema = z28.enum(SIXB_RUN_KINDS);
11674
- var LogLevelSchema = z28.enum(LOG_LEVELS);
11675
- 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");
11676
12683
  var DEFAULT_LOGS_PAGE_LIMIT = 200;
11677
12684
  var MAX_LOGS_PAGE_LIMIT = 1000;
11678
- var LogsLimitSchema = z28.coerce.number().int().positive().max(MAX_LOGS_PAGE_LIMIT);
11679
- var LogsQuerySchema = z28.object({
12685
+ var LogsLimitSchema = z29.coerce.number().int().positive().max(MAX_LOGS_PAGE_LIMIT);
12686
+ var LogsQuerySchema = z29.object({
11680
12687
  kind: SixbRunKindSchema.optional(),
11681
12688
  runId: LogRunIdSchema.optional(),
11682
12689
  level: LogLevelSchema.optional(),
11683
- direction: z28.enum(["forward", "backward"]).optional(),
11684
- afterCursor: z28.string().optional(),
11685
- beforeCursor: z28.string().optional(),
12690
+ direction: z29.enum(["forward", "backward"]).optional(),
12691
+ afterCursor: z29.string().optional(),
12692
+ beforeCursor: z29.string().optional(),
11686
12693
  limit: LogsLimitSchema.optional()
11687
12694
  }).superRefine((query, context) => {
11688
12695
  if (query.runId !== undefined && query.kind === undefined) {
11689
12696
  context.addIssue({
11690
- code: z28.ZodIssueCode.custom,
12697
+ code: z29.ZodIssueCode.custom,
11691
12698
  path: ["runId"],
11692
12699
  message: "kind is required when runId is provided"
11693
12700
  });
11694
12701
  }
11695
12702
  if (query.afterCursor && query.beforeCursor) {
11696
12703
  context.addIssue({
11697
- code: z28.ZodIssueCode.custom,
12704
+ code: z29.ZodIssueCode.custom,
11698
12705
  message: "afterCursor and beforeCursor are mutually exclusive"
11699
12706
  });
11700
12707
  }
11701
12708
  if (query.direction === "backward" && query.afterCursor) {
11702
12709
  context.addIssue({
11703
- code: z28.ZodIssueCode.custom,
12710
+ code: z29.ZodIssueCode.custom,
11704
12711
  path: ["afterCursor"],
11705
12712
  message: "afterCursor cannot be used with backward reads"
11706
12713
  });
11707
12714
  }
11708
12715
  if (query.direction !== "backward" && query.beforeCursor) {
11709
12716
  context.addIssue({
11710
- code: z28.ZodIssueCode.custom,
12717
+ code: z29.ZodIssueCode.custom,
11711
12718
  path: ["beforeCursor"],
11712
12719
  message: "beforeCursor requires direction=backward"
11713
12720
  });
11714
12721
  }
11715
12722
  });
11716
- var LogLineSchema = z28.object({
12723
+ var LogLineSchema = z29.object({
11717
12724
  level: LogLevelSchema,
11718
- message: z28.string(),
11719
- fields: z28.record(z28.unknown()).optional(),
11720
- at: z28.string(),
11721
- context: z28.object({
11722
- 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({
11723
12730
  kind: SixbRunKindSchema,
11724
- id: z28.string()
12731
+ id: z29.string()
11725
12732
  }),
11726
- stepId: z28.string().optional(),
11727
- phase: z28.string().optional(),
11728
- attempt: z28.number().optional()
12733
+ stepId: z29.string().optional(),
12734
+ phase: z29.string().optional(),
12735
+ attempt: z29.number().optional()
11729
12736
  }),
11730
- cursor: z28.string()
12737
+ cursor: z29.string()
11731
12738
  });
11732
- var LogsResponseSchema = z28.object({
11733
- count: z28.number(),
11734
- lines: z28.array(LogLineSchema),
11735
- cursor: z28.string().optional(),
11736
- 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()
11737
12744
  });
11738
12745
 
11739
12746
  // src/routes/logs.ts
@@ -11778,9 +12785,9 @@ function registerLogRoutes(app, _host) {
11778
12785
  }
11779
12786
 
11780
12787
  // src/routes/model-calls.ts
11781
- import { z as z29 } from "zod";
12788
+ import { z as z30 } from "zod";
11782
12789
  var ModelCallFileContentQuerySchema = FileContentQuerySchema.extend({
11783
- 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/")
11784
12791
  });
11785
12792
  function serializeModelCallFiles(call) {
11786
12793
  return ModelCallFilesSchema.parse({
@@ -12417,111 +13424,112 @@ function registerOntologyRoutes(app, host) {
12417
13424
  import {
12418
13425
  PIPELINE_RUN_FAILURE_CODES
12419
13426
  } from "@sixb/core/storage";
12420
- import { z as z30 } from "zod";
13427
+ import { z as z31 } from "zod";
12421
13428
  var PipelineRunFailureSchema = sixbFailureSchema(PIPELINE_RUN_FAILURE_CODES);
12422
- var PipelineParamsSchema = z30.object({
12423
- pipelineId: z30.string().min(1)
13429
+ var PipelineParamsSchema = z31.object({
13430
+ pipelineId: z31.string().min(1)
12424
13431
  });
12425
- var PipelineRunParamsSchema = z30.object({
12426
- runId: z30.string().min(1)
13432
+ var PipelineRunParamsSchema = z31.object({
13433
+ runId: z31.string().min(1)
12427
13434
  });
12428
- var PipelineRunStatusSchema = z30.enum([
13435
+ var PipelineRunStatusSchema = z31.enum([
12429
13436
  "queued",
12430
13437
  "running",
12431
13438
  "succeeded",
12432
13439
  "failed",
12433
13440
  "cancelled"
12434
13441
  ]);
12435
- var PipelineStepRunStatusSchema = z30.enum(["running", "succeeded", "failed", "cancelled"]);
12436
- var PipelineRunsQuerySchema = z30.object({
12437
- pipelineId: z30.string().optional(),
13442
+ var PipelineStepRunStatusSchema = z31.enum(["running", "succeeded", "failed", "cancelled"]);
13443
+ var PipelineRunsQuerySchema = z31.object({
13444
+ pipelineId: z31.string().optional(),
12438
13445
  status: PipelineRunStatusSchema.optional(),
12439
- startedAfter: z30.string().optional(),
12440
- startedBefore: z30.string().optional(),
12441
- limit: z30.string().optional(),
12442
- offset: z30.string().optional(),
12443
- order: z30.enum(["asc", "desc"]).optional()
12444
- });
12445
- var DatasetVersionRefSchema2 = z30.object({
12446
- datasetId: z30.string(),
12447
- versionId: z30.string()
12448
- });
12449
- var PipelineTriggerSchema = z30.object({
12450
- type: z30.literal("schedule"),
12451
- scheduleId: z30.string()
12452
- });
12453
- var PipelineStepExecutorSchema = z30.union([
12454
- z30.object({
12455
- kind: z30.literal("sql"),
12456
- 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")
12457
13464
  }),
12458
- z30.object({
12459
- kind: z30.literal("run")
13465
+ z31.object({
13466
+ kind: z31.literal("run")
12460
13467
  })
12461
13468
  ]);
12462
- var PipelineRunSchema = z30.object({
12463
- id: z30.string(),
12464
- projectId: z30.string(),
12465
- pipelineId: z30.string(),
13469
+ var PipelineRunSchema = z31.object({
13470
+ id: z31.string(),
13471
+ projectId: z31.string(),
13472
+ pipelineId: z31.string(),
12466
13473
  status: PipelineRunStatusSchema,
12467
- queuedAt: z30.string(),
12468
- startedAt: z30.string().optional(),
12469
- finishedAt: z30.string().optional(),
13474
+ attempt: z31.number(),
13475
+ queuedAt: z31.string(),
13476
+ startedAt: z31.string().optional(),
13477
+ finishedAt: z31.string().optional(),
12470
13478
  output: DatasetVersionRefSchema2.optional(),
12471
13479
  error: PipelineRunFailureSchema.optional()
12472
13480
  });
12473
- var PipelineStepRunSchema = z30.object({
12474
- id: z30.string(),
12475
- projectId: z30.string(),
12476
- pipelineRunId: z30.string(),
12477
- pipelineId: z30.string(),
12478
- stepId: z30.string(),
12479
- datasetId: z30.string(),
12480
- 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"]),
12481
13489
  status: PipelineStepRunStatusSchema,
12482
- startedAt: z30.string(),
12483
- finishedAt: z30.string().optional(),
12484
- inputs: z30.array(DatasetVersionRefSchema2),
13490
+ startedAt: z31.string(),
13491
+ finishedAt: z31.string().optional(),
13492
+ inputs: z31.array(DatasetVersionRefSchema2),
12485
13493
  output: DatasetVersionRefSchema2.optional(),
12486
- rowsWritten: z30.number().optional(),
13494
+ rowsWritten: z31.number().optional(),
12487
13495
  error: PipelineRunFailureSchema.optional()
12488
13496
  });
12489
- var PipelineStepSchema = z30.object({
12490
- id: z30.string(),
12491
- mode: z30.enum(["snapshot", "append"]),
13497
+ var PipelineStepSchema = z31.object({
13498
+ id: z31.string(),
13499
+ mode: z31.enum(["snapshot", "append"]),
12492
13500
  executor: PipelineStepExecutorSchema,
12493
- inputs: z30.array(z30.object({
12494
- name: z30.string(),
13501
+ inputs: z31.array(z31.object({
13502
+ name: z31.string(),
12495
13503
  dataset: DatasetDefinitionSchema
12496
13504
  })),
12497
13505
  output: DatasetDefinitionSchema
12498
13506
  });
12499
- var PipelineSchema = z30.object({
12500
- id: z30.string(),
12501
- triggers: z30.array(PipelineTriggerSchema),
12502
- graph: z30.object({
12503
- kind: z30.literal("sequence"),
12504
- nodes: z30.array(z30.object({
12505
- 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"),
12506
13514
  step: PipelineStepSchema
12507
13515
  }))
12508
13516
  }),
12509
13517
  latestRun: PipelineRunSchema.nullable()
12510
13518
  });
12511
- var PipelineRunListResponseSchema = z30.object({
12512
- runs: z30.array(PipelineRunSchema),
12513
- hasMore: z30.boolean(),
12514
- total: z30.number()
13519
+ var PipelineRunListResponseSchema = z31.object({
13520
+ runs: z31.array(PipelineRunSchema),
13521
+ hasMore: z31.boolean(),
13522
+ total: z31.number()
12515
13523
  });
12516
- var PipelineRunDetailResponseSchema = z30.object({
13524
+ var PipelineRunDetailResponseSchema = z31.object({
12517
13525
  run: PipelineRunSchema,
12518
- steps: z30.array(PipelineStepRunSchema)
13526
+ steps: z31.array(PipelineStepRunSchema)
12519
13527
  });
12520
- var RequestPipelineRunResponseSchema = z30.object({
12521
- runId: z30.string(),
12522
- jobId: z30.string(),
12523
- pipelineId: z30.string(),
12524
- queuedAt: z30.string()
13528
+ var RequestPipelineRunResponseSchema = z31.object({
13529
+ runId: z31.string(),
13530
+ jobId: z31.string(),
13531
+ pipelineId: z31.string(),
13532
+ queuedAt: z31.string()
12525
13533
  });
12526
13534
 
12527
13535
  // src/routes/pipelines.ts
@@ -12531,6 +13539,7 @@ function serializePipelineRun(run) {
12531
13539
  projectId: run.projectId,
12532
13540
  pipelineId: run.pipelineId,
12533
13541
  status: run.status,
13542
+ attempt: run.attempt,
12534
13543
  queuedAt: toIsoString(run.queuedAt),
12535
13544
  startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
12536
13545
  finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
@@ -12747,11 +13756,11 @@ function registerPipelineRoutes(app, host) {
12747
13756
  }
12748
13757
 
12749
13758
  // src/schemas/project.ts
12750
- import { z as z31 } from "zod";
12751
- var ProjectInfoResponseSchema = z31.object({
12752
- id: z31.string(),
12753
- locale: z31.string(),
12754
- 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()
12755
13764
  });
12756
13765
 
12757
13766
  // src/routes/project.ts
@@ -12770,10 +13779,10 @@ function registerProjectRoutes(app, host) {
12770
13779
 
12771
13780
  // src/schemas/projections.ts
12772
13781
  import { PROJECTION_RUN_FAILURE_CODES } from "@sixb/core/storage";
12773
- import { z as z32 } from "zod";
13782
+ import { z as z33 } from "zod";
12774
13783
  var ProjectionRunFailureSchema = sixbFailureSchema(PROJECTION_RUN_FAILURE_CODES);
12775
- var ProjectionKindSchema = z32.enum(["object", "link", "telemetry"]);
12776
- var ProjectionRunStatusSchema = z32.enum([
13784
+ var ProjectionKindSchema = z33.enum(["object", "link", "telemetry"]);
13785
+ var ProjectionRunStatusSchema = z33.enum([
12777
13786
  "queued",
12778
13787
  "running",
12779
13788
  "succeeded",
@@ -12781,139 +13790,139 @@ var ProjectionRunStatusSchema = z32.enum([
12781
13790
  "cancelled",
12782
13791
  "superseded"
12783
13792
  ]);
12784
- var ProjectionRunIdentityBaseSchema = z32.object({
12785
- projectionId: z32.string(),
12786
- datasetVersion: z32.object({
12787
- datasetId: z32.string(),
12788
- versionId: z32.string(),
12789
- 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()
12790
13799
  }),
12791
- ontologyRevision: z32.string(),
12792
- projectionRevision: z32.string(),
12793
- ownershipHash: z32.string()
13800
+ ontologyRevision: z33.string(),
13801
+ projectionRevision: z33.string(),
13802
+ ownershipHash: z33.string()
12794
13803
  });
12795
- var ProjectionRunBaseSchema = z32.object({
12796
- id: z32.string(),
12797
- projectId: z32.string(),
12798
- executionId: z32.string(),
13804
+ var ProjectionRunBaseSchema = z33.object({
13805
+ id: z33.string(),
13806
+ projectId: z33.string(),
13807
+ executionId: z33.string(),
12799
13808
  status: ProjectionRunStatusSchema,
12800
- attempt: z32.number(),
12801
- progress: z32.object({
12802
- sourceRowsRead: z32.number(),
12803
- sourceRowsSkipped: z32.number(),
12804
- 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()
12805
13814
  }),
12806
- queuedAt: z32.string(),
12807
- startedAt: z32.string().optional(),
12808
- finishedAt: z32.string().optional(),
13815
+ queuedAt: z33.string(),
13816
+ startedAt: z33.string().optional(),
13817
+ finishedAt: z33.string().optional(),
12809
13818
  error: ProjectionRunFailureSchema.optional()
12810
13819
  });
12811
13820
  var ObjectProjectionRunSchema = ProjectionRunBaseSchema.extend({
12812
13821
  identity: ProjectionRunIdentityBaseSchema.extend({
12813
- projectionKind: z32.literal("object"),
12814
- protocol: z32.literal("replacement")
13822
+ projectionKind: z33.literal("object"),
13823
+ protocol: z33.literal("replacement")
12815
13824
  }),
12816
- target: z32.object({ objectTypeId: z32.string() })
13825
+ target: z33.object({ objectTypeId: z33.string() })
12817
13826
  });
12818
13827
  var LinkProjectionRunSchema = ProjectionRunBaseSchema.extend({
12819
13828
  identity: ProjectionRunIdentityBaseSchema.extend({
12820
- projectionKind: z32.literal("link"),
12821
- protocol: z32.literal("replacement")
13829
+ projectionKind: z33.literal("link"),
13830
+ protocol: z33.literal("replacement")
12822
13831
  }),
12823
- target: z32.object({
12824
- sourceObjectTypeId: z32.string(),
12825
- targetObjectTypeId: z32.string()
13832
+ target: z33.object({
13833
+ sourceObjectTypeId: z33.string(),
13834
+ targetObjectTypeId: z33.string()
12826
13835
  })
12827
13836
  });
12828
13837
  var TelemetryProjectionRunSchema = ProjectionRunBaseSchema.extend({
12829
13838
  identity: ProjectionRunIdentityBaseSchema.extend({
12830
- projectionKind: z32.literal("telemetry"),
12831
- protocol: z32.literal("telemetry")
13839
+ projectionKind: z33.literal("telemetry"),
13840
+ protocol: z33.literal("telemetry")
12832
13841
  }),
12833
- target: z32.object({ objectTypeId: z32.string() })
13842
+ target: z33.object({ objectTypeId: z33.string() })
12834
13843
  });
12835
- var ProjectionRunSchema = z32.union([
13844
+ var ProjectionRunSchema = z33.union([
12836
13845
  ObjectProjectionRunSchema,
12837
13846
  LinkProjectionRunSchema,
12838
13847
  TelemetryProjectionRunSchema
12839
13848
  ]);
12840
- var ForeignKeyDescriptorSchema = z32.object({
12841
- linkId: z32.string(),
12842
- sourcePropertyId: z32.string().optional(),
12843
- sourceField: z32.string().optional(),
12844
- targetObjectTypeId: z32.string()
12845
- });
12846
- var SourceEditConflictResolutionSchema = z32.union([
12847
- z32.object({ strategy: z32.literal("editsWin") }),
12848
- 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() })
12849
13858
  ]);
12850
- var ObjectProjectionSchema = z32.object({
12851
- _tag: z32.literal("ObjectProjectionDefinition"),
12852
- id: z32.string(),
12853
- objectTypeId: z32.string(),
12854
- datasetId: z32.string(),
12855
- properties: z32.record(z32.string()),
12856
- users: z32.record(z32.literal("email")).optional(),
12857
- 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),
12858
13867
  conflictResolution: SourceEditConflictResolutionSchema,
12859
13868
  latestRun: ProjectionRunSchema.nullable()
12860
13869
  });
12861
- var LinkProjectionSchema = z32.object({
12862
- _tag: z32.literal("LinkProjectionDefinition"),
12863
- id: z32.string(),
12864
- linkId: z32.string(),
12865
- sourceObjectTypeId: z32.string(),
12866
- targetObjectTypeId: z32.string(),
12867
- datasetId: z32.string(),
12868
- sourceField: z32.string(),
12869
- 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(),
12870
13879
  latestRun: ProjectionRunSchema.nullable()
12871
13880
  });
12872
- var TelemetryProjectionSchema = z32.object({
12873
- _tag: z32.literal("TelemetryProjectionDefinition"),
12874
- id: z32.string(),
12875
- objectTypeId: z32.string(),
12876
- datasetId: z32.string(),
12877
- objectIdField: z32.string(),
12878
- atField: z32.string(),
12879
- properties: z32.record(z32.object({
12880
- valueField: z32.string(),
12881
- 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()
12882
13891
  })),
12883
13892
  latestRun: ProjectionRunSchema.nullable()
12884
13893
  });
12885
- var ProjectionListResponseSchema = z32.object({
12886
- objectProjections: z32.array(ObjectProjectionSchema),
12887
- linkProjections: z32.array(LinkProjectionSchema),
12888
- telemetryProjections: z32.array(TelemetryProjectionSchema)
13894
+ var ProjectionListResponseSchema = z33.object({
13895
+ objectProjections: z33.array(ObjectProjectionSchema),
13896
+ linkProjections: z33.array(LinkProjectionSchema),
13897
+ telemetryProjections: z33.array(TelemetryProjectionSchema)
12889
13898
  });
12890
- var ProjectionParamsSchema = z32.object({
12891
- projectionId: z32.string().min(1)
13899
+ var ProjectionParamsSchema = z33.object({
13900
+ projectionId: z33.string().min(1)
12892
13901
  });
12893
- var ProjectionResponseSchema = z32.union([
13902
+ var ProjectionResponseSchema = z33.union([
12894
13903
  ObjectProjectionSchema,
12895
13904
  LinkProjectionSchema,
12896
13905
  TelemetryProjectionSchema
12897
13906
  ]);
12898
- var ProjectionRunParamsSchema = z32.object({
12899
- runId: z32.string().min(1)
13907
+ var ProjectionRunParamsSchema = z33.object({
13908
+ runId: z33.string().min(1)
12900
13909
  });
12901
- var ProjectionRunsQuerySchema = z32.object({
12902
- projectionId: z32.string().optional(),
13910
+ var ProjectionRunsQuerySchema = z33.object({
13911
+ projectionId: z33.string().optional(),
12903
13912
  projectionKind: ProjectionKindSchema.optional(),
12904
- datasetId: z32.string().optional(),
12905
- datasetVersionId: z32.string().optional(),
13913
+ datasetId: z33.string().optional(),
13914
+ datasetVersionId: z33.string().optional(),
12906
13915
  status: ProjectionRunStatusSchema.optional(),
12907
- startedAfter: z32.string().optional(),
12908
- startedBefore: z32.string().optional(),
12909
- limit: z32.string().optional(),
12910
- offset: z32.string().optional(),
12911
- 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()
12912
13921
  });
12913
- var ProjectionRunListResponseSchema = z32.object({
12914
- runs: z32.array(ProjectionRunSchema),
12915
- hasMore: z32.boolean(),
12916
- total: z32.number()
13922
+ var ProjectionRunListResponseSchema = z33.object({
13923
+ runs: z33.array(ProjectionRunSchema),
13924
+ hasMore: z33.boolean(),
13925
+ total: z33.number()
12917
13926
  });
12918
13927
 
12919
13928
  // src/routes/projections.ts
@@ -13081,88 +14090,88 @@ function registerProjectionRoutes(app, host) {
13081
14090
  import { deriveRuleEventDependencies } from "@sixb/core/internal/rules";
13082
14091
 
13083
14092
  // src/schemas/rules.ts
13084
- import { z as z33 } from "zod";
13085
- var RuleParamsSchema = z33.object({
13086
- ruleId: z33.string().min(1)
13087
- });
13088
- var RuleStatesQuerySchema = z33.object({
13089
- ruleId: z33.string().optional(),
13090
- objectTypeId: z33.string().optional(),
13091
- primaryId: z33.string().optional(),
13092
- limit: z33.string().optional(),
13093
- offset: z33.string().optional(),
13094
- order: z33.enum(["asc", "desc"]).optional()
13095
- });
13096
- var RuleValueSchema = z33.union([z33.string(), z33.number(), z33.boolean()]).nullable();
13097
- var RuleSubjectSchema = z33.object({
13098
- kind: z33.literal("object"),
13099
- objectTypeId: z33.string()
13100
- });
13101
- var RuleEventSubjectSchema = z33.object({
13102
- kind: z33.literal("object"),
13103
- objectTypeId: z33.string(),
13104
- primaryId: z33.string()
13105
- });
13106
- var RulePropertyPredicateSchema = z33.object({
13107
- kind: z33.literal("property"),
13108
- propertyId: z33.string(),
13109
- 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"]),
13110
14119
  value: RuleValueSchema.optional()
13111
14120
  });
13112
- var RuleLinkPredicateSchema = z33.object({
13113
- kind: z33.literal("link"),
13114
- linkId: z33.string(),
13115
- 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"])
13116
14125
  });
13117
14126
  function createRulePredicateSchema(childPredicateSchema) {
13118
- return z33.union([
13119
- z33.object({
13120
- kind: z33.literal("all"),
13121
- predicates: z33.array(childPredicateSchema)
14127
+ return z34.union([
14128
+ z34.object({
14129
+ kind: z34.literal("all"),
14130
+ predicates: z34.array(childPredicateSchema)
13122
14131
  }),
13123
- z33.object({
13124
- kind: z33.literal("any"),
13125
- predicates: z33.array(childPredicateSchema)
14132
+ z34.object({
14133
+ kind: z34.literal("any"),
14134
+ predicates: z34.array(childPredicateSchema)
13126
14135
  }),
13127
- z33.object({
13128
- kind: z33.literal("not"),
14136
+ z34.object({
14137
+ kind: z34.literal("not"),
13129
14138
  predicate: childPredicateSchema
13130
14139
  }),
13131
14140
  RulePropertyPredicateSchema,
13132
14141
  RuleLinkPredicateSchema
13133
14142
  ]);
13134
14143
  }
13135
- var DeepRulePredicateSchema = createRulePredicateSchema(z33.unknown());
14144
+ var DeepRulePredicateSchema = createRulePredicateSchema(z34.unknown());
13136
14145
  var NestedRulePredicateSchema = createRulePredicateSchema(DeepRulePredicateSchema);
13137
14146
  var RulePredicateSchema = NestedRulePredicateSchema;
13138
- var RuleEventDependencySchema = z33.union([
13139
- z33.object({
13140
- type: z33.enum(["object.created", "object.updated", "object.deleted"]),
13141
- 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()
13142
14151
  }),
13143
- z33.object({
13144
- type: z33.enum(["link.created", "link.updated", "link.deleted"]),
13145
- sourceTypeId: z33.string(),
13146
- linkId: z33.string()
14152
+ z34.object({
14153
+ type: z34.enum(["link.created", "link.updated", "link.deleted"]),
14154
+ sourceTypeId: z34.string(),
14155
+ linkId: z34.string()
13147
14156
  })
13148
14157
  ]);
13149
- var RuleSchema = z33.object({
13150
- kind: z33.literal("rule"),
13151
- id: z33.string(),
14158
+ var RuleSchema = z34.object({
14159
+ kind: z34.literal("rule"),
14160
+ id: z34.string(),
13152
14161
  subject: RuleSubjectSchema,
13153
14162
  predicate: RulePredicateSchema,
13154
- dependencies: z33.array(RuleEventDependencySchema)
14163
+ dependencies: z34.array(RuleEventDependencySchema)
13155
14164
  });
13156
- var RuleStateSchema = z33.object({
13157
- projectId: z33.string(),
13158
- ruleId: z33.string(),
14165
+ var RuleStateSchema = z34.object({
14166
+ projectId: z34.string(),
14167
+ ruleId: z34.string(),
13159
14168
  subject: RuleEventSubjectSchema,
13160
- triggeredAt: z33.string()
14169
+ triggeredAt: z34.string()
13161
14170
  });
13162
- var RuleStateListResponseSchema = z33.object({
13163
- states: z33.array(RuleStateSchema),
13164
- hasMore: z33.boolean(),
13165
- total: z33.number()
14171
+ var RuleStateListResponseSchema = z34.object({
14172
+ states: z34.array(RuleStateSchema),
14173
+ hasMore: z34.boolean(),
14174
+ total: z34.number()
13166
14175
  });
13167
14176
 
13168
14177
  // src/routes/rules.ts
@@ -13243,52 +14252,52 @@ function registerRuleRoutes(app, host) {
13243
14252
 
13244
14253
  // src/routes/share-grants.ts
13245
14254
  import {
13246
- AuthorizationError as AuthorizationError5,
14255
+ AuthorizationError as AuthorizationError6,
13247
14256
  ShareError
13248
14257
  } from "@sixb/core";
13249
14258
  import { ObjectNotFoundError as ObjectNotFoundError2 } from "@sixb/core/storage";
13250
14259
 
13251
14260
  // src/schemas/share-grants.ts
13252
- import { z as z34 } from "zod";
13253
- var StoredIdentifierSchema = z34.string().min(1).refine(isStoredIdentifier2, {
14261
+ import { z as z35 } from "zod";
14262
+ var StoredIdentifierSchema = z35.string().min(1).refine(isStoredIdentifier2, {
13254
14263
  message: "stored identifier must not be blank or contain NUL bytes"
13255
14264
  });
13256
- var Rfc3339DateSchema2 = z34.string().datetime({ offset: true });
13257
- var DestinationPathSchema = z34.string().min(1).max(4096);
13258
- 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) => {
13259
14268
  if (value === "true" || value === true)
13260
14269
  return true;
13261
14270
  if (value === "false" || value === false)
13262
14271
  return false;
13263
14272
  return value;
13264
- }, z34.boolean());
13265
- var ShareGrantListLimitSchema = z34.preprocess(parseUnsignedQueryInteger, z34.number().int().min(1).max(200));
13266
- 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));
13267
14276
  function parseUnsignedQueryInteger(value) {
13268
14277
  if (typeof value !== "string" || !/^\d+$/.test(value))
13269
14278
  return value;
13270
14279
  const parsed = Number(value);
13271
14280
  return Number.isSafeInteger(parsed) ? parsed : value;
13272
14281
  }
13273
- var ShareGrantTargetSchema = z34.object({
14282
+ var ShareGrantTargetSchema = z35.object({
13274
14283
  objectTypeId: StoredIdentifierSchema,
13275
14284
  primaryId: StoredIdentifierSchema
13276
14285
  });
13277
- var ShareGrantTargetInputSchema = z34.object({
14286
+ var ShareGrantTargetInputSchema = z35.object({
13278
14287
  objectTypeId: StoredIdentifierSchema,
13279
- primaryId: z34.string().min(1).refine(isStoredIdentifier2, {
14288
+ primaryId: z35.string().min(1).refine(isStoredIdentifier2, {
13280
14289
  message: "primaryId must not be blank or contain NUL bytes"
13281
14290
  })
13282
14291
  });
13283
- var AuthorizablePrincipalSchema = z34.object({
13284
- type: z34.enum(["user", "serviceAccount"]),
14292
+ var AuthorizablePrincipalSchema = z35.object({
14293
+ type: z35.enum(["user", "serviceAccount"]),
13285
14294
  id: StoredIdentifierSchema
13286
14295
  });
13287
- var PrincipalSchema2 = z34.object({
13288
- type: z34.enum(["user", "serviceAccount", "system"]),
14296
+ var PrincipalSchema2 = z35.object({
14297
+ type: z35.enum(["user", "serviceAccount", "system"]),
13289
14298
  id: StoredIdentifierSchema
13290
14299
  });
13291
- var SharedAccessGrantSchema = z34.object({
14300
+ var SharedAccessGrantSchema = z35.object({
13292
14301
  id: StoredIdentifierSchema,
13293
14302
  definitionId: StoredIdentifierSchema,
13294
14303
  target: ShareGrantTargetSchema,
@@ -13299,19 +14308,19 @@ var SharedAccessGrantSchema = z34.object({
13299
14308
  revokedAt: Rfc3339DateSchema2.optional(),
13300
14309
  revokedBy: PrincipalSchema2.optional()
13301
14310
  });
13302
- var IssueSharedAccessGrantBodySchema = z34.object({
14311
+ var IssueSharedAccessGrantBodySchema = z35.object({
13303
14312
  definitionId: StoredIdentifierSchema,
13304
14313
  target: ShareGrantTargetInputSchema,
13305
14314
  destinationPath: DestinationPathSchema,
13306
14315
  expiresAt: Rfc3339DateSchema2
13307
14316
  });
13308
- var IssueSharedAccessGrantResponseSchema = z34.object({
14317
+ var IssueSharedAccessGrantResponseSchema = z35.object({
13309
14318
  grant: SharedAccessGrantSchema,
13310
- url: z34.string().startsWith("/shared/")
14319
+ url: z35.string().startsWith("/shared/")
13311
14320
  });
13312
- var ListSharedAccessGrantsQuerySchema = z34.object({
14321
+ var ListSharedAccessGrantsQuerySchema = z35.object({
13313
14322
  definitionId: StoredIdentifierSchema,
13314
- primaryId: z34.string().min(1).refine(isStoredIdentifier2, {
14323
+ primaryId: z35.string().min(1).refine(isStoredIdentifier2, {
13315
14324
  message: "primaryId must not be blank or contain NUL bytes"
13316
14325
  }).optional(),
13317
14326
  includeRevoked: QueryBooleanSchema.optional(),
@@ -13319,15 +14328,15 @@ var ListSharedAccessGrantsQuerySchema = z34.object({
13319
14328
  limit: ShareGrantListLimitSchema.optional(),
13320
14329
  offset: ShareGrantListOffsetSchema.optional()
13321
14330
  });
13322
- var ListSharedAccessGrantsResponseSchema = z34.object({
13323
- grants: z34.array(SharedAccessGrantSchema),
13324
- hasMore: z34.boolean(),
13325
- 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()
13326
14335
  });
13327
- var SharedAccessGrantIdParamsSchema = z34.object({
14336
+ var SharedAccessGrantIdParamsSchema = z35.object({
13328
14337
  grantId: StoredIdentifierSchema
13329
14338
  });
13330
- var RevokeSharedAccessGrantResponseSchema = z34.object({
14339
+ var RevokeSharedAccessGrantResponseSchema = z35.object({
13331
14340
  grant: SharedAccessGrantSchema
13332
14341
  });
13333
14342
  function isStoredIdentifier2(value) {
@@ -13475,7 +14484,7 @@ function handleShareGrantRouteError(error, set) {
13475
14484
  return { error: "Authentication required." };
13476
14485
  return { error: error.message };
13477
14486
  }
13478
- if (error instanceof AuthorizationError5) {
14487
+ if (error instanceof AuthorizationError6) {
13479
14488
  set.status = 403;
13480
14489
  return { error: error.message };
13481
14490
  }
@@ -13523,27 +14532,35 @@ function setNoStore(set) {
13523
14532
  set.headers["cache-control"] = "no-store";
13524
14533
  }
13525
14534
 
14535
+ // src/routes/shared-access.ts
14536
+ import { GUEST_NAME_MAX_LENGTH } from "@sixb/core/internal/shares";
14537
+
13526
14538
  // src/schemas/shared-access.ts
13527
- import { z as z35 } from "zod";
13528
- 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"), {
13529
14541
  message: "stored identifier must not be blank or contain NUL bytes"
13530
14542
  });
13531
- var Rfc3339DateSchema3 = z35.string().datetime({ offset: true });
13532
- var SharedAccessGrantParamsSchema = z35.object({
14543
+ var Rfc3339DateSchema3 = z36.string().datetime({ offset: true });
14544
+ var SharedAccessGrantParamsSchema = z36.object({
13533
14545
  grantId: StoredIdentifierSchema2
13534
14546
  });
13535
- var ExchangeSharedAccessBodySchema = z35.object({
13536
- secret: z35.string().regex(/^[A-Za-z0-9_-]{43}$/)
14547
+ var ExchangeSharedAccessBodySchema = z36.object({
14548
+ secret: z36.string().regex(/^[A-Za-z0-9_-]{43}$/)
13537
14549
  });
13538
- var SharedAccessSessionResponseSchema = z35.object({
14550
+ var SharedAccessSessionResponseSchema = z36.object({
13539
14551
  grantId: StoredIdentifierSchema2,
13540
- destinationPath: z35.string().min(1).max(4096),
14552
+ destinationPath: z36.string().min(1).max(4096),
13541
14553
  expiresAt: Rfc3339DateSchema3,
13542
14554
  absoluteExpiresAt: Rfc3339DateSchema3,
13543
- 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")
13544
14561
  });
13545
- var SharedAccessSignOutResponseSchema = z35.object({
13546
- signedOut: z35.literal(true)
14562
+ var SharedAccessSignOutResponseSchema = z36.object({
14563
+ signedOut: z36.literal(true)
13547
14564
  });
13548
14565
 
13549
14566
  // src/routes/shared-access.ts
@@ -13596,6 +14613,43 @@ function registerSharedAccessRoutes(app, boundary) {
13596
14613
  operationId: "getSharedAccessSession",
13597
14614
  security: []
13598
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
+ }
13599
14653
  }).post("/api/shared-access/:grantId/sign-out", async ({ params, request }) => {
13600
14654
  try {
13601
14655
  const result = await boundary.signOut(request, params.grantId);
@@ -13639,7 +14693,9 @@ function sharedSessionResponse(context, cookies) {
13639
14693
  destinationPath: context.destinationPath,
13640
14694
  expiresAt: context.expiresAt.toISOString(),
13641
14695
  absoluteExpiresAt: context.absoluteExpiresAt.toISOString(),
13642
- csrfToken: cookies.csrfToken
14696
+ csrfToken: cookies.csrfToken,
14697
+ guestId: context.sessionId,
14698
+ ...context.guestName === undefined ? {} : { guestName: context.guestName }
13643
14699
  }), { status: 200, headers });
13644
14700
  }
13645
14701
  function withSetCookies(response, setCookies) {
@@ -13663,40 +14719,36 @@ function isRecord(value) {
13663
14719
  }
13664
14720
 
13665
14721
  // src/schemas/status.ts
13666
- import { z as z36 } from "zod";
13667
- var HealthResponseSchema = z36.object({ status: z36.literal("ok") });
13668
- var StorageReadinessSchema = z36.object({
13669
- reachable: z36.boolean(),
13670
- 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()
13671
14727
  });
13672
- var ReadinessResponseSchema = z36.object({
13673
- status: z36.enum(["ready", "unready"]),
14728
+ var ReadinessResponseSchema = z37.object({
14729
+ status: z37.enum(["ready", "unready"]),
13674
14730
  storage: StorageReadinessSchema,
13675
- reason: z36.string().optional()
13676
- });
13677
- var MaintenanceSummarySchema = z36.object({
13678
- running: z36.boolean(),
13679
- intervalMs: z36.number().int().positive(),
13680
- lastStartedAt: z36.string().nullable(),
13681
- lastCompletedAt: z36.string().nullable(),
13682
- lastDurationMs: z36.number().nonnegative().nullable(),
13683
- consecutiveFailures: z36.number().int().nonnegative(),
13684
- lastError: z36.string().nullable(),
13685
- outbox: z36.object({
13686
- pendingCount: z36.number().int().nonnegative(),
13687
- oldestPendingAt: z36.string().nullable(),
13688
- retryingCount: z36.number().int().nonnegative(),
13689
- maxAttempts: z36.number().int().nonnegative()
13690
- }).nullable(),
13691
- cleanup: z36.object({
13692
- publishedOutboxRowsDeleted: z36.number().int().nonnegative(),
13693
- terminalSourceRowsDeleted: z36.number().int().nonnegative(),
13694
- terminalSourceMaterializationsDeleted: z36.number().int().nonnegative()
13695
- }).nullable()
13696
- });
13697
- var StatusResponseSchema = z36.object({
13698
- status: z36.enum(["ok", "degraded"]),
13699
- 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(),
13700
14752
  maintenance: MaintenanceSummarySchema
13701
14753
  });
13702
14754
 
@@ -13725,10 +14777,14 @@ function registerStatusRoutes(app, host) {
13725
14777
  operationId: "getReadiness"
13726
14778
  }
13727
14779
  });
13728
- return app.get("/api/status", async () => ({
13729
- ...host.getOntologyOperationalStatus(),
13730
- objectTypes: host.definitions.ontology.listObjectTypes().length
13731
- }), {
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
+ }, {
13732
14788
  response: { 200: StatusResponseSchema },
13733
14789
  detail: {
13734
14790
  summary: "Get runtime status",
@@ -13742,74 +14798,75 @@ function registerStatusRoutes(app, host) {
13742
14798
  import {
13743
14799
  SYNC_RUN_FAILURE_CODES
13744
14800
  } from "@sixb/core/storage";
13745
- import { z as z37 } from "zod";
14801
+ import { z as z38 } from "zod";
13746
14802
  var SyncRunFailureSchema = sixbFailureSchema(SYNC_RUN_FAILURE_CODES);
13747
- var SyncParamsSchema = z37.object({
13748
- syncId: z37.string().min(1)
13749
- });
13750
- var SyncRunStatusSchema = z37.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
13751
- var SyncModeSchema = z37.enum(["snapshot", "append", "merge"]);
13752
- var SyncRunsQuerySchema = z37.object({
13753
- syncId: z37.string().optional(),
13754
- 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(),
13755
14811
  status: SyncRunStatusSchema.optional(),
13756
- startedAfter: z37.string().optional(),
13757
- startedBefore: z37.string().optional(),
13758
- limit: z37.string().optional(),
13759
- offset: z37.string().optional(),
13760
- order: z37.enum(["asc", "desc"]).optional()
13761
- });
13762
- var RequestSyncRunBodySchema = z37.object({
13763
- expectedLatestVersionId: z37.string().optional(),
13764
- commitMessage: z37.string().optional()
13765
- });
13766
- var SyncTriggerSchema = z37.object({
13767
- type: z37.literal("schedule"),
13768
- scheduleId: z37.string()
13769
- });
13770
- var SyncRunSchema = z37.object({
13771
- id: z37.string(),
13772
- projectId: z37.string(),
13773
- syncId: z37.string(),
13774
- 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(),
13775
14831
  mode: SyncModeSchema,
13776
14832
  status: SyncRunStatusSchema,
13777
- queuedAt: z37.string(),
13778
- startedAt: z37.string().optional(),
13779
- finishedAt: z37.string().optional(),
13780
- rowsRead: z37.number().optional(),
13781
- output: z37.object({
13782
- datasetId: z37.string(),
13783
- 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()
13784
14841
  }).optional(),
13785
- expectedLatestVersionId: z37.string().optional(),
13786
- commitMessage: z37.string().optional(),
14842
+ expectedLatestVersionId: z38.string().optional(),
14843
+ commitMessage: z38.string().optional(),
13787
14844
  error: SyncRunFailureSchema.optional()
13788
14845
  });
13789
- var SyncSchema = z37.object({
13790
- id: z37.string(),
14846
+ var SyncSchema = z38.object({
14847
+ id: z38.string(),
13791
14848
  mode: SyncModeSchema,
13792
- connector: z37.object({
13793
- id: z37.string(),
13794
- type: z37.string()
14849
+ connector: z38.object({
14850
+ id: z38.string(),
14851
+ type: z38.string()
13795
14852
  }),
13796
- target: z37.object({
13797
- kind: z37.literal("dataset"),
14853
+ target: z38.object({
14854
+ kind: z38.literal("dataset"),
13798
14855
  dataset: DatasetDefinitionSchema
13799
14856
  }),
13800
- triggers: z37.array(SyncTriggerSchema),
14857
+ triggers: z38.array(SyncTriggerSchema),
13801
14858
  latestRun: SyncRunSchema.nullable()
13802
14859
  });
13803
- var SyncRunListResponseSchema = z37.object({
13804
- runs: z37.array(SyncRunSchema),
13805
- hasMore: z37.boolean(),
13806
- total: z37.number()
14860
+ var SyncRunListResponseSchema = z38.object({
14861
+ runs: z38.array(SyncRunSchema),
14862
+ hasMore: z38.boolean(),
14863
+ total: z38.number()
13807
14864
  });
13808
- var RequestSyncRunResponseSchema = z37.object({
13809
- runId: z37.string(),
13810
- jobId: z37.string(),
13811
- syncId: z37.string(),
13812
- queuedAt: z37.string()
14865
+ var RequestSyncRunResponseSchema = z38.object({
14866
+ runId: z38.string(),
14867
+ jobId: z38.string(),
14868
+ syncId: z38.string(),
14869
+ queuedAt: z38.string()
13813
14870
  });
13814
14871
 
13815
14872
  // src/routes/syncs.ts
@@ -13821,6 +14878,7 @@ function serializeSyncRun(run) {
13821
14878
  datasetId: run.datasetId,
13822
14879
  mode: run.mode,
13823
14880
  status: run.status,
14881
+ attempt: run.attempt,
13824
14882
  queuedAt: toIsoString(run.queuedAt),
13825
14883
  startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
13826
14884
  finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
@@ -13966,47 +15024,47 @@ function registerSyncRoutes(app, host) {
13966
15024
  }
13967
15025
 
13968
15026
  // src/schemas/telemetry.ts
13969
- import { z as z38 } from "zod";
13970
- var TelemetryParamsSchema = z38.object({
13971
- objectTypeId: z38.string().min(1),
13972
- objectId: z38.string().min(1),
13973
- propertyId: z38.string().min(1)
13974
- });
13975
- var TelemetryHistoryQuerySchema = z38.object({
13976
- from: z38.string().optional(),
13977
- to: z38.string().optional(),
13978
- limit: z38.string().optional(),
13979
- order: z38.enum(["asc", "desc"]).optional()
13980
- });
13981
- var BulkTelemetryHistorySeriesInputSchema = z38.object({
13982
- objectTypeId: z38.string().min(1),
13983
- objectId: z38.string().min(1),
13984
- 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)
13985
15043
  }).strict();
13986
- var BulkTelemetryHistoryBodySchema = z38.object({
13987
- series: z38.array(BulkTelemetryHistorySeriesInputSchema).min(1),
13988
- from: z38.string().optional(),
13989
- to: z38.string().optional(),
13990
- limitPerSeries: z38.number().int().nonnegative().optional(),
13991
- 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()
13992
15050
  }).strict();
13993
- var TelemetryPointSchema = z38.object({
13994
- projectId: z38.string(),
13995
- objectTypeId: z38.string(),
13996
- objectId: z38.string(),
13997
- propertyId: z38.string(),
13998
- value: z38.unknown(),
13999
- unit: z38.string().optional(),
14000
- at: z38.string()
14001
- });
14002
- var BulkTelemetryHistorySeriesSchema = z38.object({
14003
- objectTypeId: z38.string(),
14004
- objectId: z38.string(),
14005
- propertyId: z38.string(),
14006
- points: z38.array(TelemetryPointSchema)
14007
- });
14008
- var BulkTelemetryHistoryResponseSchema = z38.object({
14009
- 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)
14010
15068
  });
14011
15069
 
14012
15070
  // src/routes/telemetry.ts
@@ -14134,24 +15192,24 @@ function registerTelemetryRoutes(app, _host) {
14134
15192
  import { userRef } from "@sixb/core";
14135
15193
 
14136
15194
  // src/schemas/users.ts
14137
- import { z as z39 } from "zod";
15195
+ import { z as z40 } from "zod";
14138
15196
  var MAX_USERS_PAGE_LIMIT = 200;
14139
15197
  var MAX_USERS_SEARCH_LENGTH = 200;
14140
15198
  var MAX_USER_EMAIL_LENGTH = 320;
14141
- var ListUsersQuerySchema = z39.object({
14142
- status: z39.enum(["active", "suspended", "all"]).optional(),
14143
- search: z39.string().max(MAX_USERS_SEARCH_LENGTH).optional(),
14144
- limit: z39.coerce.number().int().min(1).max(MAX_USERS_PAGE_LIMIT).optional(),
14145
- offset: z39.coerce.number().int().min(0).optional(),
14146
- email: z39.string().min(1).max(MAX_USER_EMAIL_LENGTH).optional()
14147
- });
14148
- var ListUsersResponseSchema = z39.object({
14149
- users: z39.array(UserProfileSchema),
14150
- hasMore: z39.boolean(),
14151
- 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()
14152
15210
  });
14153
- var UserParamsSchema = z39.object({
14154
- userId: z39.string().min(1)
15211
+ var UserParamsSchema = z40.object({
15212
+ userId: z40.string().min(1)
14155
15213
  });
14156
15214
 
14157
15215
  // src/routes/users.ts
@@ -14220,40 +15278,40 @@ function registerUserRoutes(app, _host) {
14220
15278
 
14221
15279
  // src/schemas/webhook-runs.ts
14222
15280
  import { WEBHOOK_RUN_FAILURE_CODES } from "@sixb/core/storage";
14223
- import { z as z40 } from "zod";
15281
+ import { z as z41 } from "zod";
14224
15282
  var WebhookRunFailureSchema = sixbFailureSchema(WEBHOOK_RUN_FAILURE_CODES);
14225
- var WebhookRunStatusSchema = z40.enum(["running", "succeeded", "failed"]);
14226
- var WebhookRunsQuerySchema = z40.object({
14227
- connectorId: z40.string().optional(),
14228
- 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(),
14229
15287
  status: WebhookRunStatusSchema.optional(),
14230
- idempotencyKey: z40.string().optional(),
14231
- startedAfter: z40.string().optional(),
14232
- startedBefore: z40.string().optional(),
14233
- limit: z40.string().optional(),
14234
- offset: z40.string().optional(),
14235
- order: z40.enum(["asc", "desc"]).optional()
14236
- });
14237
- var WebhookRunSchema = z40.object({
14238
- id: z40.string(),
14239
- projectId: z40.string(),
14240
- executionId: z40.string(),
14241
- connectorId: z40.string(),
14242
- 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(),
14243
15301
  status: WebhookRunStatusSchema,
14244
- method: z40.string(),
14245
- route: z40.string(),
14246
- startedAt: z40.string(),
14247
- finishedAt: z40.string().optional(),
14248
- requestBodyBytes: z40.number(),
14249
- responseStatus: z40.number().optional(),
14250
- 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(),
14251
15309
  error: WebhookRunFailureSchema.optional()
14252
15310
  });
14253
- var WebhookRunListResponseSchema = z40.object({
14254
- runs: z40.array(WebhookRunSchema),
14255
- hasMore: z40.boolean(),
14256
- total: z40.number()
15311
+ var WebhookRunListResponseSchema = z41.object({
15312
+ runs: z41.array(WebhookRunSchema),
15313
+ hasMore: z41.boolean(),
15314
+ total: z41.number()
14257
15315
  });
14258
15316
 
14259
15317
  // src/routes/webhook-runs.ts
@@ -14329,15 +15387,15 @@ import {
14329
15387
  snapshotWorkflowInterventionResponse
14330
15388
  } from "@sixb/core/internal/workflows";
14331
15389
  import { AGENT_RUN_FAILURE_CODES as AGENT_RUN_FAILURE_CODES2, WORKFLOW_RUN_FAILURE_CODES as WORKFLOW_RUN_FAILURE_CODES2 } from "@sixb/core/storage";
14332
- import { z as z41 } from "zod";
15390
+ import { z as z42 } from "zod";
14333
15391
  var WorkflowRunFileContentQuerySchema = FileContentQuerySchema.extend({
14334
- 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/")
14335
15393
  });
14336
15394
  var WorkflowNodeFileContentQuerySchema = FileContentQuerySchema.extend({
14337
- 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/")
14338
15396
  });
14339
15397
  var WorkflowNodeFileContentParamsSchema = WorkflowRunParamsSchema.extend({
14340
- nodeKey: z41.string().min(1)
15398
+ nodeKey: z42.string().min(1)
14341
15399
  });
14342
15400
  function serializeWorkflowRunSummary(run) {
14343
15401
  return {
@@ -15367,6 +16425,7 @@ function registerHttpRoutes(app, host, options) {
15367
16425
  registerConnectorConnectionRoutes(app, host);
15368
16426
  registerConnectorConnectionRunRoutes(app, host, options.connectorConnections);
15369
16427
  registerDatasetRoutes(app, host);
16428
+ registerLakeRoutes(app, host);
15370
16429
  registerSyncRoutes(app, host);
15371
16430
  registerPipelineRoutes(app, host);
15372
16431
  registerWorkflowRoutes(app, host);
@@ -15401,7 +16460,7 @@ function registerHttpRoutes(app, host, options) {
15401
16460
  }
15402
16461
 
15403
16462
  // src/routes/auth.ts
15404
- import { createHash as createHash3, randomBytes, randomUUID, timingSafeEqual } from "crypto";
16463
+ import { createHash as createHash4, randomBytes, randomUUID, timingSafeEqual } from "crypto";
15405
16464
  import {
15406
16465
  AuthRuntimeError,
15407
16466
  clearCsrfCookieHeader,
@@ -16841,7 +17900,7 @@ var DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10;
16841
17900
  var DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2;
16842
17901
  var DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789";
16843
17902
  function hashDeviceCode(deviceCode) {
16844
- return createHash3("sha256").update(deviceCode).digest("base64url");
17903
+ return createHash4("sha256").update(deviceCode).digest("base64url");
16845
17904
  }
16846
17905
  function parseDeviceAuthorizationId(deviceCode) {
16847
17906
  const separator = deviceCode.indexOf(".");
@@ -16972,7 +18031,7 @@ function createMagicLinkPendingCredential() {
16972
18031
  return { secret, hash: hashMagicLinkPendingSecret(secret) };
16973
18032
  }
16974
18033
  function hashMagicLinkPendingSecret(secret) {
16975
- return createHash3("sha256").update(secret).digest("base64url");
18034
+ return createHash4("sha256").update(secret).digest("base64url");
16976
18035
  }
16977
18036
  function matchesMagicLinkRequester(pendingSecret, requesterHash) {
16978
18037
  const expected = Buffer.from(hashMagicLinkPendingSecret(pendingSecret));
@@ -17032,7 +18091,7 @@ async function completeMagicLinkCallback(input) {
17032
18091
  }
17033
18092
  }
17034
18093
  function oidcStateCookieName(state) {
17035
- 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)}`;
17036
18095
  }
17037
18096
  function oidcSignInRedirect(request, host, result) {
17038
18097
  const response = redirectResponse(result.redirectTo);
@@ -17897,13 +18956,14 @@ function jsonResponse2(body, status, headersInit) {
17897
18956
  }
17898
18957
 
17899
18958
  // src/routes/webhooks.ts
17900
- import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
18959
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "crypto";
17901
18960
  import { reportRunFailure } from "@sixb/core/internal/error-reporting";
17902
18961
  import { captureSixbFailure, createSixbError as createSixbError6, toSixbFailure as toSixbFailure2 } from "@sixb/core/internal/errors";
17903
18962
  import { bindDurablePrimitiveExecution } from "@sixb/core/internal/primitive-execution";
17904
18963
  import {
17905
18964
  admitWebhookRun,
17906
18965
  createWebhookConnections,
18966
+ holdWebhookRun,
17907
18967
  isStaticConnectorDefinition
17908
18968
  } from "@sixb/core/internal/webhooks";
17909
18969
  import { WEBHOOK_RUN_FAILURE_CODES as WEBHOOK_RUN_FAILURE_CODES2, WebhookRunError } from "@sixb/core/storage";
@@ -17926,15 +18986,25 @@ async function dispatchWebhook(options) {
17926
18986
  const admission = await admitPreparedWebhook(options, candidateRunId, prepared.request);
17927
18987
  if (admission.status === "responded")
17928
18988
  return admission.response;
18989
+ if (admission.status === "in_progress")
18990
+ return retryLater(options.set, admission.run);
17929
18991
  if (admission.status !== "admitted")
17930
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
+ });
17931
19000
  const executionLogs = options.host.logging.startExecution({
17932
19001
  kind: "webhook",
17933
19002
  id: admission.run.id
17934
19003
  });
17935
19004
  try {
17936
- return await executeWebhookHandler(options, prepared.request, admission, executionLogs.withContext({ phase: "handle" }));
19005
+ return await executeWebhookHandler(options, prepared.request, admission, execution, executionLogs.withContext({ phase: "handle" }));
17937
19006
  } finally {
19007
+ stopHolding();
17938
19008
  await executionLogs.flush();
17939
19009
  }
17940
19010
  }
@@ -18010,7 +19080,7 @@ async function admitPreparedWebhook(options, runId, prepared) {
18010
19080
  method: options.request.method.toUpperCase(),
18011
19081
  route: options.registered.route,
18012
19082
  requestBodyBytes: prepared.rawBody.byteLength,
18013
- requestBodySha256: createHash4("sha256").update(prepared.rawBody).digest("hex"),
19083
+ requestBodySha256: createHash5("sha256").update(prepared.rawBody).digest("hex"),
18014
19084
  idempotencyKey: prepared.idempotencyKey
18015
19085
  });
18016
19086
  } catch (error) {
@@ -18022,7 +19092,7 @@ async function admitPreparedWebhook(options, runId, prepared) {
18022
19092
  return { status: "responded", response: { error: "Webhook admission failed" } };
18023
19093
  }
18024
19094
  }
18025
- async function executeWebhookHandler(options, prepared, admission, logger) {
19095
+ async function executeWebhookHandler(options, prepared, admission, { token: executionToken }, logger) {
18026
19096
  const { host, registered, request, set } = options;
18027
19097
  const { connector, webhook } = registered;
18028
19098
  const runId = admission.run.id;
@@ -18057,6 +19127,7 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18057
19127
  try {
18058
19128
  await finishWebhookRun(host, {
18059
19129
  runId,
19130
+ executionToken,
18060
19131
  status: "failed",
18061
19132
  responseStatus: 500,
18062
19133
  failure: failed.failure
@@ -18075,7 +19146,7 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18075
19146
  message: `Webhook handler returned HTTP ${responseStatus}`
18076
19147
  });
18077
19148
  try {
18078
- 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 });
18079
19150
  } catch (error) {
18080
19151
  const failure = captureSixbFailure(error, {
18081
19152
  allowedCodes: WEBHOOK_RUN_FAILURE_CODES2,
@@ -18096,6 +19167,17 @@ async function executeWebhookHandler(options, prepared, admission, logger) {
18096
19167
  }
18097
19168
  return applyWebhookResponse(set, response);
18098
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
+ }
18099
19181
  function createFailureReporter(host, registered, runId) {
18100
19182
  let reported = false;
18101
19183
  return (error, failure) => {
@@ -18122,6 +19204,7 @@ async function finishWebhookRun(host, input) {
18122
19204
  const terminal = {
18123
19205
  id: input.runId,
18124
19206
  projectId: host.id,
19207
+ executionToken: input.executionToken,
18125
19208
  responseStatus: input.responseStatus
18126
19209
  };
18127
19210
  await storage.finish(input.status === "failed" ? {
@@ -18192,7 +19275,7 @@ function isWebhookResponse(value) {
18192
19275
  }
18193
19276
 
18194
19277
  // src/routes/ws/agents.ts
18195
- import { principalsEqual as principalsEqual3 } from "@sixb/core";
19278
+ import { principalsEqual as principalsEqual4 } from "@sixb/core";
18196
19279
  import {
18197
19280
  AGENT_ACTIVITY_STREAM_ID,
18198
19281
  isAgentActivityEvent
@@ -18203,7 +19286,7 @@ import {
18203
19286
  agentRunStreamDefinition,
18204
19287
  agentRunStreamId as agentRunStreamId3
18205
19288
  } from "@sixb/core/internal/agents/streams";
18206
- import { z as z42 } from "zod";
19289
+ import { z as z43 } from "zod";
18207
19290
 
18208
19291
  // src/utils/ws.ts
18209
19292
  function safeSend(target, payload) {
@@ -18219,6 +19302,10 @@ function wsRequestSixb(ws) {
18219
19302
  const data = ws.data;
18220
19303
  return data?.sixb ?? null;
18221
19304
  }
19305
+ function wsSharedSession(ws) {
19306
+ const data = ws.data;
19307
+ return data?.sharedSession ?? null;
19308
+ }
18222
19309
  function parseJson(text) {
18223
19310
  try {
18224
19311
  return JSON.parse(text);
@@ -18251,25 +19338,25 @@ async function decodeWsMessage(message) {
18251
19338
  }
18252
19339
 
18253
19340
  // src/routes/ws/agents.ts
18254
- var SubscribeSchema = z42.object({
18255
- type: z42.literal("subscribe"),
18256
- runId: z42.string().min(1),
18257
- 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()
18258
19345
  });
18259
- var SubscribeActivitySchema = z42.object({
18260
- type: z42.literal("subscribe.activity")
19346
+ var SubscribeActivitySchema = z43.object({
19347
+ type: z43.literal("subscribe.activity")
18261
19348
  });
18262
- var ReplaySchema = z42.object({
18263
- type: z42.literal("replay"),
18264
- runId: z42.string().min(1),
18265
- afterCursor: z42.string().min(1).optional(),
18266
- 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()
18267
19354
  });
18268
- var UnsubscribeSchema = z42.object({
18269
- type: z42.literal("unsubscribe"),
18270
- runId: z42.string().min(1).optional()
19355
+ var UnsubscribeSchema = z43.object({
19356
+ type: z43.literal("unsubscribe"),
19357
+ runId: z43.string().min(1).optional()
18271
19358
  });
18272
- var AgentStreamMessageSchema = z42.union([
19359
+ var AgentStreamMessageSchema = z43.union([
18273
19360
  SubscribeSchema,
18274
19361
  SubscribeActivitySchema,
18275
19362
  ReplaySchema,
@@ -18297,7 +19384,7 @@ async function canAccessAgentRunStream(sixb, runId) {
18297
19384
  }
18298
19385
  async function canAccessAgentThreadActivity(sixb, event) {
18299
19386
  if (event.type === "agent.computer.activity" || event.type === "agent.thread.moved") {
18300
- return principalsEqual3(event.ownerPrincipal, requestActor(sixb));
19387
+ return principalsEqual4(event.ownerPrincipal, requestActor(sixb));
18301
19388
  }
18302
19389
  const run = await sixb.agent.runs.getById(event.runId);
18303
19390
  return run?.projectId === event.projectId && run.threadId === event.threadId;
@@ -18567,9 +19654,1018 @@ function errorMessage(error) {
18567
19654
  return error instanceof Error ? error.message : String(error);
18568
19655
  }
18569
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
+
18570
20666
  // src/routes/ws/events.ts
18571
20667
  import { scopeKeysForEvent } from "@sixb/core/internal/event-scope";
18572
- import { z as z43 } from "zod";
20668
+ import { z as z45 } from "zod";
18573
20669
 
18574
20670
  // src/routes/ws/subscription-hub.ts
18575
20671
  import { BrokerCursorExpiredError as BrokerCursorExpiredError2 } from "@sixb/core/broker";
@@ -18900,20 +20996,20 @@ function socketBufferedAmount(ws) {
18900
20996
 
18901
20997
  // src/routes/ws/events.ts
18902
20998
  var DEFAULT_READ_LIMIT = 200;
18903
- var SubscribeSchema2 = z43.object({
18904
- type: z43.literal("subscribe"),
18905
- topic: z43.enum(EVENT_TOPICS).optional(),
18906
- types: z43.array(z43.enum(EVENT_TYPES)).optional(),
18907
- objectTypeId: z43.string().optional(),
18908
- primaryId: z43.string().optional(),
18909
- runId: z43.string().optional(),
18910
- afterCursor: z43.string().optional(),
18911
- limit: z43.number().int().positive().max(500).optional()
18912
- });
18913
- var UnsubscribeSchema2 = z43.object({
18914
- type: z43.literal("unsubscribe")
18915
- });
18916
- 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]);
18917
21013
  function parseSubscriptionMessage(payload) {
18918
21014
  if (!payload || typeof payload !== "object") {
18919
21015
  return { ok: false, error: "Message must be a JSON object." };
@@ -18927,7 +21023,7 @@ function parseSubscriptionMessage(payload) {
18927
21023
  }
18928
21024
  return { ok: true, data: parsed.data };
18929
21025
  }
18930
- function registerEventStreamRoutes(app, server) {
21026
+ function registerEventStreamRoutes(app, server, shared) {
18931
21027
  const events = server.getHost().events;
18932
21028
  const states = new WeakMap;
18933
21029
  const hub = new SubscriptionHub({
@@ -18958,6 +21054,7 @@ function registerEventStreamRoutes(app, server) {
18958
21054
  app.onStop(() => hub.close());
18959
21055
  return app.ws("/ws/events", {
18960
21056
  async open(ws) {
21057
+ shared.open(ws);
18961
21058
  const state = {
18962
21059
  replayFrom: null,
18963
21060
  initialized: Promise.resolve(),
@@ -18972,6 +21069,8 @@ function registerEventStreamRoutes(app, server) {
18972
21069
  safeSend(ws, { type: "connected", channel: "events" });
18973
21070
  },
18974
21071
  async message(ws, message) {
21072
+ if (!await shared.holds(ws))
21073
+ return;
18975
21074
  const decoded = await decodeWsMessage(message);
18976
21075
  const parsed = parseSubscriptionMessage(decoded);
18977
21076
  if (!parsed.ok) {
@@ -19036,6 +21135,7 @@ function registerEventStreamRoutes(app, server) {
19036
21135
  }
19037
21136
  },
19038
21137
  close(ws) {
21138
+ shared.close(ws);
19039
21139
  hub.unsubscribe(wsStateKey(ws));
19040
21140
  states.delete(wsStateKey(ws));
19041
21141
  }
@@ -19060,28 +21160,28 @@ function eventMatchesScope(event, filter) {
19060
21160
  }
19061
21161
 
19062
21162
  // src/routes/ws/logs.ts
19063
- import { z as z44 } from "zod";
21163
+ import { z as z46 } from "zod";
19064
21164
  var READ_PAGE_SIZE = 500;
19065
- var SubscribeSchema3 = z44.object({
19066
- type: z44.literal("subscribe"),
19067
- kinds: z44.array(z44.enum(SIXB_RUN_KINDS)).min(1).optional(),
19068
- levels: z44.array(z44.enum(LOG_LEVELS)).min(1).optional(),
19069
- run: z44.object({
19070
- 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),
19071
21171
  id: LogRunIdSchema
19072
21172
  }).optional(),
19073
- afterCursor: z44.string().optional()
21173
+ afterCursor: z46.string().optional()
19074
21174
  }).superRefine((value, context) => {
19075
21175
  if (value.run && value.kinds && !value.kinds.includes(value.run.kind)) {
19076
21176
  context.addIssue({
19077
- code: z44.ZodIssueCode.custom,
21177
+ code: z46.ZodIssueCode.custom,
19078
21178
  path: ["run"],
19079
21179
  message: "run.kind must be included in kinds"
19080
21180
  });
19081
21181
  }
19082
21182
  });
19083
- var UnsubscribeSchema3 = z44.object({ type: z44.literal("unsubscribe") });
19084
- var SubscriptionMessageSchema2 = z44.union([SubscribeSchema3, UnsubscribeSchema3]);
21183
+ var UnsubscribeSchema3 = z46.object({ type: z46.literal("unsubscribe") });
21184
+ var SubscriptionMessageSchema2 = z46.union([SubscribeSchema3, UnsubscribeSchema3]);
19085
21185
  function parseLogSubscriptionMessage(payload) {
19086
21186
  if (!payload || typeof payload !== "object") {
19087
21187
  return { ok: false, error: "Message must be a JSON object." };
@@ -19206,11 +21306,103 @@ function matchesLogFilter(line, filter) {
19206
21306
  return true;
19207
21307
  }
19208
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
+
19209
21399
  // src/routes/ws/index.ts
19210
- function registerWebSocketRoutes(app, server) {
19211
- registerEventStreamRoutes(app, server);
21400
+ function registerWebSocketRoutes(app, server, sharedAccess) {
21401
+ const shared = new SharedSockets(sharedAccess);
21402
+ registerEventStreamRoutes(app, server, shared);
19212
21403
  registerLogStreamRoutes(app, server);
19213
21404
  registerAgentStreamRoutes(app, server);
21405
+ registerArtifactLiveRoutes(app, server, shared);
19214
21406
  return app;
19215
21407
  }
19216
21408
 
@@ -19234,6 +21426,8 @@ class SixbServer {
19234
21426
  timing;
19235
21427
  app = null;
19236
21428
  bunServer = null;
21429
+ hostsOntologyMaintenance;
21430
+ flushesIngestion;
19237
21431
  maintenance = null;
19238
21432
  stopSweeper = null;
19239
21433
  constructor(options) {
@@ -19242,6 +21436,8 @@ class SixbServer {
19242
21436
  this.hostname = options.hostname ?? "0.0.0.0";
19243
21437
  this.quiet = options.quiet ?? false;
19244
21438
  this.timing = options.timing ?? {};
21439
+ this.hostsOntologyMaintenance = options.ontologyMaintenance ?? true;
21440
+ this.flushesIngestion = options.ingestFlush ?? true;
19245
21441
  this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser);
19246
21442
  if (this.apiBrowserPolicy.publicOrigin) {
19247
21443
  setApiPublicOrigin(this.hostRuntime, this.apiBrowserPolicy.publicOrigin);
@@ -19288,7 +21484,9 @@ class SixbServer {
19288
21484
  lakeStorage: this.hostRuntime.lakeStorage
19289
21485
  });
19290
21486
  warmAppliedMarkings(this.hostRuntime);
19291
- 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;
19292
21490
  this.maintenance = maintenance;
19293
21491
  try {
19294
21492
  this.app = createSixbApi(this);
@@ -19302,7 +21500,7 @@ class SixbServer {
19302
21500
  this.app = null;
19303
21501
  this.bunServer = null;
19304
21502
  this.maintenance = null;
19305
- await maintenance.stop();
21503
+ await maintenance?.stop();
19306
21504
  const message = error instanceof Error ? error.message : String(error);
19307
21505
  throw new Error(`[SixbServer] Failed to listen on ${this.hostname}:${this.port}: ${message}`);
19308
21506
  }
@@ -19313,7 +21511,13 @@ class SixbServer {
19313
21511
  console.log(`OpenAPI docs at ${base}/docs`);
19314
21512
  }
19315
21513
  }
21514
+ setIngestFlush(inline) {
21515
+ const ingest = findDatasetIngestRuntime(this.hostRuntime);
21516
+ if (ingest)
21517
+ ingest.writesInline = inline;
21518
+ }
19316
21519
  async stop() {
21520
+ this.setIngestFlush(false);
19317
21521
  this.stopSweeper?.();
19318
21522
  this.stopSweeper = null;
19319
21523
  if (this.bunServer) {
@@ -19395,6 +21599,7 @@ function createSixbApi(server) {
19395
21599
  return {
19396
21600
  auth: { kind: "allow", session: null },
19397
21601
  sharedAccessCookies: null,
21602
+ sharedSession: null,
19398
21603
  ...agentState,
19399
21604
  sixb: bindAgentRunRequestExecution2(host, { signal: request.signal, ...runExecution })
19400
21605
  };
@@ -19405,6 +21610,7 @@ function createSixbApi(server) {
19405
21610
  return {
19406
21611
  auth: { kind: "deny", response: shared.response },
19407
21612
  sharedAccessCookies: null,
21613
+ sharedSession: null,
19408
21614
  sixb: null
19409
21615
  };
19410
21616
  }
@@ -19412,6 +21618,7 @@ function createSixbApi(server) {
19412
21618
  return {
19413
21619
  auth: { kind: "allow", session: null },
19414
21620
  sharedAccessCookies: shared.cookies,
21621
+ sharedSession: shared.context,
19415
21622
  sixb: bindRequestExecution(host, {
19416
21623
  request,
19417
21624
  authorization: {
@@ -19431,6 +21638,7 @@ function createSixbApi(server) {
19431
21638
  return {
19432
21639
  auth,
19433
21640
  sharedAccessCookies: null,
21641
+ sharedSession: null,
19434
21642
  sixb: auth.kind === "allow" && !guard.isAuthEnabled() ? bindRequestExecution(host, {
19435
21643
  request,
19436
21644
  authorization: { type: "disabled" }
@@ -19442,6 +21650,7 @@ function createSixbApi(server) {
19442
21650
  return {
19443
21651
  auth,
19444
21652
  sharedAccessCookies: null,
21653
+ sharedSession: null,
19445
21654
  sixb: bindRequestExecution(host, {
19446
21655
  request,
19447
21656
  authorization: { type: "principal", context: authz, credential }
@@ -19528,7 +21737,7 @@ function createSixbApi(server) {
19528
21737
  }
19529
21738
  });
19530
21739
  registerWebhookRoutes(app, host);
19531
- registerWebSocketRoutes(app, server);
21740
+ registerWebSocketRoutes(app, server, sharedAccess);
19532
21741
  return app;
19533
21742
  }
19534
21743
  function appendSetCookieHeaders(set, values) {
@@ -19612,4 +21821,4 @@ export {
19612
21821
  requestTimingOptionsFromEnv
19613
21822
  };
19614
21823
 
19615
- //# debugId=198F4D789C21C75264756E2164756E21
21824
+ //# debugId=B5AFC4B93CECC31464756E2164756E21