@sixb/server 0.1.0 → 0.1.1

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 (49) hide show
  1. package/dist/auth/scope.d.ts +8 -0
  2. package/dist/auth/scope.d.ts.map +1 -1
  3. package/dist/files/content.d.ts +11 -0
  4. package/dist/files/content.d.ts.map +1 -1
  5. package/dist/index.js +2114 -2080
  6. package/dist/index.js.map +14 -14
  7. package/dist/routes/action-runs.d.ts.map +1 -1
  8. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  9. package/dist/routes/agents.d.ts +21 -21
  10. package/dist/routes/auth.d.ts +6 -6
  11. package/dist/routes/datasets.d.ts +7 -5
  12. package/dist/routes/datasets.d.ts.map +1 -1
  13. package/dist/routes/events.d.ts +1 -1
  14. package/dist/routes/files.d.ts.map +1 -1
  15. package/dist/routes/links.d.ts.map +1 -1
  16. package/dist/routes/logs.d.ts +2 -2
  17. package/dist/routes/ontology.d.ts +24 -24
  18. package/dist/routes/pipelines.d.ts +4 -0
  19. package/dist/routes/pipelines.d.ts.map +1 -1
  20. package/dist/routes/syncs.d.ts +7 -5
  21. package/dist/routes/syncs.d.ts.map +1 -1
  22. package/dist/routes/workflows.d.ts +61 -62
  23. package/dist/routes/workflows.d.ts.map +1 -1
  24. package/dist/routes/ws/logs.d.ts +10 -10
  25. package/dist/schemas/agents.d.ts +84 -84
  26. package/dist/schemas/auth.d.ts +26 -26
  27. package/dist/schemas/datasets.d.ts +27 -21
  28. package/dist/schemas/datasets.d.ts.map +1 -1
  29. package/dist/schemas/events.d.ts +10 -10
  30. package/dist/schemas/logs.d.ts +18 -18
  31. package/dist/schemas/ontology.d.ts +88 -88
  32. package/dist/schemas/pipelines.d.ts +36 -0
  33. package/dist/schemas/pipelines.d.ts.map +1 -1
  34. package/dist/schemas/syncs.d.ts +23 -16
  35. package/dist/schemas/syncs.d.ts.map +1 -1
  36. package/dist/schemas/workflows.d.ts +299 -246
  37. package/dist/schemas/workflows.d.ts.map +1 -1
  38. package/package.json +8 -5
  39. package/src/auth/scope.ts +16 -2
  40. package/src/files/content.ts +11 -0
  41. package/src/routes/action-runs.ts +10 -3
  42. package/src/routes/agent-api-gateway.ts +46 -4
  43. package/src/routes/files.ts +2 -1
  44. package/src/routes/links.ts +1 -0
  45. package/src/routes/workflows.ts +39 -16
  46. package/src/schemas/datasets.ts +3 -2
  47. package/src/schemas/pipelines.ts +1 -25
  48. package/src/schemas/syncs.ts +3 -2
  49. package/src/schemas/workflows.ts +27 -20
package/dist/index.js CHANGED
@@ -521,8 +521,18 @@ function consumeInternalRequestAuthState(request) {
521
521
  return authState;
522
522
  }
523
523
  function requestAuthState(context) {
524
- const { authz = null, scoped = null, agentRun } = context;
525
- return { authz, scoped, ...agentRun === undefined ? {} : { agentRun } };
524
+ const {
525
+ authz = null,
526
+ scoped = null,
527
+ agentRun,
528
+ agentExecution
529
+ } = context;
530
+ return {
531
+ authz,
532
+ scoped,
533
+ ...agentRun === undefined ? {} : { agentRun },
534
+ ...agentExecution === undefined ? {} : { agentExecution }
535
+ };
526
536
  }
527
537
 
528
538
  // src/auth/session-cookies.ts
@@ -730,6 +740,12 @@ var unconfiguredStorageResponse = {
730
740
  }
731
741
  }
732
742
  };
743
+ function handleFileContentQueryValidationError(context) {
744
+ if (context.code !== "VALIDATION" || context.error.type !== "query")
745
+ return;
746
+ context.set.status = 400;
747
+ return { error: "Invalid file content query" };
748
+ }
733
749
  function fileContentGetResponses(options = {}) {
734
750
  return {
735
751
  200: {
@@ -1410,7 +1426,7 @@ function fileUploadSessionErrorStatus(reason) {
1410
1426
 
1411
1427
  // src/routes/action-runs.ts
1412
1428
  var ActionRunFileContentQuerySchema = FileContentQuerySchema.extend({
1413
- path: z5.string().min(1).regex(/^\/params(?:\/|$)/, "Action run file content paths must start with /params/")
1429
+ path: z5.string().min(1).regex(/^\/(?:params|writeback\/result)(?:\/|$)/, "Action run file content paths must start with /params/ or /writeback/result/")
1414
1430
  });
1415
1431
  function serializeActionRunSummary(run) {
1416
1432
  return ActionRunSummarySchema.parse({
@@ -1511,7 +1527,8 @@ function registerActionRunRoutes(app, sixb) {
1511
1527
  detail: {
1512
1528
  summary: "List action run history",
1513
1529
  tags: [OPENAPI_TAGS.actionRuns.name],
1514
- operationId: "listActionRuns"
1530
+ operationId: "listActionRuns",
1531
+ security: bearerSecurityRequirement("listActionRuns")
1515
1532
  }
1516
1533
  }).get("/api/action-runs/:runId", async (context) => {
1517
1534
  const { params, set } = context;
@@ -1546,7 +1563,8 @@ function registerActionRunRoutes(app, sixb) {
1546
1563
  }
1547
1564
  }).get("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(sixb, context), {
1548
1565
  params: ActionRunIdParamsSchema,
1549
- query: FileContentQuerySchema,
1566
+ query: ActionRunFileContentQuerySchema,
1567
+ error: handleFileContentQueryValidationError,
1550
1568
  detail: {
1551
1569
  summary: "Get action run file content",
1552
1570
  tags: ["Actions"],
@@ -1556,7 +1574,8 @@ function registerActionRunRoutes(app, sixb) {
1556
1574
  }
1557
1575
  }).head("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(sixb, context, { head: true }), {
1558
1576
  params: ActionRunIdParamsSchema,
1559
- query: FileContentQuerySchema,
1577
+ query: ActionRunFileContentQuerySchema,
1578
+ error: handleFileContentQueryValidationError,
1560
1579
  detail: {
1561
1580
  summary: "Head action run file content",
1562
1581
  tags: ["Actions"],
@@ -1666,2256 +1685,2272 @@ import {
1666
1685
  isValidAgentApiGatewayCapability
1667
1686
  } from "@sixb/core/internal/agents";
1668
1687
  import { normalizeRoutePath as normalizeRoutePath2, pathSegmentsFor } from "@sixb/core/internal/http";
1669
- var MAX_AGENT_API_BODY_BYTES = 1e6;
1670
- var HOP_BY_HOP_RESPONSE_HEADERS = new Set([
1671
- "connection",
1672
- "keep-alive",
1673
- "proxy-authenticate",
1674
- "proxy-authorization",
1675
- "te",
1676
- "trailer",
1677
- "transfer-encoding",
1678
- "upgrade"
1679
- ]);
1680
- function registerAgentApiGatewayRoutes(app, sixb) {
1681
- for (const route of AGENT_API_ROUTES) {
1682
- const path = `${AGENT_API_GATEWAY_PREFIX2}/:agentGatewayRunId/:agentGatewayCapability${route.path}`;
1683
- const handler = async (context) => handleAgentApiGatewayRequest({
1684
- sixb,
1685
- app,
1686
- request: context.request,
1687
- agentRunId: context.params.agentGatewayRunId ?? "",
1688
- capability: context.params.agentGatewayCapability ?? ""
1689
- });
1690
- if (route.method === "GET") {
1691
- app.get(path, handler, { detail: { hide: true } });
1692
- continue;
1693
- }
1694
- if (route.method === "POST") {
1695
- app.post(path, handler, { detail: { hide: true } });
1696
- continue;
1697
- }
1698
- throw new Error(`[SixbServer] Unsupported agent API gateway method '${route.method}'.`);
1699
- }
1700
- }
1701
- async function handleAgentApiGatewayRequest(input) {
1702
- const sourceUrl = new URL(input.request.url);
1703
- const upstreamPath = gatewayUpstreamPath(sourceUrl.pathname);
1704
- if (!isAllowedAgentApiRequest(input.request.method, upstreamPath)) {
1705
- return jsonError(403, `Agent API gateway does not allow ${input.request.method} ${upstreamPath}.`);
1706
- }
1707
- const authState = await resolveAgentRunAuthState(input.sixb, {
1708
- runId: input.agentRunId,
1709
- capability: input.capability
1710
- });
1711
- if (authState instanceof Response) {
1712
- return authState;
1713
- }
1714
- let body;
1715
- try {
1716
- body = await readRequestBody(input.request);
1717
- } catch (error) {
1718
- if (error instanceof PayloadTooLargeError) {
1719
- return jsonError(413, error.message);
1720
- }
1721
- throw error;
1722
- }
1723
- const internalUrl = new URL(`${upstreamPath}${sourceUrl.search}`, input.request.url);
1724
- const internalRequest = new Request(internalUrl, {
1725
- method: input.request.method,
1726
- headers: forwardedRequestHeaders(input.request.headers),
1727
- body
1728
- });
1729
- registerInternalRequestAuthState(internalRequest, authState);
1730
- const response = await input.app.fetch(internalRequest);
1731
- return new Response(response.body, {
1732
- status: response.status,
1733
- statusText: response.statusText,
1734
- headers: forwardedResponseHeaders(response.headers)
1735
- });
1736
- }
1737
- async function resolveAgentRunAuthState(sixb, input) {
1738
- const agentStorage = sixb.storage.agents;
1739
- const workflowRuns = sixb.storage.workflowRuns;
1740
- if (!agentStorage && !workflowRuns) {
1741
- return jsonError(501, "Agent API gateway is not configured for this runtime.");
1742
- }
1743
- const conversationalRun = await agentStorage?.runs.getById({
1744
- projectId: sixb.id,
1745
- id: input.runId
1746
- });
1747
- const workflowRun = conversationalRun ? null : await workflowRuns?.agentNodes.getByNodeRunId({
1748
- projectId: sixb.id,
1749
- nodeRunId: input.runId
1750
- });
1751
- const run = conversationalRun ?? workflowRun;
1752
- if (!run || run.status !== "running" || !run.execution || run.execution.queueLeaseExpiresAt.getTime() <= Date.now() || !isValidAgentApiGatewayCapability({
1753
- projectId: sixb.id,
1754
- runId: input.runId,
1755
- executionToken: run.execution.token,
1756
- capability: input.capability
1757
- })) {
1758
- return jsonError(403, "Agent API gateway capability is not valid for this run.");
1759
- }
1760
- if (!sixb.auth.isEnabled()) {
1761
- return {
1762
- authz: null,
1763
- scoped: null,
1764
- ...conversationalRun ? { agentRun: conversationalRun } : {}
1765
- };
1766
- }
1767
- const auth = sixb.storage.auth;
1768
- if (!auth) {
1769
- return jsonError(501, "Agent API gateway is not configured for authenticated agent access.");
1770
- }
1771
- if (!run.executionPrincipal) {
1772
- return jsonError(403, "Agent run has no execution identity.");
1773
- }
1774
- const serviceAccount = await auth.serviceAccounts.getById({
1775
- projectId: sixb.id,
1776
- id: run.executionPrincipal.id
1777
- });
1778
- if (!serviceAccount || serviceAccount.status !== "active") {
1779
- return jsonError(403, "Agent execution identity is not active.");
1780
- }
1781
- const memberships = await auth.serviceAccountGroupMemberships.listForServiceAccount({
1782
- projectId: sixb.id,
1783
- serviceAccountId: serviceAccount.id
1784
- });
1785
- const authz = resolveAuthorizationContext({
1786
- principal: run.executionPrincipal,
1787
- groupIds: memberships.map((membership) => membership.groupId),
1788
- roles: sixb.security.listResolvedRoles()
1789
- });
1790
- return {
1791
- authz,
1792
- scoped: sixb.as(authz),
1793
- ...conversationalRun ? { agentRun: conversationalRun } : {}
1794
- };
1795
- }
1796
- function gatewayUpstreamPath(pathname) {
1797
- const prefixLength = pathSegmentsFor(AGENT_API_GATEWAY_PREFIX2).length;
1798
- const segments = pathSegmentsFor(pathname);
1799
- const upstreamSegments = segments.slice(prefixLength + 2);
1800
- return normalizeRoutePath2(`/${upstreamSegments.join("/")}`);
1801
- }
1802
- function forwardedRequestHeaders(source) {
1803
- const headers = new Headers;
1804
- copyHeader(source, headers, "accept");
1805
- copyHeader(source, headers, "content-type");
1806
- return headers;
1807
- }
1808
- function forwardedResponseHeaders(source) {
1809
- const headers = new Headers;
1810
- for (const [key, value] of source) {
1811
- const normalized = key.toLowerCase();
1812
- if (HOP_BY_HOP_RESPONSE_HEADERS.has(normalized) || normalized === "content-length" || normalized === "set-cookie") {
1813
- continue;
1814
- }
1815
- headers.append(key, value);
1816
- }
1817
- return headers;
1818
- }
1819
- function copyHeader(source, target, name) {
1820
- const value = source.get(name);
1821
- if (value !== null) {
1822
- target.set(name, value);
1823
- }
1824
- }
1825
- async function readRequestBody(request) {
1826
- if (!request.body || request.method === "GET" || request.method === "HEAD") {
1827
- return;
1828
- }
1829
- const reader = request.body.getReader();
1830
- const chunks = [];
1831
- let total = 0;
1832
- while (true) {
1833
- const { done, value } = await reader.read();
1834
- if (done)
1835
- break;
1836
- total += value.byteLength;
1837
- if (total > MAX_AGENT_API_BODY_BYTES) {
1838
- throw new PayloadTooLargeError("Agent API gateway request body exceeds 1MB.");
1839
- }
1840
- chunks.push(value);
1841
- }
1842
- return concatChunks(chunks, total);
1843
- }
1844
- function concatChunks(chunks, total) {
1845
- const buffer = new ArrayBuffer(total);
1846
- const result = new Uint8Array(buffer);
1847
- let offset = 0;
1848
- for (const chunk of chunks) {
1849
- result.set(chunk, offset);
1850
- offset += chunk.byteLength;
1851
- }
1852
- return buffer;
1853
- }
1854
- function jsonError(status, message) {
1855
- return Response.json({ error: message }, { status });
1856
- }
1857
-
1858
- class PayloadTooLargeError extends Error {
1859
- }
1860
1688
 
1861
- // src/routes/agents.ts
1689
+ // src/routes/files.ts
1862
1690
  import {
1863
- AgentRequestError,
1864
- SYSTEM_PRINCIPAL
1691
+ DEFAULT_SIMPLE_FILE_UPLOAD_BYTES,
1692
+ InMemoryFileUploadSessions
1865
1693
  } from "@sixb/core";
1866
- import { agentRunStreamId } from "@sixb/core/agents/streams";
1867
- import {
1868
- createAgentRunId,
1869
- createAgentThreadId,
1870
- dispatchQueuedAgentRuns,
1871
- publishAgentRunCancel,
1872
- publishAgentRunFinished
1873
- } from "@sixb/core/internal/agents";
1694
+ import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
1874
1695
  import {
1875
- AgentStorageError
1696
+ createFileUploadId,
1697
+ createUploadExpiresAt,
1698
+ FileUploadSessionError as FileUploadSessionError2
1876
1699
  } from "@sixb/core/storage";
1877
- import { ZodError as ZodError2, z as z7 } from "zod";
1878
-
1879
- // src/schemas/agents.ts
1880
- import { AGENT_REASONING_LEVELS, MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core";
1881
- import { AGENT_RUN_DIAGNOSTIC_CODES } from "@sixb/core/storage";
1882
- import { z as z6 } from "zod";
1883
- var AgentIdParamsSchema = z6.object({
1884
- agentId: z6.string().min(1)
1885
- });
1886
- var AgentThreadParamsSchema = z6.object({
1887
- threadId: z6.string().min(1)
1888
- });
1889
- var AgentRunParamsSchema = z6.object({
1890
- runId: z6.string().min(1)
1891
- });
1892
- var AgentMessageFileContentParamsSchema = AgentThreadParamsSchema.extend({
1893
- messageId: z6.string().min(1)
1894
- });
1895
- var AgentPrincipalSchema = z6.object({
1896
- type: z6.enum(["user", "serviceAccount", "system"]),
1897
- id: z6.string().min(1)
1898
- });
1899
- var AgentObjectContextSchema = z6.object({
1900
- kind: z6.literal("object"),
1901
- ref: z6.object({
1902
- objectTypeId: z6.string().min(1),
1903
- primaryId: z6.string().min(1)
1904
- })
1905
- });
1906
- var AgentAppStateContextSchema = z6.object({
1907
- kind: z6.literal("app-state"),
1908
- id: z6.string().min(1),
1909
- label: z6.string().min(1),
1910
- description: z6.string().min(1),
1911
- value: JsonValueSchema
1912
- });
1913
- var AgentContextInputSchema = z6.discriminatedUnion("kind", [
1914
- AgentObjectContextSchema,
1915
- AgentAppStateContextSchema
1916
- ]);
1917
- var AgentContextOriginSchema = z6.enum(["ambient", "explicit"]);
1918
- var AgentContextEntryInputSchema = z6.object({
1919
- context: AgentContextInputSchema,
1920
- origin: AgentContextOriginSchema
1921
- });
1922
- var AgentContextPartSchema = AgentContextEntryInputSchema.extend({
1923
- type: z6.literal("context")
1924
- });
1925
- var AgentLoopConfigSchema = z6.object({
1926
- stopWhen: z6.object({
1927
- maxSteps: z6.number().int().positive().optional()
1928
- }).optional()
1929
- });
1930
- var AgentReasoningLevelSchema = z6.enum(AGENT_REASONING_LEVELS);
1931
- var AgentCatalogItemSchema = z6.object({
1932
- id: z6.string(),
1933
- name: z6.string(),
1934
- description: z6.string().optional(),
1935
- modelId: z6.string().optional(),
1936
- reasoning: AgentReasoningLevelSchema.optional(),
1937
- groupIds: z6.array(z6.string()),
1938
- loop: AgentLoopConfigSchema.optional()
1939
- });
1940
- var AgentThreadStatusSchema = z6.enum(["active", "archived"]);
1941
- var AgentThreadListQuerySchema = z6.object({
1942
- agentId: z6.string().optional(),
1943
- status: AgentThreadStatusSchema.optional(),
1944
- limit: z6.string().optional(),
1945
- offset: z6.string().optional(),
1946
- order: z6.enum(["asc", "desc"]).optional()
1947
- });
1948
- var CreateAgentThreadBodySchema = z6.object({
1949
- agentId: z6.string().min(1),
1950
- title: z6.string().trim().min(1).optional(),
1951
- threadId: z6.string().trim().min(1).optional()
1952
- });
1953
- var AgentThreadSchema = z6.object({
1954
- id: z6.string(),
1955
- projectId: z6.string(),
1956
- agentId: z6.string(),
1957
- ownerPrincipal: AgentPrincipalSchema,
1958
- title: z6.string().optional(),
1959
- status: AgentThreadStatusSchema,
1960
- activeRunId: z6.string().nullable(),
1961
- lastMessageAt: z6.string().optional(),
1962
- messageCount: z6.number(),
1963
- createdAt: z6.string(),
1964
- updatedAt: z6.string()
1965
- });
1966
- var AgentThreadListResponseSchema = z6.object({
1967
- threads: z6.array(AgentThreadSchema),
1968
- hasMore: z6.boolean(),
1969
- total: z6.number()
1970
- });
1971
- var CreateAgentThreadResponseSchema = z6.object({
1972
- thread: AgentThreadSchema
1973
- });
1974
- var AgentMessageRoleSchema = z6.enum(["system", "user", "assistant"]);
1975
- var AgentTextPartSchema = z6.object({
1976
- type: z6.literal("text"),
1977
- text: z6.string(),
1978
- providerMetadata: JsonValueSchema.optional()
1979
- });
1980
- var AgentReasoningPartSchema = z6.object({
1981
- type: z6.literal("reasoning"),
1982
- text: z6.string(),
1983
- providerMetadata: JsonValueSchema.optional()
1984
- });
1985
- var AgentStepStartPartSchema = z6.object({
1986
- type: z6.literal("step-start")
1987
- });
1988
- var AgentFilePartSchema = z6.object({
1989
- type: z6.literal("file"),
1990
- fileRef: FileRefSchema,
1991
- providerMetadata: JsonValueSchema.optional()
1992
- });
1993
- var AgentToolCallBaseSchema = z6.object({
1994
- type: z6.literal("tool-call"),
1995
- toolCallId: z6.string(),
1996
- toolName: z6.string(),
1997
- dynamic: z6.boolean().optional(),
1998
- providerExecuted: z6.boolean().optional(),
1999
- input: JsonValueSchema,
2000
- providerMetadata: JsonValueSchema.optional()
2001
- });
2002
- var AgentToolCallOutputSchema = AgentToolCallBaseSchema.extend({
2003
- state: z6.literal("output-available"),
2004
- output: JsonValueSchema
2005
- });
2006
- var AgentToolCallErrorSchema = AgentToolCallBaseSchema.extend({
2007
- state: z6.literal("output-error"),
2008
- errorText: z6.string()
2009
- });
2010
- var AgentMessagePartSchema = z6.union([
2011
- AgentTextPartSchema,
2012
- AgentReasoningPartSchema,
2013
- AgentStepStartPartSchema,
2014
- AgentFilePartSchema,
2015
- AgentContextPartSchema,
2016
- AgentToolCallOutputSchema,
2017
- AgentToolCallErrorSchema
2018
- ]);
2019
- var AgentRunDiagnosticSchema = z6.object({
2020
- code: z6.enum(AGENT_RUN_DIAGNOSTIC_CODES),
2021
- severity: z6.enum(["warning", "error"]),
2022
- scope: z6.literal("output"),
2023
- path: z6.string().optional(),
2024
- message: z6.string()
2025
- });
2026
- var AgentMessageSchema = z6.object({
2027
- id: z6.string(),
2028
- projectId: z6.string(),
2029
- threadId: z6.string(),
2030
- runId: z6.string().nullable(),
2031
- role: AgentMessageRoleSchema,
2032
- authorPrincipal: AgentPrincipalSchema.optional(),
2033
- seq: z6.number(),
2034
- parts: z6.array(AgentMessagePartSchema),
2035
- annotations: z6.array(AgentRunDiagnosticSchema),
2036
- metadata: JsonValueSchema.optional(),
2037
- contentVersion: z6.number(),
2038
- createdAt: z6.string(),
2039
- completedAt: z6.string().optional()
2040
- });
2041
- var AgentMessagesQuerySchema = z6.object({
2042
- role: AgentMessageRoleSchema.optional(),
2043
- limit: z6.string().optional(),
2044
- offset: z6.string().optional(),
2045
- order: z6.enum(["asc", "desc"]).optional()
2046
- });
2047
- var AgentMessageListResponseSchema = z6.object({
2048
- messages: z6.array(AgentMessageSchema),
2049
- hasMore: z6.boolean(),
2050
- total: z6.number()
2051
- });
2052
- var PostAgentMessageBodySchema = z6.object({
2053
- text: z6.string().trim().min(1),
2054
- attachments: z6.array(FileRefSchema).optional(),
2055
- context: z6.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
2056
- messageId: z6.string().trim().min(1).optional()
2057
- });
2058
- var CancelAgentRunBodySchema = z6.object({
2059
- runId: z6.string().trim().min(1)
2060
- });
2061
- var AgentRunStatusSchema = z6.enum([
2062
- "queued",
2063
- "running",
2064
- "succeeded",
2065
- "failed",
2066
- "cancelled"
2067
- ]);
2068
- var AgentRunFinishReasonSchema = z6.enum([
2069
- "stop",
2070
- "length",
2071
- "content-filter",
2072
- "tool-calls",
2073
- "error",
2074
- "other",
2075
- "unknown"
2076
- ]);
2077
- var AgentRunUsageSchema = z6.object({
2078
- inputTokens: z6.number().optional(),
2079
- outputTokens: z6.number().optional(),
2080
- totalTokens: z6.number().optional(),
2081
- reasoningTokens: z6.number().optional(),
2082
- cachedInputTokens: z6.number().optional()
2083
- });
2084
- var AgentRunSchema = z6.object({
2085
- id: z6.string(),
2086
- projectId: z6.string(),
2087
- threadId: z6.string(),
2088
- agentId: z6.string(),
2089
- triggerMessageId: z6.string(),
2090
- requestedByPrincipal: AgentPrincipalSchema,
2091
- executionPrincipal: AgentPrincipalSchema.optional(),
2092
- status: AgentRunStatusSchema,
2093
- modelId: z6.string().optional(),
2094
- finishReason: AgentRunFinishReasonSchema.optional(),
2095
- usage: AgentRunUsageSchema.optional(),
2096
- diagnostics: z6.array(AgentRunDiagnosticSchema).optional(),
2097
- error: z6.string().optional(),
2098
- attempt: z6.number(),
2099
- streamId: z6.string(),
2100
- createdAt: z6.string(),
2101
- startedAt: z6.string().optional(),
2102
- completedAt: z6.string().optional()
2103
- });
2104
- var PostAgentMessageResponseSchema = z6.object({
2105
- run: AgentRunSchema
2106
- });
2107
- var CancelAgentRunResponseSchema = z6.object({
2108
- run: AgentRunSchema
2109
- });
2110
- var RetryAgentRunResponseSchema = z6.object({
2111
- run: AgentRunSchema
2112
- });
2113
- var AgentRunListQuerySchema = z6.object({
2114
- status: AgentRunStatusSchema.optional(),
2115
- limit: z6.string().optional(),
2116
- offset: z6.string().optional(),
2117
- order: z6.enum(["asc", "desc"]).optional()
2118
- });
2119
- var AgentRunListResponseSchema = z6.object({
2120
- runs: z6.array(AgentRunSchema),
2121
- hasMore: z6.boolean(),
2122
- total: z6.number()
2123
- });
2124
-
2125
- // src/routes/agents.ts
2126
- var AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
2127
- path: z7.string().min(1).regex(/^\/parts(?:\/|$)/, "Agent message file content paths must start with /parts/")
2128
- });
2129
- function serializeAgent(agent) {
2130
- return AgentCatalogItemSchema.parse({
2131
- id: agent.id,
2132
- name: agent.name,
2133
- description: agent.description,
2134
- modelId: agent.model.modelId,
2135
- reasoning: agent.reasoning,
2136
- groupIds: agent.groupIds,
2137
- loop: agent.loop
2138
- });
2139
- }
2140
- function serializeThread(thread) {
2141
- return AgentThreadSchema.parse({
2142
- id: thread.id,
2143
- projectId: thread.projectId,
2144
- agentId: thread.agentId,
2145
- ownerPrincipal: thread.ownerPrincipal,
2146
- title: thread.title,
2147
- status: thread.status,
2148
- activeRunId: thread.activeRunId,
2149
- lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
2150
- messageCount: thread.messageCount,
2151
- createdAt: toIsoString(thread.createdAt),
2152
- updatedAt: toIsoString(thread.updatedAt)
2153
- });
2154
- }
2155
- function serializeMessage(message, annotations = []) {
2156
- return AgentMessageSchema.parse({
2157
- id: message.id,
2158
- projectId: message.projectId,
2159
- threadId: message.threadId,
2160
- runId: message.runId,
2161
- role: message.role,
2162
- authorPrincipal: message.authorPrincipal,
2163
- seq: message.seq,
2164
- parts: message.parts,
2165
- annotations,
2166
- metadata: message.metadata,
2167
- contentVersion: message.contentVersion,
2168
- createdAt: toIsoString(message.createdAt),
2169
- completedAt: message.completedAt ? toIsoString(message.completedAt) : undefined
2170
- });
2171
- }
2172
- function serializeAgentRun(run) {
2173
- return AgentRunSchema.parse({
2174
- id: run.id,
2175
- projectId: run.projectId,
2176
- threadId: run.threadId,
2177
- agentId: run.agentId,
2178
- triggerMessageId: run.triggerMessageId,
2179
- requestedByPrincipal: run.requestedByPrincipal,
2180
- executionPrincipal: run.executionPrincipal,
2181
- status: run.status,
2182
- modelId: run.modelId,
2183
- finishReason: run.finishReason,
2184
- usage: run.usage,
2185
- diagnostics: run.diagnostics,
2186
- error: run.error,
2187
- attempt: run.attempt,
2188
- streamId: agentRunStreamId(run.id),
2189
- createdAt: toIsoString(run.createdAt),
2190
- startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
2191
- completedAt: run.completedAt ? toIsoString(run.completedAt) : undefined
2192
- });
2193
- }
2194
- async function getAccessibleThread(params) {
2195
- if (params.scoped) {
2196
- return params.scoped.getThread(params.threadId);
2197
- }
2198
- return params.storage.threads.getById({ projectId: params.projectId, id: params.threadId });
2199
- }
2200
- async function getAgentMessageFileContentThread(params) {
2201
- const { agentRun } = params.authState;
2202
- if (agentRun) {
2203
- if (agentRun.projectId !== params.projectId || agentRun.threadId !== params.threadId) {
2204
- return null;
2205
- }
2206
- return params.storage.threads.getById({ projectId: params.projectId, id: params.threadId });
2207
- }
2208
- return getAccessibleThread({
2209
- scoped: params.authState.scoped,
2210
- storage: params.storage,
2211
- projectId: params.projectId,
2212
- threadId: params.threadId
2213
- });
2214
- }
2215
- function principalForRequest(authz) {
2216
- return authz?.principal ?? SYSTEM_PRINCIPAL;
2217
- }
2218
- async function publishQueuedRunCancellation(sixb, run) {
2219
- try {
2220
- await publishAgentRunFinished(sixb.broker, run);
2221
- } catch (error) {
2222
- console.error(`[SixbServer] Agent run '${run.id}' cancellation stream publish failed:`, error);
2223
- }
2224
- }
2225
- function handleAgentRouteError(error, set) {
2226
- if (error instanceof AgentStorageError && error.code === "duplicate_id") {
2227
- set.status = 409;
2228
- return { error: "Agent thread already exists" };
2229
- }
2230
- if (error instanceof AgentStorageError && error.code === "active_run_exists") {
2231
- set.status = 409;
2232
- return { error: "This conversation already has a response in progress" };
2233
- }
2234
- if (error instanceof AgentRequestError) {
2235
- switch (error.code) {
2236
- case "agent_not_found":
2237
- case "thread_not_found":
2238
- set.status = 404;
2239
- break;
2240
- case "active_run_exists":
2241
- set.status = 409;
2242
- break;
2243
- case "storage_unavailable":
2244
- case "thread_agent_mismatch":
2245
- case "invalid_context":
2246
- set.status = 400;
2247
- break;
2248
- }
2249
- return { error: error.message };
2250
- }
2251
- return handleRouteError(error, set);
2252
- }
2253
- function missingAgentStorageResponse(set) {
2254
- return unconfiguredStorageResponse2(set, "Agent storage");
2255
- }
2256
- async function agentMessageFileContentResponse(sixb, context, options = {}) {
2257
- const authState = requestAuthState(context);
2258
- try {
2259
- const storage = sixb.storage.agents;
2260
- if (!storage) {
2261
- return missingAgentStorageResponse(context.set);
2262
- }
2263
- const parsed = AgentMessageFileContentQuerySchema.parse(context.query);
2264
- const thread = await getAgentMessageFileContentThread({
2265
- authState,
2266
- storage,
2267
- projectId: sixb.id,
2268
- threadId: context.params.threadId
2269
- });
2270
- if (!thread) {
2271
- context.set.status = 404;
2272
- return { error: "File not found" };
2273
- }
2274
- const message = await storage.messages.getById({
2275
- projectId: sixb.id,
2276
- id: context.params.messageId
2277
- });
2278
- if (!message || message.threadId !== thread.id) {
2279
- context.set.status = 404;
2280
- return { error: "File not found" };
2281
- }
2282
- const fileRef = resolveFileRefAtPath(serializeMessage(message), parsed.path);
2283
- if (!fileRef) {
2284
- context.set.status = 404;
2285
- return { error: "File not found" };
2286
- }
2287
- const response = await createFileContentResponse({
2288
- blobStorage: sixb.blobStorage,
2289
- fileRef,
2290
- disposition: parsed.disposition,
2291
- head: options.head,
2292
- rangeHeader: context.request.headers.get("range")
2293
- });
2294
- if (!response) {
2295
- context.set.status = 404;
2296
- return { error: "File not found" };
2297
- }
2298
- return response;
2299
- } catch (error) {
2300
- if (error instanceof ZodError2) {
2301
- context.set.status = 400;
2302
- return { error: "Invalid file content query" };
2303
- }
2304
- throw error;
2305
- }
2306
- }
2307
- function registerAgentRoutes(app, sixb) {
2308
- return app.get("/api/agents", (context) => {
2309
- const { scoped } = requestAuthState(context);
2310
- const agents = scoped ? scoped.listAgents() : sixb.agents.list();
2311
- return agents.map(serializeAgent);
2312
- }, {
2313
- response: { 200: AgentCatalogItemSchema.array() },
2314
- detail: {
2315
- summary: "List registered agents",
2316
- tags: [OPENAPI_TAGS.agents.name],
2317
- operationId: "listAgents"
2318
- }
2319
- }).get("/api/agents/:agentId", (context) => {
2320
- const { params, set } = context;
2321
- const { scoped } = requestAuthState(context);
2322
- const agent = scoped ? scoped.getAgentById(params.agentId) : sixb.agents.getById(params.agentId);
2323
- if (!agent) {
2324
- set.status = 404;
2325
- return { error: "Agent not found" };
2326
- }
2327
- return serializeAgent(agent);
2328
- }, {
2329
- params: AgentIdParamsSchema,
2330
- response: { 200: AgentCatalogItemSchema, 404: ErrorResponseSchema },
2331
- detail: {
2332
- summary: "Get agent metadata",
2333
- tags: [OPENAPI_TAGS.agents.name],
2334
- operationId: "getAgent"
2335
- }
2336
- }).get("/api/agent-threads", async (context) => {
2337
- const { query, set } = context;
2338
- const { scoped } = requestAuthState(context);
2339
- try {
2340
- const storage = sixb.storage.agents;
2341
- if (!storage) {
2342
- return missingAgentStorageResponse(set);
2343
- }
2344
- const parsed = AgentThreadListQuerySchema.parse(query);
2345
- const listInput = {
2346
- agentId: parsed.agentId,
2347
- statuses: parsed.status ? [parsed.status] : undefined,
2348
- limit: parseOptionalInt(parsed.limit),
2349
- offset: parseOptionalInt(parsed.offset),
2350
- order: parsed.order
2351
- };
2352
- const result = scoped ? await scoped.listThreads(listInput) : await storage.threads.list({ projectId: sixb.id, ...listInput });
2353
- return AgentThreadListResponseSchema.parse({
2354
- threads: result.threads.map(serializeThread),
2355
- hasMore: result.hasMore,
2356
- total: result.total
2357
- });
2358
- } catch (error) {
2359
- return handleAgentRouteError(error, set);
2360
- }
2361
- }, {
2362
- query: AgentThreadListQuerySchema,
2363
- response: {
2364
- 200: AgentThreadListResponseSchema,
2365
- 400: ErrorResponseSchema,
2366
- 501: ErrorResponseSchema
2367
- },
2368
- detail: {
2369
- summary: "List agent threads",
2370
- tags: [OPENAPI_TAGS.agentThreads.name],
2371
- operationId: "listAgentThreads"
2372
- }
2373
- }).post("/api/agent-threads", async (context) => {
2374
- const { body, set } = context;
2375
- const { authz, scoped } = requestAuthState(context);
2376
- try {
2377
- const parsed = CreateAgentThreadBodySchema.parse(body);
2378
- const agent = scoped ? scoped.getAgentById(parsed.agentId) : sixb.agents.getById(parsed.agentId);
2379
- if (!agent) {
2380
- set.status = 404;
2381
- return { error: "Agent not found" };
2382
- }
2383
- const storage = sixb.storage.agents;
2384
- if (!storage) {
2385
- return missingAgentStorageResponse(set);
2386
- }
2387
- const thread = await storage.threads.create({
2388
- id: parsed.threadId ?? createAgentThreadId(),
2389
- projectId: sixb.id,
2390
- agentId: agent.id,
2391
- ownerPrincipal: principalForRequest(authz),
2392
- ...parsed.title === undefined ? {} : { title: parsed.title }
2393
- });
2394
- set.status = 201;
2395
- return CreateAgentThreadResponseSchema.parse({ thread: serializeThread(thread) });
2396
- } catch (error) {
2397
- return handleAgentRouteError(error, set);
2398
- }
2399
- }, {
2400
- body: CreateAgentThreadBodySchema,
2401
- response: {
2402
- 201: CreateAgentThreadResponseSchema,
2403
- 400: ErrorResponseSchema,
2404
- 404: ErrorResponseSchema,
2405
- 409: ErrorResponseSchema,
2406
- 501: ErrorResponseSchema
2407
- },
2408
- detail: {
2409
- summary: "Create an agent thread",
2410
- tags: [OPENAPI_TAGS.agentThreads.name],
2411
- operationId: "createAgentThread",
2412
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2413
- }
2414
- }).get("/api/agent-threads/:threadId", async (context) => {
2415
- const { params, set } = context;
2416
- const { scoped } = requestAuthState(context);
1700
+ var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
1701
+ var SYSTEM_PRINCIPAL = { type: "system", id: "system" };
1702
+ function registerFileRoutes(app, sixb) {
1703
+ const uploadSessions = sixb.storage.fileUploadSessions ?? new InMemoryFileUploadSessions;
1704
+ return app.post("/api/files", async ({ request, set }) => {
2417
1705
  try {
2418
- const storage = sixb.storage.agents;
2419
- if (!storage) {
2420
- return missingAgentStorageResponse(set);
1706
+ const requestSizeError = requestSizeLimitError(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES);
1707
+ if (requestSizeError) {
1708
+ set.status = 413;
1709
+ return { error: requestSizeError };
2421
1710
  }
2422
- const thread = await getAccessibleThread({
2423
- scoped,
2424
- storage,
2425
- projectId: sixb.id,
2426
- threadId: params.threadId
2427
- });
2428
- if (!thread) {
2429
- set.status = 404;
2430
- return { error: "Agent thread not found" };
1711
+ const form = await request.formData();
1712
+ const file = form.get("file");
1713
+ const logicalPath = form.get("logicalPath");
1714
+ if (!(file instanceof File)) {
1715
+ set.status = 400;
1716
+ return { error: "Expected multipart field 'file' to be a file." };
2431
1717
  }
2432
- return serializeThread(thread);
2433
- } catch (error) {
2434
- return handleAgentRouteError(error, set);
2435
- }
2436
- }, {
2437
- params: AgentThreadParamsSchema,
2438
- response: {
2439
- 200: AgentThreadSchema,
2440
- 400: ErrorResponseSchema,
2441
- 404: ErrorResponseSchema,
2442
- 501: ErrorResponseSchema
2443
- },
2444
- detail: {
2445
- summary: "Get agent thread",
2446
- tags: [OPENAPI_TAGS.agentThreads.name],
2447
- operationId: "getAgentThread"
2448
- }
2449
- }).get("/api/agent-threads/:threadId/messages", async (context) => {
2450
- const { params, query, set } = context;
2451
- const { scoped } = requestAuthState(context);
2452
- try {
2453
- const storage = sixb.storage.agents;
2454
- if (!storage) {
2455
- return missingAgentStorageResponse(set);
1718
+ if (logicalPath !== null && typeof logicalPath !== "string") {
1719
+ set.status = 400;
1720
+ return { error: "Expected multipart field 'logicalPath' to be a string." };
2456
1721
  }
2457
- const thread = await getAccessibleThread({
2458
- scoped,
2459
- storage,
2460
- projectId: sixb.id,
2461
- threadId: params.threadId
2462
- });
2463
- if (!thread) {
2464
- set.status = 404;
2465
- return { error: "Agent thread not found" };
1722
+ if (file.size > DEFAULT_SIMPLE_FILE_UPLOAD_BYTES) {
1723
+ set.status = 413;
1724
+ return {
1725
+ error: `File upload exceeds the ${DEFAULT_SIMPLE_FILE_UPLOAD_BYTES} byte limit.`
1726
+ };
2466
1727
  }
2467
- const parsed = AgentMessagesQuerySchema.parse(query);
2468
- const limit = parseOptionalInt(parsed.limit);
2469
- const offset = parseOptionalInt(parsed.offset);
2470
- const result = await storage.messages.list({
2471
- projectId: sixb.id,
2472
- threadId: thread.id,
2473
- roles: parsed.role ? [parsed.role] : undefined,
2474
- limit,
2475
- offset,
2476
- order: parsed.order
2477
- });
2478
- const runIds = result.messages.flatMap((message) => message.runId === null ? [] : [message.runId]);
2479
- const runs = await storage.runs.getByIds({ projectId: sixb.id, ids: runIds });
2480
- const diagnosticsByRunId = new Map(runs.map((run) => [run.id, run.diagnostics ?? []]));
2481
- return AgentMessageListResponseSchema.parse({
2482
- messages: result.messages.map((message) => serializeMessage(message, message.runId === null ? [] : diagnosticsByRunId.get(message.runId) ?? [])),
2483
- hasMore: result.hasMore,
2484
- total: result.total
1728
+ const fileRef = await sixb.blobStorage.put({
1729
+ body: file,
1730
+ fileName: file.name || undefined,
1731
+ mediaType: file.type || undefined,
1732
+ logicalPath: logicalPath ?? undefined
2485
1733
  });
1734
+ return FileRefSchema.parse(fileRef);
2486
1735
  } catch (error) {
2487
- return handleAgentRouteError(error, set);
1736
+ return handleRouteError(error, set);
2488
1737
  }
2489
1738
  }, {
2490
- params: AgentThreadParamsSchema,
2491
- query: AgentMessagesQuerySchema,
2492
1739
  response: {
2493
- 200: AgentMessageListResponseSchema,
1740
+ 200: FileRefSchema,
2494
1741
  400: ErrorResponseSchema,
2495
- 404: ErrorResponseSchema,
2496
- 501: ErrorResponseSchema
1742
+ 413: ErrorResponseSchema
2497
1743
  },
2498
1744
  detail: {
2499
- summary: "List agent thread messages",
2500
- tags: [OPENAPI_TAGS.agentThreads.name],
2501
- operationId: "listAgentThreadMessages"
2502
- }
2503
- }).get("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(sixb, context), {
2504
- params: AgentMessageFileContentParamsSchema,
2505
- query: FileContentQuerySchema,
2506
- detail: {
2507
- summary: "Get agent message file content",
2508
- tags: ["Agents"],
2509
- operationId: "getAgentMessageFileContent",
2510
- security: bearerSecurityRequirement("getAgentMessageFileContent"),
2511
- responses: fileContentGetResponses({ optionalStorage: true })
2512
- }
2513
- }).head("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(sixb, context, { head: true }), {
2514
- params: AgentMessageFileContentParamsSchema,
2515
- query: FileContentQuerySchema,
2516
- detail: {
2517
- summary: "Head agent message file content",
2518
- tags: ["Agents"],
2519
- operationId: "headAgentMessageFileContent",
2520
- security: bearerSecurityRequirement("headAgentMessageFileContent"),
2521
- responses: fileContentHeadResponses({ optionalStorage: true })
1745
+ summary: "Upload a file",
1746
+ tags: [OPENAPI_TAGS.files.name],
1747
+ operationId: "uploadFileRaw",
1748
+ security: bearerSecurityRequirement("uploadFileRaw"),
1749
+ requestBody: {
1750
+ required: true,
1751
+ content: {
1752
+ "multipart/form-data": {
1753
+ schema: {
1754
+ type: "object",
1755
+ required: ["file"],
1756
+ properties: {
1757
+ file: {
1758
+ type: "string",
1759
+ format: "binary"
1760
+ },
1761
+ logicalPath: {
1762
+ type: "string"
1763
+ }
1764
+ }
1765
+ }
1766
+ }
1767
+ }
1768
+ }
2522
1769
  }
2523
- }).post("/api/agent-threads/:threadId/messages", async (context) => {
2524
- const { params, body, set } = context;
2525
- const { authz, scoped } = requestAuthState(context);
1770
+ }).post("/api/files/uploads", async (context) => {
1771
+ const { body, set } = context;
1772
+ const { authz } = requestAuthState(context);
2526
1773
  try {
2527
- const storage = sixb.storage.agents;
2528
- if (!storage) {
2529
- return missingAgentStorageResponse(set);
2530
- }
2531
- const thread = await getAccessibleThread({
2532
- scoped,
2533
- storage,
1774
+ const parsed = CreateFileUploadBodySchema.parse(body);
1775
+ const principal = authz?.principal ?? SYSTEM_PRINCIPAL;
1776
+ const uploadId = createFileUploadId();
1777
+ const expiresAt = createUploadExpiresAt();
1778
+ const expectedDigest = parsed.digest;
1779
+ const providerUpload = supportsDirectUpload(sixb.blobStorage) && expectedDigest !== undefined && parsed.sizeBytes !== undefined ? await sixb.blobStorage.createUpload({
1780
+ uploadId,
1781
+ expiresAt,
1782
+ ...parsed.fileName === undefined ? {} : { fileName: parsed.fileName },
1783
+ ...parsed.mediaType === undefined ? {} : { mediaType: parsed.mediaType },
1784
+ ...parsed.logicalPath === undefined ? {} : { logicalPath: parsed.logicalPath },
1785
+ ...parsed.sizeBytes === undefined ? {} : { sizeBytes: parsed.sizeBytes },
1786
+ expectedDigest
1787
+ }) : undefined;
1788
+ const session = await uploadSessions.create({
1789
+ id: uploadId,
2534
1790
  projectId: sixb.id,
2535
- threadId: params.threadId
1791
+ principal,
1792
+ strategy: providerUpload?.strategy ?? "server",
1793
+ expiresAt,
1794
+ ...parsed.fileName === undefined ? {} : { fileName: parsed.fileName },
1795
+ ...parsed.mediaType === undefined ? {} : { mediaType: parsed.mediaType },
1796
+ ...parsed.logicalPath === undefined ? {} : { logicalPath: parsed.logicalPath },
1797
+ ...parsed.sizeBytes === undefined ? {} : { expectedSizeBytes: parsed.sizeBytes },
1798
+ ...expectedDigest === undefined ? {} : { expectedDigest },
1799
+ ...providerUpload === undefined ? {} : { providerUpload }
2536
1800
  });
2537
- if (!thread) {
2538
- set.status = 404;
2539
- return { error: "Agent thread not found" };
2540
- }
2541
- const parsed = PostAgentMessageBodySchema.parse(body);
2542
- const requestInput = {
2543
- agentId: thread.agentId,
2544
- threadId: thread.id,
2545
- text: parsed.text,
2546
- attachments: parsed.attachments,
2547
- context: parsed.context,
2548
- messageId: parsed.messageId,
2549
- principal: principalForRequest(authz)
2550
- };
2551
- const result = await (scoped ? scoped.requestAgentRun(requestInput) : sixb.agents.request(requestInput));
2552
- set.status = 202;
2553
- return PostAgentMessageResponseSchema.parse({ run: serializeAgentRun(result.run) });
1801
+ set.status = 201;
1802
+ return CreateFileUploadResponseSchema.parse(fileUploadResponse(session));
2554
1803
  } catch (error) {
2555
- return handleAgentRouteError(error, set);
1804
+ return handleRouteError(error, set);
2556
1805
  }
2557
1806
  }, {
2558
- params: AgentThreadParamsSchema,
2559
- body: PostAgentMessageBodySchema,
1807
+ body: CreateFileUploadBodySchema,
2560
1808
  response: {
2561
- 202: PostAgentMessageResponseSchema,
2562
- 400: ErrorResponseSchema,
2563
- 403: ErrorResponseSchema,
2564
- 404: ErrorResponseSchema,
2565
- 409: ErrorResponseSchema,
2566
- 501: ErrorResponseSchema
1809
+ 201: CreateFileUploadResponseSchema,
1810
+ 400: ErrorResponseSchema
2567
1811
  },
2568
1812
  detail: {
2569
- summary: "Post an agent thread message",
2570
- tags: [OPENAPI_TAGS.agentThreads.name],
2571
- operationId: "postAgentThreadMessage",
1813
+ summary: "Create a staged file upload",
1814
+ tags: [OPENAPI_TAGS.files.name],
1815
+ operationId: "createFileUpload",
2572
1816
  security: SIXB_CSRF_SECURITY_REQUIREMENT
2573
1817
  }
2574
- }).post("/api/agent-threads/:threadId/cancel", async (context) => {
2575
- const { params, body, set } = context;
2576
- const { scoped } = requestAuthState(context);
1818
+ }).put("/api/files/uploads/:uploadId/content", async (context) => {
1819
+ const { params, request, set } = context;
1820
+ const { authz } = requestAuthState(context);
2577
1821
  try {
2578
- const storage = sixb.storage.agents;
2579
- if (!storage) {
2580
- return missingAgentStorageResponse(set);
1822
+ const principal = authz?.principal ?? SYSTEM_PRINCIPAL;
1823
+ const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
1824
+ if (session.status !== "pending") {
1825
+ throw terminalSessionError(session.status);
2581
1826
  }
2582
- const thread = await getAccessibleThread({
2583
- scoped,
2584
- storage,
2585
- projectId: sixb.id,
2586
- threadId: params.threadId
2587
- });
2588
- if (!thread) {
2589
- set.status = 404;
2590
- return { error: "Agent thread not found" };
1827
+ if (session.strategy !== "server") {
1828
+ set.status = 400;
1829
+ return { error: "Upload content is only accepted for server staged uploads." };
2591
1830
  }
2592
- const parsed = CancelAgentRunBodySchema.parse(body);
2593
- const run = await storage.runs.getById({ projectId: sixb.id, id: parsed.runId });
2594
- if (!run || run.threadId !== thread.id) {
2595
- set.status = 404;
2596
- return { error: "Agent run not found" };
1831
+ const contentLengthSizeError = expectedContentLengthError(session, request);
1832
+ if (contentLengthSizeError) {
1833
+ set.status = 400;
1834
+ return { error: contentLengthSizeError };
2597
1835
  }
2598
- let current = run;
2599
- let cancelledWhileQueued = false;
2600
- if (current.status === "queued") {
2601
- try {
2602
- current = await storage.runs.finishQueued({
2603
- projectId: sixb.id,
2604
- id: current.id,
2605
- status: "cancelled"
2606
- });
2607
- cancelledWhileQueued = true;
2608
- } catch (error) {
2609
- if (!(error instanceof AgentStorageError) || error.code !== "invalid_state") {
2610
- throw error;
2611
- }
2612
- const refreshed = await storage.runs.getById({ projectId: sixb.id, id: current.id });
2613
- if (!refreshed || refreshed.threadId !== thread.id) {
2614
- set.status = 404;
2615
- return { error: "Agent run not found" };
2616
- }
2617
- current = refreshed;
2618
- }
1836
+ const uploadBytes = readParsedUploadBytes(context);
1837
+ if (uploadBytes.byteLength === 0) {
1838
+ set.status = 400;
1839
+ return { error: "Expected upload content body." };
2619
1840
  }
2620
- if (cancelledWhileQueued) {
2621
- await publishQueuedRunCancellation(sixb, current);
2622
- } else if (current.status === "running") {
2623
- await publishAgentRunCancel(sixb.broker, { projectId: sixb.id, runId: current.id });
2624
- } else {
2625
- set.status = 409;
2626
- return { error: "Agent run is not active" };
1841
+ const sizeError = expectedSizeBytesError(session, uploadBytes.byteLength);
1842
+ if (sizeError) {
1843
+ set.status = 400;
1844
+ return { error: sizeError };
2627
1845
  }
2628
- set.status = 202;
2629
- return CancelAgentRunResponseSchema.parse({ run: serializeAgentRun(current) });
1846
+ const digest = computeBlobDigest(uploadBytes);
1847
+ const digestError = expectedDigestError(session.expectedDigest, digest);
1848
+ if (digestError) {
1849
+ set.status = 400;
1850
+ return { error: digestError };
1851
+ }
1852
+ const fileRef = await sixb.blobStorage.put({
1853
+ body: uploadBytes,
1854
+ ...session.fileName === undefined ? {} : { fileName: session.fileName },
1855
+ ...session.mediaType === undefined ? {} : { mediaType: session.mediaType },
1856
+ ...session.logicalPath === undefined ? {} : { logicalPath: session.logicalPath }
1857
+ });
1858
+ await uploadSessions.markUploaded(session.id, fileRef);
1859
+ return { success: true };
2630
1860
  } catch (error) {
2631
- return handleAgentRouteError(error, set);
1861
+ return handleRouteError(error, set);
2632
1862
  }
2633
1863
  }, {
2634
- params: AgentThreadParamsSchema,
2635
- body: CancelAgentRunBodySchema,
1864
+ params: FileUploadIdParamsSchema,
1865
+ parse: readCappedUploadBody,
1866
+ error: mapUploadContentError,
2636
1867
  response: {
2637
- 202: CancelAgentRunResponseSchema,
1868
+ 200: SuccessResponseSchema,
2638
1869
  400: ErrorResponseSchema,
2639
1870
  404: ErrorResponseSchema,
2640
1871
  409: ErrorResponseSchema,
2641
- 501: ErrorResponseSchema
1872
+ 410: ErrorResponseSchema
2642
1873
  },
2643
1874
  detail: {
2644
- summary: "Cancel an agent thread's active run",
2645
- tags: [OPENAPI_TAGS.agentRuns.name],
2646
- operationId: "cancelAgentRun",
2647
- security: SIXB_CSRF_SECURITY_REQUIREMENT
1875
+ summary: "Upload staged file content through Sixb",
1876
+ tags: [OPENAPI_TAGS.files.name],
1877
+ operationId: "uploadFileContent",
1878
+ security: SIXB_CSRF_SECURITY_REQUIREMENT,
1879
+ requestBody: {
1880
+ required: true,
1881
+ content: {
1882
+ "application/octet-stream": {
1883
+ schema: {
1884
+ type: "string",
1885
+ format: "binary"
1886
+ }
1887
+ }
1888
+ }
1889
+ }
2648
1890
  }
2649
- }).post("/api/agent-threads/:threadId/runs/:runId/retry", async (context) => {
1891
+ }).post("/api/files/uploads/:uploadId/parts/:partNumber", async (context) => {
2650
1892
  const { params, set } = context;
2651
- const { authz, scoped } = requestAuthState(context);
1893
+ const { authz } = requestAuthState(context);
2652
1894
  try {
2653
- const storage = sixb.storage.agents;
2654
- if (!storage) {
2655
- return missingAgentStorageResponse(set);
2656
- }
2657
- const thread = await getAccessibleThread({
2658
- scoped,
2659
- storage,
2660
- projectId: sixb.id,
2661
- threadId: params.threadId
2662
- });
2663
- if (!thread) {
2664
- set.status = 404;
2665
- return { error: "Agent thread not found" };
1895
+ const principal = authz?.principal ?? SYSTEM_PRINCIPAL;
1896
+ const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
1897
+ if (session.status !== "pending") {
1898
+ throw terminalSessionError(session.status);
2666
1899
  }
2667
- const failedRun = await storage.runs.getById({ projectId: sixb.id, id: params.runId });
2668
- if (!failedRun || failedRun.threadId !== thread.id) {
2669
- set.status = 404;
2670
- return { error: "Agent run not found" };
1900
+ if (session.strategy !== "multipart" || session.providerUpload?.strategy !== "multipart") {
1901
+ set.status = 400;
1902
+ return { error: "Upload session does not use multipart strategy." };
2671
1903
  }
2672
- if (failedRun.status !== "failed") {
2673
- set.status = 409;
2674
- return { error: "Only failed agent runs can be retried" };
1904
+ if (!supportsDirectUpload(sixb.blobStorage)) {
1905
+ set.status = 400;
1906
+ return { error: "Blob storage does not support direct uploads." };
2675
1907
  }
2676
- const run = await storage.runs.create({
2677
- id: createAgentRunId(),
2678
- projectId: sixb.id,
2679
- threadId: thread.id,
2680
- agentId: failedRun.agentId,
2681
- triggerMessageId: failedRun.triggerMessageId,
2682
- requestedByPrincipal: principalForRequest(authz)
1908
+ const signedPart = await sixb.blobStorage.signUploadPart({
1909
+ uploadId: session.id,
1910
+ stagingKey: session.providerUpload.stagingKey,
1911
+ providerUploadId: session.providerUpload.providerUploadId,
1912
+ partNumber: Number.parseInt(params.partNumber, 10),
1913
+ expiresAt: session.expiresAt
1914
+ });
1915
+ await uploadSessions.addSignedPart(session.id, signedPart);
1916
+ return SignedFileUploadPartSchema.parse({
1917
+ ...signedPart,
1918
+ expiresAt: signedPart.expiresAt.toISOString()
2683
1919
  });
2684
- try {
2685
- const dispatch = await dispatchQueuedAgentRuns({
2686
- projectId: sixb.id,
2687
- storage,
2688
- queue: sixb.queues.agents,
2689
- runIds: [run.id]
2690
- });
2691
- const failure = dispatch.failures[0];
2692
- if (failure) {
2693
- console.error(`[SixbServer] Could not dispatch retried agent run '${run.id}'; retrying later.`, failure.error);
2694
- }
2695
- } catch (error) {
2696
- console.error(`[SixbServer] Could not dispatch retried agent run '${run.id}'; retrying later.`, error);
2697
- }
2698
- set.status = 202;
2699
- return RetryAgentRunResponseSchema.parse({ run: serializeAgentRun(run) });
2700
1920
  } catch (error) {
2701
- return handleAgentRouteError(error, set);
1921
+ return handleRouteError(error, set);
2702
1922
  }
2703
1923
  }, {
2704
- params: AgentRunParamsSchema.extend({ threadId: z7.string().trim().min(1) }),
1924
+ params: FileUploadPartParamsSchema,
2705
1925
  response: {
2706
- 202: RetryAgentRunResponseSchema,
1926
+ 200: SignedFileUploadPartSchema,
2707
1927
  400: ErrorResponseSchema,
2708
1928
  404: ErrorResponseSchema,
2709
1929
  409: ErrorResponseSchema,
2710
- 501: ErrorResponseSchema
1930
+ 410: ErrorResponseSchema
2711
1931
  },
2712
1932
  detail: {
2713
- summary: "Retry a failed agent run",
2714
- tags: [OPENAPI_TAGS.agentRuns.name],
2715
- operationId: "retryAgentRun",
1933
+ summary: "Sign a staged multipart upload part",
1934
+ tags: [OPENAPI_TAGS.files.name],
1935
+ operationId: "signFileUploadPart",
2716
1936
  security: SIXB_CSRF_SECURITY_REQUIREMENT
2717
1937
  }
2718
- }).get("/api/agent-threads/:threadId/runs", async (context) => {
2719
- const { params, query, set } = context;
2720
- const { scoped } = requestAuthState(context);
1938
+ }).post("/api/files/uploads/:uploadId/complete", async (context) => {
1939
+ const { body, params, set } = context;
1940
+ const { authz } = requestAuthState(context);
2721
1941
  try {
2722
- const storage = sixb.storage.agents;
2723
- if (!storage) {
2724
- return missingAgentStorageResponse(set);
1942
+ const principal = authz?.principal ?? SYSTEM_PRINCIPAL;
1943
+ const parsed = CompleteFileUploadBodySchema.parse(body ?? {});
1944
+ const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
1945
+ if (session.status === "completed" && session.fileRef) {
1946
+ return FileRefSchema.parse(session.fileRef);
2725
1947
  }
2726
- const thread = await getAccessibleThread({
2727
- scoped,
2728
- storage,
2729
- projectId: sixb.id,
2730
- threadId: params.threadId
2731
- });
2732
- if (!thread) {
2733
- set.status = 404;
2734
- return { error: "Agent thread not found" };
1948
+ if (session.status !== "pending") {
1949
+ throw terminalSessionError(session.status);
2735
1950
  }
2736
- const parsed = AgentRunListQuerySchema.parse(query);
2737
- const result = await storage.runs.list({
2738
- projectId: sixb.id,
2739
- threadId: thread.id,
2740
- statuses: parsed.status ? [parsed.status] : undefined,
2741
- limit: parseOptionalInt(parsed.limit),
2742
- offset: parseOptionalInt(parsed.offset),
2743
- order: parsed.order
1951
+ const expected = resolveExpectedUploadIdentity({
1952
+ session,
1953
+ requestedDigest: parsed.digest,
1954
+ requestedSizeBytes: parsed.sizeBytes
2744
1955
  });
2745
- return AgentRunListResponseSchema.parse({
2746
- runs: result.runs.map(serializeAgentRun),
2747
- hasMore: result.hasMore,
2748
- total: result.total
1956
+ if (session.strategy !== "server" && (expected.digest === undefined || expected.sizeBytes === undefined)) {
1957
+ throw new Error("Direct file uploads require an expected digest and size.");
1958
+ }
1959
+ const fileRef = session.strategy === "server" ? completeServerUpload(session) : await completeProviderUpload({
1960
+ session,
1961
+ expectedDigest: expected.digest,
1962
+ expectedSizeBytes: expected.sizeBytes,
1963
+ parts: parsed.parts,
1964
+ blobStorage: sixb.blobStorage
2749
1965
  });
1966
+ const identityError = expectedFileRefError(expected, fileRef);
1967
+ if (identityError) {
1968
+ throw new Error(identityError);
1969
+ }
1970
+ await uploadSessions.complete(session.id, fileRef);
1971
+ return FileRefSchema.parse(fileRef);
2750
1972
  } catch (error) {
2751
- return handleAgentRouteError(error, set);
1973
+ return handleRouteError(error, set);
2752
1974
  }
2753
1975
  }, {
2754
- params: AgentThreadParamsSchema,
2755
- query: AgentRunListQuerySchema,
1976
+ params: FileUploadIdParamsSchema,
1977
+ body: CompleteFileUploadBodySchema,
2756
1978
  response: {
2757
- 200: AgentRunListResponseSchema,
1979
+ 200: FileRefSchema,
2758
1980
  400: ErrorResponseSchema,
2759
1981
  404: ErrorResponseSchema,
2760
- 501: ErrorResponseSchema
1982
+ 409: ErrorResponseSchema,
1983
+ 410: ErrorResponseSchema
2761
1984
  },
2762
1985
  detail: {
2763
- summary: "List an agent thread's runs",
2764
- tags: [OPENAPI_TAGS.agentRuns.name],
2765
- operationId: "listAgentThreadRuns"
1986
+ summary: "Complete a staged file upload",
1987
+ tags: [OPENAPI_TAGS.files.name],
1988
+ operationId: "completeFileUpload",
1989
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
2766
1990
  }
2767
- }).get("/api/agent-runs/:runId", async (context) => {
1991
+ }).post("/api/files/uploads/:uploadId/abort", async (context) => {
2768
1992
  const { params, set } = context;
2769
- const { scoped } = requestAuthState(context);
1993
+ const { authz } = requestAuthState(context);
2770
1994
  try {
2771
- const storage = sixb.storage.agents;
2772
- if (!storage) {
2773
- return missingAgentStorageResponse(set);
1995
+ const principal = authz?.principal ?? SYSTEM_PRINCIPAL;
1996
+ const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
1997
+ if (session.status === "completed") {
1998
+ throw new FileUploadSessionError2("already_completed", "File upload session is already completed.");
2774
1999
  }
2775
- const run = await storage.runs.getById({ projectId: sixb.id, id: params.runId });
2776
- if (!run) {
2777
- set.status = 404;
2778
- return { error: "Agent run not found" };
2000
+ if (session.status === "pending" && session.providerUpload) {
2001
+ if (!supportsDirectUpload(sixb.blobStorage)) {
2002
+ set.status = 400;
2003
+ return { error: "Blob storage does not support direct uploads." };
2004
+ }
2005
+ await sixb.blobStorage.abortUpload({
2006
+ uploadId: session.id,
2007
+ stagingKey: session.providerUpload.stagingKey,
2008
+ providerUploadId: session.providerUpload.providerUploadId
2009
+ });
2779
2010
  }
2780
- const thread = await getAccessibleThread({
2781
- scoped,
2782
- storage,
2783
- projectId: sixb.id,
2784
- threadId: run.threadId
2785
- });
2786
- if (!thread) {
2787
- set.status = 404;
2788
- return { error: "Agent run not found" };
2011
+ if (session.status === "pending") {
2012
+ await uploadSessions.abort(session.id);
2789
2013
  }
2790
- return serializeAgentRun(run);
2014
+ return { success: true };
2791
2015
  } catch (error) {
2792
- return handleAgentRouteError(error, set);
2016
+ return handleRouteError(error, set);
2793
2017
  }
2794
2018
  }, {
2795
- params: AgentRunParamsSchema,
2019
+ params: FileUploadIdParamsSchema,
2796
2020
  response: {
2797
- 200: AgentRunSchema,
2021
+ 200: SuccessResponseSchema,
2798
2022
  400: ErrorResponseSchema,
2799
2023
  404: ErrorResponseSchema,
2800
- 501: ErrorResponseSchema
2024
+ 409: ErrorResponseSchema,
2025
+ 410: ErrorResponseSchema
2801
2026
  },
2802
2027
  detail: {
2803
- summary: "Get agent run",
2804
- tags: [OPENAPI_TAGS.agentRuns.name],
2805
- operationId: "getAgentRun"
2028
+ summary: "Abort a staged file upload",
2029
+ tags: [OPENAPI_TAGS.files.name],
2030
+ operationId: "abortFileUpload",
2031
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
2032
+ }
2033
+ });
2034
+ }
2035
+ function fileUploadResponse(session) {
2036
+ if (session.providerUpload?.strategy === "direct-put") {
2037
+ return {
2038
+ strategy: "direct-put",
2039
+ uploadId: session.id,
2040
+ method: session.providerUpload.method,
2041
+ url: session.providerUpload.url,
2042
+ headers: session.providerUpload.headers,
2043
+ expiresAt: session.providerUpload.expiresAt.toISOString()
2044
+ };
2045
+ }
2046
+ if (session.providerUpload?.strategy === "multipart") {
2047
+ return {
2048
+ strategy: "multipart",
2049
+ uploadId: session.id,
2050
+ partSizeBytes: session.providerUpload.partSizeBytes,
2051
+ expiresAt: session.providerUpload.expiresAt.toISOString()
2052
+ };
2053
+ }
2054
+ return {
2055
+ strategy: "server",
2056
+ uploadId: session.id,
2057
+ method: "PUT",
2058
+ url: `/api/files/uploads/${encodeURIComponent(session.id)}/content`,
2059
+ expiresAt: session.expiresAt.toISOString()
2060
+ };
2061
+ }
2062
+ function readCappedUploadBody(context) {
2063
+ return readRequestBodyWithLimit(context.request, DEFAULT_SIMPLE_FILE_UPLOAD_BYTES);
2064
+ }
2065
+ function readParsedUploadBytes(context) {
2066
+ return context.body instanceof Uint8Array ? context.body : new Uint8Array(0);
2067
+ }
2068
+ function mapUploadContentError(context) {
2069
+ const tooLarge = asRequestBodyTooLarge(context.error);
2070
+ if (tooLarge) {
2071
+ context.set.status = 413;
2072
+ return { error: tooLarge.message };
2073
+ }
2074
+ return;
2075
+ }
2076
+ function asRequestBodyTooLarge(error) {
2077
+ if (error instanceof RequestBodyTooLargeError) {
2078
+ return error;
2079
+ }
2080
+ const cause = error?.cause;
2081
+ return cause instanceof RequestBodyTooLargeError ? cause : undefined;
2082
+ }
2083
+ function terminalSessionError(status) {
2084
+ return new FileUploadSessionError2(status === "completed" ? "already_completed" : "already_aborted", `File upload session is already ${status}.`);
2085
+ }
2086
+ function completeServerUpload(session) {
2087
+ if (!session.fileRef) {
2088
+ throw new Error("Upload content has not been received.");
2089
+ }
2090
+ return session.fileRef;
2091
+ }
2092
+ async function completeProviderUpload(input) {
2093
+ const { blobStorage, session } = input;
2094
+ if (!session.providerUpload) {
2095
+ throw new Error("Upload session does not have provider upload state.");
2096
+ }
2097
+ if (!supportsDirectUpload(blobStorage)) {
2098
+ throw new Error("Blob storage does not support direct uploads.");
2099
+ }
2100
+ const fileRef = await blobStorage.completeUpload({
2101
+ uploadId: session.id,
2102
+ stagingKey: session.providerUpload.stagingKey,
2103
+ providerUploadId: session.providerUpload.providerUploadId,
2104
+ ...session.fileName === undefined ? {} : { fileName: session.fileName },
2105
+ ...session.mediaType === undefined ? {} : { mediaType: session.mediaType },
2106
+ ...session.logicalPath === undefined ? {} : { logicalPath: session.logicalPath },
2107
+ ...input.expectedSizeBytes === undefined ? {} : { expectedSizeBytes: input.expectedSizeBytes },
2108
+ ...input.expectedDigest === undefined ? {} : { expectedDigest: input.expectedDigest },
2109
+ ...input.parts === undefined ? {} : { parts: input.parts }
2110
+ });
2111
+ return fileRef;
2112
+ }
2113
+ function resolveExpectedUploadIdentity(input) {
2114
+ const digestError = expectedDigestError(input.session.expectedDigest, input.requestedDigest);
2115
+ if (digestError) {
2116
+ throw new Error(digestError);
2117
+ }
2118
+ const sizeError = expectedSizeBytesValueError(input.session.expectedSizeBytes, input.requestedSizeBytes);
2119
+ if (sizeError) {
2120
+ throw new Error(sizeError);
2121
+ }
2122
+ const digest = input.session.expectedDigest ?? input.requestedDigest;
2123
+ const sizeBytes = input.session.expectedSizeBytes ?? input.requestedSizeBytes;
2124
+ return {
2125
+ ...digest === undefined ? {} : { digest },
2126
+ ...sizeBytes === undefined ? {} : { sizeBytes }
2127
+ };
2128
+ }
2129
+ function expectedFileRefError(expected, fileRef) {
2130
+ return expectedSizeBytesValueError(expected.sizeBytes, fileRef.sizeBytes) ?? expectedDigestError(expected.digest, fileRef.digest);
2131
+ }
2132
+ function expectedDigestError(expectedDigest, actualDigest) {
2133
+ return expectedDigest !== undefined && actualDigest !== undefined && actualDigest !== expectedDigest ? `File upload digest mismatch: expected ${expectedDigest}, received ${actualDigest}.` : null;
2134
+ }
2135
+ function expectedSizeBytesError(session, actualSizeBytes) {
2136
+ return expectedSizeBytesValueError(session.expectedSizeBytes, actualSizeBytes);
2137
+ }
2138
+ function expectedSizeBytesValueError(expectedSizeBytes, actualSizeBytes) {
2139
+ return expectedSizeBytes !== undefined && actualSizeBytes !== undefined && actualSizeBytes !== expectedSizeBytes ? `File upload size mismatch: expected ${expectedSizeBytes} bytes, received ${actualSizeBytes}.` : null;
2140
+ }
2141
+ function requestSizeLimitError(request, maxSizeBytes) {
2142
+ const value = request.headers.get("content-length");
2143
+ if (value === null) {
2144
+ return null;
2145
+ }
2146
+ const sizeBytes = Number(value);
2147
+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= maxSizeBytes) {
2148
+ return null;
2149
+ }
2150
+ return `File upload request exceeds the ${maxSizeBytes} byte limit.`;
2151
+ }
2152
+ function expectedContentLengthError(session, request) {
2153
+ if (session.expectedSizeBytes === undefined) {
2154
+ return null;
2155
+ }
2156
+ const value = request.headers.get("content-length");
2157
+ if (value === null) {
2158
+ return null;
2159
+ }
2160
+ const sizeBytes = Number(value);
2161
+ if (!Number.isSafeInteger(sizeBytes)) {
2162
+ return null;
2163
+ }
2164
+ return expectedSizeBytesError(session, sizeBytes);
2165
+ }
2166
+
2167
+ // src/routes/agent-api-gateway.ts
2168
+ var MAX_AGENT_API_BODY_BYTES = 1e6;
2169
+ var HOP_BY_HOP_RESPONSE_HEADERS = new Set([
2170
+ "connection",
2171
+ "keep-alive",
2172
+ "proxy-authenticate",
2173
+ "proxy-authorization",
2174
+ "te",
2175
+ "trailer",
2176
+ "transfer-encoding",
2177
+ "upgrade"
2178
+ ]);
2179
+ function registerAgentApiGatewayRoutes(app, sixb) {
2180
+ for (const route of AGENT_API_ROUTES) {
2181
+ const path = `${AGENT_API_GATEWAY_PREFIX2}/:agentGatewayRunId/:agentGatewayCapability${route.path}`;
2182
+ const handler = async (context) => handleAgentApiGatewayRequest({
2183
+ sixb,
2184
+ app,
2185
+ request: context.request,
2186
+ agentRunId: context.params.agentGatewayRunId ?? "",
2187
+ capability: context.params.agentGatewayCapability ?? ""
2188
+ });
2189
+ if (route.method === "GET") {
2190
+ app.get(path, handler, { detail: { hide: true } });
2191
+ continue;
2192
+ }
2193
+ if (route.method === "POST") {
2194
+ app.post(path, handler, { detail: { hide: true } });
2195
+ continue;
2196
+ }
2197
+ throw new Error(`[SixbServer] Unsupported agent API gateway method '${route.method}'.`);
2198
+ }
2199
+ }
2200
+ async function handleAgentApiGatewayRequest(input) {
2201
+ const sourceUrl = new URL(input.request.url);
2202
+ const upstreamPath = gatewayUpstreamPath(sourceUrl.pathname);
2203
+ if (!isAllowedAgentApiRequest(input.request.method, upstreamPath)) {
2204
+ return jsonError(403, `Agent API gateway does not allow ${input.request.method} ${upstreamPath}.`);
2205
+ }
2206
+ const authState = await resolveAgentRunAuthState(input.sixb, {
2207
+ runId: input.agentRunId,
2208
+ capability: input.capability
2209
+ });
2210
+ if (authState instanceof Response) {
2211
+ return authState;
2212
+ }
2213
+ if (authState.agentExecution.kind === "workflow" && input.request.method === "POST" && matchesWorkflowRunStart(upstreamPath)) {
2214
+ return jsonError(409, "Workflow agent nodes cannot start another workflow run.");
2215
+ }
2216
+ let body;
2217
+ try {
2218
+ body = await readRequestBody(input.request, isSimpleFileUpload(input.request.method, upstreamPath) ? DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES : MAX_AGENT_API_BODY_BYTES);
2219
+ } catch (error) {
2220
+ if (error instanceof PayloadTooLargeError) {
2221
+ return jsonError(413, error.message);
2806
2222
  }
2223
+ throw error;
2224
+ }
2225
+ const internalUrl = new URL(`${upstreamPath}${sourceUrl.search}`, input.request.url);
2226
+ const internalRequest = new Request(internalUrl, {
2227
+ method: input.request.method,
2228
+ headers: forwardedRequestHeaders(input.request.headers),
2229
+ body
2230
+ });
2231
+ registerInternalRequestAuthState(internalRequest, authState);
2232
+ const response = await input.app.fetch(internalRequest);
2233
+ return new Response(response.body, {
2234
+ status: response.status,
2235
+ statusText: response.statusText,
2236
+ headers: forwardedResponseHeaders(response.headers)
2237
+ });
2238
+ }
2239
+ async function resolveAgentRunAuthState(sixb, input) {
2240
+ const agentStorage = sixb.storage.agents;
2241
+ const workflowRuns = sixb.storage.workflowRuns;
2242
+ if (!agentStorage && !workflowRuns) {
2243
+ return jsonError(501, "Agent API gateway is not configured for this runtime.");
2244
+ }
2245
+ const conversationalRun = await agentStorage?.runs.getById({
2246
+ projectId: sixb.id,
2247
+ id: input.runId
2248
+ });
2249
+ const workflowRun = conversationalRun ? null : await workflowRuns?.agentNodes.getByNodeRunId({
2250
+ projectId: sixb.id,
2251
+ nodeRunId: input.runId
2252
+ });
2253
+ const run = conversationalRun ?? workflowRun;
2254
+ const agentExecution = conversationalRun ? { kind: "conversation", runId: conversationalRun.id } : workflowRun ? { kind: "workflow", nodeRunId: workflowRun.nodeRunId } : null;
2255
+ if (!run || !agentExecution || run.status !== "running" || !run.execution || run.execution.queueLeaseExpiresAt.getTime() <= Date.now() || !isValidAgentApiGatewayCapability({
2256
+ projectId: sixb.id,
2257
+ runId: input.runId,
2258
+ executionToken: run.execution.token,
2259
+ capability: input.capability
2260
+ })) {
2261
+ return jsonError(403, "Agent API gateway capability is not valid for this run.");
2262
+ }
2263
+ if (!sixb.auth.isEnabled()) {
2264
+ return {
2265
+ authz: null,
2266
+ scoped: null,
2267
+ agentExecution,
2268
+ ...conversationalRun ? { agentRun: conversationalRun } : {}
2269
+ };
2270
+ }
2271
+ const auth = sixb.storage.auth;
2272
+ if (!auth) {
2273
+ return jsonError(501, "Agent API gateway is not configured for authenticated agent access.");
2274
+ }
2275
+ if (!run.executionPrincipal) {
2276
+ return jsonError(403, "Agent run has no execution identity.");
2277
+ }
2278
+ const serviceAccount = await auth.serviceAccounts.getById({
2279
+ projectId: sixb.id,
2280
+ id: run.executionPrincipal.id
2281
+ });
2282
+ if (!serviceAccount || serviceAccount.status !== "active") {
2283
+ return jsonError(403, "Agent execution identity is not active.");
2284
+ }
2285
+ const memberships = await auth.serviceAccountGroupMemberships.listForServiceAccount({
2286
+ projectId: sixb.id,
2287
+ serviceAccountId: serviceAccount.id
2288
+ });
2289
+ const authz = resolveAuthorizationContext({
2290
+ principal: run.executionPrincipal,
2291
+ groupIds: memberships.map((membership) => membership.groupId),
2292
+ roles: sixb.security.listResolvedRoles()
2807
2293
  });
2294
+ return {
2295
+ authz,
2296
+ scoped: sixb.as(authz),
2297
+ agentExecution,
2298
+ ...conversationalRun ? { agentRun: conversationalRun } : {}
2299
+ };
2300
+ }
2301
+ function gatewayUpstreamPath(pathname) {
2302
+ const prefixLength = pathSegmentsFor(AGENT_API_GATEWAY_PREFIX2).length;
2303
+ const segments = pathSegmentsFor(pathname);
2304
+ const upstreamSegments = segments.slice(prefixLength + 2);
2305
+ return normalizeRoutePath2(`/${upstreamSegments.join("/")}`);
2306
+ }
2307
+ function forwardedRequestHeaders(source) {
2308
+ const headers = new Headers;
2309
+ copyHeader(source, headers, "accept");
2310
+ copyHeader(source, headers, "content-type");
2311
+ return headers;
2312
+ }
2313
+ function forwardedResponseHeaders(source) {
2314
+ const headers = new Headers;
2315
+ for (const [key, value] of source) {
2316
+ const normalized = key.toLowerCase();
2317
+ if (HOP_BY_HOP_RESPONSE_HEADERS.has(normalized) || normalized === "content-length" || normalized === "set-cookie") {
2318
+ continue;
2319
+ }
2320
+ headers.append(key, value);
2321
+ }
2322
+ return headers;
2323
+ }
2324
+ function copyHeader(source, target, name) {
2325
+ const value = source.get(name);
2326
+ if (value !== null) {
2327
+ target.set(name, value);
2328
+ }
2329
+ }
2330
+ async function readRequestBody(request, maxBytes) {
2331
+ if (!request.body || request.method === "GET" || request.method === "HEAD") {
2332
+ return;
2333
+ }
2334
+ const reader = request.body.getReader();
2335
+ const chunks = [];
2336
+ let total = 0;
2337
+ while (true) {
2338
+ const { done, value } = await reader.read();
2339
+ if (done)
2340
+ break;
2341
+ total += value.byteLength;
2342
+ if (total > maxBytes) {
2343
+ 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.`);
2344
+ }
2345
+ chunks.push(value);
2346
+ }
2347
+ return concatChunks(chunks, total);
2348
+ }
2349
+ function isSimpleFileUpload(method, pathname) {
2350
+ return method === "POST" && normalizeRoutePath2(pathname) === "/api/files";
2351
+ }
2352
+ function matchesWorkflowRunStart(pathname) {
2353
+ const segments = pathSegmentsFor(pathname);
2354
+ return segments.length === 4 && segments[0] === "api" && segments[1] === "workflows" && segments[3] === "runs";
2355
+ }
2356
+ function concatChunks(chunks, total) {
2357
+ const buffer = new ArrayBuffer(total);
2358
+ const result = new Uint8Array(buffer);
2359
+ let offset = 0;
2360
+ for (const chunk of chunks) {
2361
+ result.set(chunk, offset);
2362
+ offset += chunk.byteLength;
2363
+ }
2364
+ return buffer;
2365
+ }
2366
+ function jsonError(status, message) {
2367
+ return Response.json({ error: message }, { status });
2808
2368
  }
2809
2369
 
2810
- // src/schemas/connectors.ts
2811
- import { z as z8 } from "zod";
2812
- var ConnectorParamsSchema = z8.object({
2813
- connectorId: z8.string().min(1)
2370
+ class PayloadTooLargeError extends Error {
2371
+ }
2372
+
2373
+ // src/routes/agents.ts
2374
+ import {
2375
+ AgentRequestError,
2376
+ SYSTEM_PRINCIPAL as SYSTEM_PRINCIPAL2
2377
+ } from "@sixb/core";
2378
+ import { agentRunStreamId } from "@sixb/core/agents/streams";
2379
+ import {
2380
+ createAgentRunId,
2381
+ createAgentThreadId,
2382
+ dispatchQueuedAgentRuns,
2383
+ publishAgentRunCancel,
2384
+ publishAgentRunFinished
2385
+ } from "@sixb/core/internal/agents";
2386
+ import {
2387
+ AgentStorageError
2388
+ } from "@sixb/core/storage";
2389
+ import { ZodError as ZodError2, z as z7 } from "zod";
2390
+
2391
+ // src/schemas/agents.ts
2392
+ import { AGENT_REASONING_LEVELS, MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core";
2393
+ import { AGENT_RUN_DIAGNOSTIC_CODES } from "@sixb/core/storage";
2394
+ import { z as z6 } from "zod";
2395
+ var AgentIdParamsSchema = z6.object({
2396
+ agentId: z6.string().min(1)
2397
+ });
2398
+ var AgentThreadParamsSchema = z6.object({
2399
+ threadId: z6.string().min(1)
2400
+ });
2401
+ var AgentRunParamsSchema = z6.object({
2402
+ runId: z6.string().min(1)
2403
+ });
2404
+ var AgentMessageFileContentParamsSchema = AgentThreadParamsSchema.extend({
2405
+ messageId: z6.string().min(1)
2406
+ });
2407
+ var AgentPrincipalSchema = z6.object({
2408
+ type: z6.enum(["user", "serviceAccount", "system"]),
2409
+ id: z6.string().min(1)
2410
+ });
2411
+ var AgentObjectContextSchema = z6.object({
2412
+ kind: z6.literal("object"),
2413
+ ref: z6.object({
2414
+ objectTypeId: z6.string().min(1),
2415
+ primaryId: z6.string().min(1)
2416
+ })
2417
+ });
2418
+ var AgentAppStateContextSchema = z6.object({
2419
+ kind: z6.literal("app-state"),
2420
+ id: z6.string().min(1),
2421
+ label: z6.string().min(1),
2422
+ description: z6.string().min(1),
2423
+ value: JsonValueSchema
2424
+ });
2425
+ var AgentContextInputSchema = z6.discriminatedUnion("kind", [
2426
+ AgentObjectContextSchema,
2427
+ AgentAppStateContextSchema
2428
+ ]);
2429
+ var AgentContextOriginSchema = z6.enum(["ambient", "explicit"]);
2430
+ var AgentContextEntryInputSchema = z6.object({
2431
+ context: AgentContextInputSchema,
2432
+ origin: AgentContextOriginSchema
2433
+ });
2434
+ var AgentContextPartSchema = AgentContextEntryInputSchema.extend({
2435
+ type: z6.literal("context")
2436
+ });
2437
+ var AgentLoopConfigSchema = z6.object({
2438
+ stopWhen: z6.object({
2439
+ maxSteps: z6.number().int().positive().optional()
2440
+ }).optional()
2441
+ });
2442
+ var AgentReasoningLevelSchema = z6.enum(AGENT_REASONING_LEVELS);
2443
+ var AgentCatalogItemSchema = z6.object({
2444
+ id: z6.string(),
2445
+ name: z6.string(),
2446
+ description: z6.string().optional(),
2447
+ modelId: z6.string().optional(),
2448
+ reasoning: AgentReasoningLevelSchema.optional(),
2449
+ groupIds: z6.array(z6.string()),
2450
+ loop: AgentLoopConfigSchema.optional()
2451
+ });
2452
+ var AgentThreadStatusSchema = z6.enum(["active", "archived"]);
2453
+ var AgentThreadListQuerySchema = z6.object({
2454
+ agentId: z6.string().optional(),
2455
+ status: AgentThreadStatusSchema.optional(),
2456
+ limit: z6.string().optional(),
2457
+ offset: z6.string().optional(),
2458
+ order: z6.enum(["asc", "desc"]).optional()
2459
+ });
2460
+ var CreateAgentThreadBodySchema = z6.object({
2461
+ agentId: z6.string().min(1),
2462
+ title: z6.string().trim().min(1).optional(),
2463
+ threadId: z6.string().trim().min(1).optional()
2464
+ });
2465
+ var AgentThreadSchema = z6.object({
2466
+ id: z6.string(),
2467
+ projectId: z6.string(),
2468
+ agentId: z6.string(),
2469
+ ownerPrincipal: AgentPrincipalSchema,
2470
+ title: z6.string().optional(),
2471
+ status: AgentThreadStatusSchema,
2472
+ activeRunId: z6.string().nullable(),
2473
+ lastMessageAt: z6.string().optional(),
2474
+ messageCount: z6.number(),
2475
+ createdAt: z6.string(),
2476
+ updatedAt: z6.string()
2814
2477
  });
2815
- var ConnectorWebhookSchema = z8.object({
2816
- id: z8.string(),
2817
- method: z8.literal("POST"),
2818
- route: z8.string(),
2819
- bodyFormat: z8.enum(["json", "text", "raw"]),
2820
- hasVerify: z8.boolean(),
2821
- hasIdempotency: z8.boolean()
2478
+ var AgentThreadListResponseSchema = z6.object({
2479
+ threads: z6.array(AgentThreadSchema),
2480
+ hasMore: z6.boolean(),
2481
+ total: z6.number()
2822
2482
  });
2823
- var ConnectorSchema = z8.object({
2824
- id: z8.string(),
2825
- type: z8.string(),
2826
- syncIds: z8.array(z8.string()),
2827
- webhooks: z8.array(ConnectorWebhookSchema)
2483
+ var CreateAgentThreadResponseSchema = z6.object({
2484
+ thread: AgentThreadSchema
2828
2485
  });
2829
-
2830
- // src/routes/connectors.ts
2831
- function serializeConnector(connector, sixb) {
2832
- return {
2833
- id: connector.id,
2834
- type: connector.adapter.type,
2835
- syncIds: sixb.listSyncs().filter((sync) => sync.connector.id === connector.id).map((sync) => sync.id),
2836
- webhooks: sixb.listWebhooks().filter((registered) => registered.connector.id === connector.id).map(({ webhook, route }) => ({
2837
- id: webhook.id,
2838
- method: webhook.method,
2839
- route,
2840
- bodyFormat: webhook.body.format,
2841
- hasVerify: typeof webhook.verify === "function",
2842
- hasIdempotency: typeof webhook.idempotencyKey === "function"
2843
- }))
2844
- };
2845
- }
2846
- function registerConnectorRoutes(app, sixb) {
2847
- return app.get("/api/connectors", () => {
2848
- return sixb.listConnectors().map((connector) => serializeConnector(connector, sixb));
2849
- }, {
2850
- response: { 200: ConnectorSchema.array() },
2851
- detail: {
2852
- summary: "List registered connectors",
2853
- tags: [OPENAPI_TAGS.connectors.name],
2854
- operationId: "listConnectors"
2855
- }
2856
- }).get("/api/connectors/:connectorId", ({ params, set }) => {
2857
- const connector = sixb.getConnectorById(params.connectorId);
2858
- if (!connector) {
2859
- set.status = 404;
2860
- return { error: "Connector not found" };
2861
- }
2862
- return serializeConnector(connector, sixb);
2863
- }, {
2864
- params: ConnectorParamsSchema,
2865
- response: { 200: ConnectorSchema, 404: ErrorResponseSchema },
2866
- detail: {
2867
- summary: "Get connector metadata",
2868
- tags: [OPENAPI_TAGS.connectors.name],
2869
- operationId: "getConnector"
2870
- }
2871
- });
2872
- }
2873
-
2874
- // src/schemas/datasets.ts
2875
- import { z as z9 } from "zod";
2876
- var DatasetParamsSchema = z9.object({
2877
- datasetId: z9.string().min(1)
2486
+ var AgentMessageRoleSchema = z6.enum(["system", "user", "assistant"]);
2487
+ var AgentTextPartSchema = z6.object({
2488
+ type: z6.literal("text"),
2489
+ text: z6.string(),
2490
+ providerMetadata: JsonValueSchema.optional()
2878
2491
  });
2879
- var DatasetVersionParamsSchema = DatasetParamsSchema.extend({
2880
- versionId: z9.string().min(1)
2492
+ var AgentReasoningPartSchema = z6.object({
2493
+ type: z6.literal("reasoning"),
2494
+ text: z6.string(),
2495
+ providerMetadata: JsonValueSchema.optional()
2881
2496
  });
2882
- var DatasetVersionsQuerySchema = z9.object({
2883
- limit: z9.string().optional()
2497
+ var AgentStepStartPartSchema = z6.object({
2498
+ type: z6.literal("step-start")
2884
2499
  });
2885
- var DatasetRowsQuerySchema = z9.object({
2886
- versionId: z9.string().optional(),
2887
- columns: z9.string().optional(),
2888
- limit: z9.string().optional(),
2889
- offset: z9.string().optional()
2500
+ var AgentFilePartSchema = z6.object({
2501
+ type: z6.literal("file"),
2502
+ fileRef: FileRefSchema,
2503
+ providerMetadata: JsonValueSchema.optional()
2890
2504
  });
2891
- var DatasetColumnSchema = z9.object({
2892
- name: z9.string(),
2893
- type: z9.enum([
2894
- "string",
2895
- "boolean",
2896
- "int64",
2897
- "float64",
2898
- "decimal",
2899
- "date",
2900
- "timestamp",
2901
- "json",
2902
- "fileRef"
2903
- ]),
2904
- nullable: z9.boolean().optional()
2505
+ var AgentToolCallBaseSchema = z6.object({
2506
+ type: z6.literal("tool-call"),
2507
+ toolCallId: z6.string(),
2508
+ toolName: z6.string(),
2509
+ dynamic: z6.boolean().optional(),
2510
+ providerExecuted: z6.boolean().optional(),
2511
+ input: JsonValueSchema,
2512
+ providerMetadata: JsonValueSchema.optional()
2905
2513
  });
2906
- var DatasetSchema = z9.object({
2907
- columns: z9.array(DatasetColumnSchema)
2514
+ var AgentToolCallOutputSchema = AgentToolCallBaseSchema.extend({
2515
+ state: z6.literal("output-available"),
2516
+ output: JsonValueSchema
2908
2517
  });
2909
- var DatasetDefinitionSchema = z9.object({
2910
- id: z9.string(),
2911
- description: z9.string().optional(),
2912
- partitionBy: z9.array(z9.string()).optional(),
2913
- schema: DatasetSchema
2518
+ var AgentToolCallErrorSchema = AgentToolCallBaseSchema.extend({
2519
+ state: z6.literal("output-error"),
2520
+ errorText: z6.string()
2914
2521
  });
2915
- var DatasetVersionRefSchema = z9.object({
2916
- datasetId: z9.string(),
2917
- versionId: z9.string()
2522
+ var AgentMessagePartSchema = z6.union([
2523
+ AgentTextPartSchema,
2524
+ AgentReasoningPartSchema,
2525
+ AgentStepStartPartSchema,
2526
+ AgentFilePartSchema,
2527
+ AgentContextPartSchema,
2528
+ AgentToolCallOutputSchema,
2529
+ AgentToolCallErrorSchema
2530
+ ]);
2531
+ var AgentRunDiagnosticSchema = z6.object({
2532
+ code: z6.enum(AGENT_RUN_DIAGNOSTIC_CODES),
2533
+ severity: z6.enum(["warning", "error"]),
2534
+ scope: z6.literal("output"),
2535
+ path: z6.string().optional(),
2536
+ message: z6.string()
2918
2537
  });
2919
- var DatasetProducerSchema = z9.object({
2920
- kind: z9.enum(["sync", "pipeline"]),
2921
- id: z9.string().optional(),
2922
- runId: z9.string().optional()
2538
+ var AgentMessageSchema = z6.object({
2539
+ id: z6.string(),
2540
+ projectId: z6.string(),
2541
+ threadId: z6.string(),
2542
+ runId: z6.string().nullable(),
2543
+ role: AgentMessageRoleSchema,
2544
+ authorPrincipal: AgentPrincipalSchema.optional(),
2545
+ seq: z6.number(),
2546
+ parts: z6.array(AgentMessagePartSchema),
2547
+ annotations: z6.array(AgentRunDiagnosticSchema),
2548
+ metadata: JsonValueSchema.optional(),
2549
+ contentVersion: z6.number(),
2550
+ createdAt: z6.string(),
2551
+ completedAt: z6.string().optional()
2923
2552
  });
2924
- var DatasetVersionSchema = z9.object({
2925
- datasetId: z9.string(),
2926
- versionId: z9.string(),
2927
- parentVersionId: z9.string().optional(),
2928
- mode: z9.enum(["snapshot", "append", "schema"]),
2929
- createdAt: z9.string(),
2930
- schema: DatasetSchema,
2931
- producer: DatasetProducerSchema.optional(),
2932
- inputs: z9.array(DatasetVersionRefSchema).optional(),
2933
- rowCount: z9.number().optional(),
2934
- sizeBytes: z9.number().optional()
2553
+ var AgentMessagesQuerySchema = z6.object({
2554
+ role: AgentMessageRoleSchema.optional(),
2555
+ limit: z6.string().optional(),
2556
+ offset: z6.string().optional(),
2557
+ order: z6.enum(["asc", "desc"]).optional()
2935
2558
  });
2936
- var DatasetLatestVersionSummarySchema = z9.object({
2937
- datasetId: z9.string(),
2938
- versionId: z9.string(),
2939
- mode: z9.enum(["snapshot", "append", "schema"]),
2940
- createdAt: z9.string(),
2941
- rowCount: z9.number().optional()
2559
+ var AgentMessageListResponseSchema = z6.object({
2560
+ messages: z6.array(AgentMessageSchema),
2561
+ hasMore: z6.boolean(),
2562
+ total: z6.number()
2942
2563
  });
2943
- var DatasetCatalogItemSchema = DatasetDefinitionSchema.extend({
2944
- kind: z9.literal("dataset"),
2945
- materialized: z9.boolean(),
2946
- latestVersion: DatasetLatestVersionSummarySchema.nullable(),
2947
- syncIds: z9.array(z9.string()),
2948
- sourcePipelineIds: z9.array(z9.string()),
2949
- targetPipelineIds: z9.array(z9.string()),
2950
- projectionIds: z9.array(z9.string())
2564
+ var PostAgentMessageBodySchema = z6.object({
2565
+ text: z6.string().trim().min(1),
2566
+ attachments: z6.array(FileRefSchema).optional(),
2567
+ context: z6.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
2568
+ messageId: z6.string().trim().min(1).optional()
2569
+ });
2570
+ var CancelAgentRunBodySchema = z6.object({
2571
+ runId: z6.string().trim().min(1)
2572
+ });
2573
+ var AgentRunStatusSchema = z6.enum([
2574
+ "queued",
2575
+ "running",
2576
+ "succeeded",
2577
+ "failed",
2578
+ "cancelled"
2579
+ ]);
2580
+ var AgentRunFinishReasonSchema = z6.enum([
2581
+ "stop",
2582
+ "length",
2583
+ "content-filter",
2584
+ "tool-calls",
2585
+ "error",
2586
+ "other",
2587
+ "unknown"
2588
+ ]);
2589
+ var AgentRunUsageSchema = z6.object({
2590
+ inputTokens: z6.number().optional(),
2591
+ outputTokens: z6.number().optional(),
2592
+ totalTokens: z6.number().optional(),
2593
+ reasoningTokens: z6.number().optional(),
2594
+ cachedInputTokens: z6.number().optional()
2595
+ });
2596
+ var AgentRunSchema = z6.object({
2597
+ id: z6.string(),
2598
+ projectId: z6.string(),
2599
+ threadId: z6.string(),
2600
+ agentId: z6.string(),
2601
+ triggerMessageId: z6.string(),
2602
+ requestedByPrincipal: AgentPrincipalSchema,
2603
+ executionPrincipal: AgentPrincipalSchema.optional(),
2604
+ status: AgentRunStatusSchema,
2605
+ modelId: z6.string().optional(),
2606
+ finishReason: AgentRunFinishReasonSchema.optional(),
2607
+ usage: AgentRunUsageSchema.optional(),
2608
+ diagnostics: z6.array(AgentRunDiagnosticSchema).optional(),
2609
+ error: z6.string().optional(),
2610
+ attempt: z6.number(),
2611
+ streamId: z6.string(),
2612
+ createdAt: z6.string(),
2613
+ startedAt: z6.string().optional(),
2614
+ completedAt: z6.string().optional()
2615
+ });
2616
+ var PostAgentMessageResponseSchema = z6.object({
2617
+ run: AgentRunSchema
2618
+ });
2619
+ var CancelAgentRunResponseSchema = z6.object({
2620
+ run: AgentRunSchema
2621
+ });
2622
+ var RetryAgentRunResponseSchema = z6.object({
2623
+ run: AgentRunSchema
2951
2624
  });
2952
- var DatasetVersionListResponseSchema = z9.object({
2953
- versions: z9.array(DatasetVersionSchema),
2954
- count: z9.number()
2625
+ var AgentRunListQuerySchema = z6.object({
2626
+ status: AgentRunStatusSchema.optional(),
2627
+ limit: z6.string().optional(),
2628
+ offset: z6.string().optional(),
2629
+ order: z6.enum(["asc", "desc"]).optional()
2955
2630
  });
2956
- var DatasetRowsResponseSchema = z9.object({
2957
- datasetId: z9.string(),
2958
- versionId: z9.string(),
2959
- version: DatasetVersionSchema,
2960
- columns: z9.array(z9.string()),
2961
- rows: z9.array(z9.record(z9.unknown())),
2962
- count: z9.number(),
2963
- limit: z9.number(),
2964
- offset: z9.number(),
2965
- total: z9.number().optional(),
2966
- hasMore: z9.boolean()
2631
+ var AgentRunListResponseSchema = z6.object({
2632
+ runs: z6.array(AgentRunSchema),
2633
+ hasMore: z6.boolean(),
2634
+ total: z6.number()
2967
2635
  });
2968
2636
 
2969
- // src/routes/datasets.ts
2970
- var DEFAULT_VERSION_LIMIT = 20;
2971
- var MAX_VERSION_LIMIT = 100;
2972
- var DEFAULT_ROW_LIMIT = 100;
2973
- var MAX_ROW_LIMIT = 1000;
2974
- function parseLimit(value, fallback, max) {
2975
- const parsed = parseOptionalInt(value) ?? fallback;
2976
- if (parsed < 0) {
2977
- throw new Error("Limit must be greater than or equal to 0");
2978
- }
2979
- return Math.min(parsed, max);
2637
+ // src/routes/agents.ts
2638
+ var AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
2639
+ path: z7.string().min(1).regex(/^\/parts(?:\/|$)/, "Agent message file content paths must start with /parts/")
2640
+ });
2641
+ function serializeAgent(agent) {
2642
+ return AgentCatalogItemSchema.parse({
2643
+ id: agent.id,
2644
+ name: agent.name,
2645
+ description: agent.description,
2646
+ modelId: agent.model.modelId,
2647
+ reasoning: agent.reasoning,
2648
+ groupIds: agent.groupIds,
2649
+ loop: agent.loop
2650
+ });
2980
2651
  }
2981
- function parseOffset(value) {
2982
- const parsed = parseOptionalInt(value) ?? 0;
2983
- if (parsed < 0) {
2984
- throw new Error("Offset must be greater than or equal to 0");
2652
+ function serializeThread(thread) {
2653
+ return AgentThreadSchema.parse({
2654
+ id: thread.id,
2655
+ projectId: thread.projectId,
2656
+ agentId: thread.agentId,
2657
+ ownerPrincipal: thread.ownerPrincipal,
2658
+ title: thread.title,
2659
+ status: thread.status,
2660
+ activeRunId: thread.activeRunId,
2661
+ lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
2662
+ messageCount: thread.messageCount,
2663
+ createdAt: toIsoString(thread.createdAt),
2664
+ updatedAt: toIsoString(thread.updatedAt)
2665
+ });
2666
+ }
2667
+ function serializeMessage(message, annotations = []) {
2668
+ return AgentMessageSchema.parse({
2669
+ id: message.id,
2670
+ projectId: message.projectId,
2671
+ threadId: message.threadId,
2672
+ runId: message.runId,
2673
+ role: message.role,
2674
+ authorPrincipal: message.authorPrincipal,
2675
+ seq: message.seq,
2676
+ parts: message.parts,
2677
+ annotations,
2678
+ metadata: message.metadata,
2679
+ contentVersion: message.contentVersion,
2680
+ createdAt: toIsoString(message.createdAt),
2681
+ completedAt: message.completedAt ? toIsoString(message.completedAt) : undefined
2682
+ });
2683
+ }
2684
+ function serializeAgentRun(run) {
2685
+ return AgentRunSchema.parse({
2686
+ id: run.id,
2687
+ projectId: run.projectId,
2688
+ threadId: run.threadId,
2689
+ agentId: run.agentId,
2690
+ triggerMessageId: run.triggerMessageId,
2691
+ requestedByPrincipal: run.requestedByPrincipal,
2692
+ executionPrincipal: run.executionPrincipal,
2693
+ status: run.status,
2694
+ modelId: run.modelId,
2695
+ finishReason: run.finishReason,
2696
+ usage: run.usage,
2697
+ diagnostics: run.diagnostics,
2698
+ error: run.error,
2699
+ attempt: run.attempt,
2700
+ streamId: agentRunStreamId(run.id),
2701
+ createdAt: toIsoString(run.createdAt),
2702
+ startedAt: run.startedAt ? toIsoString(run.startedAt) : undefined,
2703
+ completedAt: run.completedAt ? toIsoString(run.completedAt) : undefined
2704
+ });
2705
+ }
2706
+ async function getAccessibleThread(params) {
2707
+ if (params.scoped) {
2708
+ return params.scoped.getThread(params.threadId);
2985
2709
  }
2986
- return parsed;
2710
+ return params.storage.threads.getById({ projectId: params.projectId, id: params.threadId });
2987
2711
  }
2988
- function serializeDatasetVersion(version) {
2989
- return DatasetVersionSchema.parse({
2990
- datasetId: version.datasetId,
2991
- versionId: version.versionId,
2992
- parentVersionId: version.parentVersionId,
2993
- mode: version.mode,
2994
- createdAt: toIsoString(version.createdAt),
2995
- schema: version.schema,
2996
- producer: version.producer,
2997
- inputs: version.inputs,
2998
- rowCount: version.rowCount,
2999
- sizeBytes: version.sizeBytes
2712
+ async function getAgentMessageFileContentThread(params) {
2713
+ const { agentRun } = params.authState;
2714
+ if (agentRun) {
2715
+ if (agentRun.projectId !== params.projectId || agentRun.threadId !== params.threadId) {
2716
+ return null;
2717
+ }
2718
+ return params.storage.threads.getById({ projectId: params.projectId, id: params.threadId });
2719
+ }
2720
+ return getAccessibleThread({
2721
+ scoped: params.authState.scoped,
2722
+ storage: params.storage,
2723
+ projectId: params.projectId,
2724
+ threadId: params.threadId
3000
2725
  });
3001
2726
  }
3002
- var EMPTY_DATASET_REFERENCES = {
3003
- syncIds: [],
3004
- sourcePipelineIds: [],
3005
- targetPipelineIds: [],
3006
- projectionIds: []
3007
- };
3008
- function buildDatasetReferenceIndex(sixb, scoped = null) {
3009
- const index = new Map;
3010
- const referencesFor = (datasetId) => {
3011
- let references = index.get(datasetId);
3012
- if (!references) {
3013
- references = { syncIds: [], sourcePipelineIds: [], targetPipelineIds: [], projectionIds: [] };
3014
- index.set(datasetId, references);
2727
+ function principalForRequest(authz) {
2728
+ return authz?.principal ?? SYSTEM_PRINCIPAL2;
2729
+ }
2730
+ async function publishQueuedRunCancellation(sixb, run) {
2731
+ try {
2732
+ await publishAgentRunFinished(sixb.broker, run);
2733
+ } catch (error) {
2734
+ console.error(`[SixbServer] Agent run '${run.id}' cancellation stream publish failed:`, error);
2735
+ }
2736
+ }
2737
+ function handleAgentRouteError(error, set) {
2738
+ if (error instanceof AgentStorageError && error.code === "duplicate_id") {
2739
+ set.status = 409;
2740
+ return { error: "Agent thread already exists" };
2741
+ }
2742
+ if (error instanceof AgentStorageError && error.code === "active_run_exists") {
2743
+ set.status = 409;
2744
+ return { error: "This conversation already has a response in progress" };
2745
+ }
2746
+ if (error instanceof AgentRequestError) {
2747
+ switch (error.code) {
2748
+ case "agent_not_found":
2749
+ case "thread_not_found":
2750
+ set.status = 404;
2751
+ break;
2752
+ case "active_run_exists":
2753
+ set.status = 409;
2754
+ break;
2755
+ case "storage_unavailable":
2756
+ case "thread_agent_mismatch":
2757
+ case "invalid_context":
2758
+ set.status = 400;
2759
+ break;
2760
+ }
2761
+ return { error: error.message };
2762
+ }
2763
+ return handleRouteError(error, set);
2764
+ }
2765
+ function missingAgentStorageResponse(set) {
2766
+ return unconfiguredStorageResponse2(set, "Agent storage");
2767
+ }
2768
+ async function agentMessageFileContentResponse(sixb, context, options = {}) {
2769
+ const authState = requestAuthState(context);
2770
+ try {
2771
+ const storage = sixb.storage.agents;
2772
+ if (!storage) {
2773
+ return missingAgentStorageResponse(context.set);
2774
+ }
2775
+ const parsed = AgentMessageFileContentQuerySchema.parse(context.query);
2776
+ const thread = await getAgentMessageFileContentThread({
2777
+ authState,
2778
+ storage,
2779
+ projectId: sixb.id,
2780
+ threadId: context.params.threadId
2781
+ });
2782
+ if (!thread) {
2783
+ context.set.status = 404;
2784
+ return { error: "File not found" };
2785
+ }
2786
+ const message = await storage.messages.getById({
2787
+ projectId: sixb.id,
2788
+ id: context.params.messageId
2789
+ });
2790
+ if (!message || message.threadId !== thread.id) {
2791
+ context.set.status = 404;
2792
+ return { error: "File not found" };
2793
+ }
2794
+ const fileRef = resolveFileRefAtPath(serializeMessage(message), parsed.path);
2795
+ if (!fileRef) {
2796
+ context.set.status = 404;
2797
+ return { error: "File not found" };
2798
+ }
2799
+ const response = await createFileContentResponse({
2800
+ blobStorage: sixb.blobStorage,
2801
+ fileRef,
2802
+ disposition: parsed.disposition,
2803
+ head: options.head,
2804
+ rangeHeader: context.request.headers.get("range")
2805
+ });
2806
+ if (!response) {
2807
+ context.set.status = 404;
2808
+ return { error: "File not found" };
2809
+ }
2810
+ return response;
2811
+ } catch (error) {
2812
+ if (error instanceof ZodError2) {
2813
+ context.set.status = 400;
2814
+ return { error: "Invalid file content query" };
2815
+ }
2816
+ throw error;
2817
+ }
2818
+ }
2819
+ function registerAgentRoutes(app, sixb) {
2820
+ return app.get("/api/agents", (context) => {
2821
+ const { scoped } = requestAuthState(context);
2822
+ const agents = scoped ? scoped.listAgents() : sixb.agents.list();
2823
+ return agents.map(serializeAgent);
2824
+ }, {
2825
+ response: { 200: AgentCatalogItemSchema.array() },
2826
+ detail: {
2827
+ summary: "List registered agents",
2828
+ tags: [OPENAPI_TAGS.agents.name],
2829
+ operationId: "listAgents"
2830
+ }
2831
+ }).get("/api/agents/:agentId", (context) => {
2832
+ const { params, set } = context;
2833
+ const { scoped } = requestAuthState(context);
2834
+ const agent = scoped ? scoped.getAgentById(params.agentId) : sixb.agents.getById(params.agentId);
2835
+ if (!agent) {
2836
+ set.status = 404;
2837
+ return { error: "Agent not found" };
3015
2838
  }
3016
- return references;
3017
- };
3018
- for (const sync of scoped ? scoped.listSyncs() : sixb.listSyncs()) {
3019
- referencesFor(sync.target.dataset.id).syncIds.push(sync.id);
3020
- }
3021
- for (const pipeline of scoped ? scoped.listPipelines() : sixb.listPipelines()) {
3022
- const sourceDatasetIds = new Set;
3023
- const targetDatasetIds = new Set;
3024
- for (const node of pipeline.graph.nodes) {
3025
- for (const input of Object.values(node.step.inputs)) {
3026
- sourceDatasetIds.add(input.id);
2839
+ return serializeAgent(agent);
2840
+ }, {
2841
+ params: AgentIdParamsSchema,
2842
+ response: { 200: AgentCatalogItemSchema, 404: ErrorResponseSchema },
2843
+ detail: {
2844
+ summary: "Get agent metadata",
2845
+ tags: [OPENAPI_TAGS.agents.name],
2846
+ operationId: "getAgent"
2847
+ }
2848
+ }).get("/api/agent-threads", async (context) => {
2849
+ const { query, set } = context;
2850
+ const { scoped } = requestAuthState(context);
2851
+ try {
2852
+ const storage = sixb.storage.agents;
2853
+ if (!storage) {
2854
+ return missingAgentStorageResponse(set);
3027
2855
  }
3028
- targetDatasetIds.add(node.step.output.id);
2856
+ const parsed = AgentThreadListQuerySchema.parse(query);
2857
+ const listInput = {
2858
+ agentId: parsed.agentId,
2859
+ statuses: parsed.status ? [parsed.status] : undefined,
2860
+ limit: parseOptionalInt(parsed.limit),
2861
+ offset: parseOptionalInt(parsed.offset),
2862
+ order: parsed.order
2863
+ };
2864
+ const result = scoped ? await scoped.listThreads(listInput) : await storage.threads.list({ projectId: sixb.id, ...listInput });
2865
+ return AgentThreadListResponseSchema.parse({
2866
+ threads: result.threads.map(serializeThread),
2867
+ hasMore: result.hasMore,
2868
+ total: result.total
2869
+ });
2870
+ } catch (error) {
2871
+ return handleAgentRouteError(error, set);
3029
2872
  }
3030
- for (const datasetId of sourceDatasetIds) {
3031
- referencesFor(datasetId).sourcePipelineIds.push(pipeline.id);
2873
+ }, {
2874
+ query: AgentThreadListQuerySchema,
2875
+ response: {
2876
+ 200: AgentThreadListResponseSchema,
2877
+ 400: ErrorResponseSchema,
2878
+ 501: ErrorResponseSchema
2879
+ },
2880
+ detail: {
2881
+ summary: "List agent threads",
2882
+ tags: [OPENAPI_TAGS.agentThreads.name],
2883
+ operationId: "listAgentThreads"
3032
2884
  }
3033
- for (const datasetId of targetDatasetIds) {
3034
- referencesFor(datasetId).targetPipelineIds.push(pipeline.id);
2885
+ }).post("/api/agent-threads", async (context) => {
2886
+ const { body, set } = context;
2887
+ const { authz, scoped } = requestAuthState(context);
2888
+ try {
2889
+ const parsed = CreateAgentThreadBodySchema.parse(body);
2890
+ const agent = scoped ? scoped.getAgentById(parsed.agentId) : sixb.agents.getById(parsed.agentId);
2891
+ if (!agent) {
2892
+ set.status = 404;
2893
+ return { error: "Agent not found" };
2894
+ }
2895
+ const storage = sixb.storage.agents;
2896
+ if (!storage) {
2897
+ return missingAgentStorageResponse(set);
2898
+ }
2899
+ const thread = await storage.threads.create({
2900
+ id: parsed.threadId ?? createAgentThreadId(),
2901
+ projectId: sixb.id,
2902
+ agentId: agent.id,
2903
+ ownerPrincipal: principalForRequest(authz),
2904
+ ...parsed.title === undefined ? {} : { title: parsed.title }
2905
+ });
2906
+ set.status = 201;
2907
+ return CreateAgentThreadResponseSchema.parse({ thread: serializeThread(thread) });
2908
+ } catch (error) {
2909
+ return handleAgentRouteError(error, set);
3035
2910
  }
3036
- }
3037
- for (const projection of [
3038
- ...sixb.listObjectProjections(),
3039
- ...sixb.listLinkProjections(),
3040
- ...sixb.listTelemetryProjections()
3041
- ]) {
3042
- if (!scoped || scoped.getDatasetById(projection.datasetId)) {
3043
- referencesFor(projection.datasetId).projectionIds.push(projection.id);
2911
+ }, {
2912
+ body: CreateAgentThreadBodySchema,
2913
+ response: {
2914
+ 201: CreateAgentThreadResponseSchema,
2915
+ 400: ErrorResponseSchema,
2916
+ 404: ErrorResponseSchema,
2917
+ 409: ErrorResponseSchema,
2918
+ 501: ErrorResponseSchema
2919
+ },
2920
+ detail: {
2921
+ summary: "Create an agent thread",
2922
+ tags: [OPENAPI_TAGS.agentThreads.name],
2923
+ operationId: "createAgentThread",
2924
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
3044
2925
  }
3045
- }
3046
- return index;
3047
- }
3048
- function serializeLatestVersionSummary(summary) {
3049
- return {
3050
- datasetId: summary.datasetId,
3051
- versionId: summary.versionId,
3052
- mode: summary.mode,
3053
- createdAt: toIsoString(summary.createdAt),
3054
- rowCount: summary.rowCount
3055
- };
3056
- }
3057
- function serializeDatasetCatalogItem(dataset, state, references) {
3058
- return DatasetCatalogItemSchema.parse({
3059
- ...dataset,
3060
- materialized: state?.materialized ?? false,
3061
- latestVersion: state?.latestVersion ? serializeLatestVersionSummary(state.latestVersion) : null,
3062
- syncIds: references.syncIds,
3063
- sourcePipelineIds: references.sourcePipelineIds,
3064
- targetPipelineIds: references.targetPipelineIds,
3065
- projectionIds: references.projectionIds
3066
- });
3067
- }
3068
- async function serializeDatasetCatalogItems(sixb, definitions, scoped = null) {
3069
- const references = buildDatasetReferenceIndex(sixb, scoped);
3070
- const states = await sixb.lakeStorage.listDatasetCatalogState(definitions.map((d) => d.id));
3071
- const stateByDatasetId = new Map(states.map((state) => [state.datasetId, state]));
3072
- return definitions.map((definition) => serializeDatasetCatalogItem(definition, stateByDatasetId.get(definition.id), references.get(definition.id) ?? EMPTY_DATASET_REFERENCES));
3073
- }
3074
- function requireDataset(sixb, scoped, datasetId) {
3075
- const dataset = scoped ? scoped.getDatasetById(datasetId) : sixb.getDatasetById(datasetId);
3076
- if (!dataset) {
3077
- throw new Error("Dataset not found");
3078
- }
3079
- return dataset;
3080
- }
3081
- function parseColumns(value) {
3082
- if (!value)
3083
- return;
3084
- const columns = value.split(",").map((column) => column.trim()).filter(Boolean);
3085
- return columns.length > 0 ? columns : undefined;
3086
- }
3087
- function resolveColumns(version, requested) {
3088
- const available = new Set(version.schema.columns.map((column) => column.name));
3089
- const selected = requested ?? version.schema.columns.map((column) => column.name);
3090
- for (const column of selected) {
3091
- if (!available.has(column)) {
3092
- throw new Error(`Dataset '${version.datasetId}' does not have column '${column}' at version '${version.versionId}'`);
2926
+ }).get("/api/agent-threads/:threadId", async (context) => {
2927
+ const { params, set } = context;
2928
+ const { scoped } = requestAuthState(context);
2929
+ try {
2930
+ const storage = sixb.storage.agents;
2931
+ if (!storage) {
2932
+ return missingAgentStorageResponse(set);
2933
+ }
2934
+ const thread = await getAccessibleThread({
2935
+ scoped,
2936
+ storage,
2937
+ projectId: sixb.id,
2938
+ threadId: params.threadId
2939
+ });
2940
+ if (!thread) {
2941
+ set.status = 404;
2942
+ return { error: "Agent thread not found" };
2943
+ }
2944
+ return serializeThread(thread);
2945
+ } catch (error) {
2946
+ return handleAgentRouteError(error, set);
2947
+ }
2948
+ }, {
2949
+ params: AgentThreadParamsSchema,
2950
+ response: {
2951
+ 200: AgentThreadSchema,
2952
+ 400: ErrorResponseSchema,
2953
+ 404: ErrorResponseSchema,
2954
+ 501: ErrorResponseSchema
2955
+ },
2956
+ detail: {
2957
+ summary: "Get agent thread",
2958
+ tags: [OPENAPI_TAGS.agentThreads.name],
2959
+ operationId: "getAgentThread"
2960
+ }
2961
+ }).get("/api/agent-threads/:threadId/messages", async (context) => {
2962
+ const { params, query, set } = context;
2963
+ const { scoped } = requestAuthState(context);
2964
+ try {
2965
+ const storage = sixb.storage.agents;
2966
+ if (!storage) {
2967
+ return missingAgentStorageResponse(set);
2968
+ }
2969
+ const thread = await getAccessibleThread({
2970
+ scoped,
2971
+ storage,
2972
+ projectId: sixb.id,
2973
+ threadId: params.threadId
2974
+ });
2975
+ if (!thread) {
2976
+ set.status = 404;
2977
+ return { error: "Agent thread not found" };
2978
+ }
2979
+ const parsed = AgentMessagesQuerySchema.parse(query);
2980
+ const limit = parseOptionalInt(parsed.limit);
2981
+ const offset = parseOptionalInt(parsed.offset);
2982
+ const result = await storage.messages.list({
2983
+ projectId: sixb.id,
2984
+ threadId: thread.id,
2985
+ roles: parsed.role ? [parsed.role] : undefined,
2986
+ limit,
2987
+ offset,
2988
+ order: parsed.order
2989
+ });
2990
+ const runIds = result.messages.flatMap((message) => message.runId === null ? [] : [message.runId]);
2991
+ const runs = await storage.runs.getByIds({ projectId: sixb.id, ids: runIds });
2992
+ const diagnosticsByRunId = new Map(runs.map((run) => [run.id, run.diagnostics ?? []]));
2993
+ return AgentMessageListResponseSchema.parse({
2994
+ messages: result.messages.map((message) => serializeMessage(message, message.runId === null ? [] : diagnosticsByRunId.get(message.runId) ?? [])),
2995
+ hasMore: result.hasMore,
2996
+ total: result.total
2997
+ });
2998
+ } catch (error) {
2999
+ return handleAgentRouteError(error, set);
3000
+ }
3001
+ }, {
3002
+ params: AgentThreadParamsSchema,
3003
+ query: AgentMessagesQuerySchema,
3004
+ response: {
3005
+ 200: AgentMessageListResponseSchema,
3006
+ 400: ErrorResponseSchema,
3007
+ 404: ErrorResponseSchema,
3008
+ 501: ErrorResponseSchema
3009
+ },
3010
+ detail: {
3011
+ summary: "List agent thread messages",
3012
+ tags: [OPENAPI_TAGS.agentThreads.name],
3013
+ operationId: "listAgentThreadMessages"
3014
+ }
3015
+ }).get("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(sixb, context), {
3016
+ params: AgentMessageFileContentParamsSchema,
3017
+ query: FileContentQuerySchema,
3018
+ detail: {
3019
+ summary: "Get agent message file content",
3020
+ tags: ["Agents"],
3021
+ operationId: "getAgentMessageFileContent",
3022
+ security: bearerSecurityRequirement("getAgentMessageFileContent"),
3023
+ responses: fileContentGetResponses({ optionalStorage: true })
3093
3024
  }
3094
- }
3095
- return selected;
3096
- }
3097
- async function collectRows(rows) {
3098
- const collected = [];
3099
- for await (const row of rows) {
3100
- collected.push({ ...row });
3101
- }
3102
- return collected;
3103
- }
3104
- function registerDatasetRoutes(app, sixb) {
3105
- return app.get("/api/datasets", async (context) => {
3106
- const { set } = context;
3025
+ }).head("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(sixb, context, { head: true }), {
3026
+ params: AgentMessageFileContentParamsSchema,
3027
+ query: FileContentQuerySchema,
3028
+ detail: {
3029
+ summary: "Head agent message file content",
3030
+ tags: ["Agents"],
3031
+ operationId: "headAgentMessageFileContent",
3032
+ security: bearerSecurityRequirement("headAgentMessageFileContent"),
3033
+ responses: fileContentHeadResponses({ optionalStorage: true })
3034
+ }
3035
+ }).post("/api/agent-threads/:threadId/messages", async (context) => {
3036
+ const { params, body, set } = context;
3037
+ const { authz, scoped } = requestAuthState(context);
3038
+ try {
3039
+ const storage = sixb.storage.agents;
3040
+ if (!storage) {
3041
+ return missingAgentStorageResponse(set);
3042
+ }
3043
+ const thread = await getAccessibleThread({
3044
+ scoped,
3045
+ storage,
3046
+ projectId: sixb.id,
3047
+ threadId: params.threadId
3048
+ });
3049
+ if (!thread) {
3050
+ set.status = 404;
3051
+ return { error: "Agent thread not found" };
3052
+ }
3053
+ const parsed = PostAgentMessageBodySchema.parse(body);
3054
+ const requestInput = {
3055
+ agentId: thread.agentId,
3056
+ threadId: thread.id,
3057
+ text: parsed.text,
3058
+ attachments: parsed.attachments,
3059
+ context: parsed.context,
3060
+ messageId: parsed.messageId,
3061
+ principal: principalForRequest(authz)
3062
+ };
3063
+ const result = await (scoped ? scoped.requestAgentRun(requestInput) : sixb.agents.request(requestInput));
3064
+ set.status = 202;
3065
+ return PostAgentMessageResponseSchema.parse({ run: serializeAgentRun(result.run) });
3066
+ } catch (error) {
3067
+ return handleAgentRouteError(error, set);
3068
+ }
3069
+ }, {
3070
+ params: AgentThreadParamsSchema,
3071
+ body: PostAgentMessageBodySchema,
3072
+ response: {
3073
+ 202: PostAgentMessageResponseSchema,
3074
+ 400: ErrorResponseSchema,
3075
+ 403: ErrorResponseSchema,
3076
+ 404: ErrorResponseSchema,
3077
+ 409: ErrorResponseSchema,
3078
+ 501: ErrorResponseSchema
3079
+ },
3080
+ detail: {
3081
+ summary: "Post an agent thread message",
3082
+ tags: [OPENAPI_TAGS.agentThreads.name],
3083
+ operationId: "postAgentThreadMessage",
3084
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
3085
+ }
3086
+ }).post("/api/agent-threads/:threadId/cancel", async (context) => {
3087
+ const { params, body, set } = context;
3107
3088
  const { scoped } = requestAuthState(context);
3108
3089
  try {
3109
- const definitions = scoped ? scoped.listDatasets() : sixb.listDatasets();
3110
- return await serializeDatasetCatalogItems(sixb, definitions, scoped);
3090
+ const storage = sixb.storage.agents;
3091
+ if (!storage) {
3092
+ return missingAgentStorageResponse(set);
3093
+ }
3094
+ const thread = await getAccessibleThread({
3095
+ scoped,
3096
+ storage,
3097
+ projectId: sixb.id,
3098
+ threadId: params.threadId
3099
+ });
3100
+ if (!thread) {
3101
+ set.status = 404;
3102
+ return { error: "Agent thread not found" };
3103
+ }
3104
+ const parsed = CancelAgentRunBodySchema.parse(body);
3105
+ const run = await storage.runs.getById({ projectId: sixb.id, id: parsed.runId });
3106
+ if (!run || run.threadId !== thread.id) {
3107
+ set.status = 404;
3108
+ return { error: "Agent run not found" };
3109
+ }
3110
+ let current = run;
3111
+ let cancelledWhileQueued = false;
3112
+ if (current.status === "queued") {
3113
+ try {
3114
+ current = await storage.runs.finishQueued({
3115
+ projectId: sixb.id,
3116
+ id: current.id,
3117
+ status: "cancelled"
3118
+ });
3119
+ cancelledWhileQueued = true;
3120
+ } catch (error) {
3121
+ if (!(error instanceof AgentStorageError) || error.code !== "invalid_state") {
3122
+ throw error;
3123
+ }
3124
+ const refreshed = await storage.runs.getById({ projectId: sixb.id, id: current.id });
3125
+ if (!refreshed || refreshed.threadId !== thread.id) {
3126
+ set.status = 404;
3127
+ return { error: "Agent run not found" };
3128
+ }
3129
+ current = refreshed;
3130
+ }
3131
+ }
3132
+ if (cancelledWhileQueued) {
3133
+ await publishQueuedRunCancellation(sixb, current);
3134
+ } else if (current.status === "running") {
3135
+ await publishAgentRunCancel(sixb.broker, { projectId: sixb.id, runId: current.id });
3136
+ } else {
3137
+ set.status = 409;
3138
+ return { error: "Agent run is not active" };
3139
+ }
3140
+ set.status = 202;
3141
+ return CancelAgentRunResponseSchema.parse({ run: serializeAgentRun(current) });
3111
3142
  } catch (error) {
3112
- set.status = 400;
3113
- return { error: error instanceof Error ? error.message : String(error) };
3143
+ return handleAgentRouteError(error, set);
3114
3144
  }
3115
3145
  }, {
3116
- response: { 200: DatasetCatalogItemSchema.array(), 400: ErrorResponseSchema },
3146
+ params: AgentThreadParamsSchema,
3147
+ body: CancelAgentRunBodySchema,
3148
+ response: {
3149
+ 202: CancelAgentRunResponseSchema,
3150
+ 400: ErrorResponseSchema,
3151
+ 404: ErrorResponseSchema,
3152
+ 409: ErrorResponseSchema,
3153
+ 501: ErrorResponseSchema
3154
+ },
3117
3155
  detail: {
3118
- summary: "List registered datasets",
3119
- tags: [OPENAPI_TAGS.datasets.name],
3120
- operationId: "listDatasets"
3156
+ summary: "Cancel an agent thread's active run",
3157
+ tags: [OPENAPI_TAGS.agentRuns.name],
3158
+ operationId: "cancelAgentRun",
3159
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
3121
3160
  }
3122
- }).get("/api/datasets/:datasetId", async (context) => {
3161
+ }).post("/api/agent-threads/:threadId/runs/:runId/retry", async (context) => {
3123
3162
  const { params, set } = context;
3124
- const { scoped } = requestAuthState(context);
3163
+ const { authz, scoped } = requestAuthState(context);
3125
3164
  try {
3126
- const dataset = requireDataset(sixb, scoped, params.datasetId);
3127
- const [state] = await sixb.lakeStorage.listDatasetCatalogState([dataset.id]);
3128
- const references = buildDatasetReferenceIndex(sixb, scoped).get(dataset.id);
3129
- return serializeDatasetCatalogItem(dataset, state, references ?? EMPTY_DATASET_REFERENCES);
3165
+ const storage = sixb.storage.agents;
3166
+ if (!storage) {
3167
+ return missingAgentStorageResponse(set);
3168
+ }
3169
+ const thread = await getAccessibleThread({
3170
+ scoped,
3171
+ storage,
3172
+ projectId: sixb.id,
3173
+ threadId: params.threadId
3174
+ });
3175
+ if (!thread) {
3176
+ set.status = 404;
3177
+ return { error: "Agent thread not found" };
3178
+ }
3179
+ const failedRun = await storage.runs.getById({ projectId: sixb.id, id: params.runId });
3180
+ if (!failedRun || failedRun.threadId !== thread.id) {
3181
+ set.status = 404;
3182
+ return { error: "Agent run not found" };
3183
+ }
3184
+ if (failedRun.status !== "failed") {
3185
+ set.status = 409;
3186
+ return { error: "Only failed agent runs can be retried" };
3187
+ }
3188
+ const run = await storage.runs.create({
3189
+ id: createAgentRunId(),
3190
+ projectId: sixb.id,
3191
+ threadId: thread.id,
3192
+ agentId: failedRun.agentId,
3193
+ triggerMessageId: failedRun.triggerMessageId,
3194
+ requestedByPrincipal: principalForRequest(authz)
3195
+ });
3196
+ try {
3197
+ const dispatch = await dispatchQueuedAgentRuns({
3198
+ projectId: sixb.id,
3199
+ storage,
3200
+ queue: sixb.queues.agents,
3201
+ runIds: [run.id]
3202
+ });
3203
+ const failure = dispatch.failures[0];
3204
+ if (failure) {
3205
+ console.error(`[SixbServer] Could not dispatch retried agent run '${run.id}'; retrying later.`, failure.error);
3206
+ }
3207
+ } catch (error) {
3208
+ console.error(`[SixbServer] Could not dispatch retried agent run '${run.id}'; retrying later.`, error);
3209
+ }
3210
+ set.status = 202;
3211
+ return RetryAgentRunResponseSchema.parse({ run: serializeAgentRun(run) });
3130
3212
  } catch (error) {
3131
- return handleRouteError(error, set);
3213
+ return handleAgentRouteError(error, set);
3132
3214
  }
3133
3215
  }, {
3134
- params: DatasetParamsSchema,
3216
+ params: AgentRunParamsSchema.extend({ threadId: z7.string().trim().min(1) }),
3135
3217
  response: {
3136
- 200: DatasetCatalogItemSchema,
3218
+ 202: RetryAgentRunResponseSchema,
3137
3219
  400: ErrorResponseSchema,
3138
- 404: ErrorResponseSchema
3220
+ 404: ErrorResponseSchema,
3221
+ 409: ErrorResponseSchema,
3222
+ 501: ErrorResponseSchema
3139
3223
  },
3140
3224
  detail: {
3141
- summary: "Get dataset metadata",
3142
- tags: [OPENAPI_TAGS.datasets.name],
3143
- operationId: "getDataset"
3225
+ summary: "Retry a failed agent run",
3226
+ tags: [OPENAPI_TAGS.agentRuns.name],
3227
+ operationId: "retryAgentRun",
3228
+ security: SIXB_CSRF_SECURITY_REQUIREMENT
3144
3229
  }
3145
- }).get("/api/datasets/:datasetId/versions", async (context) => {
3230
+ }).get("/api/agent-threads/:threadId/runs", async (context) => {
3146
3231
  const { params, query, set } = context;
3147
3232
  const { scoped } = requestAuthState(context);
3148
3233
  try {
3149
- requireDataset(sixb, scoped, params.datasetId);
3150
- const parsed = DatasetVersionsQuerySchema.parse(query);
3151
- const limit = parseLimit(parsed.limit, DEFAULT_VERSION_LIMIT, MAX_VERSION_LIMIT);
3152
- const versions = await sixb.lakeStorage.listVersions(params.datasetId, limit);
3153
- return DatasetVersionListResponseSchema.parse({
3154
- versions: versions.map(serializeDatasetVersion),
3155
- count: versions.length
3234
+ const storage = sixb.storage.agents;
3235
+ if (!storage) {
3236
+ return missingAgentStorageResponse(set);
3237
+ }
3238
+ const thread = await getAccessibleThread({
3239
+ scoped,
3240
+ storage,
3241
+ projectId: sixb.id,
3242
+ threadId: params.threadId
3243
+ });
3244
+ if (!thread) {
3245
+ set.status = 404;
3246
+ return { error: "Agent thread not found" };
3247
+ }
3248
+ const parsed = AgentRunListQuerySchema.parse(query);
3249
+ const result = await storage.runs.list({
3250
+ projectId: sixb.id,
3251
+ threadId: thread.id,
3252
+ statuses: parsed.status ? [parsed.status] : undefined,
3253
+ limit: parseOptionalInt(parsed.limit),
3254
+ offset: parseOptionalInt(parsed.offset),
3255
+ order: parsed.order
3256
+ });
3257
+ return AgentRunListResponseSchema.parse({
3258
+ runs: result.runs.map(serializeAgentRun),
3259
+ hasMore: result.hasMore,
3260
+ total: result.total
3156
3261
  });
3157
3262
  } catch (error) {
3158
- return handleRouteError(error, set);
3263
+ return handleAgentRouteError(error, set);
3159
3264
  }
3160
3265
  }, {
3161
- params: DatasetParamsSchema,
3162
- query: DatasetVersionsQuerySchema,
3266
+ params: AgentThreadParamsSchema,
3267
+ query: AgentRunListQuerySchema,
3163
3268
  response: {
3164
- 200: DatasetVersionListResponseSchema,
3269
+ 200: AgentRunListResponseSchema,
3165
3270
  400: ErrorResponseSchema,
3166
- 404: ErrorResponseSchema
3271
+ 404: ErrorResponseSchema,
3272
+ 501: ErrorResponseSchema
3167
3273
  },
3168
3274
  detail: {
3169
- summary: "List dataset versions",
3170
- tags: [OPENAPI_TAGS.datasetVersions.name],
3171
- operationId: "listDatasetVersions"
3275
+ summary: "List an agent thread's runs",
3276
+ tags: [OPENAPI_TAGS.agentRuns.name],
3277
+ operationId: "listAgentThreadRuns"
3172
3278
  }
3173
- }).get("/api/datasets/:datasetId/versions/:versionId", async (context) => {
3279
+ }).get("/api/agent-runs/:runId", async (context) => {
3174
3280
  const { params, set } = context;
3175
3281
  const { scoped } = requestAuthState(context);
3176
3282
  try {
3177
- requireDataset(sixb, scoped, params.datasetId);
3178
- const version = await sixb.lakeStorage.getVersion(params.datasetId, params.versionId);
3179
- if (!version) {
3180
- set.status = 404;
3181
- return { error: "Dataset version not found" };
3283
+ const storage = sixb.storage.agents;
3284
+ if (!storage) {
3285
+ return missingAgentStorageResponse(set);
3182
3286
  }
3183
- return serializeDatasetVersion(version);
3184
- } catch (error) {
3185
- return handleRouteError(error, set);
3186
- }
3187
- }, {
3188
- params: DatasetVersionParamsSchema,
3189
- response: {
3190
- 200: DatasetVersionSchema,
3191
- 400: ErrorResponseSchema,
3192
- 404: ErrorResponseSchema
3193
- },
3194
- detail: {
3195
- summary: "Get dataset version",
3196
- tags: [OPENAPI_TAGS.datasetVersions.name],
3197
- operationId: "getDatasetVersion"
3198
- }
3199
- }).get("/api/datasets/:datasetId/rows", async (context) => {
3200
- const { params, query, set } = context;
3201
- const { scoped } = requestAuthState(context);
3202
- try {
3203
- requireDataset(sixb, scoped, params.datasetId);
3204
- const parsed = DatasetRowsQuerySchema.parse(query);
3205
- const limit = parseLimit(parsed.limit, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT);
3206
- const offset = parseOffset(parsed.offset);
3207
- const version = parsed.versionId ? await sixb.lakeStorage.getVersion(params.datasetId, parsed.versionId) : await sixb.lakeStorage.getLatestVersion(params.datasetId);
3208
- if (!version) {
3287
+ const run = await storage.runs.getById({ projectId: sixb.id, id: params.runId });
3288
+ if (!run) {
3209
3289
  set.status = 404;
3210
- return { error: "Dataset version not found" };
3290
+ return { error: "Agent run not found" };
3211
3291
  }
3212
- const requestedColumns = parseColumns(parsed.columns);
3213
- const columns = resolveColumns(version, requestedColumns);
3214
- const rows = await collectRows(sixb.lakeStorage.readRows({
3215
- datasetId: params.datasetId,
3216
- versionId: version.versionId,
3217
- columns: requestedColumns,
3218
- limit,
3219
- offset
3220
- }));
3221
- const hasMore = version.rowCount === undefined ? rows.length === limit : offset + rows.length < version.rowCount;
3222
- return DatasetRowsResponseSchema.parse({
3223
- datasetId: params.datasetId,
3224
- versionId: version.versionId,
3225
- version: serializeDatasetVersion(version),
3226
- columns: [...columns],
3227
- rows,
3228
- count: rows.length,
3229
- limit,
3230
- offset,
3231
- total: version.rowCount,
3232
- hasMore
3292
+ const thread = await getAccessibleThread({
3293
+ scoped,
3294
+ storage,
3295
+ projectId: sixb.id,
3296
+ threadId: run.threadId
3233
3297
  });
3298
+ if (!thread) {
3299
+ set.status = 404;
3300
+ return { error: "Agent run not found" };
3301
+ }
3302
+ return serializeAgentRun(run);
3234
3303
  } catch (error) {
3235
- return handleRouteError(error, set);
3304
+ return handleAgentRouteError(error, set);
3236
3305
  }
3237
3306
  }, {
3238
- params: DatasetParamsSchema,
3239
- query: DatasetRowsQuerySchema,
3307
+ params: AgentRunParamsSchema,
3240
3308
  response: {
3241
- 200: DatasetRowsResponseSchema,
3309
+ 200: AgentRunSchema,
3242
3310
  400: ErrorResponseSchema,
3243
- 404: ErrorResponseSchema
3311
+ 404: ErrorResponseSchema,
3312
+ 501: ErrorResponseSchema
3244
3313
  },
3245
3314
  detail: {
3246
- summary: "Preview dataset rows",
3247
- tags: [OPENAPI_TAGS.datasetRows.name],
3248
- operationId: "listDatasetRows"
3315
+ summary: "Get agent run",
3316
+ tags: [OPENAPI_TAGS.agentRuns.name],
3317
+ operationId: "getAgentRun"
3249
3318
  }
3250
3319
  });
3251
3320
  }
3252
3321
 
3253
- // src/routes/events.ts
3254
- import { AuthorizationError as AuthorizationError2 } from "@sixb/core";
3322
+ // src/schemas/connectors.ts
3323
+ import { z as z8 } from "zod";
3324
+ var ConnectorParamsSchema = z8.object({
3325
+ connectorId: z8.string().min(1)
3326
+ });
3327
+ var ConnectorWebhookSchema = z8.object({
3328
+ id: z8.string(),
3329
+ method: z8.literal("POST"),
3330
+ route: z8.string(),
3331
+ bodyFormat: z8.enum(["json", "text", "raw"]),
3332
+ hasVerify: z8.boolean(),
3333
+ hasIdempotency: z8.boolean()
3334
+ });
3335
+ var ConnectorSchema = z8.object({
3336
+ id: z8.string(),
3337
+ type: z8.string(),
3338
+ syncIds: z8.array(z8.string()),
3339
+ webhooks: z8.array(ConnectorWebhookSchema)
3340
+ });
3255
3341
 
3256
- // src/schemas/events.ts
3257
- import {
3258
- EVENT_TOPICS as CORE_EVENT_TOPICS,
3259
- EVENT_TYPES as CORE_EVENT_TYPES,
3260
- EVENT_DEFINITIONS,
3261
- isOntologyFactType
3262
- } from "@sixb/core/internal/events";
3263
- import { z as z11 } from "zod";
3342
+ // src/routes/connectors.ts
3343
+ function serializeConnector(connector, sixb) {
3344
+ return {
3345
+ id: connector.id,
3346
+ type: connector.adapter.type,
3347
+ syncIds: sixb.listSyncs().filter((sync) => sync.connector.id === connector.id).map((sync) => sync.id),
3348
+ webhooks: sixb.listWebhooks().filter((registered) => registered.connector.id === connector.id).map(({ webhook, route }) => ({
3349
+ id: webhook.id,
3350
+ method: webhook.method,
3351
+ route,
3352
+ bodyFormat: webhook.body.format,
3353
+ hasVerify: typeof webhook.verify === "function",
3354
+ hasIdempotency: typeof webhook.idempotencyKey === "function"
3355
+ }))
3356
+ };
3357
+ }
3358
+ function registerConnectorRoutes(app, sixb) {
3359
+ return app.get("/api/connectors", () => {
3360
+ return sixb.listConnectors().map((connector) => serializeConnector(connector, sixb));
3361
+ }, {
3362
+ response: { 200: ConnectorSchema.array() },
3363
+ detail: {
3364
+ summary: "List registered connectors",
3365
+ tags: [OPENAPI_TAGS.connectors.name],
3366
+ operationId: "listConnectors"
3367
+ }
3368
+ }).get("/api/connectors/:connectorId", ({ params, set }) => {
3369
+ const connector = sixb.getConnectorById(params.connectorId);
3370
+ if (!connector) {
3371
+ set.status = 404;
3372
+ return { error: "Connector not found" };
3373
+ }
3374
+ return serializeConnector(connector, sixb);
3375
+ }, {
3376
+ params: ConnectorParamsSchema,
3377
+ response: { 200: ConnectorSchema, 404: ErrorResponseSchema },
3378
+ detail: {
3379
+ summary: "Get connector metadata",
3380
+ tags: [OPENAPI_TAGS.connectors.name],
3381
+ operationId: "getConnector"
3382
+ }
3383
+ });
3384
+ }
3264
3385
 
3265
- // src/schemas/event-payloads.ts
3266
- import { z as z10 } from "zod";
3267
- var PropertyChangeSchema = z10.discriminatedUnion("operation", [
3268
- z10.object({ operation: z10.literal("created"), after: JsonValueSchema }),
3269
- z10.object({
3270
- operation: z10.literal("updated"),
3271
- before: JsonValueSchema,
3272
- after: JsonValueSchema
3273
- }),
3274
- z10.object({
3275
- operation: z10.literal("cleared"),
3276
- before: JsonValueSchema,
3277
- after: JsonNullSchema
3278
- })
3279
- ]);
3280
- var PropertyChangesSchema = z10.record(PropertyChangeSchema);
3281
- var ObjectMutationPayloadSchema = z10.object({
3282
- objectTypeId: z10.string(),
3283
- primaryId: z10.string(),
3284
- properties: z10.record(JsonValueSchema),
3285
- propertyChanges: PropertyChangesSchema
3286
- });
3287
- var ObjectDeletedPayloadSchema = z10.object({
3288
- objectTypeId: z10.string(),
3289
- primaryId: z10.string(),
3290
- propertyChanges: PropertyChangesSchema
3386
+ // src/schemas/datasets.ts
3387
+ import { z as z9 } from "zod";
3388
+ var DatasetParamsSchema = z9.object({
3389
+ datasetId: z9.string().min(1)
3291
3390
  });
3292
- var LinkSubjectSchema = z10.object({
3293
- sourceTypeId: z10.string(),
3294
- sourceId: z10.string(),
3295
- linkId: z10.string(),
3296
- targetTypeId: z10.string(),
3297
- targetId: z10.string()
3391
+ var DatasetVersionParamsSchema = DatasetParamsSchema.extend({
3392
+ versionId: z9.string().min(1)
3298
3393
  });
3299
- var LinkMutationPayloadSchema = LinkSubjectSchema.extend({
3300
- properties: z10.record(JsonValueSchema).optional(),
3301
- propertyChanges: PropertyChangesSchema
3394
+ var DatasetVersionsQuerySchema = z9.object({
3395
+ limit: z9.string().optional()
3302
3396
  });
3303
- var LinkDeletedPayloadSchema = LinkSubjectSchema.extend({
3304
- propertyChanges: PropertyChangesSchema
3397
+ var DatasetRowsQuerySchema = z9.object({
3398
+ versionId: z9.string().optional(),
3399
+ columns: z9.string().optional(),
3400
+ limit: z9.string().optional(),
3401
+ offset: z9.string().optional()
3305
3402
  });
3306
- var ONTOLOGY_EVENT_PAYLOAD_SCHEMAS = {
3307
- "object.created": ObjectMutationPayloadSchema,
3308
- "object.updated": ObjectMutationPayloadSchema,
3309
- "object.deleted": ObjectDeletedPayloadSchema,
3310
- "link.created": LinkMutationPayloadSchema,
3311
- "link.updated": LinkMutationPayloadSchema,
3312
- "link.deleted": LinkDeletedPayloadSchema,
3313
- "telemetry.appended": z10.object({
3314
- objectTypeId: z10.string(),
3315
- objectId: z10.string(),
3316
- propertyId: z10.string(),
3317
- value: JsonValueSchema,
3318
- unit: z10.string().optional(),
3319
- at: z10.string()
3320
- })
3321
- };
3322
-
3323
- // src/schemas/events.ts
3324
- var EVENT_TOPICS = CORE_EVENT_TOPICS;
3325
- var EVENT_TYPES = CORE_EVENT_TYPES;
3326
- var EventTopicSchema = z11.enum(EVENT_TOPICS);
3327
- var EventTypeSchema = z11.enum(EVENT_TYPES);
3328
- var ProjectionEventOriginSchema = z11.object({
3329
- kind: z11.literal("projection"),
3330
- projectionId: z11.string(),
3331
- projectionRunId: z11.string(),
3332
- datasetId: z11.string(),
3333
- datasetVersionId: z11.string()
3403
+ var DatasetColumnSchema = z9.object({
3404
+ name: z9.string(),
3405
+ type: z9.enum([
3406
+ "string",
3407
+ "boolean",
3408
+ "int64",
3409
+ "float64",
3410
+ "decimal",
3411
+ "date",
3412
+ "timestamp",
3413
+ "json",
3414
+ "fileRef"
3415
+ ]),
3416
+ nullable: z9.boolean().optional()
3334
3417
  });
3335
- var EventOriginSchema = z11.union([
3336
- z11.object({
3337
- kind: z11.literal("action"),
3338
- actionId: z11.string(),
3339
- runId: z11.string()
3340
- }),
3341
- z11.object({ kind: z11.literal("runtime"), requestId: z11.string() }),
3342
- ProjectionEventOriginSchema,
3343
- z11.object({
3344
- kind: z11.literal("telemetry"),
3345
- source: z11.union([
3346
- z11.object({ kind: z11.literal("runtime"), requestId: z11.string() }),
3347
- ProjectionEventOriginSchema.extend({ batchOrdinal: z11.number() })
3348
- ])
3349
- })
3350
- ]);
3351
- var EventsQuerySchema = z11.object({
3352
- topic: EventTopicSchema.optional(),
3353
- type: EventTypeSchema.optional(),
3354
- afterCursor: z11.string().optional(),
3355
- limit: z11.string().optional()
3418
+ var DatasetSchema = z9.object({
3419
+ columns: z9.array(DatasetColumnSchema)
3356
3420
  });
3357
- var StoredEventBaseSchema = z11.object({
3358
- id: z11.string(),
3359
- cursor: z11.string(),
3360
- schemaVersion: z11.literal(1),
3361
- projectId: z11.string(),
3362
- occurredAt: z11.string(),
3363
- actor: z11.object({
3364
- type: z11.enum(["user", "serviceAccount", "system"]),
3365
- id: z11.string()
3366
- }).optional(),
3367
- partitionKey: z11.string()
3421
+ var DatasetDefinitionSchema = z9.object({
3422
+ id: z9.string(),
3423
+ description: z9.string().optional(),
3424
+ primaryKey: z9.union([z9.string(), z9.array(z9.string()).min(2)]).optional(),
3425
+ partitionBy: z9.array(z9.string()).optional(),
3426
+ schema: DatasetSchema
3368
3427
  });
3369
- var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
3370
- correlationId: z11.string().optional(),
3371
- causationId: z11.string().optional(),
3372
- idempotencyKey: z11.string().optional(),
3373
- origin: EventOriginSchema.optional(),
3374
- metadata: z11.record(JsonValueSchema).optional()
3428
+ var DatasetVersionRefSchema = z9.object({
3429
+ datasetId: z9.string(),
3430
+ versionId: z9.string()
3375
3431
  });
3376
- var StoredOntologyEventBaseSchema = StoredEventBaseSchema.extend({
3377
- origin: EventOriginSchema,
3378
- commitId: z11.string(),
3379
- commitOrdinal: z11.number().int().nonnegative()
3432
+ var DatasetProducerSchema = z9.object({
3433
+ kind: z9.enum(["sync", "pipeline"]),
3434
+ id: z9.string().optional(),
3435
+ runId: z9.string().optional()
3380
3436
  });
3381
- var ontologyEventTypes = EVENT_TYPES.filter(isOntologyFactType);
3382
- var ontologyEventSchemas = ontologyEventTypes.map((type) => StoredOntologyEventBaseSchema.extend({
3383
- type: z11.literal(type),
3384
- topic: z11.literal(EVENT_DEFINITIONS[type].topic),
3385
- payload: ONTOLOGY_EVENT_PAYLOAD_SCHEMAS[type]
3386
- }));
3387
- var authorableEventTypes = EVENT_TYPES.filter((type) => !isOntologyFactType(type));
3388
- var StoredAuthorableEventSchema = StoredAuthorableEventBaseSchema.extend({
3389
- type: z11.enum(authorableEventTypes),
3390
- topic: EventTopicSchema,
3391
- payload: z11.record(z11.unknown())
3437
+ var DatasetVersionSchema = z9.object({
3438
+ datasetId: z9.string(),
3439
+ versionId: z9.string(),
3440
+ parentVersionId: z9.string().optional(),
3441
+ mode: z9.enum(["snapshot", "append", "merge", "schema"]),
3442
+ createdAt: z9.string(),
3443
+ schema: DatasetSchema,
3444
+ producer: DatasetProducerSchema.optional(),
3445
+ inputs: z9.array(DatasetVersionRefSchema).optional(),
3446
+ rowCount: z9.number().optional(),
3447
+ sizeBytes: z9.number().optional()
3392
3448
  });
3393
- var StoredOntologyEventSchema = z11.discriminatedUnion("type", ontologyEventSchemas);
3394
- var EventSchema = z11.union([StoredOntologyEventSchema, StoredAuthorableEventSchema]);
3395
- var EventsResponseSchema = z11.object({
3396
- count: z11.number(),
3397
- events: z11.array(EventSchema)
3449
+ var DatasetLatestVersionSummarySchema = z9.object({
3450
+ datasetId: z9.string(),
3451
+ versionId: z9.string(),
3452
+ mode: z9.enum(["snapshot", "append", "merge", "schema"]),
3453
+ createdAt: z9.string(),
3454
+ rowCount: z9.number().optional()
3455
+ });
3456
+ var DatasetCatalogItemSchema = DatasetDefinitionSchema.extend({
3457
+ kind: z9.literal("dataset"),
3458
+ materialized: z9.boolean(),
3459
+ latestVersion: DatasetLatestVersionSummarySchema.nullable(),
3460
+ syncIds: z9.array(z9.string()),
3461
+ sourcePipelineIds: z9.array(z9.string()),
3462
+ targetPipelineIds: z9.array(z9.string()),
3463
+ projectionIds: z9.array(z9.string())
3464
+ });
3465
+ var DatasetVersionListResponseSchema = z9.object({
3466
+ versions: z9.array(DatasetVersionSchema),
3467
+ count: z9.number()
3468
+ });
3469
+ var DatasetRowsResponseSchema = z9.object({
3470
+ datasetId: z9.string(),
3471
+ versionId: z9.string(),
3472
+ version: DatasetVersionSchema,
3473
+ columns: z9.array(z9.string()),
3474
+ rows: z9.array(z9.record(z9.unknown())),
3475
+ count: z9.number(),
3476
+ limit: z9.number(),
3477
+ offset: z9.number(),
3478
+ total: z9.number().optional(),
3479
+ hasMore: z9.boolean()
3398
3480
  });
3399
3481
 
3400
- // src/routes/events.ts
3401
- function registerEventRoutes(app, sixb) {
3402
- return app.get("/api/events", async (context) => {
3403
- const { query, set } = context;
3482
+ // src/routes/datasets.ts
3483
+ var DEFAULT_VERSION_LIMIT = 20;
3484
+ var MAX_VERSION_LIMIT = 100;
3485
+ var DEFAULT_ROW_LIMIT = 100;
3486
+ var MAX_ROW_LIMIT = 1000;
3487
+ function parseLimit(value, fallback, max) {
3488
+ const parsed = parseOptionalInt(value) ?? fallback;
3489
+ if (parsed < 0) {
3490
+ throw new Error("Limit must be greater than or equal to 0");
3491
+ }
3492
+ return Math.min(parsed, max);
3493
+ }
3494
+ function parseOffset(value) {
3495
+ const parsed = parseOptionalInt(value) ?? 0;
3496
+ if (parsed < 0) {
3497
+ throw new Error("Offset must be greater than or equal to 0");
3498
+ }
3499
+ return parsed;
3500
+ }
3501
+ function serializeDatasetVersion(version) {
3502
+ return DatasetVersionSchema.parse({
3503
+ datasetId: version.datasetId,
3504
+ versionId: version.versionId,
3505
+ parentVersionId: version.parentVersionId,
3506
+ mode: version.mode,
3507
+ createdAt: toIsoString(version.createdAt),
3508
+ schema: version.schema,
3509
+ producer: version.producer,
3510
+ inputs: version.inputs,
3511
+ rowCount: version.rowCount,
3512
+ sizeBytes: version.sizeBytes
3513
+ });
3514
+ }
3515
+ var EMPTY_DATASET_REFERENCES = {
3516
+ syncIds: [],
3517
+ sourcePipelineIds: [],
3518
+ targetPipelineIds: [],
3519
+ projectionIds: []
3520
+ };
3521
+ function buildDatasetReferenceIndex(sixb, scoped = null) {
3522
+ const index = new Map;
3523
+ const referencesFor = (datasetId) => {
3524
+ let references = index.get(datasetId);
3525
+ if (!references) {
3526
+ references = { syncIds: [], sourcePipelineIds: [], targetPipelineIds: [], projectionIds: [] };
3527
+ index.set(datasetId, references);
3528
+ }
3529
+ return references;
3530
+ };
3531
+ for (const sync of scoped ? scoped.listSyncs() : sixb.listSyncs()) {
3532
+ referencesFor(sync.target.dataset.id).syncIds.push(sync.id);
3533
+ }
3534
+ for (const pipeline of scoped ? scoped.listPipelines() : sixb.listPipelines()) {
3535
+ const sourceDatasetIds = new Set;
3536
+ const targetDatasetIds = new Set;
3537
+ for (const node of pipeline.graph.nodes) {
3538
+ for (const input of Object.values(node.step.inputs)) {
3539
+ sourceDatasetIds.add(input.id);
3540
+ }
3541
+ targetDatasetIds.add(node.step.output.id);
3542
+ }
3543
+ for (const datasetId of sourceDatasetIds) {
3544
+ referencesFor(datasetId).sourcePipelineIds.push(pipeline.id);
3545
+ }
3546
+ for (const datasetId of targetDatasetIds) {
3547
+ referencesFor(datasetId).targetPipelineIds.push(pipeline.id);
3548
+ }
3549
+ }
3550
+ for (const projection of [
3551
+ ...sixb.listObjectProjections(),
3552
+ ...sixb.listLinkProjections(),
3553
+ ...sixb.listTelemetryProjections()
3554
+ ]) {
3555
+ if (!scoped || scoped.getDatasetById(projection.datasetId)) {
3556
+ referencesFor(projection.datasetId).projectionIds.push(projection.id);
3557
+ }
3558
+ }
3559
+ return index;
3560
+ }
3561
+ function serializeLatestVersionSummary(summary) {
3562
+ return {
3563
+ datasetId: summary.datasetId,
3564
+ versionId: summary.versionId,
3565
+ mode: summary.mode,
3566
+ createdAt: toIsoString(summary.createdAt),
3567
+ rowCount: summary.rowCount
3568
+ };
3569
+ }
3570
+ function serializeDatasetCatalogItem(dataset, state, references) {
3571
+ return DatasetCatalogItemSchema.parse({
3572
+ ...dataset,
3573
+ materialized: state?.materialized ?? false,
3574
+ latestVersion: state?.latestVersion ? serializeLatestVersionSummary(state.latestVersion) : null,
3575
+ syncIds: references.syncIds,
3576
+ sourcePipelineIds: references.sourcePipelineIds,
3577
+ targetPipelineIds: references.targetPipelineIds,
3578
+ projectionIds: references.projectionIds
3579
+ });
3580
+ }
3581
+ async function serializeDatasetCatalogItems(sixb, definitions, scoped = null) {
3582
+ const references = buildDatasetReferenceIndex(sixb, scoped);
3583
+ const states = await sixb.lakeStorage.listDatasetCatalogState(definitions.map((d) => d.id));
3584
+ const stateByDatasetId = new Map(states.map((state) => [state.datasetId, state]));
3585
+ return definitions.map((definition) => serializeDatasetCatalogItem(definition, stateByDatasetId.get(definition.id), references.get(definition.id) ?? EMPTY_DATASET_REFERENCES));
3586
+ }
3587
+ function requireDataset(sixb, scoped, datasetId) {
3588
+ const dataset = scoped ? scoped.getDatasetById(datasetId) : sixb.getDatasetById(datasetId);
3589
+ if (!dataset) {
3590
+ throw new Error("Dataset not found");
3591
+ }
3592
+ return dataset;
3593
+ }
3594
+ function parseColumns(value) {
3595
+ if (!value)
3596
+ return;
3597
+ const columns = value.split(",").map((column) => column.trim()).filter(Boolean);
3598
+ return columns.length > 0 ? columns : undefined;
3599
+ }
3600
+ function resolveColumns(version, requested) {
3601
+ const available = new Set(version.schema.columns.map((column) => column.name));
3602
+ const selected = requested ?? version.schema.columns.map((column) => column.name);
3603
+ for (const column of selected) {
3604
+ if (!available.has(column)) {
3605
+ throw new Error(`Dataset '${version.datasetId}' does not have column '${column}' at version '${version.versionId}'`);
3606
+ }
3607
+ }
3608
+ return selected;
3609
+ }
3610
+ async function collectRows(rows) {
3611
+ const collected = [];
3612
+ for await (const row of rows) {
3613
+ collected.push({ ...row });
3614
+ }
3615
+ return collected;
3616
+ }
3617
+ function registerDatasetRoutes(app, sixb) {
3618
+ return app.get("/api/datasets", async (context) => {
3619
+ const { set } = context;
3404
3620
  const { scoped } = requestAuthState(context);
3405
3621
  try {
3406
- const parsed = EventsQuerySchema.parse(query);
3407
- const input = {
3408
- topics: parsed.topic ? [parsed.topic] : undefined,
3409
- types: parsed.type ? [parsed.type] : undefined,
3410
- afterCursor: parsed.afterCursor,
3411
- limit: parseOptionalInt(parsed.limit)
3412
- };
3413
- const events = scoped ? await scoped.readEvents(input) : await sixb.events.read(input);
3414
- return {
3415
- count: events.length,
3416
- events: [...events]
3417
- };
3622
+ const definitions = scoped ? scoped.listDatasets() : sixb.listDatasets();
3623
+ return await serializeDatasetCatalogItems(sixb, definitions, scoped);
3418
3624
  } catch (error) {
3419
- if (error instanceof AuthorizationError2) {
3420
- set.status = 403;
3421
- return { error: error.message };
3422
- }
3423
3625
  set.status = 400;
3424
3626
  return { error: error instanceof Error ? error.message : String(error) };
3425
3627
  }
3426
3628
  }, {
3427
- query: EventsQuerySchema,
3428
- response: {
3429
- 200: EventsResponseSchema,
3430
- 400: ErrorResponseSchema,
3431
- 403: ErrorResponseSchema
3432
- },
3629
+ response: { 200: DatasetCatalogItemSchema.array(), 400: ErrorResponseSchema },
3433
3630
  detail: {
3434
- summary: "Read domain events",
3435
- tags: [OPENAPI_TAGS.events.name],
3436
- operationId: "listEvents",
3437
- security: bearerSecurityRequirement("listEvents")
3631
+ summary: "List registered datasets",
3632
+ tags: [OPENAPI_TAGS.datasets.name],
3633
+ operationId: "listDatasets"
3438
3634
  }
3439
- });
3440
- }
3441
-
3442
- // src/routes/files.ts
3443
- import {
3444
- DEFAULT_SIMPLE_FILE_UPLOAD_BYTES,
3445
- InMemoryFileUploadSessions
3446
- } from "@sixb/core";
3447
- import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
3448
- import {
3449
- createFileUploadId,
3450
- createUploadExpiresAt,
3451
- FileUploadSessionError as FileUploadSessionError2
3452
- } from "@sixb/core/storage";
3453
- var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
3454
- var SYSTEM_PRINCIPAL2 = { type: "system", id: "system" };
3455
- function registerFileRoutes(app, sixb) {
3456
- const uploadSessions = sixb.storage.fileUploadSessions ?? new InMemoryFileUploadSessions;
3457
- return app.post("/api/files", async ({ request, set }) => {
3635
+ }).get("/api/datasets/:datasetId", async (context) => {
3636
+ const { params, set } = context;
3637
+ const { scoped } = requestAuthState(context);
3458
3638
  try {
3459
- const requestSizeError = requestSizeLimitError(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES);
3460
- if (requestSizeError) {
3461
- set.status = 413;
3462
- return { error: requestSizeError };
3463
- }
3464
- const form = await request.formData();
3465
- const file = form.get("file");
3466
- const logicalPath = form.get("logicalPath");
3467
- if (!(file instanceof File)) {
3468
- set.status = 400;
3469
- return { error: "Expected multipart field 'file' to be a file." };
3470
- }
3471
- if (logicalPath !== null && typeof logicalPath !== "string") {
3472
- set.status = 400;
3473
- return { error: "Expected multipart field 'logicalPath' to be a string." };
3474
- }
3475
- if (file.size > DEFAULT_SIMPLE_FILE_UPLOAD_BYTES) {
3476
- set.status = 413;
3477
- return {
3478
- error: `File upload exceeds the ${DEFAULT_SIMPLE_FILE_UPLOAD_BYTES} byte limit.`
3479
- };
3480
- }
3481
- const fileRef = await sixb.blobStorage.put({
3482
- body: file,
3483
- fileName: file.name || undefined,
3484
- mediaType: file.type || undefined,
3485
- logicalPath: logicalPath ?? undefined
3486
- });
3487
- return FileRefSchema.parse(fileRef);
3639
+ const dataset = requireDataset(sixb, scoped, params.datasetId);
3640
+ const [state] = await sixb.lakeStorage.listDatasetCatalogState([dataset.id]);
3641
+ const references = buildDatasetReferenceIndex(sixb, scoped).get(dataset.id);
3642
+ return serializeDatasetCatalogItem(dataset, state, references ?? EMPTY_DATASET_REFERENCES);
3488
3643
  } catch (error) {
3489
3644
  return handleRouteError(error, set);
3490
3645
  }
3491
3646
  }, {
3647
+ params: DatasetParamsSchema,
3492
3648
  response: {
3493
- 200: FileRefSchema,
3649
+ 200: DatasetCatalogItemSchema,
3494
3650
  400: ErrorResponseSchema,
3495
- 413: ErrorResponseSchema
3496
- },
3497
- detail: {
3498
- summary: "Upload a file",
3499
- tags: [OPENAPI_TAGS.files.name],
3500
- operationId: "uploadFileRaw",
3501
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
3502
- requestBody: {
3503
- required: true,
3504
- content: {
3505
- "multipart/form-data": {
3506
- schema: {
3507
- type: "object",
3508
- required: ["file"],
3509
- properties: {
3510
- file: {
3511
- type: "string",
3512
- format: "binary"
3513
- },
3514
- logicalPath: {
3515
- type: "string"
3516
- }
3517
- }
3518
- }
3519
- }
3520
- }
3521
- }
3522
- }
3523
- }).post("/api/files/uploads", async (context) => {
3524
- const { body, set } = context;
3525
- const { authz } = requestAuthState(context);
3526
- try {
3527
- const parsed = CreateFileUploadBodySchema.parse(body);
3528
- const principal = authz?.principal ?? SYSTEM_PRINCIPAL2;
3529
- const uploadId = createFileUploadId();
3530
- const expiresAt = createUploadExpiresAt();
3531
- const expectedDigest = parsed.digest;
3532
- const providerUpload = supportsDirectUpload(sixb.blobStorage) && expectedDigest !== undefined && parsed.sizeBytes !== undefined ? await sixb.blobStorage.createUpload({
3533
- uploadId,
3534
- expiresAt,
3535
- ...parsed.fileName === undefined ? {} : { fileName: parsed.fileName },
3536
- ...parsed.mediaType === undefined ? {} : { mediaType: parsed.mediaType },
3537
- ...parsed.logicalPath === undefined ? {} : { logicalPath: parsed.logicalPath },
3538
- ...parsed.sizeBytes === undefined ? {} : { sizeBytes: parsed.sizeBytes },
3539
- expectedDigest
3540
- }) : undefined;
3541
- const session = await uploadSessions.create({
3542
- id: uploadId,
3543
- projectId: sixb.id,
3544
- principal,
3545
- strategy: providerUpload?.strategy ?? "server",
3546
- expiresAt,
3547
- ...parsed.fileName === undefined ? {} : { fileName: parsed.fileName },
3548
- ...parsed.mediaType === undefined ? {} : { mediaType: parsed.mediaType },
3549
- ...parsed.logicalPath === undefined ? {} : { logicalPath: parsed.logicalPath },
3550
- ...parsed.sizeBytes === undefined ? {} : { expectedSizeBytes: parsed.sizeBytes },
3551
- ...expectedDigest === undefined ? {} : { expectedDigest },
3552
- ...providerUpload === undefined ? {} : { providerUpload }
3553
- });
3554
- set.status = 201;
3555
- return CreateFileUploadResponseSchema.parse(fileUploadResponse(session));
3556
- } catch (error) {
3557
- return handleRouteError(error, set);
3558
- }
3559
- }, {
3560
- body: CreateFileUploadBodySchema,
3561
- response: {
3562
- 201: CreateFileUploadResponseSchema,
3563
- 400: ErrorResponseSchema
3651
+ 404: ErrorResponseSchema
3564
3652
  },
3565
3653
  detail: {
3566
- summary: "Create a staged file upload",
3567
- tags: [OPENAPI_TAGS.files.name],
3568
- operationId: "createFileUpload",
3569
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3654
+ summary: "Get dataset metadata",
3655
+ tags: [OPENAPI_TAGS.datasets.name],
3656
+ operationId: "getDataset"
3570
3657
  }
3571
- }).put("/api/files/uploads/:uploadId/content", async (context) => {
3572
- const { params, request, set } = context;
3573
- const { authz } = requestAuthState(context);
3658
+ }).get("/api/datasets/:datasetId/versions", async (context) => {
3659
+ const { params, query, set } = context;
3660
+ const { scoped } = requestAuthState(context);
3574
3661
  try {
3575
- const principal = authz?.principal ?? SYSTEM_PRINCIPAL2;
3576
- const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
3577
- if (session.status !== "pending") {
3578
- throw terminalSessionError(session.status);
3579
- }
3580
- if (session.strategy !== "server") {
3581
- set.status = 400;
3582
- return { error: "Upload content is only accepted for server staged uploads." };
3583
- }
3584
- const contentLengthSizeError = expectedContentLengthError(session, request);
3585
- if (contentLengthSizeError) {
3586
- set.status = 400;
3587
- return { error: contentLengthSizeError };
3588
- }
3589
- const uploadBytes = readParsedUploadBytes(context);
3590
- if (uploadBytes.byteLength === 0) {
3591
- set.status = 400;
3592
- return { error: "Expected upload content body." };
3593
- }
3594
- const sizeError = expectedSizeBytesError(session, uploadBytes.byteLength);
3595
- if (sizeError) {
3596
- set.status = 400;
3597
- return { error: sizeError };
3598
- }
3599
- const digest = computeBlobDigest(uploadBytes);
3600
- const digestError = expectedDigestError(session.expectedDigest, digest);
3601
- if (digestError) {
3602
- set.status = 400;
3603
- return { error: digestError };
3604
- }
3605
- const fileRef = await sixb.blobStorage.put({
3606
- body: uploadBytes,
3607
- ...session.fileName === undefined ? {} : { fileName: session.fileName },
3608
- ...session.mediaType === undefined ? {} : { mediaType: session.mediaType },
3609
- ...session.logicalPath === undefined ? {} : { logicalPath: session.logicalPath }
3662
+ requireDataset(sixb, scoped, params.datasetId);
3663
+ const parsed = DatasetVersionsQuerySchema.parse(query);
3664
+ const limit = parseLimit(parsed.limit, DEFAULT_VERSION_LIMIT, MAX_VERSION_LIMIT);
3665
+ const versions = await sixb.lakeStorage.listVersions(params.datasetId, limit);
3666
+ return DatasetVersionListResponseSchema.parse({
3667
+ versions: versions.map(serializeDatasetVersion),
3668
+ count: versions.length
3610
3669
  });
3611
- await uploadSessions.markUploaded(session.id, fileRef);
3612
- return { success: true };
3613
- } catch (error) {
3614
- return handleRouteError(error, set);
3615
- }
3616
- }, {
3617
- params: FileUploadIdParamsSchema,
3618
- parse: readCappedUploadBody,
3619
- error: mapUploadContentError,
3620
- response: {
3621
- 200: SuccessResponseSchema,
3622
- 400: ErrorResponseSchema,
3623
- 404: ErrorResponseSchema,
3624
- 409: ErrorResponseSchema,
3625
- 410: ErrorResponseSchema
3626
- },
3627
- detail: {
3628
- summary: "Upload staged file content through Sixb",
3629
- tags: [OPENAPI_TAGS.files.name],
3630
- operationId: "uploadFileContent",
3631
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
3632
- requestBody: {
3633
- required: true,
3634
- content: {
3635
- "application/octet-stream": {
3636
- schema: {
3637
- type: "string",
3638
- format: "binary"
3639
- }
3640
- }
3641
- }
3642
- }
3670
+ } catch (error) {
3671
+ return handleRouteError(error, set);
3643
3672
  }
3644
- }).post("/api/files/uploads/:uploadId/parts/:partNumber", async (context) => {
3673
+ }, {
3674
+ params: DatasetParamsSchema,
3675
+ query: DatasetVersionsQuerySchema,
3676
+ response: {
3677
+ 200: DatasetVersionListResponseSchema,
3678
+ 400: ErrorResponseSchema,
3679
+ 404: ErrorResponseSchema
3680
+ },
3681
+ detail: {
3682
+ summary: "List dataset versions",
3683
+ tags: [OPENAPI_TAGS.datasetVersions.name],
3684
+ operationId: "listDatasetVersions"
3685
+ }
3686
+ }).get("/api/datasets/:datasetId/versions/:versionId", async (context) => {
3645
3687
  const { params, set } = context;
3646
- const { authz } = requestAuthState(context);
3688
+ const { scoped } = requestAuthState(context);
3647
3689
  try {
3648
- const principal = authz?.principal ?? SYSTEM_PRINCIPAL2;
3649
- const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
3650
- if (session.status !== "pending") {
3651
- throw terminalSessionError(session.status);
3652
- }
3653
- if (session.strategy !== "multipart" || session.providerUpload?.strategy !== "multipart") {
3654
- set.status = 400;
3655
- return { error: "Upload session does not use multipart strategy." };
3656
- }
3657
- if (!supportsDirectUpload(sixb.blobStorage)) {
3658
- set.status = 400;
3659
- return { error: "Blob storage does not support direct uploads." };
3690
+ requireDataset(sixb, scoped, params.datasetId);
3691
+ const version = await sixb.lakeStorage.getVersion(params.datasetId, params.versionId);
3692
+ if (!version) {
3693
+ set.status = 404;
3694
+ return { error: "Dataset version not found" };
3660
3695
  }
3661
- const signedPart = await sixb.blobStorage.signUploadPart({
3662
- uploadId: session.id,
3663
- stagingKey: session.providerUpload.stagingKey,
3664
- providerUploadId: session.providerUpload.providerUploadId,
3665
- partNumber: Number.parseInt(params.partNumber, 10),
3666
- expiresAt: session.expiresAt
3667
- });
3668
- await uploadSessions.addSignedPart(session.id, signedPart);
3669
- return SignedFileUploadPartSchema.parse({
3670
- ...signedPart,
3671
- expiresAt: signedPart.expiresAt.toISOString()
3672
- });
3696
+ return serializeDatasetVersion(version);
3673
3697
  } catch (error) {
3674
3698
  return handleRouteError(error, set);
3675
3699
  }
3676
3700
  }, {
3677
- params: FileUploadPartParamsSchema,
3701
+ params: DatasetVersionParamsSchema,
3678
3702
  response: {
3679
- 200: SignedFileUploadPartSchema,
3703
+ 200: DatasetVersionSchema,
3680
3704
  400: ErrorResponseSchema,
3681
- 404: ErrorResponseSchema,
3682
- 409: ErrorResponseSchema,
3683
- 410: ErrorResponseSchema
3705
+ 404: ErrorResponseSchema
3684
3706
  },
3685
3707
  detail: {
3686
- summary: "Sign a staged multipart upload part",
3687
- tags: [OPENAPI_TAGS.files.name],
3688
- operationId: "signFileUploadPart",
3689
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3708
+ summary: "Get dataset version",
3709
+ tags: [OPENAPI_TAGS.datasetVersions.name],
3710
+ operationId: "getDatasetVersion"
3690
3711
  }
3691
- }).post("/api/files/uploads/:uploadId/complete", async (context) => {
3692
- const { body, params, set } = context;
3693
- const { authz } = requestAuthState(context);
3712
+ }).get("/api/datasets/:datasetId/rows", async (context) => {
3713
+ const { params, query, set } = context;
3714
+ const { scoped } = requestAuthState(context);
3694
3715
  try {
3695
- const principal = authz?.principal ?? SYSTEM_PRINCIPAL2;
3696
- const parsed = CompleteFileUploadBodySchema.parse(body ?? {});
3697
- const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
3698
- if (session.status === "completed" && session.fileRef) {
3699
- return FileRefSchema.parse(session.fileRef);
3700
- }
3701
- if (session.status !== "pending") {
3702
- throw terminalSessionError(session.status);
3703
- }
3704
- const expected = resolveExpectedUploadIdentity({
3705
- session,
3706
- requestedDigest: parsed.digest,
3707
- requestedSizeBytes: parsed.sizeBytes
3708
- });
3709
- if (session.strategy !== "server" && (expected.digest === undefined || expected.sizeBytes === undefined)) {
3710
- throw new Error("Direct file uploads require an expected digest and size.");
3716
+ requireDataset(sixb, scoped, params.datasetId);
3717
+ const parsed = DatasetRowsQuerySchema.parse(query);
3718
+ const limit = parseLimit(parsed.limit, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT);
3719
+ const offset = parseOffset(parsed.offset);
3720
+ const version = parsed.versionId ? await sixb.lakeStorage.getVersion(params.datasetId, parsed.versionId) : await sixb.lakeStorage.getLatestVersion(params.datasetId);
3721
+ if (!version) {
3722
+ set.status = 404;
3723
+ return { error: "Dataset version not found" };
3711
3724
  }
3712
- const fileRef = session.strategy === "server" ? completeServerUpload(session) : await completeProviderUpload({
3713
- session,
3714
- expectedDigest: expected.digest,
3715
- expectedSizeBytes: expected.sizeBytes,
3716
- parts: parsed.parts,
3717
- blobStorage: sixb.blobStorage
3725
+ const requestedColumns = parseColumns(parsed.columns);
3726
+ const columns = resolveColumns(version, requestedColumns);
3727
+ const rows = await collectRows(sixb.lakeStorage.readRows({
3728
+ datasetId: params.datasetId,
3729
+ versionId: version.versionId,
3730
+ columns: requestedColumns,
3731
+ limit,
3732
+ offset
3733
+ }));
3734
+ const hasMore = version.rowCount === undefined ? rows.length === limit : offset + rows.length < version.rowCount;
3735
+ return DatasetRowsResponseSchema.parse({
3736
+ datasetId: params.datasetId,
3737
+ versionId: version.versionId,
3738
+ version: serializeDatasetVersion(version),
3739
+ columns: [...columns],
3740
+ rows,
3741
+ count: rows.length,
3742
+ limit,
3743
+ offset,
3744
+ total: version.rowCount,
3745
+ hasMore
3718
3746
  });
3719
- const identityError = expectedFileRefError(expected, fileRef);
3720
- if (identityError) {
3721
- throw new Error(identityError);
3722
- }
3723
- await uploadSessions.complete(session.id, fileRef);
3724
- return FileRefSchema.parse(fileRef);
3725
3747
  } catch (error) {
3726
3748
  return handleRouteError(error, set);
3727
3749
  }
3728
3750
  }, {
3729
- params: FileUploadIdParamsSchema,
3730
- body: CompleteFileUploadBodySchema,
3751
+ params: DatasetParamsSchema,
3752
+ query: DatasetRowsQuerySchema,
3731
3753
  response: {
3732
- 200: FileRefSchema,
3754
+ 200: DatasetRowsResponseSchema,
3733
3755
  400: ErrorResponseSchema,
3734
- 404: ErrorResponseSchema,
3735
- 409: ErrorResponseSchema,
3736
- 410: ErrorResponseSchema
3756
+ 404: ErrorResponseSchema
3737
3757
  },
3738
3758
  detail: {
3739
- summary: "Complete a staged file upload",
3740
- tags: [OPENAPI_TAGS.files.name],
3741
- operationId: "completeFileUpload",
3742
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3759
+ summary: "Preview dataset rows",
3760
+ tags: [OPENAPI_TAGS.datasetRows.name],
3761
+ operationId: "listDatasetRows"
3743
3762
  }
3744
- }).post("/api/files/uploads/:uploadId/abort", async (context) => {
3745
- const { params, set } = context;
3746
- const { authz } = requestAuthState(context);
3763
+ });
3764
+ }
3765
+
3766
+ // src/routes/events.ts
3767
+ import { AuthorizationError as AuthorizationError2 } from "@sixb/core";
3768
+
3769
+ // src/schemas/events.ts
3770
+ import {
3771
+ EVENT_TOPICS as CORE_EVENT_TOPICS,
3772
+ EVENT_TYPES as CORE_EVENT_TYPES,
3773
+ EVENT_DEFINITIONS,
3774
+ isOntologyFactType
3775
+ } from "@sixb/core/internal/events";
3776
+ import { z as z11 } from "zod";
3777
+
3778
+ // src/schemas/event-payloads.ts
3779
+ import { z as z10 } from "zod";
3780
+ var PropertyChangeSchema = z10.discriminatedUnion("operation", [
3781
+ z10.object({ operation: z10.literal("created"), after: JsonValueSchema }),
3782
+ z10.object({
3783
+ operation: z10.literal("updated"),
3784
+ before: JsonValueSchema,
3785
+ after: JsonValueSchema
3786
+ }),
3787
+ z10.object({
3788
+ operation: z10.literal("cleared"),
3789
+ before: JsonValueSchema,
3790
+ after: JsonNullSchema
3791
+ })
3792
+ ]);
3793
+ var PropertyChangesSchema = z10.record(PropertyChangeSchema);
3794
+ var ObjectMutationPayloadSchema = z10.object({
3795
+ objectTypeId: z10.string(),
3796
+ primaryId: z10.string(),
3797
+ properties: z10.record(JsonValueSchema),
3798
+ propertyChanges: PropertyChangesSchema
3799
+ });
3800
+ var ObjectDeletedPayloadSchema = z10.object({
3801
+ objectTypeId: z10.string(),
3802
+ primaryId: z10.string(),
3803
+ propertyChanges: PropertyChangesSchema
3804
+ });
3805
+ var LinkSubjectSchema = z10.object({
3806
+ sourceTypeId: z10.string(),
3807
+ sourceId: z10.string(),
3808
+ linkId: z10.string(),
3809
+ targetTypeId: z10.string(),
3810
+ targetId: z10.string()
3811
+ });
3812
+ var LinkMutationPayloadSchema = LinkSubjectSchema.extend({
3813
+ properties: z10.record(JsonValueSchema).optional(),
3814
+ propertyChanges: PropertyChangesSchema
3815
+ });
3816
+ var LinkDeletedPayloadSchema = LinkSubjectSchema.extend({
3817
+ propertyChanges: PropertyChangesSchema
3818
+ });
3819
+ var ONTOLOGY_EVENT_PAYLOAD_SCHEMAS = {
3820
+ "object.created": ObjectMutationPayloadSchema,
3821
+ "object.updated": ObjectMutationPayloadSchema,
3822
+ "object.deleted": ObjectDeletedPayloadSchema,
3823
+ "link.created": LinkMutationPayloadSchema,
3824
+ "link.updated": LinkMutationPayloadSchema,
3825
+ "link.deleted": LinkDeletedPayloadSchema,
3826
+ "telemetry.appended": z10.object({
3827
+ objectTypeId: z10.string(),
3828
+ objectId: z10.string(),
3829
+ propertyId: z10.string(),
3830
+ value: JsonValueSchema,
3831
+ unit: z10.string().optional(),
3832
+ at: z10.string()
3833
+ })
3834
+ };
3835
+
3836
+ // src/schemas/events.ts
3837
+ var EVENT_TOPICS = CORE_EVENT_TOPICS;
3838
+ var EVENT_TYPES = CORE_EVENT_TYPES;
3839
+ var EventTopicSchema = z11.enum(EVENT_TOPICS);
3840
+ var EventTypeSchema = z11.enum(EVENT_TYPES);
3841
+ var ProjectionEventOriginSchema = z11.object({
3842
+ kind: z11.literal("projection"),
3843
+ projectionId: z11.string(),
3844
+ projectionRunId: z11.string(),
3845
+ datasetId: z11.string(),
3846
+ datasetVersionId: z11.string()
3847
+ });
3848
+ var EventOriginSchema = z11.union([
3849
+ z11.object({
3850
+ kind: z11.literal("action"),
3851
+ actionId: z11.string(),
3852
+ runId: z11.string()
3853
+ }),
3854
+ z11.object({ kind: z11.literal("runtime"), requestId: z11.string() }),
3855
+ ProjectionEventOriginSchema,
3856
+ z11.object({
3857
+ kind: z11.literal("telemetry"),
3858
+ source: z11.union([
3859
+ z11.object({ kind: z11.literal("runtime"), requestId: z11.string() }),
3860
+ ProjectionEventOriginSchema.extend({ batchOrdinal: z11.number() })
3861
+ ])
3862
+ })
3863
+ ]);
3864
+ var EventsQuerySchema = z11.object({
3865
+ topic: EventTopicSchema.optional(),
3866
+ type: EventTypeSchema.optional(),
3867
+ afterCursor: z11.string().optional(),
3868
+ limit: z11.string().optional()
3869
+ });
3870
+ var StoredEventBaseSchema = z11.object({
3871
+ id: z11.string(),
3872
+ cursor: z11.string(),
3873
+ schemaVersion: z11.literal(1),
3874
+ projectId: z11.string(),
3875
+ occurredAt: z11.string(),
3876
+ actor: z11.object({
3877
+ type: z11.enum(["user", "serviceAccount", "system"]),
3878
+ id: z11.string()
3879
+ }).optional(),
3880
+ partitionKey: z11.string()
3881
+ });
3882
+ var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
3883
+ correlationId: z11.string().optional(),
3884
+ causationId: z11.string().optional(),
3885
+ idempotencyKey: z11.string().optional(),
3886
+ origin: EventOriginSchema.optional(),
3887
+ metadata: z11.record(JsonValueSchema).optional()
3888
+ });
3889
+ var StoredOntologyEventBaseSchema = StoredEventBaseSchema.extend({
3890
+ origin: EventOriginSchema,
3891
+ commitId: z11.string(),
3892
+ commitOrdinal: z11.number().int().nonnegative()
3893
+ });
3894
+ var ontologyEventTypes = EVENT_TYPES.filter(isOntologyFactType);
3895
+ var ontologyEventSchemas = ontologyEventTypes.map((type) => StoredOntologyEventBaseSchema.extend({
3896
+ type: z11.literal(type),
3897
+ topic: z11.literal(EVENT_DEFINITIONS[type].topic),
3898
+ payload: ONTOLOGY_EVENT_PAYLOAD_SCHEMAS[type]
3899
+ }));
3900
+ var authorableEventTypes = EVENT_TYPES.filter((type) => !isOntologyFactType(type));
3901
+ var StoredAuthorableEventSchema = StoredAuthorableEventBaseSchema.extend({
3902
+ type: z11.enum(authorableEventTypes),
3903
+ topic: EventTopicSchema,
3904
+ payload: z11.record(z11.unknown())
3905
+ });
3906
+ var StoredOntologyEventSchema = z11.discriminatedUnion("type", ontologyEventSchemas);
3907
+ var EventSchema = z11.union([StoredOntologyEventSchema, StoredAuthorableEventSchema]);
3908
+ var EventsResponseSchema = z11.object({
3909
+ count: z11.number(),
3910
+ events: z11.array(EventSchema)
3911
+ });
3912
+
3913
+ // src/routes/events.ts
3914
+ function registerEventRoutes(app, sixb) {
3915
+ return app.get("/api/events", async (context) => {
3916
+ const { query, set } = context;
3917
+ const { scoped } = requestAuthState(context);
3747
3918
  try {
3748
- const principal = authz?.principal ?? SYSTEM_PRINCIPAL2;
3749
- const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
3750
- if (session.status === "completed") {
3751
- throw new FileUploadSessionError2("already_completed", "File upload session is already completed.");
3752
- }
3753
- if (session.status === "pending" && session.providerUpload) {
3754
- if (!supportsDirectUpload(sixb.blobStorage)) {
3755
- set.status = 400;
3756
- return { error: "Blob storage does not support direct uploads." };
3757
- }
3758
- await sixb.blobStorage.abortUpload({
3759
- uploadId: session.id,
3760
- stagingKey: session.providerUpload.stagingKey,
3761
- providerUploadId: session.providerUpload.providerUploadId
3762
- });
3763
- }
3764
- if (session.status === "pending") {
3765
- await uploadSessions.abort(session.id);
3766
- }
3767
- return { success: true };
3919
+ const parsed = EventsQuerySchema.parse(query);
3920
+ const input = {
3921
+ topics: parsed.topic ? [parsed.topic] : undefined,
3922
+ types: parsed.type ? [parsed.type] : undefined,
3923
+ afterCursor: parsed.afterCursor,
3924
+ limit: parseOptionalInt(parsed.limit)
3925
+ };
3926
+ const events = scoped ? await scoped.readEvents(input) : await sixb.events.read(input);
3927
+ return {
3928
+ count: events.length,
3929
+ events: [...events]
3930
+ };
3768
3931
  } catch (error) {
3769
- return handleRouteError(error, set);
3932
+ if (error instanceof AuthorizationError2) {
3933
+ set.status = 403;
3934
+ return { error: error.message };
3935
+ }
3936
+ set.status = 400;
3937
+ return { error: error instanceof Error ? error.message : String(error) };
3770
3938
  }
3771
3939
  }, {
3772
- params: FileUploadIdParamsSchema,
3940
+ query: EventsQuerySchema,
3773
3941
  response: {
3774
- 200: SuccessResponseSchema,
3942
+ 200: EventsResponseSchema,
3775
3943
  400: ErrorResponseSchema,
3776
- 404: ErrorResponseSchema,
3777
- 409: ErrorResponseSchema,
3778
- 410: ErrorResponseSchema
3944
+ 403: ErrorResponseSchema
3779
3945
  },
3780
3946
  detail: {
3781
- summary: "Abort a staged file upload",
3782
- tags: [OPENAPI_TAGS.files.name],
3783
- operationId: "abortFileUpload",
3784
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3947
+ summary: "Read domain events",
3948
+ tags: [OPENAPI_TAGS.events.name],
3949
+ operationId: "listEvents",
3950
+ security: bearerSecurityRequirement("listEvents")
3785
3951
  }
3786
3952
  });
3787
3953
  }
3788
- function fileUploadResponse(session) {
3789
- if (session.providerUpload?.strategy === "direct-put") {
3790
- return {
3791
- strategy: "direct-put",
3792
- uploadId: session.id,
3793
- method: session.providerUpload.method,
3794
- url: session.providerUpload.url,
3795
- headers: session.providerUpload.headers,
3796
- expiresAt: session.providerUpload.expiresAt.toISOString()
3797
- };
3798
- }
3799
- if (session.providerUpload?.strategy === "multipart") {
3800
- return {
3801
- strategy: "multipart",
3802
- uploadId: session.id,
3803
- partSizeBytes: session.providerUpload.partSizeBytes,
3804
- expiresAt: session.providerUpload.expiresAt.toISOString()
3805
- };
3806
- }
3807
- return {
3808
- strategy: "server",
3809
- uploadId: session.id,
3810
- method: "PUT",
3811
- url: `/api/files/uploads/${encodeURIComponent(session.id)}/content`,
3812
- expiresAt: session.expiresAt.toISOString()
3813
- };
3814
- }
3815
- function readCappedUploadBody(context) {
3816
- return readRequestBodyWithLimit(context.request, DEFAULT_SIMPLE_FILE_UPLOAD_BYTES);
3817
- }
3818
- function readParsedUploadBytes(context) {
3819
- return context.body instanceof Uint8Array ? context.body : new Uint8Array(0);
3820
- }
3821
- function mapUploadContentError(context) {
3822
- const tooLarge = asRequestBodyTooLarge(context.error);
3823
- if (tooLarge) {
3824
- context.set.status = 413;
3825
- return { error: tooLarge.message };
3826
- }
3827
- return;
3828
- }
3829
- function asRequestBodyTooLarge(error) {
3830
- if (error instanceof RequestBodyTooLargeError) {
3831
- return error;
3832
- }
3833
- const cause = error?.cause;
3834
- return cause instanceof RequestBodyTooLargeError ? cause : undefined;
3835
- }
3836
- function terminalSessionError(status) {
3837
- return new FileUploadSessionError2(status === "completed" ? "already_completed" : "already_aborted", `File upload session is already ${status}.`);
3838
- }
3839
- function completeServerUpload(session) {
3840
- if (!session.fileRef) {
3841
- throw new Error("Upload content has not been received.");
3842
- }
3843
- return session.fileRef;
3844
- }
3845
- async function completeProviderUpload(input) {
3846
- const { blobStorage, session } = input;
3847
- if (!session.providerUpload) {
3848
- throw new Error("Upload session does not have provider upload state.");
3849
- }
3850
- if (!supportsDirectUpload(blobStorage)) {
3851
- throw new Error("Blob storage does not support direct uploads.");
3852
- }
3853
- const fileRef = await blobStorage.completeUpload({
3854
- uploadId: session.id,
3855
- stagingKey: session.providerUpload.stagingKey,
3856
- providerUploadId: session.providerUpload.providerUploadId,
3857
- ...session.fileName === undefined ? {} : { fileName: session.fileName },
3858
- ...session.mediaType === undefined ? {} : { mediaType: session.mediaType },
3859
- ...session.logicalPath === undefined ? {} : { logicalPath: session.logicalPath },
3860
- ...input.expectedSizeBytes === undefined ? {} : { expectedSizeBytes: input.expectedSizeBytes },
3861
- ...input.expectedDigest === undefined ? {} : { expectedDigest: input.expectedDigest },
3862
- ...input.parts === undefined ? {} : { parts: input.parts }
3863
- });
3864
- return fileRef;
3865
- }
3866
- function resolveExpectedUploadIdentity(input) {
3867
- const digestError = expectedDigestError(input.session.expectedDigest, input.requestedDigest);
3868
- if (digestError) {
3869
- throw new Error(digestError);
3870
- }
3871
- const sizeError = expectedSizeBytesValueError(input.session.expectedSizeBytes, input.requestedSizeBytes);
3872
- if (sizeError) {
3873
- throw new Error(sizeError);
3874
- }
3875
- const digest = input.session.expectedDigest ?? input.requestedDigest;
3876
- const sizeBytes = input.session.expectedSizeBytes ?? input.requestedSizeBytes;
3877
- return {
3878
- ...digest === undefined ? {} : { digest },
3879
- ...sizeBytes === undefined ? {} : { sizeBytes }
3880
- };
3881
- }
3882
- function expectedFileRefError(expected, fileRef) {
3883
- return expectedSizeBytesValueError(expected.sizeBytes, fileRef.sizeBytes) ?? expectedDigestError(expected.digest, fileRef.digest);
3884
- }
3885
- function expectedDigestError(expectedDigest, actualDigest) {
3886
- return expectedDigest !== undefined && actualDigest !== undefined && actualDigest !== expectedDigest ? `File upload digest mismatch: expected ${expectedDigest}, received ${actualDigest}.` : null;
3887
- }
3888
- function expectedSizeBytesError(session, actualSizeBytes) {
3889
- return expectedSizeBytesValueError(session.expectedSizeBytes, actualSizeBytes);
3890
- }
3891
- function expectedSizeBytesValueError(expectedSizeBytes, actualSizeBytes) {
3892
- return expectedSizeBytes !== undefined && actualSizeBytes !== undefined && actualSizeBytes !== expectedSizeBytes ? `File upload size mismatch: expected ${expectedSizeBytes} bytes, received ${actualSizeBytes}.` : null;
3893
- }
3894
- function requestSizeLimitError(request, maxSizeBytes) {
3895
- const value = request.headers.get("content-length");
3896
- if (value === null) {
3897
- return null;
3898
- }
3899
- const sizeBytes = Number(value);
3900
- if (!Number.isSafeInteger(sizeBytes) || sizeBytes <= maxSizeBytes) {
3901
- return null;
3902
- }
3903
- return `File upload request exceeds the ${maxSizeBytes} byte limit.`;
3904
- }
3905
- function expectedContentLengthError(session, request) {
3906
- if (session.expectedSizeBytes === undefined) {
3907
- return null;
3908
- }
3909
- const value = request.headers.get("content-length");
3910
- if (value === null) {
3911
- return null;
3912
- }
3913
- const sizeBytes = Number(value);
3914
- if (!Number.isSafeInteger(sizeBytes)) {
3915
- return null;
3916
- }
3917
- return expectedSizeBytesError(session, sizeBytes);
3918
- }
3919
3954
 
3920
3955
  // src/routes/links.ts
3921
3956
  import { isAllowed } from "@sixb/core";
@@ -3995,7 +4030,8 @@ function registerLinkRoutes(app, sixb) {
3995
4030
  detail: {
3996
4031
  summary: "List object links",
3997
4032
  tags: [OPENAPI_TAGS.links.name],
3998
- operationId: "listObjectLinks"
4033
+ operationId: "listObjectLinks",
4034
+ security: bearerSecurityRequirement("listObjectLinks")
3999
4035
  }
4000
4036
  }).put("/api/objects/:objectTypeId/:objectId/links/:linkId", async (context) => {
4001
4037
  const { params, body, set } = context;
@@ -5555,29 +5591,6 @@ var DatasetVersionRefSchema2 = z16.object({
5555
5591
  datasetId: z16.string(),
5556
5592
  versionId: z16.string()
5557
5593
  });
5558
- var DatasetColumnSchema2 = z16.object({
5559
- name: z16.string(),
5560
- type: z16.enum([
5561
- "string",
5562
- "boolean",
5563
- "int64",
5564
- "float64",
5565
- "decimal",
5566
- "date",
5567
- "timestamp",
5568
- "json",
5569
- "fileRef"
5570
- ]),
5571
- nullable: z16.boolean().optional()
5572
- });
5573
- var DatasetDefinitionSchema2 = z16.object({
5574
- id: z16.string(),
5575
- description: z16.string().optional(),
5576
- partitionBy: z16.array(z16.string()).optional(),
5577
- schema: z16.object({
5578
- columns: z16.array(DatasetColumnSchema2)
5579
- })
5580
- });
5581
5594
  var PipelineTriggerSchema = z16.object({
5582
5595
  type: z16.literal("schedule"),
5583
5596
  scheduleId: z16.string()
@@ -5629,9 +5642,9 @@ var PipelineStepSchema = z16.object({
5629
5642
  executor: PipelineStepExecutorSchema,
5630
5643
  inputs: z16.array(z16.object({
5631
5644
  name: z16.string(),
5632
- dataset: DatasetDefinitionSchema2
5645
+ dataset: DatasetDefinitionSchema
5633
5646
  })),
5634
- output: DatasetDefinitionSchema2
5647
+ output: DatasetDefinitionSchema
5635
5648
  });
5636
5649
  var PipelineSchema = z16.object({
5637
5650
  id: z16.string(),
@@ -6468,6 +6481,7 @@ var SyncParamsSchema = z21.object({
6468
6481
  syncId: z21.string().min(1)
6469
6482
  });
6470
6483
  var SyncRunStatusSchema = z21.enum(["running", "succeeded", "failed", "cancelled"]);
6484
+ var SyncModeSchema = z21.enum(["snapshot", "append", "merge"]);
6471
6485
  var SyncRunsQuerySchema = z21.object({
6472
6486
  syncId: z21.string().optional(),
6473
6487
  datasetId: z21.string().optional(),
@@ -6491,7 +6505,7 @@ var SyncRunSchema = z21.object({
6491
6505
  projectId: z21.string(),
6492
6506
  syncId: z21.string(),
6493
6507
  datasetId: z21.string(),
6494
- mode: z21.enum(["snapshot", "append"]),
6508
+ mode: SyncModeSchema,
6495
6509
  status: SyncRunStatusSchema,
6496
6510
  startedAt: z21.string(),
6497
6511
  finishedAt: z21.string().optional(),
@@ -6509,7 +6523,7 @@ var SyncRunSchema = z21.object({
6509
6523
  });
6510
6524
  var SyncSchema = z21.object({
6511
6525
  id: z21.string(),
6512
- mode: z21.enum(["snapshot", "append"]),
6526
+ mode: SyncModeSchema,
6513
6527
  connector: z21.object({
6514
6528
  id: z21.string(),
6515
6529
  type: z21.string()
@@ -7024,6 +7038,7 @@ import { z as z25 } from "zod";
7024
7038
 
7025
7039
  // src/schemas/workflows.ts
7026
7040
  import { z as z24 } from "zod";
7041
+ var WorkflowIOSnapshotSchema = z24.record(JsonValueSchema);
7027
7042
  var WorkflowParamsSchema = z24.object({
7028
7043
  workflowId: z24.string().min(1)
7029
7044
  });
@@ -7071,7 +7086,7 @@ var WorkflowInterventionsQuerySchema = z24.object({
7071
7086
  order: z24.enum(["asc", "desc"]).optional()
7072
7087
  });
7073
7088
  var RequestWorkflowRunBodySchema = z24.object({
7074
- input: z24.record(z24.unknown()).optional()
7089
+ input: WorkflowIOSnapshotSchema.optional()
7075
7090
  }).default({});
7076
7091
  var WorkflowInterventionActorSchema = z24.object({
7077
7092
  principalType: z24.enum(["user", "serviceAccount", "system"]),
@@ -7079,7 +7094,7 @@ var WorkflowInterventionActorSchema = z24.object({
7079
7094
  });
7080
7095
  var CancelWorkflowRunBodySchema = z24.object({}).default({});
7081
7096
  var SubmitWorkflowInterventionBodySchema = z24.object({
7082
- response: z24.record(z24.unknown())
7097
+ response: WorkflowIOSnapshotSchema
7083
7098
  });
7084
7099
  var CancelWorkflowInterventionBodySchema = z24.object({}).default({});
7085
7100
  var WorkflowTriggerSchema = z24.object({
@@ -7091,22 +7106,22 @@ var WorkflowNodeSchema = z24.union([
7091
7106
  type: z24.literal("step"),
7092
7107
  id: z24.string(),
7093
7108
  key: z24.string(),
7094
- input: z24.record(z24.unknown()),
7095
- output: z24.record(z24.unknown())
7109
+ input: WorkflowIOSnapshotSchema,
7110
+ output: WorkflowIOSnapshotSchema
7096
7111
  }),
7097
7112
  z24.object({
7098
7113
  type: z24.literal("action"),
7099
7114
  id: z24.string(),
7100
7115
  key: z24.string(),
7101
7116
  objectTypeId: z24.string().optional(),
7102
- params: z24.record(z24.unknown())
7117
+ params: WorkflowIOSnapshotSchema
7103
7118
  }),
7104
7119
  z24.object({
7105
7120
  type: z24.literal("intervention"),
7106
7121
  id: z24.string(),
7107
7122
  key: z24.string(),
7108
- input: z24.record(z24.unknown()),
7109
- response: z24.record(z24.unknown()),
7123
+ input: WorkflowIOSnapshotSchema,
7124
+ response: WorkflowIOSnapshotSchema,
7110
7125
  description: z24.string().optional()
7111
7126
  }),
7112
7127
  z24.object({
@@ -7114,22 +7129,25 @@ var WorkflowNodeSchema = z24.union([
7114
7129
  id: z24.string(),
7115
7130
  key: z24.string(),
7116
7131
  agentId: z24.string(),
7117
- input: z24.record(z24.unknown()),
7118
- output: z24.record(z24.unknown())
7132
+ input: WorkflowIOSnapshotSchema,
7133
+ output: WorkflowIOSnapshotSchema
7119
7134
  })
7120
7135
  ]);
7121
- var WorkflowRunSchema = z24.object({
7136
+ var WorkflowRunSummarySchema = z24.object({
7122
7137
  id: z24.string(),
7123
7138
  projectId: z24.string(),
7124
7139
  workflowId: z24.string(),
7125
7140
  status: WorkflowRunStatusSchema,
7126
- input: z24.record(z24.unknown()),
7127
7141
  queuedAt: z24.string().optional(),
7128
7142
  startedAt: z24.string(),
7129
7143
  finishedAt: z24.string().optional(),
7130
7144
  error: z24.string().optional(),
7131
7145
  requestedBy: WorkflowInterventionActorSchema
7132
7146
  });
7147
+ var WorkflowRunDetailSchema = WorkflowRunSummarySchema.extend({
7148
+ input: WorkflowIOSnapshotSchema,
7149
+ output: WorkflowIOSnapshotSchema.optional()
7150
+ });
7133
7151
  var WorkflowAgentNodeExecutionSummarySchema = z24.object({
7134
7152
  agentId: z24.string(),
7135
7153
  status: z24.enum(["queued", "running", "succeeded", "failed", "cancelled"]),
@@ -7159,10 +7177,10 @@ var WorkflowNodeRunSchema = z24.object({
7159
7177
  nodeId: z24.string(),
7160
7178
  nodeKey: z24.string(),
7161
7179
  status: z24.enum(["running", "waiting", "succeeded", "failed", "cancelled"]),
7162
- input: z24.record(z24.unknown()),
7180
+ input: WorkflowIOSnapshotSchema,
7163
7181
  startedAt: z24.string(),
7164
7182
  finishedAt: z24.string().optional(),
7165
- output: z24.record(z24.unknown()).optional(),
7183
+ output: WorkflowIOSnapshotSchema.optional(),
7166
7184
  error: z24.string().optional(),
7167
7185
  agentExecution: WorkflowAgentNodeExecutionSummarySchema.optional()
7168
7186
  });
@@ -7176,32 +7194,32 @@ var WorkflowInterventionSchema = z24.object({
7176
7194
  nodeId: z24.string(),
7177
7195
  nodeKey: z24.string(),
7178
7196
  interventionId: z24.string(),
7179
- input: z24.record(z24.unknown()),
7180
- defaultResponse: z24.record(z24.unknown()),
7197
+ input: WorkflowIOSnapshotSchema,
7198
+ defaultResponse: WorkflowIOSnapshotSchema,
7181
7199
  status: WorkflowInterventionStatusSchema,
7182
7200
  requestedAt: z24.string(),
7183
7201
  expiresAt: z24.string().optional(),
7184
7202
  submittedAt: z24.string().optional(),
7185
7203
  submittedBy: WorkflowInterventionActorSchema.optional(),
7186
- response: z24.record(z24.unknown()).optional(),
7204
+ response: WorkflowIOSnapshotSchema.optional(),
7187
7205
  cancelledAt: z24.string().optional(),
7188
7206
  cancelledBy: WorkflowInterventionActorSchema.optional(),
7189
7207
  expiredAt: z24.string().optional()
7190
7208
  });
7191
7209
  var WorkflowSchema = z24.object({
7192
7210
  id: z24.string(),
7193
- input: z24.record(z24.unknown()),
7211
+ input: WorkflowIOSnapshotSchema,
7194
7212
  triggers: z24.array(WorkflowTriggerSchema),
7195
7213
  nodes: z24.array(WorkflowNodeSchema),
7196
- latestRun: WorkflowRunSchema.nullable()
7214
+ latestRun: WorkflowRunSummarySchema.nullable()
7197
7215
  });
7198
7216
  var WorkflowRunListResponseSchema = z24.object({
7199
- runs: z24.array(WorkflowRunSchema),
7217
+ runs: z24.array(WorkflowRunSummarySchema),
7200
7218
  hasMore: z24.boolean(),
7201
7219
  total: z24.number()
7202
7220
  });
7203
7221
  var WorkflowRunDetailResponseSchema = z24.object({
7204
- run: WorkflowRunSchema,
7222
+ run: WorkflowRunDetailSchema,
7205
7223
  nodes: z24.array(WorkflowNodeRunSchema)
7206
7224
  });
7207
7225
  var CancelWorkflowRunResponseSchema = WorkflowRunDetailResponseSchema;
@@ -7226,7 +7244,7 @@ var RequestWorkflowRunResponseSchema = z24.object({
7226
7244
 
7227
7245
  // src/routes/workflows.ts
7228
7246
  var WorkflowRunFileContentQuerySchema = FileContentQuerySchema.extend({
7229
- path: z25.string().min(1).regex(/^\/input(?:\/|$)/, "Workflow run file content paths must start with /input/")
7247
+ path: z25.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow run file content paths must start with /input/ or /output/")
7230
7248
  });
7231
7249
  var WorkflowNodeFileContentQuerySchema = FileContentQuerySchema.extend({
7232
7250
  path: z25.string().min(1).regex(/^\/(?:input|output)(?:\/|$)/, "Workflow node file content paths must start with /input/ or /output/")
@@ -7234,13 +7252,12 @@ var WorkflowNodeFileContentQuerySchema = FileContentQuerySchema.extend({
7234
7252
  var WorkflowNodeFileContentParamsSchema = WorkflowRunParamsSchema.extend({
7235
7253
  nodeKey: z25.string().min(1)
7236
7254
  });
7237
- function serializeWorkflowRun(run) {
7255
+ function serializeWorkflowRunSummary(run) {
7238
7256
  return {
7239
7257
  id: run.id,
7240
7258
  projectId: run.projectId,
7241
7259
  workflowId: run.workflowId,
7242
7260
  status: run.status,
7243
- input: run.input,
7244
7261
  queuedAt: run.queuedAt ? toIsoString(run.queuedAt) : undefined,
7245
7262
  startedAt: toIsoString(run.startedAt),
7246
7263
  finishedAt: run.finishedAt ? toIsoString(run.finishedAt) : undefined,
@@ -7248,6 +7265,13 @@ function serializeWorkflowRun(run) {
7248
7265
  requestedBy: serializePrincipal(run.requestedByPrincipal)
7249
7266
  };
7250
7267
  }
7268
+ function serializeWorkflowRunDetail(run) {
7269
+ return {
7270
+ ...serializeWorkflowRunSummary(run),
7271
+ input: run.input,
7272
+ output: run.output
7273
+ };
7274
+ }
7251
7275
  function serializeWorkflowNodeRun(node, agentExecution) {
7252
7276
  return {
7253
7277
  id: node.id,
@@ -7346,7 +7370,7 @@ async function workflowRunFileContentResponse(sixb, context, options = {}) {
7346
7370
  if (!run || !canAccessWorkflowRun(authz, scoped, run)) {
7347
7371
  return null;
7348
7372
  }
7349
- return serializeWorkflowRun(run);
7373
+ return serializeWorkflowRunDetail(run);
7350
7374
  }
7351
7375
  });
7352
7376
  }
@@ -7393,7 +7417,7 @@ async function getLatestWorkflowRun(sixb, workflowId) {
7393
7417
  workflowIds: [workflowId]
7394
7418
  });
7395
7419
  const [latest] = result.runs;
7396
- return latest ? serializeWorkflowRun(latest) : null;
7420
+ return latest ? serializeWorkflowRunSummary(latest) : null;
7397
7421
  }
7398
7422
  async function getLatestWorkflowRuns(sixb, workflowIds) {
7399
7423
  const storage = sixb.storage.workflowRuns;
@@ -7404,7 +7428,7 @@ async function getLatestWorkflowRuns(sixb, workflowIds) {
7404
7428
  projectId: sixb.id,
7405
7429
  workflowIds
7406
7430
  });
7407
- return new Map(result.runs.map((run) => [run.workflowId, serializeWorkflowRun(run)]));
7431
+ return new Map(result.runs.map((run) => [run.workflowId, serializeWorkflowRunSummary(run)]));
7408
7432
  }
7409
7433
  function serializeWorkflow(workflow, latestRun) {
7410
7434
  return WorkflowSchema.parse({
@@ -7892,7 +7916,7 @@ function registerWorkflowRoutes(app, sixb) {
7892
7916
  order: parsed.order
7893
7917
  });
7894
7918
  return {
7895
- runs: result.runs.map(serializeWorkflowRun),
7919
+ runs: result.runs.map(serializeWorkflowRunSummary),
7896
7920
  hasMore: result.hasMore,
7897
7921
  total: result.total
7898
7922
  };
@@ -7909,11 +7933,12 @@ function registerWorkflowRoutes(app, sixb) {
7909
7933
  detail: {
7910
7934
  summary: "List workflow run history",
7911
7935
  tags: [OPENAPI_TAGS.workflowRuns.name],
7912
- operationId: "listWorkflowRuns"
7936
+ operationId: "listWorkflowRuns",
7937
+ security: bearerSecurityRequirement("listWorkflowRuns")
7913
7938
  }
7914
7939
  }).get("/api/workflow-runs/:runId", async (context) => {
7915
7940
  const { params, set } = context;
7916
- const { authz, scoped } = requestAuthState(context);
7941
+ const { agentExecution, authz, scoped } = requestAuthState(context);
7917
7942
  try {
7918
7943
  const storage = sixb.storage.workflowRuns;
7919
7944
  if (!storage) {
@@ -7924,13 +7949,17 @@ function registerWorkflowRoutes(app, sixb) {
7924
7949
  set.status = 404;
7925
7950
  return { error: "Workflow run not found" };
7926
7951
  }
7952
+ const serializedRun = serializeWorkflowRunDetail(run);
7953
+ if (agentExecution) {
7954
+ return WorkflowRunDetailResponseSchema.parse({ run: serializedRun, nodes: [] });
7955
+ }
7927
7956
  const nodes = await storage.nodes.list({
7928
7957
  projectId: sixb.id,
7929
7958
  workflowRunId: run.id,
7930
7959
  order: "asc"
7931
7960
  });
7932
7961
  return WorkflowRunDetailResponseSchema.parse({
7933
- run: serializeWorkflowRun(run),
7962
+ run: serializedRun,
7934
7963
  nodes: await Promise.all(nodes.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node)))
7935
7964
  });
7936
7965
  } catch (error) {
@@ -7947,7 +7976,8 @@ function registerWorkflowRoutes(app, sixb) {
7947
7976
  detail: {
7948
7977
  summary: "Get workflow run detail",
7949
7978
  tags: [OPENAPI_TAGS.workflowRuns.name],
7950
- operationId: "getWorkflowRun"
7979
+ operationId: "getWorkflowRun",
7980
+ security: bearerSecurityRequirement("getWorkflowRun")
7951
7981
  }
7952
7982
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/agent-execution", async (context) => {
7953
7983
  const { params, set } = context;
@@ -8026,7 +8056,7 @@ function registerWorkflowRoutes(app, sixb) {
8026
8056
  });
8027
8057
  if (existing.status === "cancelled") {
8028
8058
  return CancelWorkflowRunResponseSchema.parse({
8029
- run: serializeWorkflowRun(existing),
8059
+ run: serializeWorkflowRunDetail(existing),
8030
8060
  nodes: await Promise.all(listed.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node)))
8031
8061
  });
8032
8062
  }
@@ -8114,7 +8144,7 @@ function registerWorkflowRoutes(app, sixb) {
8114
8144
  order: "asc"
8115
8145
  });
8116
8146
  return CancelWorkflowRunResponseSchema.parse({
8117
- run: serializeWorkflowRun(result.run),
8147
+ run: serializeWorkflowRunDetail(result.run),
8118
8148
  nodes: await Promise.all(nodes.nodes.map((node) => serializeWorkflowNodeWithExecution(storage, node)))
8119
8149
  });
8120
8150
  } catch (error) {
@@ -8137,7 +8167,8 @@ function registerWorkflowRoutes(app, sixb) {
8137
8167
  }
8138
8168
  }).get("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(sixb, context), {
8139
8169
  params: WorkflowRunParamsSchema,
8140
- query: FileContentQuerySchema,
8170
+ query: WorkflowRunFileContentQuerySchema,
8171
+ error: handleFileContentQueryValidationError,
8141
8172
  detail: {
8142
8173
  summary: "Get workflow run file content",
8143
8174
  tags: ["Workflows"],
@@ -8147,7 +8178,8 @@ function registerWorkflowRoutes(app, sixb) {
8147
8178
  }
8148
8179
  }).head("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(sixb, context, { head: true }), {
8149
8180
  params: WorkflowRunParamsSchema,
8150
- query: FileContentQuerySchema,
8181
+ query: WorkflowRunFileContentQuerySchema,
8182
+ error: handleFileContentQueryValidationError,
8151
8183
  detail: {
8152
8184
  summary: "Head workflow run file content",
8153
8185
  tags: ["Workflows"],
@@ -8157,7 +8189,8 @@ function registerWorkflowRoutes(app, sixb) {
8157
8189
  }
8158
8190
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(sixb, context), {
8159
8191
  params: WorkflowNodeFileContentParamsSchema,
8160
- query: FileContentQuerySchema,
8192
+ query: WorkflowNodeFileContentQuerySchema,
8193
+ error: handleFileContentQueryValidationError,
8161
8194
  detail: {
8162
8195
  summary: "Get workflow node run file content",
8163
8196
  tags: ["Workflows"],
@@ -8167,7 +8200,8 @@ function registerWorkflowRoutes(app, sixb) {
8167
8200
  }
8168
8201
  }).head("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(sixb, context, { head: true }), {
8169
8202
  params: WorkflowNodeFileContentParamsSchema,
8170
- query: FileContentQuerySchema,
8203
+ query: WorkflowNodeFileContentQuerySchema,
8204
+ error: handleFileContentQueryValidationError,
8171
8205
  detail: {
8172
8206
  summary: "Head workflow node run file content",
8173
8207
  tags: ["Workflows"],
@@ -11519,4 +11553,4 @@ export {
11519
11553
  SixbServer
11520
11554
  };
11521
11555
 
11522
- //# debugId=7677B25AB177848964756E2164756E21
11556
+ //# debugId=A857AF6B19B6A87C64756E2164756E21