@sixb/server 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/auth/experience.d.ts +33 -0
  2. package/dist/auth/experience.d.ts.map +1 -0
  3. package/dist/auth/public-routes.d.ts.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1891 -1337
  7. package/dist/index.js.map +17 -14
  8. package/dist/openapi/tags.d.ts +6 -2
  9. package/dist/openapi/tags.d.ts.map +1 -1
  10. package/dist/registerRoutes.d.ts.map +1 -1
  11. package/dist/routes/action-runs.d.ts +6 -6
  12. package/dist/routes/actions.d.ts +3 -3
  13. package/dist/routes/agents.d.ts +149 -77
  14. package/dist/routes/agents.d.ts.map +1 -1
  15. package/dist/routes/ai-accounting.d.ts +31 -0
  16. package/dist/routes/ai-accounting.d.ts.map +1 -0
  17. package/dist/routes/auth.d.ts +110 -53
  18. package/dist/routes/auth.d.ts.map +1 -1
  19. package/dist/routes/connector-connection-runs.d.ts +56 -56
  20. package/dist/routes/connector-connections.d.ts +14 -14
  21. package/dist/routes/datasets.d.ts +12 -12
  22. package/dist/routes/events.d.ts +1 -1
  23. package/dist/routes/files.d.ts +8 -8
  24. package/dist/routes/links.d.ts +9 -9
  25. package/dist/routes/logs.d.ts +2 -2
  26. package/dist/routes/objects.d.ts +3 -3
  27. package/dist/routes/pipelines.d.ts +10 -10
  28. package/dist/routes/projections.d.ts +62 -50
  29. package/dist/routes/projections.d.ts.map +1 -1
  30. package/dist/routes/syncs.d.ts +6 -6
  31. package/dist/routes/telemetry.d.ts +7 -7
  32. package/dist/routes/webhook-runs.d.ts +2 -2
  33. package/dist/routes/workflows.d.ts +142 -57
  34. package/dist/routes/workflows.d.ts.map +1 -1
  35. package/dist/routes/ws/logs.d.ts +10 -10
  36. package/dist/schemas/actions.d.ts +16 -16
  37. package/dist/schemas/agents.d.ts +459 -142
  38. package/dist/schemas/agents.d.ts.map +1 -1
  39. package/dist/schemas/ai-accounting.d.ts +2393 -0
  40. package/dist/schemas/ai-accounting.d.ts.map +1 -0
  41. package/dist/schemas/auth.d.ts +96 -96
  42. package/dist/schemas/connectors.d.ts +24 -24
  43. package/dist/schemas/event-payloads.d.ts +6 -6
  44. package/dist/schemas/events.d.ts +6 -6
  45. package/dist/schemas/links.d.ts +2 -2
  46. package/dist/schemas/logs.d.ts +18 -18
  47. package/dist/schemas/pipelines.d.ts +20 -20
  48. package/dist/schemas/projections.d.ts +400 -288
  49. package/dist/schemas/projections.d.ts.map +1 -1
  50. package/dist/schemas/status.d.ts +2 -2
  51. package/dist/schemas/syncs.d.ts +10 -10
  52. package/dist/schemas/webhook-runs.d.ts +12 -12
  53. package/dist/schemas/workflows.d.ts +833 -162
  54. package/dist/schemas/workflows.d.ts.map +1 -1
  55. package/dist/server.d.ts +5 -0
  56. package/dist/server.d.ts.map +1 -1
  57. package/package.json +5 -5
  58. package/src/auth/experience.ts +190 -0
  59. package/src/auth/public-routes.ts +7 -0
  60. package/src/index.ts +1 -0
  61. package/src/openapi/tags.ts +4 -0
  62. package/src/registerRoutes.ts +2 -0
  63. package/src/routes/agents.ts +1 -0
  64. package/src/routes/ai-accounting.ts +166 -0
  65. package/src/routes/auth.ts +188 -32
  66. package/src/routes/projections.ts +18 -4
  67. package/src/routes/workflows.ts +16 -0
  68. package/src/schemas/agents.ts +4 -9
  69. package/src/schemas/ai-accounting.ts +182 -0
  70. package/src/schemas/projections.ts +6 -0
  71. package/src/schemas/workflows.ts +8 -3
  72. package/src/server.ts +10 -0
@@ -39,6 +39,11 @@ import {
39
39
  type ResolveRequestAuthContext,
40
40
  } from "../auth/browser-origin"
41
41
  import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "../auth/csrf"
42
+ import {
43
+ customAuthExperienceAssetResponse,
44
+ customAuthExperienceResponse,
45
+ type SixbAuthExperienceOptions,
46
+ } from "../auth/experience"
42
47
  import { hasForegroundSessionActivity } from "../auth/session-activity"
43
48
  import { createSessionRenewalCookieHeaders } from "../auth/session-cookies"
44
49
  import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
@@ -115,10 +120,21 @@ export interface AuthRoutesOptions {
115
120
  request: Request,
116
121
  input: AuthInvitationRedirectInput
117
122
  ) => AuthInvitationRedirectContext
123
+ readonly authExperience?: SixbAuthExperienceOptions
118
124
  }
119
125
 
120
126
  export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: AuthRoutesOptions) {
121
127
  return app
128
+ .get(
129
+ "/auth/assets/*",
130
+ async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
131
+ { detail: { hide: true } }
132
+ )
133
+ .head(
134
+ "/auth/assets/*",
135
+ async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
136
+ { detail: { hide: true } }
137
+ )
122
138
  .get(
123
139
  "/api/auth/session",
124
140
  async ({ request }) => {
@@ -1241,11 +1257,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1241
1257
  requesterHash: pending.hash,
1242
1258
  })
1243
1259
 
1244
- const response = htmlMessageResponse(
1245
- "If this email can sign in, we sent a link. Check your inbox to continue.",
1246
- 200,
1247
- "Check your email"
1248
- )
1260
+ const response = await magicLinkRequestedResponse(options, authRedirect)
1249
1261
  // Same-device fast path: this browser keeps the preimage of the
1250
1262
  // `requester` hash embedded in the emailed callback URL, so opening
1251
1263
  // the link here signs in without the confirmation click. Always
@@ -1304,7 +1316,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1304
1316
  }
1305
1317
 
1306
1318
  if (isMagicLinkAuthStrategy(strategy)) {
1307
- return signInFormResponse(authRedirect)
1319
+ return await signInFormResponse(options, authRedirect)
1308
1320
  }
1309
1321
 
1310
1322
  if (isOidcAuthStrategy(strategy)) {
@@ -1331,9 +1343,14 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1331
1343
  const url = new URL(request.url)
1332
1344
  const magicLinkId = url.searchParams.get("magicLinkId")?.trim()
1333
1345
  const token = url.searchParams.get("token")?.trim()
1346
+ const authRedirectHint = resolveAuthExperienceRedirectHint(
1347
+ options,
1348
+ request,
1349
+ url.searchParams.get("audience")
1350
+ )
1334
1351
 
1335
1352
  if (!magicLinkId || !token) {
1336
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1353
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1337
1354
  }
1338
1355
 
1339
1356
  // Read-only peek so the page can greet the user by email and dead
@@ -1353,11 +1370,12 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1353
1370
  token,
1354
1371
  })
1355
1372
  if (!peeked) {
1356
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1373
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1357
1374
  }
1358
1375
  email = peeked.email
1359
- } catch {
1360
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1376
+ } catch (error) {
1377
+ logAuthCallbackError("Magic-link", error)
1378
+ return await authExperienceErrorResponse(options, authRedirectHint)
1361
1379
  }
1362
1380
  }
1363
1381
 
@@ -1380,10 +1398,16 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1380
1398
  magicLinkId,
1381
1399
  token,
1382
1400
  clearPendingCookie: true,
1401
+ authRedirectHint,
1383
1402
  })
1384
1403
  }
1385
1404
 
1386
- return magicLinkConfirmResponse({ magicLinkId, token, email })
1405
+ return await magicLinkConfirmResponse(options, {
1406
+ magicLinkId,
1407
+ token,
1408
+ email,
1409
+ authRedirect: authRedirectHint,
1410
+ })
1387
1411
  }
1388
1412
 
1389
1413
  if (isOidcAuthStrategy(strategy)) {
@@ -1438,16 +1462,26 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1438
1462
 
1439
1463
  const magicLinkId = body.magicLinkId?.trim()
1440
1464
  const token = body.token?.trim()
1465
+ const authRedirectHint = resolveAuthExperienceRedirectHint(options, request, body.audience)
1441
1466
  if (!magicLinkId || !token) {
1442
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1467
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1443
1468
  }
1444
1469
 
1445
- return completeMagicLinkCallback({ host, strategy, options, request, magicLinkId, token })
1470
+ return completeMagicLinkCallback({
1471
+ host,
1472
+ strategy,
1473
+ options,
1474
+ request,
1475
+ magicLinkId,
1476
+ token,
1477
+ authRedirectHint,
1478
+ })
1446
1479
  },
1447
1480
  {
1448
1481
  body: t.Object({
1449
1482
  magicLinkId: t.Optional(t.String()),
1450
1483
  token: t.Optional(t.String()),
1484
+ audience: t.Optional(t.String()),
1451
1485
  }),
1452
1486
  parse: "urlencoded",
1453
1487
  detail: { hide: true },
@@ -1520,6 +1554,7 @@ async function completeMagicLinkCallback(input: {
1520
1554
  readonly magicLinkId: string
1521
1555
  readonly token: string
1522
1556
  readonly clearPendingCookie?: boolean
1557
+ readonly authRedirectHint?: AuthRedirectContext
1523
1558
  }): Promise<Response> {
1524
1559
  const authOptions = resolveAuthOptions(input.options, input.request)
1525
1560
  const now = new Date()
@@ -1564,7 +1599,7 @@ async function completeMagicLinkCallback(input: {
1564
1599
  }
1565
1600
  return response
1566
1601
  } catch {
1567
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1602
+ return await invalidMagicLinkResponse(input.options, input.authRedirectHint)
1568
1603
  }
1569
1604
  }
1570
1605
 
@@ -1925,21 +1960,110 @@ function authPageResponse(body: string, status = 200): Response {
1925
1960
  })
1926
1961
  }
1927
1962
 
1928
- function signInFormResponse(context: AuthRedirectContext): Response {
1929
- return authPageResponse(
1930
- [
1931
- "<h1>Sign in</h1>",
1932
- "<p>We'll email you a sign-in link.</p>",
1933
- '<form method="post" action="/auth/sign-in">',
1934
- `<input type="hidden" name="audience" value="${escapeHtml(context.audience)}">`,
1935
- `<input type="hidden" name="returnTo" value="${escapeHtml(context.returnTo)}">`,
1936
- '<input name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-label="Email address" required autofocus>',
1937
- '<button type="submit">Send sign-in link</button>',
1938
- "</form>",
1939
- ].join("")
1963
+ async function signInFormResponse(
1964
+ options: AuthRoutesOptions,
1965
+ context: AuthRedirectContext
1966
+ ): Promise<Response> {
1967
+ return (
1968
+ (await customAuthExperienceResponse(options.authExperience, {
1969
+ audience: context.audience,
1970
+ state: { kind: "signIn" },
1971
+ signInUrl: authExperienceSignInUrl(context),
1972
+ submission: {
1973
+ kind: "requestMagicLink",
1974
+ action: "/auth/sign-in",
1975
+ fields: { audience: context.audience, returnTo: context.returnTo },
1976
+ },
1977
+ // Native POST forms inherit the document's referrer policy when
1978
+ // constructing their Origin header. `no-referrer` produces
1979
+ // `Origin: null`, which the API origin guard correctly rejects.
1980
+ referrerPolicy: "same-origin",
1981
+ })) ??
1982
+ authPageResponse(
1983
+ [
1984
+ "<h1>Sign in</h1>",
1985
+ "<p>We'll email you a sign-in link.</p>",
1986
+ '<form method="post" action="/auth/sign-in">',
1987
+ `<input type="hidden" name="audience" value="${escapeHtml(context.audience)}">`,
1988
+ `<input type="hidden" name="returnTo" value="${escapeHtml(context.returnTo)}">`,
1989
+ '<input name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-label="Email address" required autofocus>',
1990
+ '<button type="submit">Send sign-in link</button>',
1991
+ "</form>",
1992
+ ].join("")
1993
+ )
1940
1994
  )
1941
1995
  }
1942
1996
 
1997
+ async function magicLinkRequestedResponse(
1998
+ options: AuthRoutesOptions,
1999
+ context: AuthRedirectContext
2000
+ ): Promise<Response> {
2001
+ return (
2002
+ (await customAuthExperienceResponse(options.authExperience, {
2003
+ audience: context.audience,
2004
+ state: { kind: "checkEmail" },
2005
+ signInUrl: authExperienceSignInUrl(context),
2006
+ })) ??
2007
+ htmlMessageResponse(
2008
+ "If this email can sign in, we sent a link. Check your inbox to continue.",
2009
+ 200,
2010
+ "Check your email"
2011
+ )
2012
+ )
2013
+ }
2014
+
2015
+ async function invalidMagicLinkResponse(
2016
+ options: AuthRoutesOptions,
2017
+ context: AuthRedirectContext | undefined
2018
+ ): Promise<Response> {
2019
+ if (context) {
2020
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2021
+ audience: context.audience,
2022
+ state: { kind: "invalidLink" },
2023
+ signInUrl: authExperienceSignInUrl(context),
2024
+ status: 400,
2025
+ })
2026
+ if (custom) return custom
2027
+ }
2028
+
2029
+ return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
2030
+ }
2031
+
2032
+ async function authExperienceErrorResponse(
2033
+ options: AuthRoutesOptions,
2034
+ context: AuthRedirectContext | undefined
2035
+ ): Promise<Response> {
2036
+ if (context) {
2037
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2038
+ audience: context.audience,
2039
+ state: { kind: "error" },
2040
+ signInUrl: authExperienceSignInUrl(context),
2041
+ status: 500,
2042
+ })
2043
+ if (custom) return custom
2044
+ }
2045
+
2046
+ return await invalidMagicLinkResponse(options, undefined)
2047
+ }
2048
+
2049
+ function authExperienceSignInUrl(context: AuthRedirectContext): string {
2050
+ const params = new URLSearchParams({ audience: context.audience, returnTo: context.returnTo })
2051
+ return `/auth/sign-in?${params.toString()}`
2052
+ }
2053
+
2054
+ function resolveAuthExperienceRedirectHint(
2055
+ options: AuthRoutesOptions,
2056
+ request: Request,
2057
+ audience: string | null | undefined
2058
+ ): AuthRedirectContext | undefined {
2059
+ if (audience !== "app" && audience !== "atlas") {
2060
+ return undefined
2061
+ }
2062
+
2063
+ const context = resolveInvitationDeliveryContext(options, request, { destinationId: audience })
2064
+ return context instanceof Response ? undefined : context
2065
+ }
2066
+
1943
2067
  // Deliberately a plain form with no auto-submit: link scanners that execute
1944
2068
  // pages headlessly still won't press the button, so the token survives until a
1945
2069
  // person clicks Continue. The extra click also keeps the link reusable when a
@@ -1948,12 +2072,39 @@ function signInFormResponse(context: AuthRedirectContext): Response {
1948
2072
  // a disabled spinner. The form POST is a normal navigation, so this page stays
1949
2073
  // visible (spinner and all) until the server responds; the pageshow handler
1950
2074
  // resets the button when the page is restored from the back/forward cache.
1951
- function magicLinkConfirmResponse(input: {
1952
- readonly magicLinkId: string
1953
- readonly token: string
1954
- // Absent when the strategy doesn't support the read-only peek.
1955
- readonly email?: string
1956
- }): Response {
2075
+ async function magicLinkConfirmResponse(
2076
+ options: AuthRoutesOptions,
2077
+ input: {
2078
+ readonly magicLinkId: string
2079
+ readonly token: string
2080
+ // Absent when the strategy doesn't support the read-only peek.
2081
+ readonly email?: string
2082
+ readonly authRedirect?: AuthRedirectContext
2083
+ }
2084
+ ): Promise<Response> {
2085
+ if (input.authRedirect) {
2086
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2087
+ audience: input.authRedirect.audience,
2088
+ state: { kind: "confirm", ...(input.email ? { email: input.email } : {}) },
2089
+ signInUrl: authExperienceSignInUrl(input.authRedirect),
2090
+ submission: {
2091
+ kind: "confirmSignIn",
2092
+ action: "/auth/callback",
2093
+ fields: {
2094
+ magicLinkId: input.magicLinkId,
2095
+ token: input.token,
2096
+ audience: input.authRedirect.audience,
2097
+ },
2098
+ },
2099
+ referrerPolicy: "same-origin",
2100
+ // The callback POST is same-origin, but its successful 303 continues to
2101
+ // the validated custom-app origin. CSP applies form-action across that
2102
+ // redirect chain, so permit that exact origin for this state only.
2103
+ formActionOrigins: [new URL(input.authRedirect.returnTo).origin],
2104
+ })
2105
+ if (custom) return custom
2106
+ }
2107
+
1957
2108
  const response = authPageResponse(
1958
2109
  [
1959
2110
  "<h1>Sign in</h1>",
@@ -1963,6 +2114,11 @@ function magicLinkConfirmResponse(input: {
1963
2114
  '<form method="post" action="/auth/callback" id="confirm">',
1964
2115
  `<input type="hidden" name="magicLinkId" value="${escapeHtml(input.magicLinkId)}">`,
1965
2116
  `<input type="hidden" name="token" value="${escapeHtml(input.token)}">`,
2117
+ ...(input.authRedirect
2118
+ ? [
2119
+ `<input type="hidden" name="audience" value="${escapeHtml(input.authRedirect.audience)}">`,
2120
+ ]
2121
+ : []),
1966
2122
  '<button type="submit" id="confirm-button">Continue</button>',
1967
2123
  "</form>",
1968
2124
  "<script>",
@@ -3,6 +3,7 @@ import type {
3
3
  ObjectProjectionDefinition,
4
4
  ProjectionDefinition,
5
5
  SixbHostView,
6
+ SourceEditConflictResolution,
6
7
  TelemetryProjectionDefinition,
7
8
  } from "@sixb/core"
8
9
  import type { ProjectionRunRecord } from "@sixb/core/storage"
@@ -81,14 +82,27 @@ function projectionCatalogIds(catalog: ViewableProjectionCatalog): string[] {
81
82
  ].map((projection) => projection.id)
82
83
  }
83
84
 
85
+ type SerializedProjection<TProjection extends ProjectionDefinition> =
86
+ TProjection extends ObjectProjectionDefinition
87
+ ? Omit<TProjection, "conflictResolution"> & {
88
+ conflictResolution: SourceEditConflictResolution
89
+ latestRun: SerializedProjectionRun | null
90
+ }
91
+ : TProjection & { latestRun: SerializedProjectionRun | null }
92
+
84
93
  function serializeProjection<TProjection extends ProjectionDefinition>(
85
94
  projection: TProjection,
86
95
  latestRuns: ReadonlyMap<string, SerializedProjectionRun>
87
- ): TProjection & { latestRun: SerializedProjectionRun | null } {
88
- return {
89
- ...projection,
90
- latestRun: latestRuns.get(projection.id) ?? null,
96
+ ): SerializedProjection<TProjection> {
97
+ const latestRun = latestRuns.get(projection.id) ?? null
98
+ if (projection._tag === "ObjectProjectionDefinition") {
99
+ return {
100
+ ...projection,
101
+ conflictResolution: projection.conflictResolution ?? { strategy: "editsWin" },
102
+ latestRun,
103
+ } as SerializedProjection<TProjection>
91
104
  }
105
+ return { ...projection, latestRun } as SerializedProjection<TProjection>
92
106
  }
93
107
 
94
108
  function serializeProjectionCatalog(
@@ -145,6 +145,7 @@ function serializeWorkflowAgentExecutionSummary(execution: WorkflowAgentNodeRunV
145
145
  modelId: execution.modelId,
146
146
  finishReason: execution.finishReason,
147
147
  usage: execution.usage,
148
+ cost: execution.cost,
148
149
  startedAt: execution.startedAt ? toIsoString(execution.startedAt) : undefined,
149
150
  completedAt: execution.completedAt ? toIsoString(execution.completedAt) : undefined,
150
151
  }
@@ -157,11 +158,26 @@ function serializeWorkflowAgentExecution(execution: WorkflowAgentNodeRunView) {
157
158
  prompt: execution.prompt,
158
159
  trace: execution.trace,
159
160
  diagnostics: execution.diagnostics,
161
+ failurePhase: workflowAgentFailurePhase(execution),
160
162
  error: execution.error,
161
163
  createdAt: toIsoString(execution.createdAt),
162
164
  }
163
165
  }
164
166
 
167
+ function workflowAgentFailurePhase(
168
+ execution: WorkflowAgentNodeRunView
169
+ ): "agent-loop" | "structured-finalizer" | undefined {
170
+ const details = execution.error?.details
171
+ if (!isRecord(details)) return undefined
172
+
173
+ const phase = details.failurePhase
174
+ return phase === "agent-loop" || phase === "structured-finalizer" ? phase : undefined
175
+ }
176
+
177
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
178
+ return value !== null && typeof value === "object" && !Array.isArray(value)
179
+ }
180
+
165
181
  function principalForExecution(sixb: Sixb<readonly OntologySource[]>): Principal {
166
182
  return sixb.execution.requestedBy ?? SYSTEM_PRINCIPAL
167
183
  }
@@ -2,10 +2,12 @@ import { AGENT_REASONING_LEVELS, MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core"
2
2
  import {
3
3
  AGENT_RUN_DIAGNOSTIC_CODES,
4
4
  AGENT_RUN_FAILURE_CODES,
5
+ AGENT_RUN_FINISH_REASONS,
5
6
  type AgentRunFailureCode,
6
7
  type SixbFailure,
7
8
  } from "@sixb/core/storage"
8
9
  import { z } from "zod"
10
+ import { AiCostSummarySchema } from "./ai-accounting"
9
11
  import { AiUsageSummarySchema } from "./ai-usage"
10
12
  import { JsonValueSchema, sixbFailureSchema } from "./common"
11
13
  import { FileRefSchema } from "./files"
@@ -242,15 +244,7 @@ export const AgentRunStatusSchema = z.enum([
242
244
  "cancelled",
243
245
  ])
244
246
 
245
- export const AgentRunFinishReasonSchema = z.enum([
246
- "stop",
247
- "length",
248
- "content-filter",
249
- "tool-calls",
250
- "error",
251
- "other",
252
- "unknown",
253
- ])
247
+ export const AgentRunFinishReasonSchema = z.enum(AGENT_RUN_FINISH_REASONS)
254
248
 
255
249
  export const AgentRunSchema = z.object({
256
250
  id: z.string(),
@@ -263,6 +257,7 @@ export const AgentRunSchema = z.object({
263
257
  modelId: z.string().optional(),
264
258
  finishReason: AgentRunFinishReasonSchema.optional(),
265
259
  usage: AiUsageSummarySchema.optional(),
260
+ cost: AiCostSummarySchema.optional(),
266
261
  diagnostics: z.array(AgentRunDiagnosticSchema).optional(),
267
262
  error: AgentRunFailureSchema.optional(),
268
263
  attempt: z.number(),
@@ -0,0 +1,182 @@
1
+ import { z } from "zod"
2
+ import { AiUsageSummarySchema } from "./ai-usage"
3
+
4
+ const IntegerStringSchema = z.string().regex(/^\d+$/)
5
+ const IsoDateSchema = z.string().datetime({ offset: true })
6
+
7
+ export const AiAccountingBucketSchema = z.enum(["hour", "day", "week"])
8
+ export const AiValuationStatusSchema = z.enum(["rated", "unpriceable", "unvalued"])
9
+
10
+ export const AiAccountingRangeQuerySchema = z.object({
11
+ from: IsoDateSchema,
12
+ to: IsoDateSchema,
13
+ providerId: z.string().trim().min(1).optional(),
14
+ modelId: z.string().trim().min(1).optional(),
15
+ })
16
+
17
+ export const AiAccountingOverviewQuerySchema = AiAccountingRangeQuerySchema.extend({
18
+ bucket: AiAccountingBucketSchema,
19
+ })
20
+
21
+ export const AiModelCallAccountingListQuerySchema = AiAccountingRangeQuerySchema.extend({
22
+ executionId: z.string().trim().min(1).optional(),
23
+ valuationStatus: AiValuationStatusSchema.optional(),
24
+ limit: IntegerStringSchema.optional(),
25
+ offset: IntegerStringSchema.optional(),
26
+ })
27
+
28
+ export const AiMoneySchema = z.object({
29
+ currency: z.string().regex(/^[A-Z]{3}$/),
30
+ amountNanos: IntegerStringSchema,
31
+ })
32
+
33
+ export const AiCostSummarySchema = z.object({
34
+ amounts: z.array(AiMoneySchema),
35
+ ratedCallCount: z.number().int().nonnegative(),
36
+ unpriceableCallCount: z.number().int().nonnegative(),
37
+ unvaluedCallCount: z.number().int().nonnegative(),
38
+ })
39
+
40
+ const AiAccountingAggregateSchema = z.object({
41
+ modelCallCount: z.number().int().nonnegative(),
42
+ usage: AiUsageSummarySchema,
43
+ costs: AiCostSummarySchema,
44
+ })
45
+
46
+ export const AiAccountingOverviewResponseSchema = z.object({
47
+ range: z.object({ from: IsoDateSchema, to: IsoDateSchema }),
48
+ bucket: AiAccountingBucketSchema,
49
+ totals: AiAccountingAggregateSchema,
50
+ series: z.array(
51
+ AiAccountingAggregateSchema.extend({
52
+ start: IsoDateSchema,
53
+ end: IsoDateSchema,
54
+ })
55
+ ),
56
+ models: z.array(
57
+ AiAccountingAggregateSchema.extend({
58
+ providerId: z.string(),
59
+ modelId: z.string(),
60
+ })
61
+ ),
62
+ agents: z.array(
63
+ AiAccountingAggregateSchema.extend({
64
+ agentId: z.string(),
65
+ })
66
+ ),
67
+ workflows: z.array(
68
+ AiAccountingAggregateSchema.extend({
69
+ workflowId: z.string(),
70
+ })
71
+ ),
72
+ })
73
+
74
+ export const AiPricingContextSchema = z.object({
75
+ serviceTier: z.string().optional(),
76
+ batch: z.boolean().optional(),
77
+ region: z.string().optional(),
78
+ inferenceGeo: z.string().optional(),
79
+ routedProviderId: z.string().optional(),
80
+ deploymentId: z.string().optional(),
81
+ inferenceProfileId: z.string().optional(),
82
+ cacheWriteTtlSeconds: z.number().int().positive().optional(),
83
+ mode: z.string().optional(),
84
+ })
85
+
86
+ const AiCostComponentSchema = z.object({
87
+ meter: z.enum([
88
+ "tokens.input.total",
89
+ "tokens.input.uncached",
90
+ "tokens.input.cacheRead",
91
+ "tokens.input.cacheWrite",
92
+ "tokens.output.total",
93
+ "tokens.output.text",
94
+ "tokens.output.reasoning",
95
+ ]),
96
+ quantity: IntegerStringSchema,
97
+ rateAmountNanosPerMillion: IntegerStringSchema,
98
+ chargeAmountNanos: IntegerStringSchema,
99
+ })
100
+
101
+ const AiBillingIdentitySchema = z.object({
102
+ providerId: z.string(),
103
+ modelId: z.string(),
104
+ })
105
+
106
+ const AiPriceSourceSchema = z.object({
107
+ sourceId: z.string(),
108
+ sourceEntryId: z.string(),
109
+ sourceVersion: z.string(),
110
+ sourceUrl: z.string().url(),
111
+ observedAt: IsoDateSchema,
112
+ })
113
+
114
+ const AiModelCallCostSchema = z.discriminatedUnion("status", [
115
+ z.object({
116
+ status: z.literal("rated"),
117
+ billingIdentity: AiBillingIdentitySchema,
118
+ pricingContext: AiPricingContextSchema,
119
+ priceSource: AiPriceSourceSchema,
120
+ money: AiMoneySchema,
121
+ components: z.array(AiCostComponentSchema),
122
+ ratedAt: IsoDateSchema,
123
+ }),
124
+ z.object({
125
+ status: z.literal("unpriceable"),
126
+ billingIdentity: AiBillingIdentitySchema.optional(),
127
+ pricingContext: AiPricingContextSchema,
128
+ priceSource: AiPriceSourceSchema,
129
+ reason: z.enum([
130
+ "missingBillingIdentity",
131
+ "missingCatalogEntry",
132
+ "missingUsageMeter",
133
+ "unsupportedPricingDimension",
134
+ "invalidUsageForFormula",
135
+ ]),
136
+ missingMeters: z.array(AiCostComponentSchema.shape.meter).optional(),
137
+ ratedAt: IsoDateSchema,
138
+ }),
139
+ ])
140
+
141
+ const AiModelCallUsageRecordSchema = z.object({
142
+ id: z.string(),
143
+ executionId: z.string(),
144
+ attempt: z.number().int().positive(),
145
+ callId: z.string(),
146
+ providerId: z.string(),
147
+ requestedModelId: z.string(),
148
+ responseModelId: z.string().optional(),
149
+ responseId: z.string(),
150
+ usage: AiUsageSummarySchema,
151
+ occurredAt: IsoDateSchema,
152
+ recordedAt: IsoDateSchema,
153
+ })
154
+
155
+ export const AiModelCallAccountingItemSchema = z.object({
156
+ usage: AiModelCallUsageRecordSchema,
157
+ attribution: z
158
+ .discriminatedUnion("kind", [
159
+ z.object({
160
+ kind: z.literal("agent"),
161
+ agentId: z.string(),
162
+ agentRunId: z.string(),
163
+ threadId: z.string(),
164
+ }),
165
+ z.object({
166
+ kind: z.literal("workflowAgent"),
167
+ agentId: z.string(),
168
+ nodeRunId: z.string(),
169
+ workflowId: z.string(),
170
+ workflowRunId: z.string(),
171
+ }),
172
+ ])
173
+ .optional(),
174
+ cost: AiModelCallCostSchema.optional(),
175
+ valuationStatus: AiValuationStatusSchema,
176
+ })
177
+
178
+ export const AiModelCallAccountingListResponseSchema = z.object({
179
+ items: z.array(AiModelCallAccountingItemSchema),
180
+ hasMore: z.boolean(),
181
+ total: z.number().int().nonnegative(),
182
+ })
@@ -83,6 +83,11 @@ export const ForeignKeyDescriptorSchema = z.object({
83
83
  targetObjectTypeId: z.string(),
84
84
  })
85
85
 
86
+ export const SourceEditConflictResolutionSchema = z.union([
87
+ z.object({ strategy: z.literal("editsWin") }),
88
+ z.object({ strategy: z.literal("mostRecent"), sourceTimestamp: z.string() }),
89
+ ])
90
+
86
91
  export const ObjectProjectionSchema = z.object({
87
92
  _tag: z.literal("ObjectProjectionDefinition"),
88
93
  id: z.string(),
@@ -90,6 +95,7 @@ export const ObjectProjectionSchema = z.object({
90
95
  datasetId: z.string(),
91
96
  properties: z.record(z.string()),
92
97
  links: z.record(ForeignKeyDescriptorSchema),
98
+ conflictResolution: SourceEditConflictResolutionSchema,
93
99
  latestRun: ProjectionRunSchema.nullable(),
94
100
  })
95
101
 
@@ -4,7 +4,8 @@ import {
4
4
  type WorkflowRunFailureCode,
5
5
  } from "@sixb/core/storage"
6
6
  import { z } from "zod"
7
- import { AgentRunFailureSchema } from "./agents"
7
+ import { AgentMessagePartSchema, AgentRunFailureSchema } from "./agents"
8
+ import { AiCostSummarySchema } from "./ai-accounting"
8
9
  import { AiUsageSummarySchema } from "./ai-usage"
9
10
  import { JsonValueSchema, sixbFailureSchema } from "./common"
10
11
 
@@ -148,15 +149,19 @@ export const WorkflowAgentNodeExecutionSummarySchema = z.object({
148
149
  modelId: z.string().optional(),
149
150
  finishReason: z.string().optional(),
150
151
  usage: AiUsageSummarySchema.optional(),
152
+ cost: AiCostSummarySchema.optional(),
151
153
  startedAt: z.string().optional(),
152
154
  completedAt: z.string().optional(),
153
155
  })
154
156
 
157
+ export const WorkflowAgentFailurePhaseSchema = z.enum(["agent-loop", "structured-finalizer"])
158
+
155
159
  export const WorkflowAgentNodeExecutionSchema = WorkflowAgentNodeExecutionSummarySchema.extend({
156
160
  nodeRunId: z.string(),
157
161
  prompt: z.string(),
158
- trace: z.array(z.unknown()).optional(),
159
- diagnostics: z.array(z.unknown()).optional(),
162
+ trace: z.array(AgentMessagePartSchema).optional(),
163
+ diagnostics: z.array(JsonValueSchema).optional(),
164
+ failurePhase: WorkflowAgentFailurePhaseSchema.optional(),
160
165
  error: AgentRunFailureSchema.optional(),
161
166
  createdAt: z.string(),
162
167
  })