@sixb/server 0.1.17 → 0.1.18

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 (69) hide show
  1. package/dist/auth/experience.d.ts +5 -1
  2. package/dist/auth/experience.d.ts.map +1 -1
  3. package/dist/files/content.d.ts +0 -1
  4. package/dist/files/content.d.ts.map +1 -1
  5. package/dist/index.js +204 -136
  6. package/dist/index.js.map +24 -24
  7. package/dist/routes/agents.d.ts +48 -28
  8. package/dist/routes/agents.d.ts.map +1 -1
  9. package/dist/routes/auth.d.ts +3 -2
  10. package/dist/routes/auth.d.ts.map +1 -1
  11. package/dist/routes/datasets.d.ts +4 -1
  12. package/dist/routes/datasets.d.ts.map +1 -1
  13. package/dist/routes/files.d.ts.map +1 -1
  14. package/dist/routes/models.d.ts +1 -0
  15. package/dist/routes/models.d.ts.map +1 -1
  16. package/dist/routes/objects.d.ts +21 -4
  17. package/dist/routes/objects.d.ts.map +1 -1
  18. package/dist/routes/project.d.ts +2 -0
  19. package/dist/routes/project.d.ts.map +1 -1
  20. package/dist/routes/workflows.d.ts +3 -0
  21. package/dist/routes/workflows.d.ts.map +1 -1
  22. package/dist/routes/ws/events.d.ts.map +1 -1
  23. package/dist/routes/ws/subscription-hub.d.ts +5 -0
  24. package/dist/routes/ws/subscription-hub.d.ts.map +1 -1
  25. package/dist/schemas/agents.d.ts +222 -123
  26. package/dist/schemas/agents.d.ts.map +1 -1
  27. package/dist/schemas/ai-accounting.d.ts +10 -10
  28. package/dist/schemas/auth.d.ts +7 -0
  29. package/dist/schemas/auth.d.ts.map +1 -1
  30. package/dist/schemas/common.d.ts +8 -0
  31. package/dist/schemas/common.d.ts.map +1 -1
  32. package/dist/schemas/datasets.d.ts +18 -3
  33. package/dist/schemas/datasets.d.ts.map +1 -1
  34. package/dist/schemas/event-payloads.d.ts +39 -0
  35. package/dist/schemas/event-payloads.d.ts.map +1 -1
  36. package/dist/schemas/files.d.ts +1 -1
  37. package/dist/schemas/files.d.ts.map +1 -1
  38. package/dist/schemas/models.d.ts +10 -0
  39. package/dist/schemas/models.d.ts.map +1 -1
  40. package/dist/schemas/objects.d.ts +32 -0
  41. package/dist/schemas/objects.d.ts.map +1 -1
  42. package/dist/schemas/project.d.ts +8 -0
  43. package/dist/schemas/project.d.ts.map +1 -1
  44. package/dist/schemas/workflows.d.ts +17 -0
  45. package/dist/schemas/workflows.d.ts.map +1 -1
  46. package/dist/server.d.ts.map +1 -1
  47. package/package.json +6 -5
  48. package/src/auth/experience.ts +20 -2
  49. package/src/files/content.ts +43 -88
  50. package/src/routes/agents.ts +29 -9
  51. package/src/routes/auth.ts +84 -19
  52. package/src/routes/datasets.ts +12 -43
  53. package/src/routes/files.ts +3 -1
  54. package/src/routes/models.ts +3 -0
  55. package/src/routes/objects.ts +12 -2
  56. package/src/routes/project.ts +2 -1
  57. package/src/routes/workflows.ts +5 -0
  58. package/src/routes/ws/events.ts +5 -3
  59. package/src/routes/ws/subscription-hub.ts +20 -5
  60. package/src/schemas/agents.ts +28 -3
  61. package/src/schemas/auth.ts +5 -0
  62. package/src/schemas/common.ts +3 -0
  63. package/src/schemas/datasets.ts +23 -1
  64. package/src/schemas/event-payloads.ts +3 -1
  65. package/src/schemas/files.ts +7 -1
  66. package/src/schemas/models.ts +2 -0
  67. package/src/schemas/objects.ts +13 -0
  68. package/src/schemas/project.ts +4 -0
  69. package/src/server.ts +2 -1
package/dist/index.js CHANGED
@@ -1170,8 +1170,13 @@ import { z as z5 } from "zod";
1170
1170
 
1171
1171
  // src/files/content.ts
1172
1172
  import { createHash as createHash2 } from "crypto";
1173
- import { isFileRef } from "@sixb/core";
1173
+ import { fileNameFor } from "@sixb/core";
1174
1174
  import { BlobStorageError, supportsRangeRead } from "@sixb/core/blob-storage/server";
1175
+ import {
1176
+ canonicalMediaType,
1177
+ resolveFileRefAtPath,
1178
+ statFileRef
1179
+ } from "@sixb/core/internal/blob-storage";
1175
1180
  import { ZodError } from "zod";
1176
1181
  var unconfiguredStorageResponse = {
1177
1182
  501: {
@@ -1266,8 +1271,8 @@ function fileContentHeadResponses(options = {}) {
1266
1271
  };
1267
1272
  }
1268
1273
  async function createFileContentResponse(input) {
1269
- const stat = await input.blobStorage.stat(input.fileRef.blobId);
1270
- if (!stat || !blobMatchesFileRef(stat, input.fileRef)) {
1274
+ const stat = await statFileRef(input.blobStorage, input.fileRef);
1275
+ if (!stat) {
1271
1276
  return null;
1272
1277
  }
1273
1278
  const canReadRange = supportsRangeRead(input.blobStorage);
@@ -1346,58 +1351,36 @@ async function createContextualFileContentResponse(input) {
1346
1351
  throw error;
1347
1352
  }
1348
1353
  }
1349
- function resolveFileRefAtPath(root, path) {
1350
- const value = resolveJsonPointer(root, path);
1351
- return isFileRef(value) ? value : null;
1352
- }
1353
1354
  function fileContentNotFound(set, message) {
1354
1355
  set.status = 404;
1355
1356
  return { error: message };
1356
1357
  }
1357
- function blobMatchesFileRef(stat, fileRef) {
1358
- return stat.blobId === fileRef.blobId && stat.digest === fileRef.digest && stat.sizeBytes === fileRef.sizeBytes;
1359
- }
1360
1358
  function matchesIfNoneMatch(header, etag) {
1361
1359
  return header?.trim() === "*" || (header?.split(",").some((value) => value.trim().replace(/^W\//, "") === etag) ?? false);
1362
1360
  }
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
- }
1361
+ var INLINE_MEDIA_TYPES = new Set([
1362
+ "application/json",
1363
+ "application/pdf",
1364
+ "image/avif",
1365
+ "image/bmp",
1366
+ "image/gif",
1367
+ "image/jpeg",
1368
+ "image/png",
1369
+ "image/webp",
1370
+ "text/markdown",
1371
+ "text/plain"
1372
+ ]);
1373
+ var FILE_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
1374
+ var PDF_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; object-src 'self'";
1394
1375
  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";
1376
+ const mediaType = canonicalMediaType(fileRef.mediaType) ?? "application/octet-stream";
1377
+ const baseType = mediaType.split(";", 1)[0];
1378
+ const disposition = (requestedDisposition ?? "inline") === "inline" && INLINE_MEDIA_TYPES.has(baseType) ? "inline" : "attachment";
1397
1379
  const headers = new Headers;
1398
1380
  headers.set("content-type", mediaType);
1399
1381
  headers.set("content-length", stat.sizeBytes.toString());
1400
1382
  headers.set("content-disposition", contentDispositionHeader(disposition, fileNameFor(fileRef)));
1383
+ headers.set("content-security-policy", baseType === "application/pdf" ? PDF_CONTENT_SECURITY_POLICY : FILE_CONTENT_SECURITY_POLICY);
1401
1384
  const representation = JSON.stringify([
1402
1385
  fileRef.digest,
1403
1386
  mediaType,
@@ -1463,24 +1446,6 @@ function rangeNotSatisfiableResponse(sizeBytes) {
1463
1446
  headers.set("content-range", `bytes */${sizeBytes}`);
1464
1447
  return new Response(null, { status: 416, headers });
1465
1448
  }
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
1449
  function contentDispositionHeader(disposition, fileName) {
1485
1450
  const asciiFileName = fileName.replace(/[^\x20-\x7e]/g, "_").replaceAll('"', "'");
1486
1451
  return `${disposition}; filename="${asciiFileName}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
@@ -1503,6 +1468,7 @@ function codedErrorResponseSchema(codes) {
1503
1468
  code: z.enum(codes).describe("Stable machine-readable failure code for programmatic handling.")
1504
1469
  });
1505
1470
  }
1471
+ var RedactionsSchema = z.record(z.object({ reason: z.literal("missing_clearance") }));
1506
1472
  var SuccessResponseSchema = z.object({ success: z.boolean() });
1507
1473
  var PrincipalSchema = z.object({
1508
1474
  type: z.enum(["user", "serviceAccount", "system"]),
@@ -1768,6 +1734,7 @@ var ActionRunListResponseSchema = z3.object({
1768
1734
  });
1769
1735
 
1770
1736
  // src/schemas/files.ts
1737
+ import { canonicalMediaType as canonicalMediaType2 } from "@sixb/core/internal/blob-storage";
1771
1738
  import { z as z4 } from "zod";
1772
1739
  var BlobDigestSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
1773
1740
  var FileRefSchema = z4.object({
@@ -1780,7 +1747,9 @@ var FileRefSchema = z4.object({
1780
1747
  });
1781
1748
  var CreateFileUploadBodySchema = z4.object({
1782
1749
  fileName: z4.string().optional(),
1783
- mediaType: z4.string().optional(),
1750
+ mediaType: z4.string().refine((value) => canonicalMediaType2(value) !== null, {
1751
+ message: 'Expected a single media type, such as "application/pdf"'
1752
+ }).optional(),
1784
1753
  sizeBytes: z4.number().int().nonnegative().optional(),
1785
1754
  digest: BlobDigestSchema.optional(),
1786
1755
  logicalPath: z4.string().optional()
@@ -2276,6 +2245,7 @@ import {
2276
2245
  SYSTEM_PRINCIPAL
2277
2246
  } from "@sixb/core";
2278
2247
  import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
2248
+ import { canonicalMediaType as canonicalMediaType3 } from "@sixb/core/internal/blob-storage";
2279
2249
  import { createFileUploadId, createUploadExpiresAt } from "@sixb/core/internal/storage";
2280
2250
  import { FileUploadSessionError as FileUploadSessionError2 } from "@sixb/core/storage";
2281
2251
  var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
@@ -2308,7 +2278,7 @@ function registerFileRoutes(app, host) {
2308
2278
  const fileRef = await host.blobStorage.put({
2309
2279
  body: file,
2310
2280
  fileName: file.name || undefined,
2311
- mediaType: file.type || undefined,
2281
+ mediaType: canonicalMediaType3(file.type) ?? undefined,
2312
2282
  logicalPath: logicalPath ?? undefined
2313
2283
  });
2314
2284
  return FileRefSchema.parse(fileRef);
@@ -3031,9 +3001,16 @@ class PayloadTooLargeError extends Error {
3031
3001
  }
3032
3002
 
3033
3003
  // src/routes/agents.ts
3034
- import { AgentRequestError } from "@sixb/core";
3035
- import { publishAgentRunCancel, publishAgentRunFinished } from "@sixb/core/internal/agents";
3004
+ import {
3005
+ AgentRequestError
3006
+ } from "@sixb/core";
3007
+ import {
3008
+ isRetryableAgentRun,
3009
+ publishAgentRunCancel,
3010
+ publishAgentRunFinished
3011
+ } from "@sixb/core/internal/agents";
3036
3012
  import { agentRunStreamId } from "@sixb/core/internal/agents/streams";
3013
+ import { resolveFileRefAtPath as resolveFileRefAtPath2 } from "@sixb/core/internal/blob-storage";
3037
3014
  import {
3038
3015
  AgentStorageError
3039
3016
  } from "@sixb/core/storage";
@@ -3041,6 +3018,7 @@ import { ZodError as ZodError2, z as z10 } from "zod";
3041
3018
 
3042
3019
  // src/schemas/agents.ts
3043
3020
  import { MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core";
3021
+ import { MAX_AGENT_CONTEXT_LABEL_LENGTH } from "@sixb/core/agents/context";
3044
3022
  import {
3045
3023
  AGENT_RUN_DIAGNOSTIC_CODES,
3046
3024
  AGENT_RUN_FAILURE_CODES,
@@ -3092,7 +3070,8 @@ var LanguageModelSchema = LanguageModelRefSchema.extend({
3092
3070
  structuredOutput: z7.boolean().optional(),
3093
3071
  contextWindowTokens: z7.number().int().positive().optional()
3094
3072
  }),
3095
- reasoningLevels: z7.array(z7.enum(MODEL_REASONING_LEVELS))
3073
+ reasoningLevels: z7.array(z7.enum(MODEL_REASONING_LEVELS)),
3074
+ defaultReasoning: z7.enum(MODEL_REASONING_LEVELS).optional()
3096
3075
  });
3097
3076
  var ModelCatalogSchema = z7.object({
3098
3077
  language: z7.array(LanguageModelSchema)
@@ -3359,7 +3338,8 @@ var AgentObjectContextSchema = z9.object({
3359
3338
  ref: z9.object({
3360
3339
  objectTypeId: z9.string().min(1),
3361
3340
  primaryId: z9.string().min(1)
3362
- })
3341
+ }),
3342
+ 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
3343
  });
3364
3344
  var AgentAppStateContextSchema = z9.object({
3365
3345
  kind: z9.literal("app-state"),
@@ -3463,8 +3443,12 @@ var AgentToolCallErrorSchema = AgentToolCallBaseSchema.extend({
3463
3443
  state: z9.literal("output-error"),
3464
3444
  errorText: z9.string()
3465
3445
  });
3446
+ var AgentContinuationPartSchema = z9.object({
3447
+ type: z9.literal("continuation")
3448
+ });
3466
3449
  var AgentMessagePartSchema = z9.union([
3467
3450
  AgentTextPartSchema,
3451
+ AgentContinuationPartSchema,
3468
3452
  AgentReasoningPartSchema,
3469
3453
  AgentStepStartPartSchema,
3470
3454
  AgentFilePartSchema,
@@ -3476,7 +3460,7 @@ var AgentMessagePartSchema = z9.union([
3476
3460
  var AgentRunDiagnosticSchema = z9.object({
3477
3461
  code: z9.enum(AGENT_RUN_DIAGNOSTIC_CODES),
3478
3462
  severity: z9.enum(["warning", "error"]),
3479
- scope: z9.literal("output"),
3463
+ scope: z9.enum(["output", "run"]),
3480
3464
  path: z9.string().optional(),
3481
3465
  message: z9.string()
3482
3466
  });
@@ -3513,13 +3497,19 @@ var AgentMessageListResponseSchema = z9.object({
3513
3497
  total: z9.number()
3514
3498
  });
3515
3499
  var PostAgentMessageBodySchema = z9.object({
3516
- text: z9.string().trim().min(1),
3500
+ text: z9.string().trim().min(1).optional(),
3501
+ continue: z9.literal(true).optional(),
3517
3502
  model: LanguageModelRefSchema.optional(),
3518
3503
  reasoning: ModelReasoningSchema.optional(),
3504
+ timeZone: z9.string().trim().min(1).max(100).optional(),
3505
+ locale: z9.string().trim().min(1).max(100).optional(),
3519
3506
  attachments: z9.array(FileRefSchema).optional(),
3520
3507
  context: z9.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
3521
3508
  messageId: z9.string().trim().min(1).optional()
3522
3509
  }).strict();
3510
+ var AgentRequestErrorResponseSchema = ErrorResponseSchema.extend({
3511
+ code: z9.string().optional()
3512
+ });
3523
3513
  var CancelAgentRunBodySchema = z9.object({
3524
3514
  runId: z9.string().trim().min(1)
3525
3515
  });
@@ -3691,12 +3681,15 @@ function handleAgentRouteError(error, set) {
3691
3681
  case "invalid_sandbox_params":
3692
3682
  case "agent_selector_removed":
3693
3683
  case "invalid_context":
3684
+ case "invalid_attachment":
3694
3685
  case "invalid_model_selection":
3686
+ case "invalid_locale":
3687
+ case "invalid_message":
3695
3688
  case "model_not_found":
3696
3689
  set.status = 400;
3697
3690
  break;
3698
3691
  }
3699
- return { error: error.message };
3692
+ return { error: error.message, code: error.code };
3700
3693
  }
3701
3694
  return handleRouteError(error, set);
3702
3695
  }
@@ -3729,7 +3722,7 @@ async function agentMessageFileContentResponse(host, context, options = {}) {
3729
3722
  context.set.status = 404;
3730
3723
  return { error: "File not found" };
3731
3724
  }
3732
- const fileRef = resolveFileRefAtPath(serializeMessage(message), parsed.path);
3725
+ const fileRef = resolveFileRefAtPath2(serializeMessage(message), parsed.path);
3733
3726
  if (!fileRef) {
3734
3727
  context.set.status = 404;
3735
3728
  return { error: "File not found" };
@@ -3986,8 +3979,11 @@ function registerAgentRoutes(app, host) {
3986
3979
  const requestInput = {
3987
3980
  threadId: thread.id,
3988
3981
  text: parsed.text,
3982
+ continue: parsed.continue,
3989
3983
  model: parsed.model,
3990
3984
  reasoning: parsed.reasoning,
3985
+ timeZone: parsed.timeZone,
3986
+ locale: parsed.locale,
3991
3987
  attachments: parsed.attachments,
3992
3988
  context: parsed.context,
3993
3989
  messageId: parsed.messageId
@@ -4005,7 +4001,7 @@ function registerAgentRoutes(app, host) {
4005
4001
  body: PostAgentMessageBodySchema,
4006
4002
  response: {
4007
4003
  202: PostAgentMessageResponseSchema,
4008
- 400: ErrorResponseSchema,
4004
+ 400: AgentRequestErrorResponseSchema,
4009
4005
  403: ErrorResponseSchema,
4010
4006
  404: ErrorResponseSchema,
4011
4007
  409: ErrorResponseSchema,
@@ -4117,9 +4113,9 @@ function registerAgentRoutes(app, host) {
4117
4113
  set.status = 404;
4118
4114
  return { error: "Agent run not found" };
4119
4115
  }
4120
- if (failedRun.status !== "failed") {
4116
+ if (!isRetryableAgentRun(failedRun)) {
4121
4117
  set.status = 409;
4122
- return { error: "Only failed agent runs can be retried" };
4118
+ return { error: "Only failed or interrupted agent runs can be retried" };
4123
4119
  }
4124
4120
  const { run } = await sixb.agent.runs.retry(failedRun.id);
4125
4121
  set.status = 202;
@@ -4140,7 +4136,7 @@ function registerAgentRoutes(app, host) {
4140
4136
  501: ErrorResponseSchema
4141
4137
  },
4142
4138
  detail: {
4143
- summary: "Retry a failed agent run",
4139
+ summary: "Retry a failed or interrupted agent run",
4144
4140
  tags: [OPENAPI_TAGS.agentRuns.name],
4145
4141
  operationId: "retryAgentRun",
4146
4142
  security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
@@ -5462,9 +5458,18 @@ var DatasetVersionParamsSchema = DatasetParamsSchema.extend({
5462
5458
  var DatasetVersionsQuerySchema = z13.object({
5463
5459
  limit: z13.string().optional()
5464
5460
  });
5461
+ var QueryStringListSchema = z13.preprocess(flattenQueryStringList, z13.array(z13.string()));
5462
+ function flattenQueryStringList(value) {
5463
+ if (typeof value !== "string" && !Array.isArray(value))
5464
+ return value;
5465
+ const items = [value].flat(Number.POSITIVE_INFINITY);
5466
+ if (!items.every((item) => typeof item === "string"))
5467
+ return value;
5468
+ return items.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
5469
+ }
5465
5470
  var DatasetRowsQuerySchema = z13.object({
5466
5471
  versionId: z13.string().optional(),
5467
- columns: z13.string().optional(),
5472
+ columns: QueryStringListSchema.optional(),
5468
5473
  limit: z13.string().optional(),
5469
5474
  offset: z13.string().optional()
5470
5475
  });
@@ -5540,6 +5545,7 @@ var DatasetRowsResponseSchema = z13.object({
5540
5545
  versionId: z13.string(),
5541
5546
  version: DatasetVersionSchema,
5542
5547
  columns: z13.array(z13.string()),
5548
+ redactions: RedactionsSchema.optional(),
5543
5549
  rows: z13.array(z13.record(z13.unknown())),
5544
5550
  count: z13.number(),
5545
5551
  limit: z13.number(),
@@ -5668,22 +5674,6 @@ function datasetVersionNotFound(datasetId, versionId) {
5668
5674
  details: { datasetId, ...versionId === undefined ? {} : { versionId } }
5669
5675
  });
5670
5676
  }
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
5677
  async function collectRows(rows) {
5688
5678
  const collected = [];
5689
5679
  for await (const row of rows) {
@@ -5789,29 +5779,28 @@ function registerDatasetRoutes(app, host) {
5789
5779
  const { params, query, set } = context;
5790
5780
  const sixb = requireRequestSixb(context);
5791
5781
  try {
5792
- requireDataset(sixb, params.datasetId);
5782
+ const dataset = requireDataset(sixb, params.datasetId);
5793
5783
  const parsed = DatasetRowsQuerySchema.parse(query);
5794
5784
  const limit = parseLimit(parsed.limit, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT);
5795
5785
  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,
5786
+ const page = await sixb.datasets.readRows(dataset, {
5787
+ versionId: parsed.versionId,
5788
+ columns: parsed.columns?.length ? parsed.columns : undefined,
5806
5789
  limit,
5807
5790
  offset
5808
- }));
5791
+ });
5792
+ if (!page) {
5793
+ throw datasetVersionNotFound(params.datasetId, parsed.versionId);
5794
+ }
5795
+ const { version, columns, redactions } = page;
5796
+ const rows = await collectRows(page.rows);
5809
5797
  const hasMore = version.rowCount === undefined ? rows.length === limit : offset + rows.length < version.rowCount;
5810
5798
  return DatasetRowsResponseSchema.parse({
5811
5799
  datasetId: params.datasetId,
5812
5800
  versionId: version.versionId,
5813
5801
  version: serializeDatasetVersion(version),
5814
5802
  columns: [...columns],
5803
+ ...redactions === undefined ? {} : { redactions },
5815
5804
  rows,
5816
5805
  count: rows.length,
5817
5806
  limit,
@@ -5870,12 +5859,14 @@ var ObjectMutationPayloadSchema = z14.object({
5870
5859
  objectTypeId: z14.string(),
5871
5860
  primaryId: z14.string(),
5872
5861
  properties: z14.record(JsonValueSchema),
5873
- propertyChanges: PropertyChangesSchema
5862
+ propertyChanges: PropertyChangesSchema,
5863
+ redactions: RedactionsSchema.optional()
5874
5864
  });
5875
5865
  var ObjectDeletedPayloadSchema = z14.object({
5876
5866
  objectTypeId: z14.string(),
5877
5867
  primaryId: z14.string(),
5878
- propertyChanges: PropertyChangesSchema
5868
+ propertyChanges: PropertyChangesSchema,
5869
+ redactions: RedactionsSchema.optional()
5879
5870
  });
5880
5871
  var LinkSubjectSchema = z14.object({
5881
5872
  sourceTypeId: z14.string(),
@@ -6356,7 +6347,8 @@ async function serializeLanguageModel(entry, defaultEntry) {
6356
6347
  ...await languageModelDisplay(entry),
6357
6348
  provider: entry.provider,
6358
6349
  modelId: entry.modelId,
6359
- isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId
6350
+ isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId,
6351
+ ...entry.model.defaultReasoning === undefined ? {} : { defaultReasoning: entry.model.defaultReasoning }
6360
6352
  };
6361
6353
  }
6362
6354
  function registerModelRoutes(app, host) {
@@ -6616,6 +6608,7 @@ var TwinObjectSchema = z18.object({
6616
6608
  primaryId: z18.string(),
6617
6609
  objectTypeId: z18.string(),
6618
6610
  properties: z18.record(z18.unknown()),
6611
+ redactions: RedactionsSchema.optional(),
6619
6612
  createdAt: z18.string(),
6620
6613
  updatedAt: z18.string()
6621
6614
  });
@@ -6643,6 +6636,15 @@ var ObjectQueryOpenApiSchemas = {
6643
6636
  error: { type: "string" }
6644
6637
  }
6645
6638
  },
6639
+ Redactions: {
6640
+ type: "object",
6641
+ additionalProperties: {
6642
+ type: "object",
6643
+ required: ["reason"],
6644
+ additionalProperties: false,
6645
+ properties: { reason: { type: "string", enum: ["missing_clearance"] } }
6646
+ }
6647
+ },
6646
6648
  ObjectQueryObject: {
6647
6649
  type: "object",
6648
6650
  required: ["primaryId", "objectTypeId", "properties", "createdAt", "updatedAt"],
@@ -6652,6 +6654,7 @@ var ObjectQueryOpenApiSchemas = {
6652
6654
  primaryId: { type: "string" },
6653
6655
  objectTypeId: { type: "string" },
6654
6656
  properties: { type: "object", additionalProperties: true },
6657
+ redactions: { $ref: "#/components/schemas/Redactions" },
6655
6658
  createdAt: { type: "string" },
6656
6659
  updatedAt: { type: "string" },
6657
6660
  links: {
@@ -7168,6 +7171,7 @@ function serializeObject(row) {
7168
7171
  primaryId: row.primaryId,
7169
7172
  objectTypeId: row.objectTypeId,
7170
7173
  properties: row.properties,
7174
+ ...row.redactions === undefined ? {} : { redactions: row.redactions },
7171
7175
  createdAt: toIsoString(row.createdAt),
7172
7176
  updatedAt: toIsoString(row.updatedAt)
7173
7177
  };
@@ -7284,8 +7288,14 @@ async function searchObjects(host, sixb, query, limit) {
7284
7288
  input: { kind: "start", objectTypeId: objectType.id }
7285
7289
  }
7286
7290
  };
7287
- const result = await sixb.objects.executeQuery({ query: objectQuery });
7288
- return result.objects;
7291
+ try {
7292
+ const result = await sixb.objects.executeQuery({ query: objectQuery });
7293
+ return result.objects;
7294
+ } catch (error) {
7295
+ if (error instanceof AuthorizationError3)
7296
+ return [];
7297
+ throw error;
7298
+ }
7289
7299
  }));
7290
7300
  const items = new Map;
7291
7301
  for (const row of [...primaryMatches.objects, ...textMatches.flat()]) {
@@ -8286,12 +8296,15 @@ function registerPipelineRoutes(app, host) {
8286
8296
  // src/schemas/project.ts
8287
8297
  import { z as z21 } from "zod";
8288
8298
  var ProjectInfoResponseSchema = z21.object({
8289
- id: z21.string()
8299
+ id: z21.string(),
8300
+ locale: z21.string(),
8301
+ timeZone: z21.string()
8290
8302
  });
8291
8303
 
8292
8304
  // src/routes/project.ts
8293
8305
  function registerProjectRoutes(app, host) {
8294
- return app.get("/api/project", async () => ({ id: host.id }), {
8306
+ const project = { id: host.id, locale: host.locale, timeZone: host.timeZone };
8307
+ return app.get("/api/project", async () => project, {
8295
8308
  response: { 200: ProjectInfoResponseSchema },
8296
8309
  detail: {
8297
8310
  summary: "Get current project metadata",
@@ -9803,6 +9816,7 @@ import {
9803
9816
  } from "@sixb/core";
9804
9817
  import { publishAgentRunCancel as publishAgentRunCancel2 } from "@sixb/core/internal/agents";
9805
9818
  import { createSixbError as createSixbError4, toSixbFailure } from "@sixb/core/internal/errors";
9819
+ import { assertValidFileRefs } from "@sixb/core/internal/ontology";
9806
9820
  import {
9807
9821
  snapshotWorkflowInterventionResponse
9808
9822
  } from "@sixb/core/internal/workflows";
@@ -10516,6 +10530,7 @@ function registerWorkflowRoutes(app, host) {
10516
10530
  value: parsedBody.response,
10517
10531
  valueTypesById: host.definitions.ontology.getValueTypesById()
10518
10532
  });
10533
+ assertValidFileRefs(parsedBody.response, `Workflow "${workflow.id}" intervention "${node.intervention.id}" response`);
10519
10534
  const submitted = await storage.submit({
10520
10535
  projectId: host.id,
10521
10536
  id: intervention.id,
@@ -11126,7 +11141,8 @@ async function customAuthExperienceResponse(options, input) {
11126
11141
  ...input.submission ? { submission: input.submission } : {}
11127
11142
  })).toString("base64url");
11128
11143
  const formAction = ["'self'", ...(input.formActionOrigins ?? []).map(normalizeCspOrigin)].join(" ");
11129
- return new Response(html.replace(AUTH_BOOTSTRAP_PLACEHOLDER, bootstrap), {
11144
+ const page = withDocumentLanguage(html.replace(AUTH_BOOTSTRAP_PLACEHOLDER, bootstrap), options.locale);
11145
+ return new Response(page, {
11130
11146
  status: input.status ?? 200,
11131
11147
  headers: {
11132
11148
  "content-type": "text/html; charset=utf-8",
@@ -11146,6 +11162,9 @@ async function customAuthExperienceResponse(options, input) {
11146
11162
  }
11147
11163
  });
11148
11164
  }
11165
+ function withDocumentLanguage(html, locale) {
11166
+ return html.replace(/<html\b([^>]*)>/i, (_tag, attributes) => `<html${attributes.replace(/\s+lang\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i, "")} lang="${locale}">`);
11167
+ }
11149
11168
  function normalizeCspOrigin(value) {
11150
11169
  let url;
11151
11170
  try {
@@ -11497,7 +11516,8 @@ var RevokeAuthInvitationResponseSchema = z32.object({
11497
11516
  });
11498
11517
  var AuthSessionResponseSchema = z32.union([
11499
11518
  z32.object({
11500
- authenticated: z32.literal(false)
11519
+ authenticated: z32.literal(false),
11520
+ authEnabled: z32.boolean()
11501
11521
  }),
11502
11522
  z32.object({
11503
11523
  authenticated: z32.literal(true),
@@ -11802,14 +11822,14 @@ function registerAuthRoutes(app, host, options) {
11802
11822
  credentialSource: "any"
11803
11823
  });
11804
11824
  if (!caller.authenticated || caller.credentialSource !== "session") {
11805
- return jsonResponse2({ authenticated: false }, 200);
11825
+ return signedOutSessionResponse(host);
11806
11826
  }
11807
11827
  if (caller.session.bearer) {
11808
11828
  return jsonResponse2(authSessionBody(host, caller, DEFAULT_AUTH_SESSION_AUDIENCE2), 200);
11809
11829
  }
11810
11830
  const session = hasForegroundSessionActivity(request) && sessionCanAccessApplication(host, caller, authOptions.audience) ? await host.auth.getSession(request, { ...authOptions, sessionActivity: "foreground" }) : caller;
11811
11831
  if (!session.authenticated) {
11812
- return jsonResponse2({ authenticated: false }, 200);
11832
+ return signedOutSessionResponse(host);
11813
11833
  }
11814
11834
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11815
11835
  const csrf = resolveSessionCsrfToken({
@@ -12013,7 +12033,7 @@ function registerAuthRoutes(app, host, options) {
12013
12033
  summary: "Create a personal access token",
12014
12034
  tags: [OPENAPI_TAGS.authAccessTokens.name],
12015
12035
  operationId: "createAuthPersonalAccessToken",
12016
- security: accessTokenSecurityRequirement("createAuthPersonalAccessToken")
12036
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12017
12037
  }
12018
12038
  }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
12019
12039
  try {
@@ -12185,7 +12205,7 @@ function registerAuthRoutes(app, host, options) {
12185
12205
  summary: "Create an access token for an auth service account",
12186
12206
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
12187
12207
  operationId: "createAuthServiceAccountAccessToken",
12188
- security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken")
12208
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12189
12209
  }
12190
12210
  }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
12191
12211
  try {
@@ -12492,9 +12512,10 @@ function registerAuthRoutes(app, host, options) {
12492
12512
  });
12493
12513
  const response = await magicLinkRequestedResponse(options, authRedirect);
12494
12514
  const existingPending = getCookie4(request, MAGIC_LINK_PENDING_COOKIE_NAME)?.trim();
12495
- response.headers.append("set-cookie", magicLinkPendingCookieHeader({
12515
+ response.headers.append("set-cookie", callbackCookieHeader({
12496
12516
  request,
12497
12517
  host,
12518
+ name: MAGIC_LINK_PENDING_COOKIE_NAME,
12498
12519
  value: result.status === "sent" ? pending.secret : existingPending || pending.secret,
12499
12520
  maxAgeSeconds: magicLinkPendingCookieMaxAgeSeconds(strategy)
12500
12521
  }));
@@ -12508,7 +12529,7 @@ function registerAuthRoutes(app, host, options) {
12508
12529
  returnTo: authRedirect.returnTo,
12509
12530
  requestOrigin: authRedirect.requestOrigin
12510
12531
  });
12511
- return redirectResponse(result.redirectTo);
12532
+ return oidcSignInRedirect(request, host, result);
12512
12533
  }
12513
12534
  return strategyNotImplementedResponse("Sign-in is not implemented yet.");
12514
12535
  }, {
@@ -12540,7 +12561,7 @@ function registerAuthRoutes(app, host, options) {
12540
12561
  returnTo: authRedirect.returnTo,
12541
12562
  requestOrigin: authRedirect.requestOrigin
12542
12563
  });
12543
- return redirectResponse(result.redirectTo);
12564
+ return oidcSignInRedirect(request, host, result);
12544
12565
  }
12545
12566
  return strategyNotImplementedResponse("Sign-in is not implemented yet.");
12546
12567
  }, { detail: { hide: true } }).get("/auth/callback", async ({ request }) => {
@@ -12596,7 +12617,12 @@ function registerAuthRoutes(app, host, options) {
12596
12617
  const now = new Date;
12597
12618
  const sessionCredential = createSessionCredential();
12598
12619
  const device = resolveSessionDevice(request);
12620
+ const state = new URL(request.url).searchParams.get("state");
12621
+ let response;
12599
12622
  try {
12623
+ if (!state || !matchesOidcStateCookie(request, state)) {
12624
+ throw new Error("[SixbServer] OIDC callback reached a browser that did not start this sign-in.");
12625
+ }
12600
12626
  const authOptions = resolveAuthOptions(options, request);
12601
12627
  const result = await strategy.completeOidcSignIn({
12602
12628
  projectId: host.id,
@@ -12612,7 +12638,7 @@ function registerAuthRoutes(app, host, options) {
12612
12638
  ...device
12613
12639
  }
12614
12640
  });
12615
- return sessionCallbackCompletionResponse({
12641
+ response = sessionCallbackCompletionResponse({
12616
12642
  host,
12617
12643
  request,
12618
12644
  apiOrigin: options.resolveAuthRequestOrigin(request),
@@ -12623,11 +12649,18 @@ function registerAuthRoutes(app, host, options) {
12623
12649
  });
12624
12650
  } catch (error) {
12625
12651
  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);
12652
+ response = error instanceof SignInRefusedError ? htmlMessageResponse(signInRefusalMessage(error), 403, "You can't sign in") : htmlMessageResponse("This sign-in attempt could not be completed.", 400);
12630
12653
  }
12654
+ if (state) {
12655
+ response.headers.append("set-cookie", callbackCookieHeader({
12656
+ request,
12657
+ host,
12658
+ name: oidcStateCookieName(state),
12659
+ value: "",
12660
+ maxAgeSeconds: 0
12661
+ }));
12662
+ }
12663
+ return response;
12631
12664
  }
12632
12665
  return strategyNotImplementedResponse("Auth callback is not implemented yet.");
12633
12666
  }, { detail: { hide: true } }).post("/auth/callback", async ({ body, request }) => {
@@ -12702,9 +12735,9 @@ function matchesMagicLinkRequester(pendingSecret, requesterHash) {
12702
12735
  const provided = Buffer.from(requesterHash);
12703
12736
  return expected.length === provided.length && timingSafeEqual(expected, provided);
12704
12737
  }
12705
- function magicLinkPendingCookieHeader(params) {
12738
+ function callbackCookieHeader(params) {
12706
12739
  const parts = [
12707
- `${MAGIC_LINK_PENDING_COOKIE_NAME}=${params.value}`,
12740
+ `${params.name}=${params.value}`,
12708
12741
  "Path=/auth/callback",
12709
12742
  "SameSite=Lax",
12710
12743
  "HttpOnly",
@@ -12745,9 +12778,10 @@ async function completeMagicLinkCallback(input) {
12745
12778
  returnTo: result.returnTo
12746
12779
  });
12747
12780
  if (input.clearPendingCookie) {
12748
- response.headers.append("set-cookie", magicLinkPendingCookieHeader({
12781
+ response.headers.append("set-cookie", callbackCookieHeader({
12749
12782
  request: input.request,
12750
12783
  host: input.host,
12784
+ name: MAGIC_LINK_PENDING_COOKIE_NAME,
12751
12785
  value: "",
12752
12786
  maxAgeSeconds: 0
12753
12787
  }));
@@ -12757,6 +12791,28 @@ async function completeMagicLinkCallback(input) {
12757
12791
  return await invalidMagicLinkResponse(input.options, input.authRedirectHint);
12758
12792
  }
12759
12793
  }
12794
+ function oidcStateCookieName(state) {
12795
+ return `sixb_oidc_${createHash3("sha256").update(state).digest("base64url").slice(0, 22)}`;
12796
+ }
12797
+ function oidcSignInRedirect(request, host, result) {
12798
+ const response = redirectResponse(result.redirectTo);
12799
+ response.headers.append("set-cookie", callbackCookieHeader({
12800
+ request,
12801
+ host,
12802
+ name: oidcStateCookieName(result.state),
12803
+ value: encodeURIComponent(result.state),
12804
+ maxAgeSeconds: Math.max(0, Math.floor((result.expiresAt.getTime() - Date.now()) / 1000))
12805
+ }));
12806
+ return response;
12807
+ }
12808
+ function matchesOidcStateCookie(request, state) {
12809
+ const held = getCookie4(request, oidcStateCookieName(state));
12810
+ if (!held)
12811
+ return false;
12812
+ const expected = Buffer.from(encodeURIComponent(state));
12813
+ const provided = Buffer.from(held);
12814
+ return expected.length === provided.length && timingSafeEqual(expected, provided);
12815
+ }
12760
12816
  function bearerTokensBody(tokens, bearer, issuedAt) {
12761
12817
  return {
12762
12818
  accessToken: tokens.accessToken,
@@ -12872,6 +12928,9 @@ function authSessionBody(host, session, audience) {
12872
12928
  session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) }
12873
12929
  };
12874
12930
  }
12931
+ function signedOutSessionResponse(host) {
12932
+ return jsonResponse2({ authenticated: false, authEnabled: host.auth.isEnabled() }, 200);
12933
+ }
12875
12934
  function authSessionJsonResponse(body, setCookies) {
12876
12935
  const headers = new Headers({
12877
12936
  "content-type": "application/json; charset=utf-8",
@@ -14145,12 +14204,13 @@ class SubscriptionHub {
14145
14204
  deliverLive(records) {
14146
14205
  for (const state of this.clients.values()) {
14147
14206
  for (const record of records) {
14148
- if (!state.subscription.matches(record))
14207
+ const visible = visibleRecord(state.subscription, record);
14208
+ if (!visible)
14149
14209
  continue;
14150
14210
  if (state.catchingUp)
14151
- this.enqueuePendingLive(state, record);
14211
+ this.enqueuePendingLive(state, visible);
14152
14212
  else
14153
- this.enqueue(state, record);
14213
+ this.enqueue(state, visible);
14154
14214
  }
14155
14215
  }
14156
14216
  }
@@ -14166,9 +14226,10 @@ class SubscriptionHub {
14166
14226
  if (state.pendingCursors.has(record.cursor)) {
14167
14227
  state.replayedPendingCursors.add(record.cursor);
14168
14228
  }
14169
- if (!state.subscription.matches(record))
14229
+ const visible = visibleRecord(state.subscription, record);
14230
+ if (!visible)
14170
14231
  continue;
14171
- if (!await this.enqueueReplay(state, record))
14232
+ if (!await this.enqueueReplay(state, visible))
14172
14233
  return;
14173
14234
  }
14174
14235
  if (state.closed)
@@ -14319,6 +14380,11 @@ class SubscriptionHub {
14319
14380
  } catch {}
14320
14381
  }
14321
14382
  }
14383
+ function visibleRecord(subscription, record) {
14384
+ if (!subscription.matches(record))
14385
+ return;
14386
+ return subscription.view ? subscription.view(record) : record;
14387
+ }
14322
14388
  function hasQueueCapacity(state, bytes) {
14323
14389
  return state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS && state.queuedBytes + state.pendingBytes + bytes <= MAX_CLIENT_BYTES;
14324
14390
  }
@@ -14439,7 +14505,8 @@ function registerEventStreamRoutes(app, server) {
14439
14505
  state.replayFrom = null;
14440
14506
  try {
14441
14507
  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),
14508
+ matches: (event) => (!filter.topic || event.topic === filter.topic) && (!filter.types?.length || filter.types.includes(event.type)) && eventMatchesScope(event, filter),
14509
+ view: (event) => sixb.events.readable(event),
14443
14510
  replay: replayFrom ? {
14444
14511
  afterCursor: replayFrom.afterCursor,
14445
14512
  read: async (afterCursor) => {
@@ -14923,12 +14990,13 @@ function createSixbApi(server) {
14923
14990
  })
14924
14991
  }
14925
14992
  }));
14993
+ const authExperience = server.getAuthExperience();
14926
14994
  registerAuthRoutes(app, host, {
14927
14995
  resolveAuthContext: (request) => server.resolveAuthContext(request),
14928
14996
  resolveAuthRedirectContext: (request, input) => server.resolveAuthRedirectContext(request, input),
14929
14997
  getInvitationDestinationOptions: (request) => server.getInvitationDestinationOptions(request),
14930
14998
  resolveAuthRequestOrigin: (request) => server.resolveAuthRequestOrigin(request),
14931
- authExperience: server.getAuthExperience(),
14999
+ authExperience: authExperience && { ...authExperience, locale: host.locale },
14932
15000
  resolveInvitationRedirectContext: (request, input) => server.resolveInvitationRedirectContext(request, input)
14933
15001
  });
14934
15002
  registerHttpRoutes(app, host, {
@@ -15028,4 +15096,4 @@ export {
15028
15096
  createSixbServer
15029
15097
  };
15030
15098
 
15031
- //# debugId=A2358A8A15C4EC4564756E2164756E21
15099
+ //# debugId=D65B0A82168FF4ED64756E2164756E21