@sixb/server 0.1.17 → 0.1.19

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 (110) hide show
  1. package/README.md +3 -3
  2. package/dist/actions/serialize.d.ts +7 -0
  3. package/dist/actions/serialize.d.ts.map +1 -0
  4. package/dist/auth/experience.d.ts +5 -1
  5. package/dist/auth/experience.d.ts.map +1 -1
  6. package/dist/files/content.d.ts +0 -1
  7. package/dist/files/content.d.ts.map +1 -1
  8. package/dist/index.js +812 -769
  9. package/dist/index.js.map +32 -31
  10. package/dist/routes/action-runs.d.ts +11 -13
  11. package/dist/routes/action-runs.d.ts.map +1 -1
  12. package/dist/routes/actions.d.ts +44 -13
  13. package/dist/routes/actions.d.ts.map +1 -1
  14. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  15. package/dist/routes/agents.d.ts +67 -47
  16. package/dist/routes/agents.d.ts.map +1 -1
  17. package/dist/routes/auth.d.ts +3 -2
  18. package/dist/routes/auth.d.ts.map +1 -1
  19. package/dist/routes/connector-connection-runs.d.ts +21 -21
  20. package/dist/routes/connector-connections.d.ts +8 -8
  21. package/dist/routes/connectors.d.ts +2 -2
  22. package/dist/routes/datasets.d.ts +9 -6
  23. package/dist/routes/datasets.d.ts.map +1 -1
  24. package/dist/routes/events.d.ts +4 -4
  25. package/dist/routes/files.d.ts +15 -12
  26. package/dist/routes/files.d.ts.map +1 -1
  27. package/dist/routes/models.d.ts +1 -0
  28. package/dist/routes/models.d.ts.map +1 -1
  29. package/dist/routes/objects.d.ts +21 -4
  30. package/dist/routes/objects.d.ts.map +1 -1
  31. package/dist/routes/ontology.d.ts +6 -6
  32. package/dist/routes/pipelines.d.ts +16 -16
  33. package/dist/routes/project.d.ts +2 -0
  34. package/dist/routes/project.d.ts.map +1 -1
  35. package/dist/routes/projections.d.ts +49 -49
  36. package/dist/routes/syncs.d.ts +10 -10
  37. package/dist/routes/webhook-runs.d.ts +2 -2
  38. package/dist/routes/workflows.d.ts +51 -48
  39. package/dist/routes/workflows.d.ts.map +1 -1
  40. package/dist/routes/ws/events.d.ts +6 -9
  41. package/dist/routes/ws/events.d.ts.map +1 -1
  42. package/dist/routes/ws/subscription-hub.d.ts +5 -0
  43. package/dist/routes/ws/subscription-hub.d.ts.map +1 -1
  44. package/dist/schemas/actions.d.ts +100 -84
  45. package/dist/schemas/actions.d.ts.map +1 -1
  46. package/dist/schemas/agents.d.ts +242 -143
  47. package/dist/schemas/agents.d.ts.map +1 -1
  48. package/dist/schemas/ai-accounting.d.ts +10 -10
  49. package/dist/schemas/ai-limits.d.ts +10 -10
  50. package/dist/schemas/auth.d.ts +7 -0
  51. package/dist/schemas/auth.d.ts.map +1 -1
  52. package/dist/schemas/common.d.ts +8 -0
  53. package/dist/schemas/common.d.ts.map +1 -1
  54. package/dist/schemas/connectors.d.ts +8 -8
  55. package/dist/schemas/datasets.d.ts +58 -43
  56. package/dist/schemas/datasets.d.ts.map +1 -1
  57. package/dist/schemas/event-payloads.d.ts +39 -0
  58. package/dist/schemas/event-payloads.d.ts.map +1 -1
  59. package/dist/schemas/events.d.ts +24 -24
  60. package/dist/schemas/events.d.ts.map +1 -1
  61. package/dist/schemas/files.d.ts +5 -5
  62. package/dist/schemas/files.d.ts.map +1 -1
  63. package/dist/schemas/models.d.ts +10 -0
  64. package/dist/schemas/models.d.ts.map +1 -1
  65. package/dist/schemas/objects.d.ts +32 -0
  66. package/dist/schemas/objects.d.ts.map +1 -1
  67. package/dist/schemas/ontology.d.ts +40 -40
  68. package/dist/schemas/pipelines.d.ts +92 -92
  69. package/dist/schemas/project.d.ts +8 -0
  70. package/dist/schemas/project.d.ts.map +1 -1
  71. package/dist/schemas/projections.d.ts +290 -290
  72. package/dist/schemas/syncs.d.ts +34 -34
  73. package/dist/schemas/webhook-runs.d.ts +8 -8
  74. package/dist/schemas/workflows.d.ts +177 -160
  75. package/dist/schemas/workflows.d.ts.map +1 -1
  76. package/dist/server.d.ts +1 -0
  77. package/dist/server.d.ts.map +1 -1
  78. package/dist/utils/http.d.ts.map +1 -1
  79. package/dist/utils/request-body.d.ts +20 -6
  80. package/dist/utils/request-body.d.ts.map +1 -1
  81. package/package.json +6 -5
  82. package/src/actions/serialize.ts +55 -0
  83. package/src/auth/experience.ts +20 -2
  84. package/src/files/content.ts +43 -88
  85. package/src/routes/action-runs.ts +1 -54
  86. package/src/routes/actions.ts +26 -8
  87. package/src/routes/agent-api-gateway.ts +18 -42
  88. package/src/routes/agents.ts +29 -9
  89. package/src/routes/auth.ts +84 -19
  90. package/src/routes/datasets.ts +12 -43
  91. package/src/routes/files.ts +18 -64
  92. package/src/routes/models.ts +3 -0
  93. package/src/routes/objects.ts +12 -2
  94. package/src/routes/project.ts +2 -1
  95. package/src/routes/workflows.ts +5 -0
  96. package/src/routes/ws/events.ts +7 -15
  97. package/src/routes/ws/subscription-hub.ts +20 -5
  98. package/src/schemas/actions.ts +21 -18
  99. package/src/schemas/agents.ts +28 -3
  100. package/src/schemas/auth.ts +5 -0
  101. package/src/schemas/common.ts +3 -0
  102. package/src/schemas/datasets.ts +23 -1
  103. package/src/schemas/event-payloads.ts +3 -1
  104. package/src/schemas/files.ts +7 -1
  105. package/src/schemas/models.ts +2 -0
  106. package/src/schemas/objects.ts +13 -0
  107. package/src/schemas/project.ts +4 -0
  108. package/src/server.ts +23 -4
  109. package/src/utils/http.ts +2 -0
  110. package/src/utils/request-body.ts +55 -6
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { openapi } from "@elysiajs/openapi";
5
5
  import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2, setRequestClientAddress } from "@sixb/core/internal/auth";
6
6
  import { bindRequestExecution } from "@sixb/core/internal/request-execution";
7
7
  import { setApiPublicOrigin } from "@sixb/core/internal/runtime";
8
- import { Elysia } from "elysia";
8
+ import { Elysia, ParseError } from "elysia";
9
9
  import { websocket as elysiaWebSocket } from "elysia/ws";
10
10
  import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
11
11
 
@@ -1168,325 +1168,8 @@ var OPENAPI_TAG_METADATA = Object.values(OPENAPI_TAGS).map(({ name, description
1168
1168
  // src/routes/action-runs.ts
1169
1169
  import { z as z5 } from "zod";
1170
1170
 
1171
- // src/files/content.ts
1172
- import { createHash as createHash2 } from "crypto";
1173
- import { isFileRef } from "@sixb/core";
1174
- import { BlobStorageError, supportsRangeRead } from "@sixb/core/blob-storage/server";
1175
- import { ZodError } from "zod";
1176
- var unconfiguredStorageResponse = {
1177
- 501: {
1178
- description: "The storage role backing this content is not configured",
1179
- content: {
1180
- "application/json": {
1181
- schema: { $ref: "#/components/schemas/ErrorResponse" }
1182
- }
1183
- }
1184
- }
1185
- };
1186
- function handleFileContentQueryValidationError(context) {
1187
- if (context.code !== "VALIDATION" || context.error.type !== "query")
1188
- return;
1189
- context.set.status = 400;
1190
- return { error: "Invalid file content query" };
1191
- }
1192
- function fileContentGetResponses(options = {}) {
1193
- return {
1194
- 200: {
1195
- description: "File content",
1196
- content: {
1197
- "application/octet-stream": {
1198
- schema: { type: "string", format: "binary" }
1199
- }
1200
- }
1201
- },
1202
- 206: {
1203
- description: "Partial file content",
1204
- content: {
1205
- "application/octet-stream": {
1206
- schema: { type: "string", format: "binary" }
1207
- }
1208
- }
1209
- },
1210
- 304: {
1211
- description: "File representation is unchanged; reuse the privately cached content"
1212
- },
1213
- 400: {
1214
- description: "Response for status 400",
1215
- content: {
1216
- "application/json": {
1217
- schema: { $ref: "#/components/schemas/ErrorResponse" }
1218
- }
1219
- }
1220
- },
1221
- 404: {
1222
- description: "Response for status 404",
1223
- content: {
1224
- "application/json": {
1225
- schema: { $ref: "#/components/schemas/ErrorResponse" }
1226
- }
1227
- }
1228
- },
1229
- 416: {
1230
- description: "Requested byte range is not satisfiable"
1231
- },
1232
- ...options.optionalStorage ? unconfiguredStorageResponse : {}
1233
- };
1234
- }
1235
- function fileContentHeadResponses(options = {}) {
1236
- return {
1237
- 200: {
1238
- description: "File content headers"
1239
- },
1240
- 206: {
1241
- description: "Partial file content headers"
1242
- },
1243
- 304: {
1244
- description: "File representation is unchanged; reuse the privately cached content"
1245
- },
1246
- 400: {
1247
- description: "Response for status 400",
1248
- content: {
1249
- "application/json": {
1250
- schema: { $ref: "#/components/schemas/ErrorResponse" }
1251
- }
1252
- }
1253
- },
1254
- 404: {
1255
- description: "Response for status 404",
1256
- content: {
1257
- "application/json": {
1258
- schema: { $ref: "#/components/schemas/ErrorResponse" }
1259
- }
1260
- }
1261
- },
1262
- 416: {
1263
- description: "Requested byte range is not satisfiable"
1264
- },
1265
- ...options.optionalStorage ? unconfiguredStorageResponse : {}
1266
- };
1267
- }
1268
- async function createFileContentResponse(input) {
1269
- const stat = await input.blobStorage.stat(input.fileRef.blobId);
1270
- if (!stat || !blobMatchesFileRef(stat, input.fileRef)) {
1271
- return null;
1272
- }
1273
- const canReadRange = supportsRangeRead(input.blobStorage);
1274
- const headers = fileContentHeaders(input.fileRef, stat, input.disposition, canReadRange);
1275
- const etag = headers.get("etag");
1276
- if (matchesIfNoneMatch(input.ifNoneMatchHeader, etag)) {
1277
- headers.delete("content-length");
1278
- return new Response(null, { status: 304, headers });
1279
- }
1280
- if (canReadRange && input.rangeHeader && (input.ifRangeHeader == null || input.ifRangeHeader.trim() === etag)) {
1281
- const range = parseSingleByteRange(input.rangeHeader, stat.sizeBytes);
1282
- if (!range) {
1283
- return rangeNotSatisfiableResponse(stat.sizeBytes);
1284
- }
1285
- const partialHeaders = partialFileContentHeaders(headers, range, stat.sizeBytes);
1286
- if (input.head) {
1287
- return new Response(null, { status: 206, headers: partialHeaders });
1288
- }
1289
- try {
1290
- const stream = await input.blobStorage.openRange(input.fileRef.blobId, range);
1291
- return new Response(stream, { status: 206, headers: partialHeaders });
1292
- } catch (error) {
1293
- if (error instanceof BlobStorageError) {
1294
- return null;
1295
- }
1296
- throw error;
1297
- }
1298
- }
1299
- if (input.head) {
1300
- return new Response(null, { headers });
1301
- }
1302
- try {
1303
- const stream = await input.blobStorage.open(input.fileRef.blobId);
1304
- return new Response(stream, { headers });
1305
- } catch (error) {
1306
- if (error instanceof BlobStorageError) {
1307
- return null;
1308
- }
1309
- throw error;
1310
- }
1311
- }
1312
- async function createContextualFileContentResponse(input) {
1313
- const missingMessage = input.missingMessage ?? "File not found";
1314
- const invalidQueryMessage = input.invalidQueryMessage ?? "Invalid file content query";
1315
- try {
1316
- const parsed = input.querySchema.parse(input.query);
1317
- const root = await input.resolveRoot(parsed);
1318
- if (root === null || root === undefined) {
1319
- return fileContentNotFound(input.set, missingMessage);
1320
- }
1321
- const fileRef = resolveFileRefAtPath(root, parsed.path);
1322
- if (!fileRef) {
1323
- return fileContentNotFound(input.set, missingMessage);
1324
- }
1325
- const response = await createFileContentResponse({
1326
- blobStorage: input.blobStorage,
1327
- fileRef,
1328
- disposition: parsed.disposition,
1329
- head: input.head,
1330
- rangeHeader: input.request.headers.get("range"),
1331
- ifNoneMatchHeader: input.request.headers.get("if-none-match"),
1332
- ifRangeHeader: input.request.headers.get("if-range")
1333
- });
1334
- if (!response) {
1335
- return fileContentNotFound(input.set, missingMessage);
1336
- }
1337
- return response;
1338
- } catch (error) {
1339
- if (error instanceof ZodError) {
1340
- input.set.status = 400;
1341
- return { error: invalidQueryMessage };
1342
- }
1343
- if (input.hideError?.(error)) {
1344
- return fileContentNotFound(input.set, missingMessage);
1345
- }
1346
- throw error;
1347
- }
1348
- }
1349
- function resolveFileRefAtPath(root, path) {
1350
- const value = resolveJsonPointer(root, path);
1351
- return isFileRef(value) ? value : null;
1352
- }
1353
- function fileContentNotFound(set, message) {
1354
- set.status = 404;
1355
- return { error: message };
1356
- }
1357
- function blobMatchesFileRef(stat, fileRef) {
1358
- return stat.blobId === fileRef.blobId && stat.digest === fileRef.digest && stat.sizeBytes === fileRef.sizeBytes;
1359
- }
1360
- function matchesIfNoneMatch(header, etag) {
1361
- return header?.trim() === "*" || (header?.split(",").some((value) => value.trim().replace(/^W\//, "") === etag) ?? false);
1362
- }
1363
- function resolveJsonPointer(root, pointer) {
1364
- if (pointer === "") {
1365
- return root;
1366
- }
1367
- if (!pointer.startsWith("/")) {
1368
- return;
1369
- }
1370
- let current = root;
1371
- for (const rawSegment of pointer.slice(1).split("/")) {
1372
- const segment = decodeJsonPointerSegment(rawSegment);
1373
- if (Array.isArray(current)) {
1374
- const index = Number.parseInt(segment, 10);
1375
- if (!Number.isInteger(index) || index < 0 || index.toString() !== segment) {
1376
- return;
1377
- }
1378
- if (!Object.hasOwn(current, segment)) {
1379
- return;
1380
- }
1381
- current = current[index];
1382
- continue;
1383
- }
1384
- if (typeof current !== "object" || current === null || !Object.hasOwn(current, segment)) {
1385
- return;
1386
- }
1387
- current = current[segment];
1388
- }
1389
- return current;
1390
- }
1391
- function decodeJsonPointerSegment(segment) {
1392
- return segment.replaceAll("~1", "/").replaceAll("~0", "~");
1393
- }
1394
- function fileContentHeaders(fileRef, stat, requestedDisposition, canReadRange) {
1395
- const mediaType = fileRef.mediaType?.trim() || "application/octet-stream";
1396
- const disposition = (requestedDisposition ?? "inline") === "inline" && canRenderInline(mediaType) ? "inline" : "attachment";
1397
- const headers = new Headers;
1398
- headers.set("content-type", mediaType);
1399
- headers.set("content-length", stat.sizeBytes.toString());
1400
- headers.set("content-disposition", contentDispositionHeader(disposition, fileNameFor(fileRef)));
1401
- const representation = JSON.stringify([
1402
- fileRef.digest,
1403
- mediaType,
1404
- headers.get("content-disposition")
1405
- ]);
1406
- headers.set("etag", `"sha256:${createHash2("sha256").update(representation).digest("hex")}"`);
1407
- headers.set("x-content-type-options", "nosniff");
1408
- headers.set("cache-control", "private, no-cache");
1409
- if (canReadRange) {
1410
- headers.set("accept-ranges", "bytes");
1411
- }
1412
- return headers;
1413
- }
1414
- function parseSingleByteRange(header, sizeBytes) {
1415
- const normalized = header.trim();
1416
- if (!normalized.startsWith("bytes=") || normalized.includes(",")) {
1417
- return null;
1418
- }
1419
- if (sizeBytes <= 0) {
1420
- return null;
1421
- }
1422
- const spec = normalized.slice("bytes=".length).trim();
1423
- const match = spec.match(/^(\d*)-(\d*)$/);
1424
- if (!match) {
1425
- return null;
1426
- }
1427
- const [, rawStart, rawEnd] = match;
1428
- if (!rawStart && !rawEnd) {
1429
- return null;
1430
- }
1431
- if (!rawStart) {
1432
- const suffixLength = Number(rawEnd);
1433
- if (!Number.isSafeInteger(suffixLength) || suffixLength <= 0) {
1434
- return null;
1435
- }
1436
- return {
1437
- start: Math.max(sizeBytes - suffixLength, 0),
1438
- endInclusive: sizeBytes - 1
1439
- };
1440
- }
1441
- const start = Number(rawStart);
1442
- if (!Number.isSafeInteger(start) || start >= sizeBytes) {
1443
- return null;
1444
- }
1445
- const requestedEnd = rawEnd ? Number(rawEnd) : sizeBytes - 1;
1446
- if (!Number.isSafeInteger(requestedEnd) || requestedEnd < start) {
1447
- return null;
1448
- }
1449
- return {
1450
- start,
1451
- endInclusive: Math.min(requestedEnd, sizeBytes - 1)
1452
- };
1453
- }
1454
- function partialFileContentHeaders(baseHeaders, range, sizeBytes) {
1455
- const headers = new Headers(baseHeaders);
1456
- headers.set("content-length", (range.endInclusive - range.start + 1).toString());
1457
- headers.set("content-range", `bytes ${range.start}-${range.endInclusive}/${sizeBytes}`);
1458
- return headers;
1459
- }
1460
- function rangeNotSatisfiableResponse(sizeBytes) {
1461
- const headers = new Headers;
1462
- headers.set("accept-ranges", "bytes");
1463
- headers.set("content-range", `bytes */${sizeBytes}`);
1464
- return new Response(null, { status: 416, headers });
1465
- }
1466
- function canRenderInline(mediaType) {
1467
- const baseType = mediaType.split(";")[0]?.trim().toLowerCase();
1468
- if (!baseType) {
1469
- return false;
1470
- }
1471
- if (baseType === "text/html" || baseType === "image/svg+xml" || baseType === "application/xhtml+xml") {
1472
- return false;
1473
- }
1474
- return baseType === "application/pdf" || baseType === "text/plain" || baseType === "text/markdown" || baseType === "application/json" || baseType.startsWith("image/");
1475
- }
1476
- function fileNameFor(fileRef) {
1477
- const fromFileName = fileRef.fileName?.split(/[\\/]/).filter(Boolean).at(-1);
1478
- if (fromFileName) {
1479
- return fromFileName;
1480
- }
1481
- const fromLogicalPath = fileRef.logicalPath?.split(/[\\/]/).filter(Boolean).at(-1);
1482
- return fromLogicalPath || `${fileRef.blobId}.bin`;
1483
- }
1484
- function contentDispositionHeader(disposition, fileName) {
1485
- const asciiFileName = fileName.replace(/[^\x20-\x7e]/g, "_").replaceAll('"', "'");
1486
- return `${disposition}; filename="${asciiFileName}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
1487
- }
1488
-
1489
1171
  // src/schemas/actions.ts
1172
+ import { SIXB_ERROR_CODES } from "@sixb/core/internal/errors";
1490
1173
  import {
1491
1174
  ACTION_RUN_FAILURE_CODES,
1492
1175
  ACTION_RUN_PHASES
@@ -1503,6 +1186,7 @@ function codedErrorResponseSchema(codes) {
1503
1186
  code: z.enum(codes).describe("Stable machine-readable failure code for programmatic handling.")
1504
1187
  });
1505
1188
  }
1189
+ var RedactionsSchema = z.record(z.object({ reason: z.literal("missing_clearance") }));
1506
1190
  var SuccessResponseSchema = z.object({ success: z.boolean() });
1507
1191
  var PrincipalSchema = z.object({
1508
1192
  type: z.enum(["user", "serviceAccount", "system"]),
@@ -1659,12 +1343,11 @@ var RequestActionBodySchema = z3.object({
1659
1343
  params: z3.record(z3.unknown()).optional(),
1660
1344
  runId: z3.string().min(1).optional()
1661
1345
  });
1662
- var RequestActionResponseSchema = z3.object({
1663
- runId: z3.string(),
1664
- queuedAt: z3.string(),
1665
- jobId: z3.string().optional(),
1666
- created: z3.boolean()
1667
- });
1346
+ var ActionRunInProgressResponseSchema = codedErrorResponseSchema([
1347
+ "action.run_in_progress"
1348
+ ]);
1349
+ var ActionRequestFailedResponseSchema = codedErrorResponseSchema(SIXB_ERROR_CODES);
1350
+ var RuntimeStoppingResponseSchema = codedErrorResponseSchema(["runtime.stopping"]);
1668
1351
  var ActionCatalogItemSchema = z3.object({
1669
1352
  id: z3.string(),
1670
1353
  name: z3.string(),
@@ -1681,13 +1364,7 @@ var ActionCatalogItemSchema = z3.object({
1681
1364
  var ActionDetailSchema = ActionCatalogItemSchema.extend({
1682
1365
  inputSchema: z3.record(z3.unknown())
1683
1366
  });
1684
- var ActionRunStatusSchema = z3.enum([
1685
- "queued",
1686
- "running",
1687
- "succeeded",
1688
- "failed",
1689
- "cancelled"
1690
- ]);
1367
+ var ActionRunStatusSchema = z3.enum(["succeeded", "failed"]);
1691
1368
  var ActionRunPhaseSchema = z3.enum(ACTION_RUN_PHASES);
1692
1369
  var ActionRunsQuerySchema = z3.object({
1693
1370
  actionId: z3.string().optional(),
@@ -1727,10 +1404,9 @@ var ActionRunSummarySchema = z3.object({
1727
1404
  actionId: z3.string(),
1728
1405
  subject: ActionSubjectSchema,
1729
1406
  status: ActionRunStatusSchema,
1730
- phase: ActionRunPhaseSchema.optional(),
1731
- queuedAt: z3.string(),
1732
- startedAt: z3.string().optional(),
1733
- finishedAt: z3.string().optional(),
1407
+ phase: ActionRunPhaseSchema,
1408
+ startedAt: z3.string(),
1409
+ finishedAt: z3.string(),
1734
1410
  error: ActionRunFailureSchema.optional()
1735
1411
  });
1736
1412
  var ActionRunWritebackRecordSchema = z3.discriminatedUnion("status", [
@@ -1762,83 +1438,9 @@ var ActionRunDetailSchema = ActionRunSummarySchema.extend({
1762
1438
  effects: ActionRunEffectsRecordSchema.optional()
1763
1439
  });
1764
1440
  var ActionRunListResponseSchema = z3.object({
1765
- runs: z3.array(ActionRunSummarySchema),
1766
- hasMore: z3.boolean(),
1767
- total: z3.number()
1768
- });
1769
-
1770
- // src/schemas/files.ts
1771
- import { z as z4 } from "zod";
1772
- var BlobDigestSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
1773
- var FileRefSchema = z4.object({
1774
- blobId: z4.string(),
1775
- digest: BlobDigestSchema,
1776
- sizeBytes: z4.number().int().nonnegative(),
1777
- fileName: z4.string().optional(),
1778
- mediaType: z4.string().optional(),
1779
- logicalPath: z4.string().optional()
1780
- });
1781
- var CreateFileUploadBodySchema = z4.object({
1782
- fileName: z4.string().optional(),
1783
- mediaType: z4.string().optional(),
1784
- sizeBytes: z4.number().int().nonnegative().optional(),
1785
- digest: BlobDigestSchema.optional(),
1786
- logicalPath: z4.string().optional()
1787
- });
1788
- var FileUploadIdParamsSchema = z4.object({
1789
- uploadId: z4.string().min(1)
1790
- });
1791
- var FileUploadPartParamsSchema = FileUploadIdParamsSchema.extend({
1792
- partNumber: z4.string().regex(/^\d+$/)
1793
- });
1794
- var ServerFileUploadSchema = z4.object({
1795
- strategy: z4.literal("server"),
1796
- uploadId: z4.string(),
1797
- method: z4.literal("PUT"),
1798
- url: z4.string(),
1799
- expiresAt: z4.string()
1800
- });
1801
- var DirectPutFileUploadSchema = z4.object({
1802
- strategy: z4.literal("direct-put"),
1803
- uploadId: z4.string(),
1804
- method: z4.literal("PUT"),
1805
- url: z4.string(),
1806
- headers: z4.record(z4.string()),
1807
- expiresAt: z4.string()
1808
- });
1809
- var MultipartFileUploadSchema = z4.object({
1810
- strategy: z4.literal("multipart"),
1811
- partReceipt: z4.enum(["etag", "none"]),
1812
- uploadId: z4.string(),
1813
- partSizeBytes: z4.number().int().positive(),
1814
- expiresAt: z4.string()
1815
- });
1816
- var CreateFileUploadResponseSchema = z4.discriminatedUnion("strategy", [
1817
- ServerFileUploadSchema,
1818
- DirectPutFileUploadSchema,
1819
- MultipartFileUploadSchema
1820
- ]);
1821
- var SignedFileUploadPartSchema = z4.object({
1822
- partNumber: z4.number().int().positive(),
1823
- method: z4.literal("PUT"),
1824
- url: z4.string(),
1825
- headers: z4.record(z4.string()),
1826
- expiresAt: z4.string()
1827
- });
1828
- var FileUploadPartSchema = z4.object({
1829
- partNumber: z4.number().int().positive(),
1830
- etag: z4.string().min(1).optional()
1831
- });
1832
- var CompleteFileUploadBodySchema = z4.object({
1833
- sizeBytes: z4.number().int().nonnegative().optional(),
1834
- digest: BlobDigestSchema.optional(),
1835
- parts: z4.array(FileUploadPartSchema).optional()
1836
- });
1837
- var FileContentQuerySchema = z4.object({
1838
- audience: z4.enum(["atlas", "app"]).optional().describe("Session audience for file navigation without Origin; must match Origin when present"),
1839
- path: z4.string().min(1),
1840
- disposition: z4.enum(["inline", "attachment"]).optional(),
1841
- v: z4.string().optional().describe("Client cache key; the route still resolves the current file")
1441
+ runs: z3.array(ActionRunSummarySchema),
1442
+ hasMore: z3.boolean(),
1443
+ total: z3.number()
1842
1444
  });
1843
1445
 
1844
1446
  // src/utils/http.ts
@@ -1854,6 +1456,8 @@ import {
1854
1456
  } from "@sixb/core/storage";
1855
1457
 
1856
1458
  // src/utils/request-body.ts
1459
+ var DEFAULT_REQUEST_BODY_LIMIT_BYTES = 1024 * 1024;
1460
+
1857
1461
  class RequestBodyTooLargeError extends Error {
1858
1462
  limitBytes;
1859
1463
  name = "RequestBodyTooLargeError";
@@ -1862,195 +1466,583 @@ class RequestBodyTooLargeError extends Error {
1862
1466
  this.limitBytes = limitBytes;
1863
1467
  }
1864
1468
  }
1865
- async function readRequestBodyWithLimit(request, limitBytes, tooLargeMessage) {
1866
- const contentLength = request.headers.get("content-length");
1867
- if (contentLength !== null) {
1868
- const declared = Number(contentLength);
1869
- if (Number.isSafeInteger(declared) && declared > limitBytes) {
1870
- throw new RequestBodyTooLargeError(limitBytes, tooLargeMessage);
1871
- }
1469
+ var requestBodyCaps = new WeakMap;
1470
+ function limitRequestBody(request) {
1471
+ if (!request.body) {
1472
+ return request;
1473
+ }
1474
+ const cap = { lifted: false };
1475
+ let total = 0;
1476
+ const body = request.body.pipeThrough(new TransformStream({
1477
+ transform(chunk, controller) {
1478
+ total += chunk.byteLength;
1479
+ if (!cap.lifted && total > DEFAULT_REQUEST_BODY_LIMIT_BYTES) {
1480
+ controller.error(new RequestBodyTooLargeError(DEFAULT_REQUEST_BODY_LIMIT_BYTES));
1481
+ return;
1482
+ }
1483
+ controller.enqueue(chunk);
1484
+ }
1485
+ }));
1486
+ const limited = new Request(request, { body, duplex: "half" });
1487
+ requestBodyCaps.set(limited, cap);
1488
+ return limited;
1489
+ }
1490
+ async function readRequestBodyWithLimit(request, limitBytes, tooLargeMessage) {
1491
+ const cap = requestBodyCaps.get(request);
1492
+ if (cap) {
1493
+ cap.lifted = true;
1494
+ }
1495
+ const contentLength = request.headers.get("content-length");
1496
+ if (contentLength !== null) {
1497
+ const declared = Number(contentLength);
1498
+ if (Number.isSafeInteger(declared) && declared > limitBytes) {
1499
+ throw new RequestBodyTooLargeError(limitBytes, tooLargeMessage);
1500
+ }
1501
+ }
1502
+ if (!request.body) {
1503
+ return new Uint8Array(0);
1504
+ }
1505
+ const reader = request.body.getReader();
1506
+ const chunks = [];
1507
+ let total = 0;
1508
+ while (true) {
1509
+ const { done, value } = await reader.read();
1510
+ if (done) {
1511
+ break;
1512
+ }
1513
+ total += value.byteLength;
1514
+ if (total > limitBytes) {
1515
+ await reader.cancel();
1516
+ throw new RequestBodyTooLargeError(limitBytes, tooLargeMessage);
1517
+ }
1518
+ chunks.push(value);
1519
+ }
1520
+ const result = new Uint8Array(total);
1521
+ let offset = 0;
1522
+ for (const chunk of chunks) {
1523
+ result.set(chunk, offset);
1524
+ offset += chunk.byteLength;
1525
+ }
1526
+ return result;
1527
+ }
1528
+
1529
+ // src/utils/http.ts
1530
+ var HTTP_STATUS_BY_ERROR_CODE = {
1531
+ "action.run_in_progress": 409,
1532
+ "connector.adapter_invalid": 502,
1533
+ "connector.authorization_invalid": 400,
1534
+ "connector.authorization_required": 409,
1535
+ "connector.configuration_invalid": 400,
1536
+ "connector.credentials_unavailable": 503,
1537
+ "connector.not_found": 404,
1538
+ "connector.operation_conflict": 409,
1539
+ "connector.operation_in_progress": 409,
1540
+ "connector.provider_failed": 502,
1541
+ "connector.provider_unavailable": 503,
1542
+ "connector.replacement_required": 409,
1543
+ "connector.revocation_pending": 409,
1544
+ "dataset.not_found": 404,
1545
+ "dataset.version_not_found": 404,
1546
+ "runtime.stopping": 503,
1547
+ "ai.usage_limit_exceeded": 429,
1548
+ "ai.usage_limit_unavailable": 429
1549
+ };
1550
+ function toIsoString(value) {
1551
+ return value.toISOString();
1552
+ }
1553
+ function parseDate(value) {
1554
+ if (!value) {
1555
+ return;
1556
+ }
1557
+ const parsed = new Date(value);
1558
+ if (Number.isNaN(parsed.getTime())) {
1559
+ throw new Error(`Invalid date: ${value}`);
1560
+ }
1561
+ return parsed;
1562
+ }
1563
+ function parseOptionalInt(value) {
1564
+ if (value === undefined) {
1565
+ return;
1566
+ }
1567
+ const parsed = Number.parseInt(value, 10);
1568
+ if (!Number.isFinite(parsed)) {
1569
+ throw new Error(`Invalid integer: ${value}`);
1570
+ }
1571
+ return parsed;
1572
+ }
1573
+ function unconfiguredStorageResponse(set, role) {
1574
+ set.status = 501;
1575
+ return { error: `[SixbServer] ${role} is not configured on this runtime.` };
1576
+ }
1577
+ function handleRouteError(error, set) {
1578
+ if (isSixbError(error)) {
1579
+ set.status = HTTP_STATUS_BY_ERROR_CODE[error.code] ?? 500;
1580
+ if (error.code === "ai.usage_limit_exceeded")
1581
+ setRetryAfterFromDetails(set, error.details);
1582
+ const exposesDetails = error.code === "ai.usage_limit_exceeded" || error.code === "ai.usage_limit_unavailable";
1583
+ return {
1584
+ error: error.message,
1585
+ code: error.code,
1586
+ ...!exposesDetails || error.details === undefined ? {} : { details: error.details }
1587
+ };
1588
+ }
1589
+ if (error instanceof AuthorizationError) {
1590
+ set.status = 403;
1591
+ return { error: error.message };
1592
+ }
1593
+ if (error instanceof FileUploadSessionError) {
1594
+ set.status = fileUploadSessionErrorStatus(error.reason);
1595
+ return { error: error.message };
1596
+ }
1597
+ if (error instanceof RequestBodyTooLargeError) {
1598
+ set.status = 413;
1599
+ return { error: error.message };
1600
+ }
1601
+ if (error instanceof OntologyNotFoundError || error instanceof ObjectNotFoundError) {
1602
+ set.status = 404;
1603
+ return { error: error.message };
1604
+ }
1605
+ if (error instanceof OntologyValidationError) {
1606
+ set.status = 400;
1607
+ return { error: error.message };
1608
+ }
1609
+ const message = error instanceof Error ? error.message : String(error);
1610
+ set.status = 400;
1611
+ return { error: message };
1612
+ }
1613
+ function setRetryAfterFromDetails(set, details) {
1614
+ if (typeof details !== "object" || details === null || Array.isArray(details))
1615
+ return;
1616
+ const resetAt = details.resetAt;
1617
+ if (typeof resetAt !== "string")
1618
+ return;
1619
+ const resetTime = Date.parse(resetAt);
1620
+ if (!Number.isFinite(resetTime))
1621
+ return;
1622
+ const seconds = String(Math.max(0, Math.ceil((resetTime - Date.now()) / 1000)));
1623
+ const headers = typeof set.headers === "object" && set.headers !== null ? set.headers : {};
1624
+ headers["Retry-After"] = seconds;
1625
+ set.headers = headers;
1626
+ }
1627
+ function fileUploadSessionErrorStatus(reason) {
1628
+ switch (reason) {
1629
+ case "not_found":
1630
+ return 404;
1631
+ case "expired":
1632
+ return 410;
1633
+ case "already_completed":
1634
+ case "already_aborted":
1635
+ return 409;
1636
+ }
1637
+ }
1638
+
1639
+ // src/actions/serialize.ts
1640
+ function serializeActionRunSummary(run) {
1641
+ return ActionRunSummarySchema.parse({
1642
+ id: run.id,
1643
+ projectId: run.projectId,
1644
+ actionId: run.actionId,
1645
+ subject: run.subject,
1646
+ status: run.status,
1647
+ phase: run.phase,
1648
+ startedAt: toIsoString(run.startedAt),
1649
+ finishedAt: toIsoString(run.finishedAt),
1650
+ error: run.error
1651
+ });
1652
+ }
1653
+ function serializeActionRunDetail(run) {
1654
+ return ActionRunDetailSchema.parse({
1655
+ ...serializeActionRunSummary(run),
1656
+ params: run.params,
1657
+ writeback: run.writeback ? run.writeback.status === "succeeded" ? {
1658
+ status: "succeeded",
1659
+ completedAt: toIsoString(run.writeback.completedAt),
1660
+ result: run.writeback.result
1661
+ } : {
1662
+ status: "failed",
1663
+ completedAt: toIsoString(run.writeback.completedAt),
1664
+ error: run.writeback.error
1665
+ } : undefined,
1666
+ effects: run.effects ? run.effects.status === "succeeded" ? {
1667
+ status: "succeeded",
1668
+ completedAt: toIsoString(run.effects.completedAt)
1669
+ } : {
1670
+ status: "failed",
1671
+ completedAt: toIsoString(run.effects.completedAt),
1672
+ error: run.effects.error
1673
+ } : undefined
1674
+ });
1675
+ }
1676
+
1677
+ // src/files/content.ts
1678
+ import { createHash as createHash2 } from "crypto";
1679
+ import { fileNameFor } from "@sixb/core";
1680
+ import { BlobStorageError, supportsRangeRead } from "@sixb/core/blob-storage/server";
1681
+ import {
1682
+ canonicalMediaType,
1683
+ resolveFileRefAtPath,
1684
+ statFileRef
1685
+ } from "@sixb/core/internal/blob-storage";
1686
+ import { ZodError } from "zod";
1687
+ var unconfiguredStorageResponse2 = {
1688
+ 501: {
1689
+ description: "The storage role backing this content is not configured",
1690
+ content: {
1691
+ "application/json": {
1692
+ schema: { $ref: "#/components/schemas/ErrorResponse" }
1693
+ }
1694
+ }
1695
+ }
1696
+ };
1697
+ function handleFileContentQueryValidationError(context) {
1698
+ if (context.code !== "VALIDATION" || context.error.type !== "query")
1699
+ return;
1700
+ context.set.status = 400;
1701
+ return { error: "Invalid file content query" };
1702
+ }
1703
+ function fileContentGetResponses(options = {}) {
1704
+ return {
1705
+ 200: {
1706
+ description: "File content",
1707
+ content: {
1708
+ "application/octet-stream": {
1709
+ schema: { type: "string", format: "binary" }
1710
+ }
1711
+ }
1712
+ },
1713
+ 206: {
1714
+ description: "Partial file content",
1715
+ content: {
1716
+ "application/octet-stream": {
1717
+ schema: { type: "string", format: "binary" }
1718
+ }
1719
+ }
1720
+ },
1721
+ 304: {
1722
+ description: "File representation is unchanged; reuse the privately cached content"
1723
+ },
1724
+ 400: {
1725
+ description: "Response for status 400",
1726
+ content: {
1727
+ "application/json": {
1728
+ schema: { $ref: "#/components/schemas/ErrorResponse" }
1729
+ }
1730
+ }
1731
+ },
1732
+ 404: {
1733
+ description: "Response for status 404",
1734
+ content: {
1735
+ "application/json": {
1736
+ schema: { $ref: "#/components/schemas/ErrorResponse" }
1737
+ }
1738
+ }
1739
+ },
1740
+ 416: {
1741
+ description: "Requested byte range is not satisfiable"
1742
+ },
1743
+ ...options.optionalStorage ? unconfiguredStorageResponse2 : {}
1744
+ };
1745
+ }
1746
+ function fileContentHeadResponses(options = {}) {
1747
+ return {
1748
+ 200: {
1749
+ description: "File content headers"
1750
+ },
1751
+ 206: {
1752
+ description: "Partial file content headers"
1753
+ },
1754
+ 304: {
1755
+ description: "File representation is unchanged; reuse the privately cached content"
1756
+ },
1757
+ 400: {
1758
+ description: "Response for status 400",
1759
+ content: {
1760
+ "application/json": {
1761
+ schema: { $ref: "#/components/schemas/ErrorResponse" }
1762
+ }
1763
+ }
1764
+ },
1765
+ 404: {
1766
+ description: "Response for status 404",
1767
+ content: {
1768
+ "application/json": {
1769
+ schema: { $ref: "#/components/schemas/ErrorResponse" }
1770
+ }
1771
+ }
1772
+ },
1773
+ 416: {
1774
+ description: "Requested byte range is not satisfiable"
1775
+ },
1776
+ ...options.optionalStorage ? unconfiguredStorageResponse2 : {}
1777
+ };
1778
+ }
1779
+ async function createFileContentResponse(input) {
1780
+ const stat = await statFileRef(input.blobStorage, input.fileRef);
1781
+ if (!stat) {
1782
+ return null;
1872
1783
  }
1873
- if (!request.body) {
1874
- return new Uint8Array(0);
1784
+ const canReadRange = supportsRangeRead(input.blobStorage);
1785
+ const headers = fileContentHeaders(input.fileRef, stat, input.disposition, canReadRange);
1786
+ const etag = headers.get("etag");
1787
+ if (matchesIfNoneMatch(input.ifNoneMatchHeader, etag)) {
1788
+ headers.delete("content-length");
1789
+ return new Response(null, { status: 304, headers });
1875
1790
  }
1876
- const reader = request.body.getReader();
1877
- const chunks = [];
1878
- let total = 0;
1879
- while (true) {
1880
- const { done, value } = await reader.read();
1881
- if (done) {
1882
- break;
1791
+ if (canReadRange && input.rangeHeader && (input.ifRangeHeader == null || input.ifRangeHeader.trim() === etag)) {
1792
+ const range = parseSingleByteRange(input.rangeHeader, stat.sizeBytes);
1793
+ if (!range) {
1794
+ return rangeNotSatisfiableResponse(stat.sizeBytes);
1883
1795
  }
1884
- total += value.byteLength;
1885
- if (total > limitBytes) {
1886
- await reader.cancel();
1887
- throw new RequestBodyTooLargeError(limitBytes, tooLargeMessage);
1796
+ const partialHeaders = partialFileContentHeaders(headers, range, stat.sizeBytes);
1797
+ if (input.head) {
1798
+ return new Response(null, { status: 206, headers: partialHeaders });
1799
+ }
1800
+ try {
1801
+ const stream = await input.blobStorage.openRange(input.fileRef.blobId, range);
1802
+ return new Response(stream, { status: 206, headers: partialHeaders });
1803
+ } catch (error) {
1804
+ if (error instanceof BlobStorageError) {
1805
+ return null;
1806
+ }
1807
+ throw error;
1888
1808
  }
1889
- chunks.push(value);
1890
- }
1891
- const result = new Uint8Array(total);
1892
- let offset = 0;
1893
- for (const chunk of chunks) {
1894
- result.set(chunk, offset);
1895
- offset += chunk.byteLength;
1896
1809
  }
1897
- return result;
1898
- }
1899
-
1900
- // src/utils/http.ts
1901
- var HTTP_STATUS_BY_ERROR_CODE = {
1902
- "connector.adapter_invalid": 502,
1903
- "connector.authorization_invalid": 400,
1904
- "connector.authorization_required": 409,
1905
- "connector.configuration_invalid": 400,
1906
- "connector.credentials_unavailable": 503,
1907
- "connector.not_found": 404,
1908
- "connector.operation_conflict": 409,
1909
- "connector.operation_in_progress": 409,
1910
- "connector.provider_failed": 502,
1911
- "connector.provider_unavailable": 503,
1912
- "connector.replacement_required": 409,
1913
- "connector.revocation_pending": 409,
1914
- "dataset.not_found": 404,
1915
- "dataset.version_not_found": 404,
1916
- "ai.usage_limit_exceeded": 429,
1917
- "ai.usage_limit_unavailable": 429
1918
- };
1919
- function toIsoString(value) {
1920
- return value.toISOString();
1921
- }
1922
- function parseDate(value) {
1923
- if (!value) {
1924
- return;
1810
+ if (input.head) {
1811
+ return new Response(null, { headers });
1925
1812
  }
1926
- const parsed = new Date(value);
1927
- if (Number.isNaN(parsed.getTime())) {
1928
- throw new Error(`Invalid date: ${value}`);
1813
+ try {
1814
+ const stream = await input.blobStorage.open(input.fileRef.blobId);
1815
+ return new Response(stream, { headers });
1816
+ } catch (error) {
1817
+ if (error instanceof BlobStorageError) {
1818
+ return null;
1819
+ }
1820
+ throw error;
1929
1821
  }
1930
- return parsed;
1931
1822
  }
1932
- function parseOptionalInt(value) {
1933
- if (value === undefined) {
1934
- return;
1935
- }
1936
- const parsed = Number.parseInt(value, 10);
1937
- if (!Number.isFinite(parsed)) {
1938
- throw new Error(`Invalid integer: ${value}`);
1823
+ async function createContextualFileContentResponse(input) {
1824
+ const missingMessage = input.missingMessage ?? "File not found";
1825
+ const invalidQueryMessage = input.invalidQueryMessage ?? "Invalid file content query";
1826
+ try {
1827
+ const parsed = input.querySchema.parse(input.query);
1828
+ const root = await input.resolveRoot(parsed);
1829
+ if (root === null || root === undefined) {
1830
+ return fileContentNotFound(input.set, missingMessage);
1831
+ }
1832
+ const fileRef = resolveFileRefAtPath(root, parsed.path);
1833
+ if (!fileRef) {
1834
+ return fileContentNotFound(input.set, missingMessage);
1835
+ }
1836
+ const response = await createFileContentResponse({
1837
+ blobStorage: input.blobStorage,
1838
+ fileRef,
1839
+ disposition: parsed.disposition,
1840
+ head: input.head,
1841
+ rangeHeader: input.request.headers.get("range"),
1842
+ ifNoneMatchHeader: input.request.headers.get("if-none-match"),
1843
+ ifRangeHeader: input.request.headers.get("if-range")
1844
+ });
1845
+ if (!response) {
1846
+ return fileContentNotFound(input.set, missingMessage);
1847
+ }
1848
+ return response;
1849
+ } catch (error) {
1850
+ if (error instanceof ZodError) {
1851
+ input.set.status = 400;
1852
+ return { error: invalidQueryMessage };
1853
+ }
1854
+ if (input.hideError?.(error)) {
1855
+ return fileContentNotFound(input.set, missingMessage);
1856
+ }
1857
+ throw error;
1939
1858
  }
1940
- return parsed;
1941
1859
  }
1942
- function unconfiguredStorageResponse2(set, role) {
1943
- set.status = 501;
1944
- return { error: `[SixbServer] ${role} is not configured on this runtime.` };
1860
+ function fileContentNotFound(set, message) {
1861
+ set.status = 404;
1862
+ return { error: message };
1945
1863
  }
1946
- function handleRouteError(error, set) {
1947
- if (isSixbError(error)) {
1948
- set.status = HTTP_STATUS_BY_ERROR_CODE[error.code] ?? 500;
1949
- if (error.code === "ai.usage_limit_exceeded")
1950
- setRetryAfterFromDetails(set, error.details);
1951
- const exposesDetails = error.code === "ai.usage_limit_exceeded" || error.code === "ai.usage_limit_unavailable";
1952
- return {
1953
- error: error.message,
1954
- code: error.code,
1955
- ...!exposesDetails || error.details === undefined ? {} : { details: error.details }
1956
- };
1864
+ function matchesIfNoneMatch(header, etag) {
1865
+ return header?.trim() === "*" || (header?.split(",").some((value) => value.trim().replace(/^W\//, "") === etag) ?? false);
1866
+ }
1867
+ var INLINE_MEDIA_TYPES = new Set([
1868
+ "application/json",
1869
+ "application/pdf",
1870
+ "image/avif",
1871
+ "image/bmp",
1872
+ "image/gif",
1873
+ "image/jpeg",
1874
+ "image/png",
1875
+ "image/webp",
1876
+ "text/markdown",
1877
+ "text/plain"
1878
+ ]);
1879
+ var FILE_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
1880
+ var PDF_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; object-src 'self'";
1881
+ function fileContentHeaders(fileRef, stat, requestedDisposition, canReadRange) {
1882
+ const mediaType = canonicalMediaType(fileRef.mediaType) ?? "application/octet-stream";
1883
+ const baseType = mediaType.split(";", 1)[0];
1884
+ const disposition = (requestedDisposition ?? "inline") === "inline" && INLINE_MEDIA_TYPES.has(baseType) ? "inline" : "attachment";
1885
+ const headers = new Headers;
1886
+ headers.set("content-type", mediaType);
1887
+ headers.set("content-length", stat.sizeBytes.toString());
1888
+ headers.set("content-disposition", contentDispositionHeader(disposition, fileNameFor(fileRef)));
1889
+ headers.set("content-security-policy", baseType === "application/pdf" ? PDF_CONTENT_SECURITY_POLICY : FILE_CONTENT_SECURITY_POLICY);
1890
+ const representation = JSON.stringify([
1891
+ fileRef.digest,
1892
+ mediaType,
1893
+ headers.get("content-disposition")
1894
+ ]);
1895
+ headers.set("etag", `"sha256:${createHash2("sha256").update(representation).digest("hex")}"`);
1896
+ headers.set("x-content-type-options", "nosniff");
1897
+ headers.set("cache-control", "private, no-cache");
1898
+ if (canReadRange) {
1899
+ headers.set("accept-ranges", "bytes");
1957
1900
  }
1958
- if (error instanceof AuthorizationError) {
1959
- set.status = 403;
1960
- return { error: error.message };
1901
+ return headers;
1902
+ }
1903
+ function parseSingleByteRange(header, sizeBytes) {
1904
+ const normalized = header.trim();
1905
+ if (!normalized.startsWith("bytes=") || normalized.includes(",")) {
1906
+ return null;
1961
1907
  }
1962
- if (error instanceof FileUploadSessionError) {
1963
- set.status = fileUploadSessionErrorStatus(error.reason);
1964
- return { error: error.message };
1908
+ if (sizeBytes <= 0) {
1909
+ return null;
1965
1910
  }
1966
- if (error instanceof RequestBodyTooLargeError) {
1967
- set.status = 413;
1968
- return { error: error.message };
1911
+ const spec = normalized.slice("bytes=".length).trim();
1912
+ const match = spec.match(/^(\d*)-(\d*)$/);
1913
+ if (!match) {
1914
+ return null;
1969
1915
  }
1970
- if (error instanceof OntologyNotFoundError || error instanceof ObjectNotFoundError) {
1971
- set.status = 404;
1972
- return { error: error.message };
1916
+ const [, rawStart, rawEnd] = match;
1917
+ if (!rawStart && !rawEnd) {
1918
+ return null;
1973
1919
  }
1974
- if (error instanceof OntologyValidationError) {
1975
- set.status = 400;
1976
- return { error: error.message };
1920
+ if (!rawStart) {
1921
+ const suffixLength = Number(rawEnd);
1922
+ if (!Number.isSafeInteger(suffixLength) || suffixLength <= 0) {
1923
+ return null;
1924
+ }
1925
+ return {
1926
+ start: Math.max(sizeBytes - suffixLength, 0),
1927
+ endInclusive: sizeBytes - 1
1928
+ };
1977
1929
  }
1978
- const message = error instanceof Error ? error.message : String(error);
1979
- set.status = 400;
1980
- return { error: message };
1930
+ const start = Number(rawStart);
1931
+ if (!Number.isSafeInteger(start) || start >= sizeBytes) {
1932
+ return null;
1933
+ }
1934
+ const requestedEnd = rawEnd ? Number(rawEnd) : sizeBytes - 1;
1935
+ if (!Number.isSafeInteger(requestedEnd) || requestedEnd < start) {
1936
+ return null;
1937
+ }
1938
+ return {
1939
+ start,
1940
+ endInclusive: Math.min(requestedEnd, sizeBytes - 1)
1941
+ };
1942
+ }
1943
+ function partialFileContentHeaders(baseHeaders, range, sizeBytes) {
1944
+ const headers = new Headers(baseHeaders);
1945
+ headers.set("content-length", (range.endInclusive - range.start + 1).toString());
1946
+ headers.set("content-range", `bytes ${range.start}-${range.endInclusive}/${sizeBytes}`);
1947
+ return headers;
1981
1948
  }
1982
- function setRetryAfterFromDetails(set, details) {
1983
- if (typeof details !== "object" || details === null || Array.isArray(details))
1984
- return;
1985
- const resetAt = details.resetAt;
1986
- if (typeof resetAt !== "string")
1987
- return;
1988
- const resetTime = Date.parse(resetAt);
1989
- if (!Number.isFinite(resetTime))
1990
- return;
1991
- const seconds = String(Math.max(0, Math.ceil((resetTime - Date.now()) / 1000)));
1992
- const headers = typeof set.headers === "object" && set.headers !== null ? set.headers : {};
1993
- headers["Retry-After"] = seconds;
1994
- set.headers = headers;
1949
+ function rangeNotSatisfiableResponse(sizeBytes) {
1950
+ const headers = new Headers;
1951
+ headers.set("accept-ranges", "bytes");
1952
+ headers.set("content-range", `bytes */${sizeBytes}`);
1953
+ return new Response(null, { status: 416, headers });
1995
1954
  }
1996
- function fileUploadSessionErrorStatus(reason) {
1997
- switch (reason) {
1998
- case "not_found":
1999
- return 404;
2000
- case "expired":
2001
- return 410;
2002
- case "already_completed":
2003
- case "already_aborted":
2004
- return 409;
2005
- }
1955
+ function contentDispositionHeader(disposition, fileName) {
1956
+ const asciiFileName = fileName.replace(/[^\x20-\x7e]/g, "_").replaceAll('"', "'");
1957
+ return `${disposition}; filename="${asciiFileName}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
2006
1958
  }
2007
1959
 
1960
+ // src/schemas/files.ts
1961
+ import { canonicalMediaType as canonicalMediaType2 } from "@sixb/core/internal/blob-storage";
1962
+ import { z as z4 } from "zod";
1963
+ var BlobDigestSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
1964
+ var FileRefSchema = z4.object({
1965
+ blobId: z4.string(),
1966
+ digest: BlobDigestSchema,
1967
+ sizeBytes: z4.number().int().nonnegative(),
1968
+ fileName: z4.string().optional(),
1969
+ mediaType: z4.string().optional(),
1970
+ logicalPath: z4.string().optional()
1971
+ });
1972
+ var CreateFileUploadBodySchema = z4.object({
1973
+ fileName: z4.string().optional(),
1974
+ mediaType: z4.string().refine((value) => canonicalMediaType2(value) !== null, {
1975
+ message: 'Expected a single media type, such as "application/pdf"'
1976
+ }).optional(),
1977
+ sizeBytes: z4.number().int().nonnegative().optional(),
1978
+ digest: BlobDigestSchema.optional(),
1979
+ logicalPath: z4.string().optional()
1980
+ });
1981
+ var FileUploadIdParamsSchema = z4.object({
1982
+ uploadId: z4.string().min(1)
1983
+ });
1984
+ var FileUploadPartParamsSchema = FileUploadIdParamsSchema.extend({
1985
+ partNumber: z4.string().regex(/^\d+$/)
1986
+ });
1987
+ var ServerFileUploadSchema = z4.object({
1988
+ strategy: z4.literal("server"),
1989
+ uploadId: z4.string(),
1990
+ method: z4.literal("PUT"),
1991
+ url: z4.string(),
1992
+ expiresAt: z4.string()
1993
+ });
1994
+ var DirectPutFileUploadSchema = z4.object({
1995
+ strategy: z4.literal("direct-put"),
1996
+ uploadId: z4.string(),
1997
+ method: z4.literal("PUT"),
1998
+ url: z4.string(),
1999
+ headers: z4.record(z4.string()),
2000
+ expiresAt: z4.string()
2001
+ });
2002
+ var MultipartFileUploadSchema = z4.object({
2003
+ strategy: z4.literal("multipart"),
2004
+ partReceipt: z4.enum(["etag", "none"]),
2005
+ uploadId: z4.string(),
2006
+ partSizeBytes: z4.number().int().positive(),
2007
+ expiresAt: z4.string()
2008
+ });
2009
+ var CreateFileUploadResponseSchema = z4.discriminatedUnion("strategy", [
2010
+ ServerFileUploadSchema,
2011
+ DirectPutFileUploadSchema,
2012
+ MultipartFileUploadSchema
2013
+ ]);
2014
+ var SignedFileUploadPartSchema = z4.object({
2015
+ partNumber: z4.number().int().positive(),
2016
+ method: z4.literal("PUT"),
2017
+ url: z4.string(),
2018
+ headers: z4.record(z4.string()),
2019
+ expiresAt: z4.string()
2020
+ });
2021
+ var FileUploadPartSchema = z4.object({
2022
+ partNumber: z4.number().int().positive(),
2023
+ etag: z4.string().min(1).optional()
2024
+ });
2025
+ var CompleteFileUploadBodySchema = z4.object({
2026
+ sizeBytes: z4.number().int().nonnegative().optional(),
2027
+ digest: BlobDigestSchema.optional(),
2028
+ parts: z4.array(FileUploadPartSchema).optional()
2029
+ });
2030
+ var FileContentQuerySchema = z4.object({
2031
+ audience: z4.enum(["atlas", "app"]).optional().describe("Session audience for file navigation without Origin; must match Origin when present"),
2032
+ path: z4.string().min(1),
2033
+ disposition: z4.enum(["inline", "attachment"]).optional(),
2034
+ v: z4.string().optional().describe("Client cache key; the route still resolves the current file")
2035
+ });
2036
+
2008
2037
  // src/routes/action-runs.ts
2009
2038
  var ActionRunFileContentQuerySchema = FileContentQuerySchema.extend({
2010
2039
  path: z5.string().min(1).regex(/^\/(?:params|writeback\/result)(?:\/|$)/, "Action run file content paths must start with /params/ or /writeback/result/")
2011
2040
  });
2012
- function serializeActionRunSummary(run) {
2013
- return ActionRunSummarySchema.parse({
2014
- id: run.id,
2015
- projectId: run.projectId,
2016
- actionId: run.actionId,
2017
- subject: run.subject,
2018
- status: run.status,
2019
- phase: run.phase,
2020
- queuedAt: toIsoString(run.queuedAt),
2021
- startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
2022
- finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
2023
- error: run.error
2024
- });
2025
- }
2026
- function serializeActionRunDetail(run) {
2027
- return ActionRunDetailSchema.parse({
2028
- ...serializeActionRunSummary(run),
2029
- params: run.params,
2030
- writeback: run.writeback ? run.writeback.status === "succeeded" ? {
2031
- status: "succeeded",
2032
- completedAt: toIsoString(run.writeback.completedAt),
2033
- result: run.writeback.result
2034
- } : {
2035
- status: "failed",
2036
- completedAt: toIsoString(run.writeback.completedAt),
2037
- error: run.writeback.error
2038
- } : undefined,
2039
- effects: run.effects ? run.effects.status === "succeeded" ? {
2040
- status: "succeeded",
2041
- completedAt: toIsoString(run.effects.completedAt)
2042
- } : {
2043
- status: "failed",
2044
- completedAt: toIsoString(run.effects.completedAt),
2045
- error: run.effects.error
2046
- } : undefined
2047
- });
2048
- }
2049
2041
  async function actionRunFileContentResponse(host, context, options = {}) {
2050
2042
  const sixb = requireRequestSixb(context);
2051
2043
  const storage = host.storage.actionRuns;
2052
2044
  if (!storage) {
2053
- return unconfiguredStorageResponse2(context.set, "Action run storage");
2045
+ return unconfiguredStorageResponse(context.set, "Action run storage");
2054
2046
  }
2055
2047
  return createContextualFileContentResponse({
2056
2048
  blobStorage: host.blobStorage,
@@ -2072,7 +2064,7 @@ function registerActionRunRoutes(app, host) {
2072
2064
  try {
2073
2065
  const storage = host.storage.actionRuns;
2074
2066
  if (!storage) {
2075
- return unconfiguredStorageResponse2(set, "Action run storage");
2067
+ return unconfiguredStorageResponse(set, "Action run storage");
2076
2068
  }
2077
2069
  const parsed = ActionRunsQuerySchema.parse(query);
2078
2070
  const limit = parseOptionalInt(parsed.limit);
@@ -2115,7 +2107,7 @@ function registerActionRunRoutes(app, host) {
2115
2107
  try {
2116
2108
  const storage = host.storage.actionRuns;
2117
2109
  if (!storage) {
2118
- return unconfiguredStorageResponse2(set, "Action run storage");
2110
+ return unconfiguredStorageResponse(set, "Action run storage");
2119
2111
  }
2120
2112
  const run = await sixb.actions.runs.getById(params.runId);
2121
2113
  if (!run) {
@@ -2224,19 +2216,18 @@ function registerActionRoutes(app, host) {
2224
2216
  security: accessTokenSecurityRequirement("getAction")
2225
2217
  }
2226
2218
  }).post("/api/actions/:actionId", async (context) => {
2227
- const { params, body, set } = context;
2219
+ const { params, body, set, request, server } = context;
2220
+ server?.timeout(request, 0);
2228
2221
  const sixb = requireRequestSixb(context);
2229
2222
  try {
2230
2223
  const parsedBody = RequestActionBodySchema.parse(body);
2231
- const input = {
2224
+ const run = await sixb.actions.request({
2232
2225
  actionId: params.actionId,
2233
2226
  subject: parsedBody.subject,
2234
2227
  params: parsedBody.params,
2235
2228
  runId: parsedBody.runId
2236
- };
2237
- const result = await sixb.actions.request(input);
2238
- set.status = 202;
2239
- return RequestActionResponseSchema.parse(result);
2229
+ });
2230
+ return serializeActionRunDetail(run);
2240
2231
  } catch (error) {
2241
2232
  return handleRouteError(error, set);
2242
2233
  }
@@ -2244,13 +2235,17 @@ function registerActionRoutes(app, host) {
2244
2235
  params: ActionIdParamsSchema,
2245
2236
  body: RequestActionBodySchema,
2246
2237
  response: {
2247
- 202: RequestActionResponseSchema,
2238
+ 200: ActionRunDetailSchema,
2248
2239
  400: ErrorResponseSchema,
2249
2240
  403: ErrorResponseSchema,
2250
- 404: ErrorResponseSchema
2241
+ 404: ErrorResponseSchema,
2242
+ 409: ActionRunInProgressResponseSchema,
2243
+ 500: ActionRequestFailedResponseSchema,
2244
+ 503: RuntimeStoppingResponseSchema
2251
2245
  },
2252
2246
  detail: {
2253
2247
  summary: "Request an action",
2248
+ description: "Runs the action and returns its terminal run. A run that fails is returned with " + "status `failed`. Its effects run after the response, which does not wait for them. " + "An error response usually means no run was requested, but a 500 can follow a run " + "that started: request again with the same `runId` to get its record if it was " + "written. A `runId` that was already recorded returns that run, and 409 while this " + "server still runs it. 503 means the server is stopping and started nothing.",
2254
2249
  tags: [OPENAPI_TAGS.actions.name],
2255
2250
  operationId: "requestAction",
2256
2251
  security: accessTokenSecurityRequirement("requestAction")
@@ -2276,6 +2271,7 @@ import {
2276
2271
  SYSTEM_PRINCIPAL
2277
2272
  } from "@sixb/core";
2278
2273
  import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
2274
+ import { canonicalMediaType as canonicalMediaType3 } from "@sixb/core/internal/blob-storage";
2279
2275
  import { createFileUploadId, createUploadExpiresAt } from "@sixb/core/internal/storage";
2280
2276
  import { FileUploadSessionError as FileUploadSessionError2 } from "@sixb/core/storage";
2281
2277
  var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
@@ -2283,12 +2279,10 @@ function registerFileRoutes(app, host) {
2283
2279
  const uploadSessions = host.storage.fileUploadSessions;
2284
2280
  return app.post("/api/files", async ({ request, set }) => {
2285
2281
  try {
2286
- const requestSizeError = requestSizeLimitError(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES);
2287
- if (requestSizeError) {
2288
- set.status = 413;
2289
- return { error: requestSizeError };
2290
- }
2291
- const form = await request.formData();
2282
+ const bytes = await readRequestBodyWithLimit(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES, `File upload request exceeds the ${DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES} byte limit.`);
2283
+ const form = await new Response(bytes, {
2284
+ headers: { "content-type": request.headers.get("content-type") ?? "" }
2285
+ }).formData();
2292
2286
  const file = form.get("file");
2293
2287
  const logicalPath = form.get("logicalPath");
2294
2288
  if (!(file instanceof File)) {
@@ -2308,7 +2302,7 @@ function registerFileRoutes(app, host) {
2308
2302
  const fileRef = await host.blobStorage.put({
2309
2303
  body: file,
2310
2304
  fileName: file.name || undefined,
2311
- mediaType: file.type || undefined,
2305
+ mediaType: canonicalMediaType3(file.type) ?? undefined,
2312
2306
  logicalPath: logicalPath ?? undefined
2313
2307
  });
2314
2308
  return FileRefSchema.parse(fileRef);
@@ -2351,7 +2345,7 @@ function registerFileRoutes(app, host) {
2351
2345
  const { body, set } = context;
2352
2346
  try {
2353
2347
  if (!uploadSessions) {
2354
- return unconfiguredStorageResponse2(set, "File upload session storage");
2348
+ return unconfiguredStorageResponse(set, "File upload session storage");
2355
2349
  }
2356
2350
  const parsed = CreateFileUploadBodySchema.parse(body);
2357
2351
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
@@ -2402,7 +2396,7 @@ function registerFileRoutes(app, host) {
2402
2396
  const { params, request, set } = context;
2403
2397
  try {
2404
2398
  if (!uploadSessions) {
2405
- return unconfiguredStorageResponse2(set, "File upload session storage");
2399
+ return unconfiguredStorageResponse(set, "File upload session storage");
2406
2400
  }
2407
2401
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2408
2402
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
@@ -2418,7 +2412,7 @@ function registerFileRoutes(app, host) {
2418
2412
  set.status = 400;
2419
2413
  return { error: contentLengthSizeError };
2420
2414
  }
2421
- const uploadBytes = readParsedUploadBytes(context);
2415
+ const uploadBytes = await readRequestBodyWithLimit(request, DEFAULT_SIMPLE_FILE_UPLOAD_BYTES);
2422
2416
  if (uploadBytes.byteLength === 0) {
2423
2417
  set.status = 400;
2424
2418
  return { error: "Expected upload content body." };
@@ -2447,14 +2441,14 @@ function registerFileRoutes(app, host) {
2447
2441
  }
2448
2442
  }, {
2449
2443
  params: FileUploadIdParamsSchema,
2450
- parse: readCappedUploadBody,
2451
- error: mapUploadContentError,
2444
+ parse: "none",
2452
2445
  response: {
2453
2446
  200: SuccessResponseSchema,
2454
2447
  400: ErrorResponseSchema,
2455
2448
  404: ErrorResponseSchema,
2456
2449
  409: ErrorResponseSchema,
2457
2450
  410: ErrorResponseSchema,
2451
+ 413: ErrorResponseSchema,
2458
2452
  501: ErrorResponseSchema
2459
2453
  },
2460
2454
  detail: {
@@ -2478,7 +2472,7 @@ function registerFileRoutes(app, host) {
2478
2472
  const { params, set } = context;
2479
2473
  try {
2480
2474
  if (!uploadSessions) {
2481
- return unconfiguredStorageResponse2(set, "File upload session storage");
2475
+ return unconfiguredStorageResponse(set, "File upload session storage");
2482
2476
  }
2483
2477
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2484
2478
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
@@ -2528,7 +2522,7 @@ function registerFileRoutes(app, host) {
2528
2522
  const { body, params, set } = context;
2529
2523
  try {
2530
2524
  if (!uploadSessions) {
2531
- return unconfiguredStorageResponse2(set, "File upload session storage");
2525
+ return unconfiguredStorageResponse(set, "File upload session storage");
2532
2526
  }
2533
2527
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2534
2528
  const parsed = CompleteFileUploadBodySchema.parse(body ?? {});
@@ -2584,7 +2578,7 @@ function registerFileRoutes(app, host) {
2584
2578
  const { params, set } = context;
2585
2579
  try {
2586
2580
  if (!uploadSessions) {
2587
- return unconfiguredStorageResponse2(set, "File upload session storage");
2581
+ return unconfiguredStorageResponse(set, "File upload session storage");
2588
2582
  }
2589
2583
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2590
2584
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
@@ -2655,27 +2649,6 @@ function fileUploadResponse(session) {
2655
2649
  expiresAt: session.expiresAt.toISOString()
2656
2650
  };
2657
2651
  }
2658
- function readCappedUploadBody(context) {
2659
- return readRequestBodyWithLimit(context.request, DEFAULT_SIMPLE_FILE_UPLOAD_BYTES);
2660
- }
2661
- function readParsedUploadBytes(context) {
2662
- return context.body instanceof Uint8Array ? context.body : new Uint8Array(0);
2663
- }
2664
- function mapUploadContentError(context) {
2665
- const tooLarge = asRequestBodyTooLarge(context.error);
2666
- if (tooLarge) {
2667
- context.set.status = 413;
2668
- return { error: tooLarge.message };
2669
- }
2670
- return;
2671
- }
2672
- function asRequestBodyTooLarge(error) {
2673
- if (error instanceof RequestBodyTooLargeError) {
2674
- return error;
2675
- }
2676
- const cause = error?.cause;
2677
- return cause instanceof RequestBodyTooLargeError ? cause : undefined;
2678
- }
2679
2652
  function terminalSessionError(status) {
2680
2653
  return new FileUploadSessionError2(status === "completed" ? "already_completed" : "already_aborted", `File upload session is already ${status}.`);
2681
2654
  }
@@ -2734,17 +2707,6 @@ function expectedSizeBytesError(session, actualSizeBytes) {
2734
2707
  function expectedSizeBytesValueError(expectedSizeBytes, actualSizeBytes) {
2735
2708
  return expectedSizeBytes !== undefined && actualSizeBytes !== undefined && actualSizeBytes !== expectedSizeBytes ? `File upload size mismatch: expected ${expectedSizeBytes} bytes, received ${actualSizeBytes}.` : null;
2736
2709
  }
2737
- function requestSizeLimitError(request, maxSizeBytes) {
2738
- const value = request.headers.get("content-length");
2739
- if (value === null) {
2740
- return null;
2741
- }
2742
- const sizeBytes = Number(value);
2743
- if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= maxSizeBytes) {
2744
- return null;
2745
- }
2746
- return `File upload request exceeds the ${maxSizeBytes} byte limit.`;
2747
- }
2748
2710
  function expectedContentLengthError(session, request) {
2749
2711
  if (session.expectedSizeBytes === undefined) {
2750
2712
  return null;
@@ -2811,9 +2773,9 @@ async function handleAgentApiGatewayRequest(input) {
2811
2773
  }
2812
2774
  let body;
2813
2775
  try {
2814
- body = await readRequestBody(input.request, isSimpleFileUpload(input.request.method, upstreamPath) ? DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES : MAX_AGENT_API_BODY_BYTES);
2776
+ body = await readGatewayRequestBody(input.request, upstreamPath);
2815
2777
  } catch (error) {
2816
- if (error instanceof PayloadTooLargeError) {
2778
+ if (error instanceof RequestBodyTooLargeError) {
2817
2779
  return jsonError(413, error.message);
2818
2780
  }
2819
2781
  throw error;
@@ -2987,24 +2949,14 @@ function copyHeader(source, target, name) {
2987
2949
  target.set(name, value);
2988
2950
  }
2989
2951
  }
2990
- async function readRequestBody(request, maxBytes) {
2952
+ async function readGatewayRequestBody(request, upstreamPath) {
2991
2953
  if (!request.body || request.method === "GET" || request.method === "HEAD") {
2992
2954
  return;
2993
2955
  }
2994
- const reader = request.body.getReader();
2995
- const chunks = [];
2996
- let total = 0;
2997
- while (true) {
2998
- const { done, value } = await reader.read();
2999
- if (done)
3000
- break;
3001
- total += value.byteLength;
3002
- if (total > maxBytes) {
3003
- throw new PayloadTooLargeError(maxBytes === MAX_AGENT_API_BODY_BYTES ? "Agent API gateway request body exceeds 1MB." : `Agent API gateway file upload request body exceeds the ${maxBytes} byte limit.`);
3004
- }
3005
- chunks.push(value);
2956
+ if (isSimpleFileUpload(request.method, upstreamPath)) {
2957
+ return readRequestBodyWithLimit(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES, `Agent API gateway file upload request body exceeds the ${DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES} byte limit.`);
3006
2958
  }
3007
- return concatChunks(chunks, total);
2959
+ return readRequestBodyWithLimit(request, MAX_AGENT_API_BODY_BYTES, "Agent API gateway request body exceeds 1MB.");
3008
2960
  }
3009
2961
  function isSimpleFileUpload(method, pathname) {
3010
2962
  return method === "POST" && normalizeRoutePath4(pathname) === "/api/files";
@@ -3013,27 +2965,21 @@ function matchesWorkflowRunStart(pathname) {
3013
2965
  const segments = pathSegmentsFor(pathname);
3014
2966
  return segments.length === 4 && segments[0] === "api" && segments[1] === "workflows" && segments[3] === "runs";
3015
2967
  }
3016
- function concatChunks(chunks, total) {
3017
- const buffer = new ArrayBuffer(total);
3018
- const result = new Uint8Array(buffer);
3019
- let offset = 0;
3020
- for (const chunk of chunks) {
3021
- result.set(chunk, offset);
3022
- offset += chunk.byteLength;
3023
- }
3024
- return buffer;
3025
- }
3026
2968
  function jsonError(status, message) {
3027
2969
  return Response.json({ error: message }, { status });
3028
2970
  }
3029
2971
 
3030
- class PayloadTooLargeError extends Error {
3031
- }
3032
-
3033
2972
  // src/routes/agents.ts
3034
- import { AgentRequestError } from "@sixb/core";
3035
- import { publishAgentRunCancel, publishAgentRunFinished } from "@sixb/core/internal/agents";
2973
+ import {
2974
+ AgentRequestError
2975
+ } from "@sixb/core";
2976
+ import {
2977
+ isRetryableAgentRun,
2978
+ publishAgentRunCancel,
2979
+ publishAgentRunFinished
2980
+ } from "@sixb/core/internal/agents";
3036
2981
  import { agentRunStreamId } from "@sixb/core/internal/agents/streams";
2982
+ import { resolveFileRefAtPath as resolveFileRefAtPath2 } from "@sixb/core/internal/blob-storage";
3037
2983
  import {
3038
2984
  AgentStorageError
3039
2985
  } from "@sixb/core/storage";
@@ -3041,6 +2987,7 @@ import { ZodError as ZodError2, z as z10 } from "zod";
3041
2987
 
3042
2988
  // src/schemas/agents.ts
3043
2989
  import { MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core";
2990
+ import { MAX_AGENT_CONTEXT_LABEL_LENGTH } from "@sixb/core/agents/context";
3044
2991
  import {
3045
2992
  AGENT_RUN_DIAGNOSTIC_CODES,
3046
2993
  AGENT_RUN_FAILURE_CODES,
@@ -3092,7 +3039,8 @@ var LanguageModelSchema = LanguageModelRefSchema.extend({
3092
3039
  structuredOutput: z7.boolean().optional(),
3093
3040
  contextWindowTokens: z7.number().int().positive().optional()
3094
3041
  }),
3095
- reasoningLevels: z7.array(z7.enum(MODEL_REASONING_LEVELS))
3042
+ reasoningLevels: z7.array(z7.enum(MODEL_REASONING_LEVELS)),
3043
+ defaultReasoning: z7.enum(MODEL_REASONING_LEVELS).optional()
3096
3044
  });
3097
3045
  var ModelCatalogSchema = z7.object({
3098
3046
  language: z7.array(LanguageModelSchema)
@@ -3359,7 +3307,8 @@ var AgentObjectContextSchema = z9.object({
3359
3307
  ref: z9.object({
3360
3308
  objectTypeId: z9.string().min(1),
3361
3309
  primaryId: z9.string().min(1)
3362
- })
3310
+ }),
3311
+ label: z9.string().min(1).max(MAX_AGENT_CONTEXT_LABEL_LENGTH).optional().describe("Shown in the chat instead of the object's title. Never sent to the model.")
3363
3312
  });
3364
3313
  var AgentAppStateContextSchema = z9.object({
3365
3314
  kind: z9.literal("app-state"),
@@ -3463,8 +3412,12 @@ var AgentToolCallErrorSchema = AgentToolCallBaseSchema.extend({
3463
3412
  state: z9.literal("output-error"),
3464
3413
  errorText: z9.string()
3465
3414
  });
3415
+ var AgentContinuationPartSchema = z9.object({
3416
+ type: z9.literal("continuation")
3417
+ });
3466
3418
  var AgentMessagePartSchema = z9.union([
3467
3419
  AgentTextPartSchema,
3420
+ AgentContinuationPartSchema,
3468
3421
  AgentReasoningPartSchema,
3469
3422
  AgentStepStartPartSchema,
3470
3423
  AgentFilePartSchema,
@@ -3476,7 +3429,7 @@ var AgentMessagePartSchema = z9.union([
3476
3429
  var AgentRunDiagnosticSchema = z9.object({
3477
3430
  code: z9.enum(AGENT_RUN_DIAGNOSTIC_CODES),
3478
3431
  severity: z9.enum(["warning", "error"]),
3479
- scope: z9.literal("output"),
3432
+ scope: z9.enum(["output", "run"]),
3480
3433
  path: z9.string().optional(),
3481
3434
  message: z9.string()
3482
3435
  });
@@ -3513,13 +3466,19 @@ var AgentMessageListResponseSchema = z9.object({
3513
3466
  total: z9.number()
3514
3467
  });
3515
3468
  var PostAgentMessageBodySchema = z9.object({
3516
- text: z9.string().trim().min(1),
3469
+ text: z9.string().trim().min(1).optional(),
3470
+ continue: z9.literal(true).optional(),
3517
3471
  model: LanguageModelRefSchema.optional(),
3518
3472
  reasoning: ModelReasoningSchema.optional(),
3473
+ timeZone: z9.string().trim().min(1).max(100).optional(),
3474
+ locale: z9.string().trim().min(1).max(100).optional(),
3519
3475
  attachments: z9.array(FileRefSchema).optional(),
3520
3476
  context: z9.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
3521
3477
  messageId: z9.string().trim().min(1).optional()
3522
3478
  }).strict();
3479
+ var AgentRequestErrorResponseSchema = ErrorResponseSchema.extend({
3480
+ code: z9.string().optional()
3481
+ });
3523
3482
  var CancelAgentRunBodySchema = z9.object({
3524
3483
  runId: z9.string().trim().min(1)
3525
3484
  });
@@ -3691,17 +3650,20 @@ function handleAgentRouteError(error, set) {
3691
3650
  case "invalid_sandbox_params":
3692
3651
  case "agent_selector_removed":
3693
3652
  case "invalid_context":
3653
+ case "invalid_attachment":
3694
3654
  case "invalid_model_selection":
3655
+ case "invalid_locale":
3656
+ case "invalid_message":
3695
3657
  case "model_not_found":
3696
3658
  set.status = 400;
3697
3659
  break;
3698
3660
  }
3699
- return { error: error.message };
3661
+ return { error: error.message, code: error.code };
3700
3662
  }
3701
3663
  return handleRouteError(error, set);
3702
3664
  }
3703
3665
  function missingAgentStorageResponse(set) {
3704
- return unconfiguredStorageResponse2(set, "Agent storage");
3666
+ return unconfiguredStorageResponse(set, "Agent storage");
3705
3667
  }
3706
3668
  async function agentMessageFileContentResponse(host, context, options = {}) {
3707
3669
  const authState = requestAuthState(context);
@@ -3729,7 +3691,7 @@ async function agentMessageFileContentResponse(host, context, options = {}) {
3729
3691
  context.set.status = 404;
3730
3692
  return { error: "File not found" };
3731
3693
  }
3732
- const fileRef = resolveFileRefAtPath(serializeMessage(message), parsed.path);
3694
+ const fileRef = resolveFileRefAtPath2(serializeMessage(message), parsed.path);
3733
3695
  if (!fileRef) {
3734
3696
  context.set.status = 404;
3735
3697
  return { error: "File not found" };
@@ -3986,8 +3948,11 @@ function registerAgentRoutes(app, host) {
3986
3948
  const requestInput = {
3987
3949
  threadId: thread.id,
3988
3950
  text: parsed.text,
3951
+ continue: parsed.continue,
3989
3952
  model: parsed.model,
3990
3953
  reasoning: parsed.reasoning,
3954
+ timeZone: parsed.timeZone,
3955
+ locale: parsed.locale,
3991
3956
  attachments: parsed.attachments,
3992
3957
  context: parsed.context,
3993
3958
  messageId: parsed.messageId
@@ -4005,7 +3970,7 @@ function registerAgentRoutes(app, host) {
4005
3970
  body: PostAgentMessageBodySchema,
4006
3971
  response: {
4007
3972
  202: PostAgentMessageResponseSchema,
4008
- 400: ErrorResponseSchema,
3973
+ 400: AgentRequestErrorResponseSchema,
4009
3974
  403: ErrorResponseSchema,
4010
3975
  404: ErrorResponseSchema,
4011
3976
  409: ErrorResponseSchema,
@@ -4117,9 +4082,9 @@ function registerAgentRoutes(app, host) {
4117
4082
  set.status = 404;
4118
4083
  return { error: "Agent run not found" };
4119
4084
  }
4120
- if (failedRun.status !== "failed") {
4085
+ if (!isRetryableAgentRun(failedRun)) {
4121
4086
  set.status = 409;
4122
- return { error: "Only failed agent runs can be retried" };
4087
+ return { error: "Only failed or interrupted agent runs can be retried" };
4123
4088
  }
4124
4089
  const { run } = await sixb.agent.runs.retry(failedRun.id);
4125
4090
  set.status = 202;
@@ -4140,7 +4105,7 @@ function registerAgentRoutes(app, host) {
4140
4105
  501: ErrorResponseSchema
4141
4106
  },
4142
4107
  detail: {
4143
- summary: "Retry a failed agent run",
4108
+ summary: "Retry a failed or interrupted agent run",
4144
4109
  tags: [OPENAPI_TAGS.agentRuns.name],
4145
4110
  operationId: "retryAgentRun",
4146
4111
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -4458,7 +4423,7 @@ function registerAiAccountingRoutes(app, host) {
4458
4423
  sixb.aiUsage.assertObservable();
4459
4424
  const parsed = AiAccountingOverviewQuerySchema.parse(query);
4460
4425
  if (!sixb.aiUsage.accountingConfigured) {
4461
- return unconfiguredStorageResponse2(set, "AI cost storage");
4426
+ return unconfiguredStorageResponse(set, "AI cost storage");
4462
4427
  }
4463
4428
  const overview = await sixb.aiUsage.queryOverview({
4464
4429
  from: new Date(parsed.from),
@@ -4493,7 +4458,7 @@ function registerAiAccountingRoutes(app, host) {
4493
4458
  sixb.aiUsage.assertObservable();
4494
4459
  const parsed = AiModelCallAccountingListQuerySchema.parse(query);
4495
4460
  if (!sixb.aiUsage.accountingConfigured) {
4496
- return unconfiguredStorageResponse2(set, "AI cost storage");
4461
+ return unconfiguredStorageResponse(set, "AI cost storage");
4497
4462
  }
4498
4463
  const result = await sixb.aiUsage.listModelCalls({
4499
4464
  from: new Date(parsed.from),
@@ -4534,7 +4499,7 @@ function registerAiAccountingRoutes(app, host) {
4534
4499
  try {
4535
4500
  const sixb = requireRequestSixb(context);
4536
4501
  if (!sixb.aiUsage.limitsConfigured) {
4537
- return unconfiguredStorageResponse2(set, "AI limit storage");
4502
+ return unconfiguredStorageResponse(set, "AI limit storage");
4538
4503
  }
4539
4504
  const parsed = AiLimitListQuerySchema.parse(query);
4540
4505
  const items = await sixb.aiUsage.listLimitPolicies({
@@ -4568,7 +4533,7 @@ function registerAiAccountingRoutes(app, host) {
4568
4533
  const sixb = requireRequestSixb(context);
4569
4534
  sixb.aiUsage.assertObservable();
4570
4535
  if (!sixb.aiUsage.limitsConfigured) {
4571
- return unconfiguredStorageResponse2(set, "AI limit storage");
4536
+ return unconfiguredStorageResponse(set, "AI limit storage");
4572
4537
  }
4573
4538
  const parsed = AiLimitStatusQuerySchema.parse(query);
4574
4539
  const items = await sixb.aiUsage.listLimitStatuses({
@@ -4624,7 +4589,7 @@ function registerAiAccountingRoutes(app, host) {
4624
4589
  const sixb = requireRequestSixb(context);
4625
4590
  sixb.aiUsage.assertManageable();
4626
4591
  if (!sixb.aiUsage.limitsConfigured) {
4627
- return unconfiguredStorageResponse2(set, "AI limit storage");
4592
+ return unconfiguredStorageResponse(set, "AI limit storage");
4628
4593
  }
4629
4594
  const parsed = CreateAiLimitPolicyBodySchema.parse(body);
4630
4595
  return serializeLimitPolicy(await sixb.aiUsage.createLimitPolicy(parsed));
@@ -4653,7 +4618,7 @@ function registerAiAccountingRoutes(app, host) {
4653
4618
  const sixb = requireRequestSixb(context);
4654
4619
  sixb.aiUsage.assertManageable();
4655
4620
  if (!sixb.aiUsage.limitsConfigured) {
4656
- return unconfiguredStorageResponse2(set, "AI limit storage");
4621
+ return unconfiguredStorageResponse(set, "AI limit storage");
4657
4622
  }
4658
4623
  const { limitId } = AiLimitPolicyParamsSchema.parse(params);
4659
4624
  const parsed = UpdateAiLimitPolicyBodySchema.parse(body);
@@ -4684,7 +4649,7 @@ function registerAiAccountingRoutes(app, host) {
4684
4649
  const sixb = requireRequestSixb(context);
4685
4650
  sixb.aiUsage.assertManageable();
4686
4651
  if (!sixb.aiUsage.limitsConfigured) {
4687
- return unconfiguredStorageResponse2(set, "AI limit storage");
4652
+ return unconfiguredStorageResponse(set, "AI limit storage");
4688
4653
  }
4689
4654
  const { limitId } = AiLimitPolicyParamsSchema.parse(params);
4690
4655
  if (!await sixb.aiUsage.deleteLimitPolicy(limitId)) {
@@ -4718,7 +4683,7 @@ function registerAiAccountingRoutes(app, host) {
4718
4683
  const sixb = requireRequestSixb(context);
4719
4684
  sixb.aiUsage.assertObservable();
4720
4685
  if (!sixb.aiUsage.accountingConfigured)
4721
- return unconfiguredStorageResponse2(set, "AI cost storage");
4686
+ return unconfiguredStorageResponse(set, "AI cost storage");
4722
4687
  const result = await sixb.aiUsage.listModelCallGroups({
4723
4688
  from: new Date(parsed.from),
4724
4689
  to: new Date(parsed.to),
@@ -5462,9 +5427,18 @@ var DatasetVersionParamsSchema = DatasetParamsSchema.extend({
5462
5427
  var DatasetVersionsQuerySchema = z13.object({
5463
5428
  limit: z13.string().optional()
5464
5429
  });
5430
+ var QueryStringListSchema = z13.preprocess(flattenQueryStringList, z13.array(z13.string()));
5431
+ function flattenQueryStringList(value) {
5432
+ if (typeof value !== "string" && !Array.isArray(value))
5433
+ return value;
5434
+ const items = [value].flat(Number.POSITIVE_INFINITY);
5435
+ if (!items.every((item) => typeof item === "string"))
5436
+ return value;
5437
+ return items.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
5438
+ }
5465
5439
  var DatasetRowsQuerySchema = z13.object({
5466
5440
  versionId: z13.string().optional(),
5467
- columns: z13.string().optional(),
5441
+ columns: QueryStringListSchema.optional(),
5468
5442
  limit: z13.string().optional(),
5469
5443
  offset: z13.string().optional()
5470
5444
  });
@@ -5540,6 +5514,7 @@ var DatasetRowsResponseSchema = z13.object({
5540
5514
  versionId: z13.string(),
5541
5515
  version: DatasetVersionSchema,
5542
5516
  columns: z13.array(z13.string()),
5517
+ redactions: RedactionsSchema.optional(),
5543
5518
  rows: z13.array(z13.record(z13.unknown())),
5544
5519
  count: z13.number(),
5545
5520
  limit: z13.number(),
@@ -5668,22 +5643,6 @@ function datasetVersionNotFound(datasetId, versionId) {
5668
5643
  details: { datasetId, ...versionId === undefined ? {} : { versionId } }
5669
5644
  });
5670
5645
  }
5671
- function parseColumns(value) {
5672
- if (!value)
5673
- return;
5674
- const columns = value.split(",").map((column) => column.trim()).filter(Boolean);
5675
- return columns.length > 0 ? columns : undefined;
5676
- }
5677
- function resolveColumns(version, requested) {
5678
- const available = new Set(version.schema.columns.map((column) => column.name));
5679
- const selected = requested ?? version.schema.columns.map((column) => column.name);
5680
- for (const column of selected) {
5681
- if (!available.has(column)) {
5682
- throw new Error(`Dataset '${version.datasetId}' does not have column '${column}' at version '${version.versionId}'`);
5683
- }
5684
- }
5685
- return selected;
5686
- }
5687
5646
  async function collectRows(rows) {
5688
5647
  const collected = [];
5689
5648
  for await (const row of rows) {
@@ -5789,29 +5748,28 @@ function registerDatasetRoutes(app, host) {
5789
5748
  const { params, query, set } = context;
5790
5749
  const sixb = requireRequestSixb(context);
5791
5750
  try {
5792
- requireDataset(sixb, params.datasetId);
5751
+ const dataset = requireDataset(sixb, params.datasetId);
5793
5752
  const parsed = DatasetRowsQuerySchema.parse(query);
5794
5753
  const limit = parseLimit(parsed.limit, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT);
5795
5754
  const offset = parseOffset(parsed.offset);
5796
- const version = parsed.versionId ? await host.lakeStorage.getVersion(params.datasetId, parsed.versionId) : await host.lakeStorage.getLatestVersion(params.datasetId);
5797
- if (!version) {
5798
- throw datasetVersionNotFound(params.datasetId, parsed.versionId);
5799
- }
5800
- const requestedColumns = parseColumns(parsed.columns);
5801
- const columns = resolveColumns(version, requestedColumns);
5802
- const rows = await collectRows(host.lakeStorage.readRows({
5803
- datasetId: params.datasetId,
5804
- versionId: version.versionId,
5805
- columns: requestedColumns,
5755
+ const page = await sixb.datasets.readRows(dataset, {
5756
+ versionId: parsed.versionId,
5757
+ columns: parsed.columns?.length ? parsed.columns : undefined,
5806
5758
  limit,
5807
5759
  offset
5808
- }));
5760
+ });
5761
+ if (!page) {
5762
+ throw datasetVersionNotFound(params.datasetId, parsed.versionId);
5763
+ }
5764
+ const { version, columns, redactions } = page;
5765
+ const rows = await collectRows(page.rows);
5809
5766
  const hasMore = version.rowCount === undefined ? rows.length === limit : offset + rows.length < version.rowCount;
5810
5767
  return DatasetRowsResponseSchema.parse({
5811
5768
  datasetId: params.datasetId,
5812
5769
  versionId: version.versionId,
5813
5770
  version: serializeDatasetVersion(version),
5814
5771
  columns: [...columns],
5772
+ ...redactions === undefined ? {} : { redactions },
5815
5773
  rows,
5816
5774
  count: rows.length,
5817
5775
  limit,
@@ -5870,12 +5828,14 @@ var ObjectMutationPayloadSchema = z14.object({
5870
5828
  objectTypeId: z14.string(),
5871
5829
  primaryId: z14.string(),
5872
5830
  properties: z14.record(JsonValueSchema),
5873
- propertyChanges: PropertyChangesSchema
5831
+ propertyChanges: PropertyChangesSchema,
5832
+ redactions: RedactionsSchema.optional()
5874
5833
  });
5875
5834
  var ObjectDeletedPayloadSchema = z14.object({
5876
5835
  objectTypeId: z14.string(),
5877
5836
  primaryId: z14.string(),
5878
- propertyChanges: PropertyChangesSchema
5837
+ propertyChanges: PropertyChangesSchema,
5838
+ redactions: RedactionsSchema.optional()
5879
5839
  });
5880
5840
  var LinkSubjectSchema = z14.object({
5881
5841
  sourceTypeId: z14.string(),
@@ -6356,7 +6316,8 @@ async function serializeLanguageModel(entry, defaultEntry) {
6356
6316
  ...await languageModelDisplay(entry),
6357
6317
  provider: entry.provider,
6358
6318
  modelId: entry.modelId,
6359
- isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId
6319
+ isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId,
6320
+ ...entry.model.defaultReasoning === undefined ? {} : { defaultReasoning: entry.model.defaultReasoning }
6360
6321
  };
6361
6322
  }
6362
6323
  function registerModelRoutes(app, host) {
@@ -6616,6 +6577,7 @@ var TwinObjectSchema = z18.object({
6616
6577
  primaryId: z18.string(),
6617
6578
  objectTypeId: z18.string(),
6618
6579
  properties: z18.record(z18.unknown()),
6580
+ redactions: RedactionsSchema.optional(),
6619
6581
  createdAt: z18.string(),
6620
6582
  updatedAt: z18.string()
6621
6583
  });
@@ -6643,6 +6605,15 @@ var ObjectQueryOpenApiSchemas = {
6643
6605
  error: { type: "string" }
6644
6606
  }
6645
6607
  },
6608
+ Redactions: {
6609
+ type: "object",
6610
+ additionalProperties: {
6611
+ type: "object",
6612
+ required: ["reason"],
6613
+ additionalProperties: false,
6614
+ properties: { reason: { type: "string", enum: ["missing_clearance"] } }
6615
+ }
6616
+ },
6646
6617
  ObjectQueryObject: {
6647
6618
  type: "object",
6648
6619
  required: ["primaryId", "objectTypeId", "properties", "createdAt", "updatedAt"],
@@ -6652,6 +6623,7 @@ var ObjectQueryOpenApiSchemas = {
6652
6623
  primaryId: { type: "string" },
6653
6624
  objectTypeId: { type: "string" },
6654
6625
  properties: { type: "object", additionalProperties: true },
6626
+ redactions: { $ref: "#/components/schemas/Redactions" },
6655
6627
  createdAt: { type: "string" },
6656
6628
  updatedAt: { type: "string" },
6657
6629
  links: {
@@ -7168,6 +7140,7 @@ function serializeObject(row) {
7168
7140
  primaryId: row.primaryId,
7169
7141
  objectTypeId: row.objectTypeId,
7170
7142
  properties: row.properties,
7143
+ ...row.redactions === undefined ? {} : { redactions: row.redactions },
7171
7144
  createdAt: toIsoString(row.createdAt),
7172
7145
  updatedAt: toIsoString(row.updatedAt)
7173
7146
  };
@@ -7284,8 +7257,14 @@ async function searchObjects(host, sixb, query, limit) {
7284
7257
  input: { kind: "start", objectTypeId: objectType.id }
7285
7258
  }
7286
7259
  };
7287
- const result = await sixb.objects.executeQuery({ query: objectQuery });
7288
- return result.objects;
7260
+ try {
7261
+ const result = await sixb.objects.executeQuery({ query: objectQuery });
7262
+ return result.objects;
7263
+ } catch (error) {
7264
+ if (error instanceof AuthorizationError3)
7265
+ return [];
7266
+ throw error;
7267
+ }
7289
7268
  }));
7290
7269
  const items = new Map;
7291
7270
  for (const row of [...primaryMatches.objects, ...textMatches.flat()]) {
@@ -8182,7 +8161,7 @@ function registerPipelineRoutes(app, host) {
8182
8161
  const parsed = PipelineRunsQuerySchema.parse(query);
8183
8162
  const storage = host.storage.pipelineRuns;
8184
8163
  if (!storage) {
8185
- return unconfiguredStorageResponse2(set, "Pipeline run storage");
8164
+ return unconfiguredStorageResponse(set, "Pipeline run storage");
8186
8165
  }
8187
8166
  const result = await sixb.pipelines.runs.list({
8188
8167
  pipelineId: parsed.pipelineId,
@@ -8219,7 +8198,7 @@ function registerPipelineRoutes(app, host) {
8219
8198
  try {
8220
8199
  const storage = host.storage.pipelineRuns;
8221
8200
  if (!storage) {
8222
- return unconfiguredStorageResponse2(set, "Pipeline run storage");
8201
+ return unconfiguredStorageResponse(set, "Pipeline run storage");
8223
8202
  }
8224
8203
  const run = await sixb.pipelines.runs.getById(params.runId);
8225
8204
  if (!run) {
@@ -8286,12 +8265,15 @@ function registerPipelineRoutes(app, host) {
8286
8265
  // src/schemas/project.ts
8287
8266
  import { z as z21 } from "zod";
8288
8267
  var ProjectInfoResponseSchema = z21.object({
8289
- id: z21.string()
8268
+ id: z21.string(),
8269
+ locale: z21.string(),
8270
+ timeZone: z21.string()
8290
8271
  });
8291
8272
 
8292
8273
  // src/routes/project.ts
8293
8274
  function registerProjectRoutes(app, host) {
8294
- return app.get("/api/project", async () => ({ id: host.id }), {
8275
+ const project = { id: host.id, locale: host.locale, timeZone: host.timeZone };
8276
+ return app.get("/api/project", async () => project, {
8295
8277
  response: { 200: ProjectInfoResponseSchema },
8296
8278
  detail: {
8297
8279
  summary: "Get current project metadata",
@@ -8542,7 +8524,7 @@ function registerProjectionRoutes(app, host) {
8542
8524
  try {
8543
8525
  const storage = host.storage.projectionRuns;
8544
8526
  if (!storage) {
8545
- return unconfiguredStorageResponse2(set, "Projection run storage");
8527
+ return unconfiguredStorageResponse(set, "Projection run storage");
8546
8528
  }
8547
8529
  const parsed = ProjectionRunsQuerySchema.parse(query);
8548
8530
  const result = await sixb.projections.runs.list({
@@ -8583,7 +8565,7 @@ function registerProjectionRoutes(app, host) {
8583
8565
  try {
8584
8566
  const storage = host.storage.projectionRuns;
8585
8567
  if (!storage) {
8586
- return unconfiguredStorageResponse2(set, "Projection run storage");
8568
+ return unconfiguredStorageResponse(set, "Projection run storage");
8587
8569
  }
8588
8570
  const run = await sixb.projections.runs.getById(params.runId);
8589
8571
  if (!run) {
@@ -8741,7 +8723,7 @@ function registerRuleRoutes(app, host) {
8741
8723
  const parsed = RuleStatesQuerySchema.parse(query);
8742
8724
  const storage = host.storage.rules;
8743
8725
  if (!storage) {
8744
- return unconfiguredStorageResponse2(set, "Rule state storage");
8726
+ return unconfiguredStorageResponse(set, "Rule state storage");
8745
8727
  }
8746
8728
  const result = await sixb.rules.states.list({
8747
8729
  ruleId: parsed.ruleId,
@@ -9429,7 +9411,7 @@ function registerSyncRoutes(app, host) {
9429
9411
  const parsed = SyncRunsQuerySchema.parse(query);
9430
9412
  const storage = host.storage.syncRuns;
9431
9413
  if (!storage) {
9432
- return unconfiguredStorageResponse2(set, "Sync run storage");
9414
+ return unconfiguredStorageResponse(set, "Sync run storage");
9433
9415
  }
9434
9416
  const result = await sixb.syncs.runs.list({
9435
9417
  syncId: parsed.syncId,
@@ -9760,7 +9742,7 @@ function registerWebhookRunRoutes(app, host) {
9760
9742
  const parsed = WebhookRunsQuerySchema.parse(query);
9761
9743
  const storage = host.storage.webhookRuns;
9762
9744
  if (!storage) {
9763
- return unconfiguredStorageResponse2(set, "Webhook run storage");
9745
+ return unconfiguredStorageResponse(set, "Webhook run storage");
9764
9746
  }
9765
9747
  const result = await storage.list({
9766
9748
  projectId: host.id,
@@ -9803,6 +9785,7 @@ import {
9803
9785
  } from "@sixb/core";
9804
9786
  import { publishAgentRunCancel as publishAgentRunCancel2 } from "@sixb/core/internal/agents";
9805
9787
  import { createSixbError as createSixbError4, toSixbFailure } from "@sixb/core/internal/errors";
9788
+ import { assertValidFileRefs } from "@sixb/core/internal/ontology";
9806
9789
  import {
9807
9790
  snapshotWorkflowInterventionResponse
9808
9791
  } from "@sixb/core/internal/workflows";
@@ -10156,7 +10139,7 @@ async function workflowRunFileContentResponse(host, context, options = {}) {
10156
10139
  const sixb = requireRequestSixb(context);
10157
10140
  const storage = host.storage.workflowRuns;
10158
10141
  if (!storage) {
10159
- return unconfiguredStorageResponse2(context.set, "Workflow run storage");
10142
+ return unconfiguredStorageResponse(context.set, "Workflow run storage");
10160
10143
  }
10161
10144
  return createContextualFileContentResponse({
10162
10145
  blobStorage: host.blobStorage,
@@ -10175,7 +10158,7 @@ async function workflowNodeFileContentResponse(host, context, options = {}) {
10175
10158
  const sixb = requireRequestSixb(context);
10176
10159
  const storage = host.storage.workflowRuns;
10177
10160
  if (!storage) {
10178
- return unconfiguredStorageResponse2(context.set, "Workflow run storage");
10161
+ return unconfiguredStorageResponse(context.set, "Workflow run storage");
10179
10162
  }
10180
10163
  return createContextualFileContentResponse({
10181
10164
  blobStorage: host.blobStorage,
@@ -10423,7 +10406,7 @@ function registerWorkflowRoutes(app, host) {
10423
10406
  const offset = parseOptionalInt(parsed.offset);
10424
10407
  const storage = host.storage.workflowInterventions;
10425
10408
  if (!storage) {
10426
- return unconfiguredStorageResponse2(set, "Workflow intervention storage");
10409
+ return unconfiguredStorageResponse(set, "Workflow intervention storage");
10427
10410
  }
10428
10411
  const result = await sixb.workflows.interventions.list({
10429
10412
  workflowId: parsed.workflowId,
@@ -10465,7 +10448,7 @@ function registerWorkflowRoutes(app, host) {
10465
10448
  try {
10466
10449
  const storage = host.storage.workflowInterventions;
10467
10450
  if (!storage) {
10468
- return unconfiguredStorageResponse2(set, "Workflow intervention storage");
10451
+ return unconfiguredStorageResponse(set, "Workflow intervention storage");
10469
10452
  }
10470
10453
  const intervention = await sixb.workflows.interventions.getById(params.interventionId);
10471
10454
  if (!intervention) {
@@ -10495,7 +10478,7 @@ function registerWorkflowRoutes(app, host) {
10495
10478
  try {
10496
10479
  const storage = host.storage.workflowInterventions;
10497
10480
  if (!storage) {
10498
- return unconfiguredStorageResponse2(set, "Workflow intervention storage");
10481
+ return unconfiguredStorageResponse(set, "Workflow intervention storage");
10499
10482
  }
10500
10483
  const intervention = await sixb.workflows.interventions.getById(params.interventionId);
10501
10484
  if (!intervention) {
@@ -10516,6 +10499,7 @@ function registerWorkflowRoutes(app, host) {
10516
10499
  value: parsedBody.response,
10517
10500
  valueTypesById: host.definitions.ontology.getValueTypesById()
10518
10501
  });
10502
+ assertValidFileRefs(parsedBody.response, `Workflow "${workflow.id}" intervention "${node.intervention.id}" response`);
10519
10503
  const submitted = await storage.submit({
10520
10504
  projectId: host.id,
10521
10505
  id: intervention.id,
@@ -10564,11 +10548,11 @@ function registerWorkflowRoutes(app, host) {
10564
10548
  try {
10565
10549
  const interventionStorage = host.storage.workflowInterventions;
10566
10550
  if (!interventionStorage) {
10567
- return unconfiguredStorageResponse2(set, "Workflow intervention storage");
10551
+ return unconfiguredStorageResponse(set, "Workflow intervention storage");
10568
10552
  }
10569
10553
  const runStorage = host.storage.workflowRuns;
10570
10554
  if (!runStorage) {
10571
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10555
+ return unconfiguredStorageResponse(set, "Workflow run storage");
10572
10556
  }
10573
10557
  const intervention = await sixb.workflows.interventions.getById(params.interventionId);
10574
10558
  if (!intervention) {
@@ -10680,7 +10664,7 @@ function registerWorkflowRoutes(app, host) {
10680
10664
  const offset = parseOptionalInt(parsed.offset);
10681
10665
  const storage = host.storage.workflowRuns;
10682
10666
  if (!storage) {
10683
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10667
+ return unconfiguredStorageResponse(set, "Workflow run storage");
10684
10668
  }
10685
10669
  const result = await sixb.workflows.runs.list({
10686
10670
  workflowId: parsed.workflowId,
@@ -10719,7 +10703,7 @@ function registerWorkflowRoutes(app, host) {
10719
10703
  try {
10720
10704
  const storage = host.storage.workflowRuns;
10721
10705
  if (!storage) {
10722
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10706
+ return unconfiguredStorageResponse(set, "Workflow run storage");
10723
10707
  }
10724
10708
  const run = await sixb.workflows.runs.getById(params.runId);
10725
10709
  if (!run) {
@@ -10761,7 +10745,7 @@ function registerWorkflowRoutes(app, host) {
10761
10745
  try {
10762
10746
  const storage = host.storage.workflowRuns;
10763
10747
  if (!storage) {
10764
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10748
+ return unconfiguredStorageResponse(set, "Workflow run storage");
10765
10749
  }
10766
10750
  const run = await sixb.workflows.runs.getById(params.runId);
10767
10751
  if (!run) {
@@ -10804,7 +10788,7 @@ function registerWorkflowRoutes(app, host) {
10804
10788
  CancelWorkflowRunBodySchema.parse(body ?? {});
10805
10789
  const storage = host.storage.workflowRuns;
10806
10790
  if (!storage) {
10807
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10791
+ return unconfiguredStorageResponse(set, "Workflow run storage");
10808
10792
  }
10809
10793
  const existing = await sixb.workflows.runs.getById(params.runId);
10810
10794
  if (!existing) {
@@ -11005,7 +10989,7 @@ function registerWorkflowRoutes(app, host) {
11005
10989
  const sixb = requireRequestSixb(context);
11006
10990
  try {
11007
10991
  if (!host.storage.workflowRuns) {
11008
- return unconfiguredStorageResponse2(set, "Workflow run storage");
10992
+ return unconfiguredStorageResponse(set, "Workflow run storage");
11009
10993
  }
11010
10994
  const parsedBody = RequestWorkflowRunBodySchema.parse(body);
11011
10995
  const input = {
@@ -11126,7 +11110,8 @@ async function customAuthExperienceResponse(options, input) {
11126
11110
  ...input.submission ? { submission: input.submission } : {}
11127
11111
  })).toString("base64url");
11128
11112
  const formAction = ["'self'", ...(input.formActionOrigins ?? []).map(normalizeCspOrigin)].join(" ");
11129
- return new Response(html.replace(AUTH_BOOTSTRAP_PLACEHOLDER, bootstrap), {
11113
+ const page = withDocumentLanguage(html.replace(AUTH_BOOTSTRAP_PLACEHOLDER, bootstrap), options.locale);
11114
+ return new Response(page, {
11130
11115
  status: input.status ?? 200,
11131
11116
  headers: {
11132
11117
  "content-type": "text/html; charset=utf-8",
@@ -11146,6 +11131,9 @@ async function customAuthExperienceResponse(options, input) {
11146
11131
  }
11147
11132
  });
11148
11133
  }
11134
+ function withDocumentLanguage(html, locale) {
11135
+ return html.replace(/<html\b([^>]*)>/i, (_tag, attributes) => `<html${attributes.replace(/\s+lang\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i, "")} lang="${locale}">`);
11136
+ }
11149
11137
  function normalizeCspOrigin(value) {
11150
11138
  let url;
11151
11139
  try {
@@ -11497,7 +11485,8 @@ var RevokeAuthInvitationResponseSchema = z32.object({
11497
11485
  });
11498
11486
  var AuthSessionResponseSchema = z32.union([
11499
11487
  z32.object({
11500
- authenticated: z32.literal(false)
11488
+ authenticated: z32.literal(false),
11489
+ authEnabled: z32.boolean()
11501
11490
  }),
11502
11491
  z32.object({
11503
11492
  authenticated: z32.literal(true),
@@ -11802,14 +11791,14 @@ function registerAuthRoutes(app, host, options) {
11802
11791
  credentialSource: "any"
11803
11792
  });
11804
11793
  if (!caller.authenticated || caller.credentialSource !== "session") {
11805
- return jsonResponse2({ authenticated: false }, 200);
11794
+ return signedOutSessionResponse(host);
11806
11795
  }
11807
11796
  if (caller.session.bearer) {
11808
11797
  return jsonResponse2(authSessionBody(host, caller, DEFAULT_AUTH_SESSION_AUDIENCE2), 200);
11809
11798
  }
11810
11799
  const session = hasForegroundSessionActivity(request) && sessionCanAccessApplication(host, caller, authOptions.audience) ? await host.auth.getSession(request, { ...authOptions, sessionActivity: "foreground" }) : caller;
11811
11800
  if (!session.authenticated) {
11812
- return jsonResponse2({ authenticated: false }, 200);
11801
+ return signedOutSessionResponse(host);
11813
11802
  }
11814
11803
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11815
11804
  const csrf = resolveSessionCsrfToken({
@@ -12013,7 +12002,7 @@ function registerAuthRoutes(app, host, options) {
12013
12002
  summary: "Create a personal access token",
12014
12003
  tags: [OPENAPI_TAGS.authAccessTokens.name],
12015
12004
  operationId: "createAuthPersonalAccessToken",
12016
- security: accessTokenSecurityRequirement("createAuthPersonalAccessToken")
12005
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12017
12006
  }
12018
12007
  }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
12019
12008
  try {
@@ -12185,7 +12174,7 @@ function registerAuthRoutes(app, host, options) {
12185
12174
  summary: "Create an access token for an auth service account",
12186
12175
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
12187
12176
  operationId: "createAuthServiceAccountAccessToken",
12188
- security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken")
12177
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12189
12178
  }
12190
12179
  }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
12191
12180
  try {
@@ -12492,9 +12481,10 @@ function registerAuthRoutes(app, host, options) {
12492
12481
  });
12493
12482
  const response = await magicLinkRequestedResponse(options, authRedirect);
12494
12483
  const existingPending = getCookie4(request, MAGIC_LINK_PENDING_COOKIE_NAME)?.trim();
12495
- response.headers.append("set-cookie", magicLinkPendingCookieHeader({
12484
+ response.headers.append("set-cookie", callbackCookieHeader({
12496
12485
  request,
12497
12486
  host,
12487
+ name: MAGIC_LINK_PENDING_COOKIE_NAME,
12498
12488
  value: result.status === "sent" ? pending.secret : existingPending || pending.secret,
12499
12489
  maxAgeSeconds: magicLinkPendingCookieMaxAgeSeconds(strategy)
12500
12490
  }));
@@ -12508,7 +12498,7 @@ function registerAuthRoutes(app, host, options) {
12508
12498
  returnTo: authRedirect.returnTo,
12509
12499
  requestOrigin: authRedirect.requestOrigin
12510
12500
  });
12511
- return redirectResponse(result.redirectTo);
12501
+ return oidcSignInRedirect(request, host, result);
12512
12502
  }
12513
12503
  return strategyNotImplementedResponse("Sign-in is not implemented yet.");
12514
12504
  }, {
@@ -12540,7 +12530,7 @@ function registerAuthRoutes(app, host, options) {
12540
12530
  returnTo: authRedirect.returnTo,
12541
12531
  requestOrigin: authRedirect.requestOrigin
12542
12532
  });
12543
- return redirectResponse(result.redirectTo);
12533
+ return oidcSignInRedirect(request, host, result);
12544
12534
  }
12545
12535
  return strategyNotImplementedResponse("Sign-in is not implemented yet.");
12546
12536
  }, { detail: { hide: true } }).get("/auth/callback", async ({ request }) => {
@@ -12596,7 +12586,12 @@ function registerAuthRoutes(app, host, options) {
12596
12586
  const now = new Date;
12597
12587
  const sessionCredential = createSessionCredential();
12598
12588
  const device = resolveSessionDevice(request);
12589
+ const state = new URL(request.url).searchParams.get("state");
12590
+ let response;
12599
12591
  try {
12592
+ if (!state || !matchesOidcStateCookie(request, state)) {
12593
+ throw new Error("[SixbServer] OIDC callback reached a browser that did not start this sign-in.");
12594
+ }
12600
12595
  const authOptions = resolveAuthOptions(options, request);
12601
12596
  const result = await strategy.completeOidcSignIn({
12602
12597
  projectId: host.id,
@@ -12612,7 +12607,7 @@ function registerAuthRoutes(app, host, options) {
12612
12607
  ...device
12613
12608
  }
12614
12609
  });
12615
- return sessionCallbackCompletionResponse({
12610
+ response = sessionCallbackCompletionResponse({
12616
12611
  host,
12617
12612
  request,
12618
12613
  apiOrigin: options.resolveAuthRequestOrigin(request),
@@ -12623,11 +12618,18 @@ function registerAuthRoutes(app, host, options) {
12623
12618
  });
12624
12619
  } catch (error) {
12625
12620
  logAuthCallbackError("OIDC", error);
12626
- if (error instanceof SignInRefusedError) {
12627
- return htmlMessageResponse(signInRefusalMessage(error), 403, "You can't sign in");
12628
- }
12629
- return htmlMessageResponse("This sign-in attempt could not be completed.", 400);
12621
+ response = error instanceof SignInRefusedError ? htmlMessageResponse(signInRefusalMessage(error), 403, "You can't sign in") : htmlMessageResponse("This sign-in attempt could not be completed.", 400);
12622
+ }
12623
+ if (state) {
12624
+ response.headers.append("set-cookie", callbackCookieHeader({
12625
+ request,
12626
+ host,
12627
+ name: oidcStateCookieName(state),
12628
+ value: "",
12629
+ maxAgeSeconds: 0
12630
+ }));
12630
12631
  }
12632
+ return response;
12631
12633
  }
12632
12634
  return strategyNotImplementedResponse("Auth callback is not implemented yet.");
12633
12635
  }, { detail: { hide: true } }).post("/auth/callback", async ({ body, request }) => {
@@ -12702,9 +12704,9 @@ function matchesMagicLinkRequester(pendingSecret, requesterHash) {
12702
12704
  const provided = Buffer.from(requesterHash);
12703
12705
  return expected.length === provided.length && timingSafeEqual(expected, provided);
12704
12706
  }
12705
- function magicLinkPendingCookieHeader(params) {
12707
+ function callbackCookieHeader(params) {
12706
12708
  const parts = [
12707
- `${MAGIC_LINK_PENDING_COOKIE_NAME}=${params.value}`,
12709
+ `${params.name}=${params.value}`,
12708
12710
  "Path=/auth/callback",
12709
12711
  "SameSite=Lax",
12710
12712
  "HttpOnly",
@@ -12745,9 +12747,10 @@ async function completeMagicLinkCallback(input) {
12745
12747
  returnTo: result.returnTo
12746
12748
  });
12747
12749
  if (input.clearPendingCookie) {
12748
- response.headers.append("set-cookie", magicLinkPendingCookieHeader({
12750
+ response.headers.append("set-cookie", callbackCookieHeader({
12749
12751
  request: input.request,
12750
12752
  host: input.host,
12753
+ name: MAGIC_LINK_PENDING_COOKIE_NAME,
12751
12754
  value: "",
12752
12755
  maxAgeSeconds: 0
12753
12756
  }));
@@ -12757,6 +12760,28 @@ async function completeMagicLinkCallback(input) {
12757
12760
  return await invalidMagicLinkResponse(input.options, input.authRedirectHint);
12758
12761
  }
12759
12762
  }
12763
+ function oidcStateCookieName(state) {
12764
+ return `sixb_oidc_${createHash3("sha256").update(state).digest("base64url").slice(0, 22)}`;
12765
+ }
12766
+ function oidcSignInRedirect(request, host, result) {
12767
+ const response = redirectResponse(result.redirectTo);
12768
+ response.headers.append("set-cookie", callbackCookieHeader({
12769
+ request,
12770
+ host,
12771
+ name: oidcStateCookieName(result.state),
12772
+ value: encodeURIComponent(result.state),
12773
+ maxAgeSeconds: Math.max(0, Math.floor((result.expiresAt.getTime() - Date.now()) / 1000))
12774
+ }));
12775
+ return response;
12776
+ }
12777
+ function matchesOidcStateCookie(request, state) {
12778
+ const held = getCookie4(request, oidcStateCookieName(state));
12779
+ if (!held)
12780
+ return false;
12781
+ const expected = Buffer.from(encodeURIComponent(state));
12782
+ const provided = Buffer.from(held);
12783
+ return expected.length === provided.length && timingSafeEqual(expected, provided);
12784
+ }
12760
12785
  function bearerTokensBody(tokens, bearer, issuedAt) {
12761
12786
  return {
12762
12787
  accessToken: tokens.accessToken,
@@ -12872,6 +12897,9 @@ function authSessionBody(host, session, audience) {
12872
12897
  session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) }
12873
12898
  };
12874
12899
  }
12900
+ function signedOutSessionResponse(host) {
12901
+ return jsonResponse2({ authenticated: false, authEnabled: host.auth.isEnabled() }, 200);
12902
+ }
12875
12903
  function authSessionJsonResponse(body, setCookies) {
12876
12904
  const headers = new Headers({
12877
12905
  "content-type": "application/json; charset=utf-8",
@@ -14145,12 +14173,13 @@ class SubscriptionHub {
14145
14173
  deliverLive(records) {
14146
14174
  for (const state of this.clients.values()) {
14147
14175
  for (const record of records) {
14148
- if (!state.subscription.matches(record))
14176
+ const visible = visibleRecord(state.subscription, record);
14177
+ if (!visible)
14149
14178
  continue;
14150
14179
  if (state.catchingUp)
14151
- this.enqueuePendingLive(state, record);
14180
+ this.enqueuePendingLive(state, visible);
14152
14181
  else
14153
- this.enqueue(state, record);
14182
+ this.enqueue(state, visible);
14154
14183
  }
14155
14184
  }
14156
14185
  }
@@ -14166,9 +14195,10 @@ class SubscriptionHub {
14166
14195
  if (state.pendingCursors.has(record.cursor)) {
14167
14196
  state.replayedPendingCursors.add(record.cursor);
14168
14197
  }
14169
- if (!state.subscription.matches(record))
14198
+ const visible = visibleRecord(state.subscription, record);
14199
+ if (!visible)
14170
14200
  continue;
14171
- if (!await this.enqueueReplay(state, record))
14201
+ if (!await this.enqueueReplay(state, visible))
14172
14202
  return;
14173
14203
  }
14174
14204
  if (state.closed)
@@ -14319,6 +14349,11 @@ class SubscriptionHub {
14319
14349
  } catch {}
14320
14350
  }
14321
14351
  }
14352
+ function visibleRecord(subscription, record) {
14353
+ if (!subscription.matches(record))
14354
+ return;
14355
+ return subscription.view ? subscription.view(record) : record;
14356
+ }
14322
14357
  function hasQueueCapacity(state, bytes) {
14323
14358
  return state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS && state.queuedBytes + state.pendingBytes + bytes <= MAX_CLIENT_BYTES;
14324
14359
  }
@@ -14341,7 +14376,6 @@ var SubscribeSchema2 = z34.object({
14341
14376
  types: z34.array(z34.enum(EVENT_TYPES)).optional(),
14342
14377
  objectTypeId: z34.string().optional(),
14343
14378
  primaryId: z34.string().optional(),
14344
- actionId: z34.string().optional(),
14345
14379
  runId: z34.string().optional(),
14346
14380
  afterCursor: z34.string().optional(),
14347
14381
  limit: z34.number().int().positive().max(500).optional()
@@ -14439,7 +14473,8 @@ function registerEventStreamRoutes(app, server) {
14439
14473
  state.replayFrom = null;
14440
14474
  try {
14441
14475
  await hub.subscribe(key, ws, {
14442
- matches: (event) => (!filter.topic || event.topic === filter.topic) && (!filter.types?.length || filter.types.includes(event.type)) && eventMatchesScope(event, filter) && sixb.events.canRead(event),
14476
+ matches: (event) => (!filter.topic || event.topic === filter.topic) && (!filter.types?.length || filter.types.includes(event.type)) && eventMatchesScope(event, filter),
14477
+ view: (event) => sixb.events.readable(event),
14443
14478
  replay: replayFrom ? {
14444
14479
  afterCursor: replayFrom.afterCursor,
14445
14480
  read: async (afterCursor) => {
@@ -14477,8 +14512,8 @@ function registerEventStreamRoutes(app, server) {
14477
14512
  });
14478
14513
  }
14479
14514
  function eventMatchesScope(event, filter) {
14480
- const { objectTypeId, primaryId, actionId, runId } = filter;
14481
- if (objectTypeId === undefined && primaryId === undefined && actionId === undefined && runId === undefined) {
14515
+ const { objectTypeId, primaryId, runId } = filter;
14516
+ if (objectTypeId === undefined && primaryId === undefined && runId === undefined) {
14482
14517
  return true;
14483
14518
  }
14484
14519
  const scope = scopeKeysForEvent(event);
@@ -14488,9 +14523,6 @@ function eventMatchesScope(event, filter) {
14488
14523
  if (primaryId !== undefined && scope.primaryId !== primaryId) {
14489
14524
  return false;
14490
14525
  }
14491
- if (actionId !== undefined && scope.actionId !== actionId) {
14492
- return false;
14493
- }
14494
14526
  if (runId !== undefined && scope.runId !== runId) {
14495
14527
  return false;
14496
14528
  }
@@ -14653,6 +14685,7 @@ function registerWebSocketRoutes(app, server) {
14653
14685
  }
14654
14686
 
14655
14687
  // src/server.ts
14688
+ var MAX_WEBSOCKET_MESSAGE_BYTES = 64 * 1024;
14656
14689
  function createSixbServer(options) {
14657
14690
  return new SixbServer(options);
14658
14691
  }
@@ -14796,6 +14829,12 @@ function createSixbApi(server) {
14796
14829
  }
14797
14830
  return shared.kind === "deny" ? shared.response : undefined;
14798
14831
  });
14832
+ app.onError(({ error, set }) => {
14833
+ if (error instanceof ParseError && error.cause instanceof RequestBodyTooLargeError) {
14834
+ set.status = 413;
14835
+ return { error: error.cause.message };
14836
+ }
14837
+ });
14799
14838
  app.derive(async ({ request }) => {
14800
14839
  const shared = preparedSharedAccess.get(request) ?? await sharedAccess.resolveRequest(request);
14801
14840
  preparedSharedAccess.delete(request);
@@ -14923,12 +14962,13 @@ function createSixbApi(server) {
14923
14962
  })
14924
14963
  }
14925
14964
  }));
14965
+ const authExperience = server.getAuthExperience();
14926
14966
  registerAuthRoutes(app, host, {
14927
14967
  resolveAuthContext: (request) => server.resolveAuthContext(request),
14928
14968
  resolveAuthRedirectContext: (request, input) => server.resolveAuthRedirectContext(request, input),
14929
14969
  getInvitationDestinationOptions: (request) => server.getInvitationDestinationOptions(request),
14930
14970
  resolveAuthRequestOrigin: (request) => server.resolveAuthRequestOrigin(request),
14931
- authExperience: server.getAuthExperience(),
14971
+ authExperience: authExperience && { ...authExperience, locale: host.locale },
14932
14972
  resolveInvitationRedirectContext: (request, input) => server.resolveInvitationRedirectContext(request, input)
14933
14973
  });
14934
14974
  registerHttpRoutes(app, host, {
@@ -15000,8 +15040,10 @@ function startApiServer(app, options) {
15000
15040
  const bunServer = Bun.serve({
15001
15041
  port: options.port,
15002
15042
  hostname: options.host,
15003
- fetch: (request, server) => {
15004
- const socketAddress = server.requestIP(request)?.address;
15043
+ maxRequestBodySize: DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES,
15044
+ fetch: (incoming, server) => {
15045
+ const socketAddress = server.requestIP(incoming)?.address;
15046
+ const request = limitRequestBody(incoming);
15005
15047
  if (socketAddress) {
15006
15048
  const forwardedFor = request.headers.get("x-forwarded-for");
15007
15049
  setRequestClientAddress(request, options.resolveClientAddress(socketAddress, forwardedFor));
@@ -15017,7 +15059,8 @@ function getElysiaWsHandler(app) {
15017
15059
  const cfg = app.config;
15018
15060
  return {
15019
15061
  ...elysiaWebSocket,
15020
- ...cfg?.websocket ?? {}
15062
+ ...cfg?.websocket ?? {},
15063
+ maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES
15021
15064
  };
15022
15065
  }
15023
15066
  function attachBunServer(app, bunServer) {
@@ -15028,4 +15071,4 @@ export {
15028
15071
  createSixbServer
15029
15072
  };
15030
15073
 
15031
- //# debugId=A2358A8A15C4EC4564756E2164756E21
15074
+ //# debugId=AA8B124AF8294E7E64756E2164756E21