@sixb/server 0.2.5 → 0.2.7

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 (106) hide show
  1. package/dist/auth/run-token.d.ts.map +1 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +596 -92
  5. package/dist/index.js.map +36 -35
  6. package/dist/registerRoutes.d.ts +1 -0
  7. package/dist/registerRoutes.d.ts.map +1 -1
  8. package/dist/routes/actions.d.ts +2 -0
  9. package/dist/routes/actions.d.ts.map +1 -1
  10. package/dist/routes/agent-approvals.d.ts +23 -1
  11. package/dist/routes/agent-approvals.d.ts.map +1 -1
  12. package/dist/routes/agent-computers.d.ts +36 -0
  13. package/dist/routes/agent-computers.d.ts.map +1 -1
  14. package/dist/routes/agent-thread-reads.d.ts +82 -0
  15. package/dist/routes/agent-thread-reads.d.ts.map +1 -0
  16. package/dist/routes/agents.d.ts +795 -13
  17. package/dist/routes/agents.d.ts.map +1 -1
  18. package/dist/routes/ai-accounting.d.ts.map +1 -1
  19. package/dist/routes/connectors.d.ts +2 -0
  20. package/dist/routes/connectors.d.ts.map +1 -1
  21. package/dist/routes/datasets.d.ts +2 -0
  22. package/dist/routes/datasets.d.ts.map +1 -1
  23. package/dist/routes/model-generations.d.ts +6 -0
  24. package/dist/routes/model-generations.d.ts.map +1 -1
  25. package/dist/routes/observed-agent-threads.d.ts +24 -2
  26. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  27. package/dist/routes/ontology.d.ts +2 -0
  28. package/dist/routes/ontology.d.ts.map +1 -1
  29. package/dist/routes/pipelines.d.ts +2 -0
  30. package/dist/routes/pipelines.d.ts.map +1 -1
  31. package/dist/routes/projections.d.ts +6 -0
  32. package/dist/routes/projections.d.ts.map +1 -1
  33. package/dist/routes/rules.d.ts +2 -0
  34. package/dist/routes/rules.d.ts.map +1 -1
  35. package/dist/routes/status.d.ts +5 -2
  36. package/dist/routes/status.d.ts.map +1 -1
  37. package/dist/routes/syncs.d.ts +177 -12
  38. package/dist/routes/syncs.d.ts.map +1 -1
  39. package/dist/routes/workflows.d.ts +8 -6
  40. package/dist/routes/workflows.d.ts.map +1 -1
  41. package/dist/routes/ws/agents.d.ts.map +1 -1
  42. package/dist/schemas/actions.d.ts +6 -0
  43. package/dist/schemas/actions.d.ts.map +1 -1
  44. package/dist/schemas/activity.d.ts +4 -4
  45. package/dist/schemas/agents.d.ts +2657 -61
  46. package/dist/schemas/agents.d.ts.map +1 -1
  47. package/dist/schemas/ai-accounting.d.ts +3 -0
  48. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  49. package/dist/schemas/common.d.ts +5 -0
  50. package/dist/schemas/common.d.ts.map +1 -1
  51. package/dist/schemas/connectors.d.ts +3 -0
  52. package/dist/schemas/connectors.d.ts.map +1 -1
  53. package/dist/schemas/datasets.d.ts +3 -0
  54. package/dist/schemas/datasets.d.ts.map +1 -1
  55. package/dist/schemas/models.d.ts +46 -0
  56. package/dist/schemas/models.d.ts.map +1 -1
  57. package/dist/schemas/ontology.d.ts +3 -0
  58. package/dist/schemas/ontology.d.ts.map +1 -1
  59. package/dist/schemas/pipelines.d.ts +3 -0
  60. package/dist/schemas/pipelines.d.ts.map +1 -1
  61. package/dist/schemas/projections.d.ts +33 -0
  62. package/dist/schemas/projections.d.ts.map +1 -1
  63. package/dist/schemas/rules.d.ts +3 -0
  64. package/dist/schemas/rules.d.ts.map +1 -1
  65. package/dist/schemas/status.d.ts +2 -2
  66. package/dist/schemas/syncs.d.ts +727 -25
  67. package/dist/schemas/syncs.d.ts.map +1 -1
  68. package/dist/schemas/workflows.d.ts +25 -22
  69. package/dist/schemas/workflows.d.ts.map +1 -1
  70. package/dist/server.d.ts +16 -1
  71. package/dist/server.d.ts.map +1 -1
  72. package/package.json +5 -5
  73. package/src/auth/run-token.ts +59 -9
  74. package/src/index.ts +6 -1
  75. package/src/registerRoutes.ts +4 -1
  76. package/src/routes/actions.ts +7 -3
  77. package/src/routes/agent-computers.ts +7 -6
  78. package/src/routes/agent-thread-reads.ts +67 -0
  79. package/src/routes/agents.ts +129 -16
  80. package/src/routes/ai-accounting.ts +1 -0
  81. package/src/routes/connectors.ts +1 -0
  82. package/src/routes/datasets.ts +11 -3
  83. package/src/routes/model-generations.ts +1 -1
  84. package/src/routes/observed-agent-threads.ts +3 -4
  85. package/src/routes/ontology.ts +17 -3
  86. package/src/routes/pipelines.ts +13 -3
  87. package/src/routes/projections.ts +14 -9
  88. package/src/routes/rules.ts +9 -3
  89. package/src/routes/status.ts +18 -1
  90. package/src/routes/syncs.ts +139 -8
  91. package/src/routes/workflows.ts +13 -3
  92. package/src/routes/ws/agents.ts +43 -3
  93. package/src/schemas/actions.ts +7 -1
  94. package/src/schemas/agents.ts +80 -10
  95. package/src/schemas/ai-accounting.ts +12 -0
  96. package/src/schemas/common.ts +24 -9
  97. package/src/schemas/connectors.ts +2 -1
  98. package/src/schemas/datasets.ts +2 -1
  99. package/src/schemas/models.ts +10 -0
  100. package/src/schemas/ontology.ts +2 -0
  101. package/src/schemas/pipelines.ts +2 -1
  102. package/src/schemas/projections.ts +4 -1
  103. package/src/schemas/rules.ts +2 -0
  104. package/src/schemas/syncs.ts +65 -2
  105. package/src/schemas/workflows.ts +7 -1
  106. package/src/server.ts +205 -13
@@ -1,4 +1,5 @@
1
- import type { SixbHostView, SyncDefinition } from "@sixb/core"
1
+ import type { SixbHostView, SyncAccount, SyncDefinition } from "@sixb/core"
2
+ import { isOAuthConnectorDefinition } from "@sixb/core/internal/connector-connections"
2
3
  import type { SyncRunRecord } from "@sixb/core/storage"
3
4
  import type { Elysia } from "elysia"
4
5
  import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
@@ -7,6 +8,10 @@ import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
7
8
  import { OPENAPI_TAGS } from "../openapi/tags"
8
9
  import { ErrorResponseSchema } from "../schemas/common"
9
10
  import {
11
+ ConnectionSyncRunsParamsSchema,
12
+ ConnectionSyncRunsResponseSchema,
13
+ ConnectorAccountListResponseSchema,
14
+ ConnectorAccountsParamsSchema,
10
15
  RequestSyncRunBodySchema,
11
16
  RequestSyncRunResponseSchema,
12
17
  SyncParamsSchema,
@@ -27,6 +32,7 @@ function serializeSyncRun(run: SyncRunRecord) {
27
32
  id: run.id,
28
33
  projectId: run.projectId,
29
34
  syncId: run.syncId,
35
+ connectionId: run.connectionId,
30
36
  datasetId: run.datasetId,
31
37
  mode: run.mode,
32
38
  status: run.status,
@@ -67,12 +73,76 @@ async function getLatestSyncRuns(
67
73
  return new Map(result.runs.map((run) => [run.syncId, serializeSyncRun(run)]))
68
74
  }
69
75
 
76
+ function serializeAccount(account: SyncAccount) {
77
+ const { id, owner, slot, account: candidate } = account.connection
78
+ return {
79
+ connection: { id, owner, slot, account: { id: candidate.id, label: candidate.label } },
80
+ latestRuns: account.latestRuns.map(serializeSyncRun),
81
+ }
82
+ }
83
+
84
+ type RequestSixb = ReturnType<typeof requireRequestSixb>
85
+
86
+ /** Each connector's accounts, read once however many of its syncs a response describes. */
87
+ function connectorAccounts(sixb: RequestSixb) {
88
+ const byConnector = new Map<string, Promise<readonly SyncAccount[]>>()
89
+ return (connectorId: string) => {
90
+ let accounts = byConnector.get(connectorId)
91
+ if (!accounts) {
92
+ accounts = sixb.syncs.accounts.list(connectorId)
93
+ byConnector.set(connectorId, accounts)
94
+ }
95
+ return accounts
96
+ }
97
+ }
98
+
99
+ /** On a sync of an OAuth connector, where the accounts the caller may see stand in it. */
100
+ async function summarizeAccounts(
101
+ sync: SyncDefinition,
102
+ accountsOf: ReturnType<typeof connectorAccounts>
103
+ ) {
104
+ if (!isOAuthConnectorDefinition(sync.connector)) return undefined
105
+
106
+ return summarizeSyncAccounts(sync.id, await accountsOf(sync.connector.id))
107
+ }
108
+
109
+ /**
110
+ * Where a sync's accounts stand, by the latest run of each. An account counts once: running,
111
+ * needing reconnecting, failing or synced. One whose latest run was cancelled, or that never ran,
112
+ * is in `total` alone.
113
+ */
114
+ export function summarizeSyncAccounts(syncId: string, accounts: readonly SyncAccount[]) {
115
+ const latest = accounts.flatMap(({ latestRuns }) =>
116
+ latestRuns.filter((run) => run.syncId === syncId)
117
+ )
118
+ const count = (matches: (run: SyncRunRecord) => boolean) => latest.filter(matches).length
119
+ const reconnect = (run: SyncRunRecord) => run.error?.code === "connector.authorization_required"
120
+
121
+ const synced = latest.filter((run) => run.status === "succeeded")
122
+ const lastSyncedAt = synced.reduce<Date | undefined>((last, run) => {
123
+ const at = run.finishedAt ?? run.queuedAt
124
+ return last && last >= at ? last : at
125
+ }, undefined)
126
+
127
+ return {
128
+ total: accounts.length,
129
+ running: count((run) => run.status === "queued" || run.status === "running"),
130
+ needsReconnecting: count((run) => run.status === "failed" && reconnect(run)),
131
+ failing: count((run) => run.status === "failed" && !reconnect(run)),
132
+ synced: synced.length,
133
+ ...(lastSyncedAt === undefined ? {} : { lastSyncedAt: toIsoString(lastSyncedAt) }),
134
+ }
135
+ }
136
+
70
137
  function serializeSync(
71
138
  sync: SyncDefinition,
72
- latestRun: SerializedSyncRun | null
139
+ latestRun: SerializedSyncRun | null,
140
+ folder: string | undefined,
141
+ accounts?: Awaited<ReturnType<typeof summarizeAccounts>>
73
142
  ): ReturnType<typeof SyncSchema.parse> {
74
143
  return SyncSchema.parse({
75
144
  id: sync.id,
145
+ folder,
76
146
  mode: sync.config.mode,
77
147
  connector: {
78
148
  id: sync.connector.id,
@@ -84,6 +154,7 @@ function serializeSync(
84
154
  },
85
155
  triggers: sync.triggers,
86
156
  latestRun,
157
+ ...(accounts === undefined ? {} : { accounts }),
87
158
  })
88
159
  }
89
160
 
@@ -98,8 +169,18 @@ export function registerSyncRoutes(app: Elysia, host: SixbHostView) {
98
169
  sixb,
99
170
  syncs.map((sync) => sync.id)
100
171
  )
172
+ const accountsOf = connectorAccounts(sixb)
101
173
 
102
- return syncs.map((sync) => serializeSync(sync, latestRuns.get(sync.id) ?? null))
174
+ return Promise.all(
175
+ syncs.map(async (sync) =>
176
+ serializeSync(
177
+ sync,
178
+ latestRuns.get(sync.id) ?? null,
179
+ host.definitions.folders.syncs?.get(sync.id),
180
+ await summarizeAccounts(sync, accountsOf)
181
+ )
182
+ )
183
+ )
103
184
  },
104
185
  {
105
186
  response: { 200: SyncSchema.array() },
@@ -122,7 +203,12 @@ export function registerSyncRoutes(app: Elysia, host: SixbHostView) {
122
203
  return { error: "Sync not found" }
123
204
  }
124
205
 
125
- return serializeSync(sync, await getLatestSyncRun(sixb, sync.id))
206
+ return serializeSync(
207
+ sync,
208
+ await getLatestSyncRun(sixb, sync.id),
209
+ host.definitions.folders.syncs?.get(sync.id),
210
+ await summarizeAccounts(sync, connectorAccounts(sixb))
211
+ )
126
212
  },
127
213
  {
128
214
  params: SyncParamsSchema,
@@ -135,6 +221,47 @@ export function registerSyncRoutes(app: Elysia, host: SixbHostView) {
135
221
  },
136
222
  }
137
223
  )
224
+ .get(
225
+ "/api/connectors/:connectorId/accounts",
226
+ async (context) => {
227
+ const { params } = context
228
+ const sixb = requireRequestSixb(context)
229
+ const accounts = await sixb.syncs.accounts.list(params.connectorId)
230
+ return { accounts: accounts.map(serializeAccount) }
231
+ },
232
+ {
233
+ params: ConnectorAccountsParamsSchema,
234
+ response: { 200: ConnectorAccountListResponseSchema },
235
+ detail: {
236
+ summary: "List a connector's accounts and how they synced",
237
+ description:
238
+ "On an OAuth connector, each connected account you may see, with the latest run of each of its syncs you may run. Empty for a static connector.",
239
+ tags: [OPENAPI_TAGS.connectorConnections.name],
240
+ operationId: "listConnectorAccounts",
241
+ security: accessTokenSecurityRequirement("listConnectorAccounts"),
242
+ },
243
+ }
244
+ )
245
+ .get(
246
+ "/api/connectors/:connectorId/connections/:connectionId/sync-runs",
247
+ async (context) => {
248
+ const { params } = context
249
+ const sixb = requireRequestSixb(context)
250
+ const runs = await sixb.syncs.accounts.latestRuns(params.connectorId, params.connectionId)
251
+ return { runs: runs.map(serializeSyncRun) }
252
+ },
253
+ {
254
+ params: ConnectionSyncRunsParamsSchema,
255
+ response: { 200: ConnectionSyncRunsResponseSchema },
256
+ detail: {
257
+ summary: "Latest sync runs of a connection",
258
+ description:
259
+ "The latest run of each sync of one connection: your own, or anyone's with can.manage on its connector. Empty for a connection you don't see.",
260
+ tags: [OPENAPI_TAGS.connectorConnections.name],
261
+ operationId: "listConnectorConnectionSyncRuns",
262
+ },
263
+ }
264
+ )
138
265
  .get(
139
266
  "/api/sync-runs",
140
267
  async (context) => {
@@ -149,6 +276,7 @@ export function registerSyncRoutes(app: Elysia, host: SixbHostView) {
149
276
 
150
277
  const result = await sixb.syncs.runs.list({
151
278
  syncId: parsed.syncId,
279
+ ...(parsed.connectionId === undefined ? {} : { connectionId: parsed.connectionId }),
152
280
  datasetId: parsed.datasetId,
153
281
  statuses: parsed.status ? [parsed.status] : undefined,
154
282
  startedAfter: parseDate(parsed.startedAfter),
@@ -193,10 +321,13 @@ export function registerSyncRoutes(app: Elysia, host: SixbHostView) {
193
321
 
194
322
  set.status = 202
195
323
  return {
196
- runId: result.runId,
197
- jobId: result.jobId ?? "",
198
- syncId: result.syncId,
199
- queuedAt: result.queuedAt,
324
+ runs: result.runs.map((run) => ({
325
+ runId: run.runId,
326
+ jobId: run.jobId ?? "",
327
+ syncId: run.syncId,
328
+ connectionId: run.connectionId,
329
+ queuedAt: run.queuedAt,
330
+ })),
200
331
  }
201
332
  } catch (error) {
202
333
  return handleRouteError(error, set)
@@ -346,10 +346,12 @@ async function getLatestWorkflowRuns(
346
346
 
347
347
  function serializeWorkflow(
348
348
  workflow: WorkflowDefinition,
349
- latestRun: SerializedWorkflowRun | null
349
+ latestRun: SerializedWorkflowRun | null,
350
+ folder: string | undefined
350
351
  ): ReturnType<typeof WorkflowSchema.parse> {
351
352
  return WorkflowSchema.parse({
352
353
  id: workflow.id,
354
+ folder,
353
355
  input: workflow.input,
354
356
  triggers: workflow.triggers,
355
357
  nodes: workflow.nodes.map((node) => {
@@ -568,7 +570,11 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
568
570
  )
569
571
 
570
572
  return workflows.map((workflow) =>
571
- serializeWorkflow(workflow, latestRuns.get(workflow.id) ?? null)
573
+ serializeWorkflow(
574
+ workflow,
575
+ latestRuns.get(workflow.id) ?? null,
576
+ host.definitions.folders.workflows?.get(workflow.id)
577
+ )
572
578
  )
573
579
  },
574
580
  {
@@ -594,7 +600,11 @@ export function registerWorkflowRoutes(app: Elysia, host: SixbHostView) {
594
600
  return { error: "Workflow not found" }
595
601
  }
596
602
 
597
- return serializeWorkflow(workflow, await getLatestWorkflowRun(sixb, workflow.id))
603
+ return serializeWorkflow(
604
+ workflow,
605
+ await getLatestWorkflowRun(sixb, workflow.id),
606
+ host.definitions.folders.workflows?.get(workflow.id)
607
+ )
598
608
  },
599
609
  {
600
610
  params: WorkflowParamsSchema,
@@ -1,4 +1,5 @@
1
1
  import { principalsEqual } from "@sixb/core"
2
+ import type { AgentRunStepsEvent } from "@sixb/core/agents/streams"
2
3
  import {
3
4
  AGENT_ACTIVITY_STREAM_ID,
4
5
  type AgentActivityEvent,
@@ -9,6 +10,8 @@ import {
9
10
  agentActivityStreamDefinition,
10
11
  agentRunStreamDefinition,
11
12
  agentRunStreamId,
13
+ coveredBySteps,
14
+ readAgentRunSteps,
12
15
  } from "@sixb/core/internal/agents/streams"
13
16
  import type { Sixb } from "@sixb/core/internal/request-execution"
14
17
  import type { Principal } from "@sixb/core/storage"
@@ -193,12 +196,21 @@ async function subscribeAgentStream(
193
196
 
194
197
  const buffered: BrokerRecord[] = []
195
198
  let live = false
199
+ // The finished steps sent first, whose live chunks this reader then skips.
200
+ let steps: AgentRunStepsEvent | null = null
201
+ const send = (records: readonly BrokerRecord[]): void => {
202
+ const current = steps
203
+ sendRecords(
204
+ ws,
205
+ current ? records.filter((record) => !coveredBySteps(current, record.payload)) : records
206
+ )
207
+ }
196
208
  const receive = (records: readonly BrokerRecord[]): void => {
197
209
  if (!live) {
198
210
  buffered.push(...records)
199
211
  return
200
212
  }
201
- sendRecords(ws, records)
213
+ send(records)
202
214
  }
203
215
 
204
216
  // Set when the requested cursor had already been trimmed, so the client learns its resume point
@@ -251,13 +263,41 @@ async function subscribeAgentStream(
251
263
  runId: message.runId,
252
264
  afterCursor: resumedFromEarliest ? null : (message.afterCursor ?? null),
253
265
  })
254
- sendRecords(ws, buffered.splice(0))
266
+ // A reader without its place in the stream, opening the turn or back after its place was
267
+ // dropped, reads the finished steps first: the live stream keeps only its newest records, and a
268
+ // long turn outgrows it.
269
+ if (message.afterCursor === undefined || resumedFromEarliest) {
270
+ steps = await readRunSteps(server, sixb, message.runId)
271
+ if (steps) safeSend(ws, { type: "run.steps", event: steps })
272
+ }
273
+ send(buffered.splice(0))
255
274
  if (!(await sendRunSnapshot(sixb, ws, message.runId))) {
256
275
  stopSubscription(state)
257
276
  return
258
277
  }
259
278
  live = true
260
- sendRecords(ws, buffered.splice(0))
279
+ send(buffered.splice(0))
280
+ }
281
+
282
+ /** The run's finished steps for its current attempt, or null: without them it streams as before. */
283
+ async function readRunSteps(
284
+ server: SixbServer,
285
+ sixb: Sixb,
286
+ runId: string
287
+ ): Promise<AgentRunStepsEvent | null> {
288
+ try {
289
+ const run = await sixb.agent.runs.getById(runId)
290
+ if (!run || (run.status !== "queued" && run.status !== "running")) return null
291
+ const host = server.getHost()
292
+ return await readAgentRunSteps(host.broker, {
293
+ projectId: host.id,
294
+ runId,
295
+ attempt: run.attempt,
296
+ })
297
+ } catch (error) {
298
+ console.error(`[SixbServer] Agent run '${runId}' finished steps could not be read:`, error)
299
+ return null
300
+ }
261
301
  }
262
302
 
263
303
  async function subscribeAgentActivity(
@@ -5,7 +5,12 @@ import {
5
5
  type ActionRunFailure,
6
6
  } from "@sixb/core/storage"
7
7
  import { z } from "zod"
8
- import { codedErrorResponseSchema, JsonValueSchema, sixbFailureSchema } from "./common"
8
+ import {
9
+ codedErrorResponseSchema,
10
+ DefinitionFolderSchema,
11
+ JsonValueSchema,
12
+ sixbFailureSchema,
13
+ } from "./common"
9
14
  import { ActionParamSchema } from "./ontology"
10
15
 
11
16
  export const ActionIdParamsSchema = z.object({
@@ -49,6 +54,7 @@ export const RuntimeStoppingResponseSchema = codedErrorResponseSchema(["runtime.
49
54
 
50
55
  export const ActionCatalogItemSchema = z.object({
51
56
  id: z.string(),
57
+ folder: DefinitionFolderSchema,
52
58
  name: z.string(),
53
59
  description: z.string().optional(),
54
60
  objectTypeId: z.string().optional(),
@@ -167,6 +167,46 @@ export const AgentThreadParticipantSchema = z.object({
167
167
  addedBy: AgentPrincipalSchema,
168
168
  })
169
169
 
170
+ export const AgentRunStatusSchema = z.enum([
171
+ "queued",
172
+ "running",
173
+ "succeeded",
174
+ "failed",
175
+ "cancelled",
176
+ ])
177
+
178
+ export const AgentRunFinishReasonSchema = z.enum(AGENT_RUN_FINISH_REASONS)
179
+
180
+ /** Your place in a conversation: how far your reading reached, and what is new. */
181
+ export const AgentThreadReadSchema = z.object({
182
+ threadId: z.string(),
183
+ /** The seq of the last message your reading reached; 0 when it reached none. */
184
+ throughSeq: z.number(),
185
+ /** The thread's newest message seq. */
186
+ headSeq: z.number(),
187
+ /** Messages past your place that someone else wrote: not yours, nor approval outcomes alone. */
188
+ unread: z.number(),
189
+ /** When you last marked it read. */
190
+ readAt: z.string().optional(),
191
+ })
192
+
193
+ /** The newest run of a thread, enough to offer Continue or Retry without reading it. */
194
+ export const AgentThreadLastRunSchema = z.object({
195
+ id: z.string(),
196
+ status: AgentRunStatusSchema,
197
+ finishReason: AgentRunFinishReasonSchema.optional(),
198
+ errorCode: z.enum(AGENT_RUN_FAILURE_CODES).optional(),
199
+ completedAt: z.string().optional(),
200
+ /** Who asked for it, when it ended short: only they can run it again. */
201
+ requestedBy: AgentAuthorizablePrincipalSchema.optional(),
202
+ })
203
+
204
+ export const MarkAgentThreadReadBodySchema = z
205
+ .object({ throughMessageId: z.string().trim().min(1).optional() })
206
+ .strict()
207
+
208
+ export const MarkAgentThreadReadResponseSchema = z.object({ read: AgentThreadReadSchema })
209
+
170
210
  export const AgentThreadSchema = z.object({
171
211
  sandboxState: z
172
212
  .object({
@@ -224,6 +264,10 @@ export const AgentThreadSchema = z.object({
224
264
  messageCount: z.number(),
225
265
  createdAt: z.string(),
226
266
  updatedAt: z.string(),
267
+ /** Your place in it: absent for an observer, and for code that is not a person. */
268
+ read: AgentThreadReadSchema.optional(),
269
+ /** Its newest run, so a client can offer Continue or Retry without reading it. */
270
+ lastRun: AgentThreadLastRunSchema.optional(),
227
271
  /** Your mode in this thread, when the thread is read alone. */
228
272
  approvalMode: AgentApprovalModeSchema.optional(),
229
273
  /**
@@ -243,6 +287,7 @@ export const CreateAgentThreadResponseSchema = z.object({
243
287
  thread: AgentThreadSchema,
244
288
  })
245
289
 
290
+ /** The computer and folder a thread moves to, whether it runs in the cloud or elsewhere. */
246
291
  export const MoveAgentThreadToComputerBodySchema = z
247
292
  .object({ computer: AgentThreadComputerInputSchema })
248
293
  .strict()
@@ -488,6 +533,24 @@ export const AgentMessageListResponseSchema = z.object({
488
533
  total: z.number(),
489
534
  })
490
535
 
536
+ export const EditAgentMessageBodySchema = z
537
+ .object({
538
+ /** Required unless `attachments` are the whole message. */
539
+ text: z.string().trim().min(1).optional(),
540
+ model: LanguageModelRefSchema.optional(),
541
+ reasoning: ModelReasoningSchema.optional(),
542
+ /** IANA time zone of the person asking. The Agent presents dates and times in it. */
543
+ timeZone: z.string().trim().min(1).max(100).optional(),
544
+ /** BCP 47 language of the person asking. */
545
+ locale: z.string().trim().min(1).max(100).optional(),
546
+ /** What this turn may change without asking you. Omitted: your choice in the thread. */
547
+ approvalMode: AgentApprovalModeSchema.optional(),
548
+ attachments: z.array(FileRefSchema).optional(),
549
+ context: z.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
550
+ nextMessageId: z.string().trim().min(1).optional(),
551
+ })
552
+ .strict()
553
+
491
554
  export const PostAgentMessageBodySchema = z
492
555
  .object({
493
556
  /** Required unless `continue` is set or `attachments` are the whole message. */
@@ -522,16 +585,6 @@ export const CancelAgentRunBodySchema = z.object({
522
585
  runId: z.string().trim().min(1),
523
586
  })
524
587
 
525
- export const AgentRunStatusSchema = z.enum([
526
- "queued",
527
- "running",
528
- "succeeded",
529
- "failed",
530
- "cancelled",
531
- ])
532
-
533
- export const AgentRunFinishReasonSchema = z.enum(AGENT_RUN_FINISH_REASONS)
534
-
535
588
  export const AgentRunSchema = z.object({
536
589
  id: z.string(),
537
590
  projectId: z.string(),
@@ -551,6 +604,12 @@ export const AgentRunSchema = z.object({
551
604
  approvalMode: AgentApprovalModeSchema.optional(),
552
605
  /** Its owner's computer claims it; absent, the cloud runs it. */
553
606
  runsOn: z.literal("computer").optional(),
607
+ /**
608
+ * The computer and folder it runs in, in the list of a thread's runs its owner reads: shown to
609
+ * them alone, as the thread's `computer` is. A turn in another place than the one before it no
610
+ * longer has the files that turn worked on.
611
+ */
612
+ computer: z.object({ id: z.string(), folder: z.string() }).optional(),
554
613
  modelId: z.string().optional(),
555
614
  /**
556
615
  * `awaiting_approval`: the turn succeeded and paused on calls waiting for its requester. It stays
@@ -592,6 +651,8 @@ export const AgentInboxItemSchema = z.object({
592
651
  locale: z.string().optional(),
593
652
  /** Sent now: it starts even when the turn it waited for ended without answering. */
594
653
  immediate: z.boolean().optional(),
654
+ /** An edit waiting for the turn it stopped: the message it replaces once that turn ends. */
655
+ replacesMessageId: z.string().optional(),
595
656
  createdAt: z.string(),
596
657
  updatedAt: z.string(),
597
658
  })
@@ -631,6 +692,15 @@ export const PostAgentMessageResponseSchema = z.object({
631
692
  item: AgentInboxItemSchema.optional(),
632
693
  })
633
694
 
695
+ /**
696
+ * `run` when the edit starts its turn now; `item` when it waits, sent now, for the running turn it
697
+ * stopped to end.
698
+ */
699
+ export const EditAgentMessageResponseSchema = z.object({
700
+ run: AgentRunSchema.optional(),
701
+ item: AgentInboxItemSchema.optional(),
702
+ })
703
+
634
704
  export const CancelAgentRunResponseSchema = z.object({
635
705
  run: AgentRunSchema,
636
706
  })
@@ -1,3 +1,4 @@
1
+ import { canonicalTimeZone } from "@sixb/core/calendar"
1
2
  import { z } from "zod"
2
3
  import { AiUsageSummarySchema } from "./ai-usage"
3
4
  import { ModelReasoningSchema } from "./models"
@@ -48,8 +49,19 @@ export const AiAccountingRangeQuerySchema = z.object({
48
49
  kind: ModelKindSchema.optional().describe("Calls to one kind of model"),
49
50
  })
50
51
 
52
+ const TimeZoneSchema = z
53
+ .string()
54
+ .trim()
55
+ .min(1)
56
+ .refine((value) => canonicalTimeZone(value) !== undefined, {
57
+ message: "Use an IANA time zone such as America/New_York",
58
+ })
59
+
51
60
  export const AiAccountingOverviewQuerySchema = AiAccountingRangeQuerySchema.extend({
52
61
  bucket: AiAccountingBucketSchema,
62
+ timeZone: TimeZoneSchema.optional().describe(
63
+ "The IANA time zone whose days, weeks or hours the periods follow, such as America/New_York; UTC when absent"
64
+ ),
53
65
  })
54
66
 
55
67
  export const AiModelCallAccountingListQuerySchema = AiAccountingRangeQuerySchema.extend({
@@ -16,6 +16,15 @@ export function codedErrorResponseSchema<
16
16
  /** Values omitted because the caller lacks a clearance for their markings. */
17
17
  export const RedactionsSchema = z.record(z.object({ reason: z.literal("missing_clearance") }))
18
18
 
19
+ /**
20
+ * The folder a definition sits in below its directory, such as `raw/erp` for
21
+ * `datasets/raw/erp/orders.ts`. Absent at the top of the directory.
22
+ */
23
+ export const DefinitionFolderSchema = z
24
+ .string()
25
+ .optional()
26
+ .describe("Folder below the definition's directory, such as `raw/erp`; absent at its top.")
27
+
19
28
  export const SuccessResponseSchema = z.object({ success: z.boolean() })
20
29
 
21
30
  /** The canonical `Principal` shape from `@sixb/core`. */
@@ -32,15 +41,21 @@ export type JsonValue =
32
41
  | JsonValue[]
33
42
  | { [key: string]: JsonValue }
34
43
 
35
- export const JsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
36
- z.union([
37
- z.string(),
38
- z.number().finite(),
39
- z.boolean(),
40
- z.null(),
41
- z.array(JsonValueSchema),
42
- z.record(JsonValueSchema),
43
- ])
44
+ // Zod calls a lazy schema's getter at every value it checks: built there, the union and its array
45
+ // and record would be built again at each node of every JSON value, which cost a thread's messages
46
+ // seconds of CPU. Built once, each check only walks the value.
47
+ let jsonValueUnion: z.ZodType<JsonValue> | undefined
48
+
49
+ export const JsonValueSchema: z.ZodType<JsonValue> = z.lazy(
50
+ () =>
51
+ (jsonValueUnion ??= z.union([
52
+ z.string(),
53
+ z.number().finite(),
54
+ z.boolean(),
55
+ z.null(),
56
+ z.array(JsonValueSchema),
57
+ z.record(JsonValueSchema),
58
+ ]))
44
59
  )
45
60
 
46
61
  /** A JSON null with an explicit runtime and generated-client type. */
@@ -3,7 +3,7 @@ import {
3
3
  type ConnectorConnectionRunFailure,
4
4
  } from "@sixb/core/storage"
5
5
  import { z } from "zod"
6
- import { ErrorResponseSchema, sixbFailureSchema } from "./common"
6
+ import { DefinitionFolderSchema, ErrorResponseSchema, sixbFailureSchema } from "./common"
7
7
 
8
8
  export const CONNECTOR_HTTP_ERROR_CODES = [
9
9
  "internal.unexpected",
@@ -71,6 +71,7 @@ export const ConnectorWebhookSchema = z.object({
71
71
 
72
72
  export const ConnectorSchema = z.object({
73
73
  id: z.string(),
74
+ folder: DefinitionFolderSchema,
74
75
  type: z.string(),
75
76
  connection: z.object({ authentication: z.literal("oauth2") }).nullable(),
76
77
  syncIds: z.array(z.string()),
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod"
2
- import { RedactionsSchema } from "./common"
2
+ import { DefinitionFolderSchema, RedactionsSchema } from "./common"
3
3
 
4
4
  export const DatasetParamsSchema = z.object({
5
5
  datasetId: z.string().min(1),
@@ -111,6 +111,7 @@ export const DatasetLatestVersionSummarySchema = z.object({
111
111
 
112
112
  export const DatasetCatalogItemSchema = DatasetDefinitionSchema.extend({
113
113
  kind: z.literal("dataset"),
114
+ folder: DefinitionFolderSchema,
114
115
  materialized: z.boolean(),
115
116
  latestVersion: DatasetLatestVersionSummarySchema.nullable(),
116
117
  syncIds: z.array(z.string()),
@@ -253,6 +253,16 @@ export const TranscriptionBodySchema = GenerationBodyBase.extend({
253
253
  audio: z.union([FileRefSchema, InlineAudioSchema]),
254
254
  })
255
255
 
256
+ /** One word the model timed, with who said it where the model labels voices. */
257
+ export const TranscriptionWordSchema = z.object({
258
+ text: z.string(),
259
+ startMs: z.number().int().nonnegative(),
260
+ endMs: z.number().int().nonnegative(),
261
+ speaker: z.string().optional(),
262
+ })
263
+
256
264
  export const TranscriptionSchema = GenerationResultBase.extend({
257
265
  text: z.string(),
266
+ /** Absent when the model returns no word timings. */
267
+ words: z.array(TranscriptionWordSchema).optional(),
258
268
  })
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod"
2
+ import { DefinitionFolderSchema } from "./common"
2
3
 
3
4
  export const ObjectTypeParamsSchema = z.object({ objectTypeId: z.string().min(1) })
4
5
 
@@ -69,6 +70,7 @@ export const ActionSchema = z.object({
69
70
 
70
71
  export const ObjectTypeSchema = z.object({
71
72
  id: z.string(),
73
+ folder: DefinitionFolderSchema,
72
74
  name: z.string(),
73
75
  description: z.string().optional(),
74
76
  extends: z.string().optional(),
@@ -4,7 +4,7 @@ import {
4
4
  type SixbFailure,
5
5
  } from "@sixb/core/storage"
6
6
  import { z } from "zod"
7
- import { sixbFailureSchema } from "./common"
7
+ import { DefinitionFolderSchema, sixbFailureSchema } from "./common"
8
8
  import { DatasetDefinitionSchema } from "./datasets"
9
9
 
10
10
  const PipelineRunFailureSchema: z.ZodType<SixbFailure<PipelineRunFailureCode>> = sixbFailureSchema(
@@ -104,6 +104,7 @@ export const PipelineStepSchema = z.object({
104
104
 
105
105
  export const PipelineSchema = z.object({
106
106
  id: z.string(),
107
+ folder: DefinitionFolderSchema,
107
108
  triggers: z.array(PipelineTriggerSchema),
108
109
  graph: z.object({
109
110
  kind: z.literal("sequence"),