@sixb/server 0.1.16 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/auth/experience.d.ts +5 -1
- package/dist/auth/experience.d.ts.map +1 -1
- package/dist/auth/public-routes.d.ts.map +1 -1
- package/dist/auth/shared-access.d.ts.map +1 -1
- package/dist/files/content.d.ts +0 -1
- package/dist/files/content.d.ts.map +1 -1
- package/dist/index.js +603 -456
- package/dist/index.js.map +34 -33
- package/dist/registerRoutes.d.ts.map +1 -1
- package/dist/routes/agents.d.ts +56 -28
- package/dist/routes/agents.d.ts.map +1 -1
- package/dist/routes/ai-accounting.d.ts.map +1 -1
- package/dist/routes/auth.d.ts +4 -3
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/datasets.d.ts +4 -1
- package/dist/routes/datasets.d.ts.map +1 -1
- package/dist/routes/file-downloads.d.ts +98 -0
- package/dist/routes/file-downloads.d.ts.map +1 -0
- package/dist/routes/files.d.ts.map +1 -1
- package/dist/routes/models.d.ts +1 -0
- package/dist/routes/models.d.ts.map +1 -1
- package/dist/routes/objects.d.ts +24 -4
- package/dist/routes/objects.d.ts.map +1 -1
- package/dist/routes/ontology.d.ts +4 -4
- package/dist/routes/project.d.ts +2 -0
- package/dist/routes/project.d.ts.map +1 -1
- package/dist/routes/status.d.ts +0 -4
- package/dist/routes/status.d.ts.map +1 -1
- package/dist/routes/workflows.d.ts +6 -0
- package/dist/routes/workflows.d.ts.map +1 -1
- package/dist/routes/ws/events.d.ts.map +1 -1
- package/dist/routes/ws/logs.d.ts +11 -0
- package/dist/routes/ws/logs.d.ts.map +1 -1
- package/dist/routes/ws/subscription-hub.d.ts +71 -0
- package/dist/routes/ws/subscription-hub.d.ts.map +1 -0
- package/dist/schemas/agents.d.ts +255 -123
- package/dist/schemas/agents.d.ts.map +1 -1
- package/dist/schemas/ai-accounting.d.ts +234 -110
- package/dist/schemas/ai-accounting.d.ts.map +1 -1
- package/dist/schemas/ai-usage.d.ts +3 -0
- package/dist/schemas/ai-usage.d.ts.map +1 -1
- package/dist/schemas/auth.d.ts +9 -2
- package/dist/schemas/auth.d.ts.map +1 -1
- package/dist/schemas/common.d.ts +8 -0
- package/dist/schemas/common.d.ts.map +1 -1
- package/dist/schemas/datasets.d.ts +18 -3
- package/dist/schemas/datasets.d.ts.map +1 -1
- package/dist/schemas/event-payloads.d.ts +39 -0
- package/dist/schemas/event-payloads.d.ts.map +1 -1
- package/dist/schemas/files.d.ts +1 -1
- package/dist/schemas/files.d.ts.map +1 -1
- package/dist/schemas/models.d.ts +10 -0
- package/dist/schemas/models.d.ts.map +1 -1
- package/dist/schemas/objects.d.ts +32 -0
- package/dist/schemas/objects.d.ts.map +1 -1
- package/dist/schemas/ontology.d.ts +18 -18
- package/dist/schemas/project.d.ts +8 -0
- package/dist/schemas/project.d.ts.map +1 -1
- package/dist/schemas/status.d.ts +0 -26
- package/dist/schemas/status.d.ts.map +1 -1
- package/dist/schemas/workflows.d.ts +52 -0
- package/dist/schemas/workflows.d.ts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/package.json +6 -5
- package/src/auth/experience.ts +20 -2
- package/src/auth/public-routes.ts +10 -0
- package/src/auth/shared-access.ts +48 -6
- package/src/files/content.ts +43 -88
- package/src/registerRoutes.ts +2 -0
- package/src/routes/agents.ts +29 -9
- package/src/routes/ai-accounting.ts +1 -0
- package/src/routes/auth.ts +84 -19
- package/src/routes/datasets.ts +12 -43
- package/src/routes/file-downloads.ts +48 -0
- package/src/routes/files.ts +3 -1
- package/src/routes/models.ts +3 -0
- package/src/routes/objects.ts +25 -5
- package/src/routes/project.ts +2 -1
- package/src/routes/workflows.ts +5 -0
- package/src/routes/ws/events.ts +98 -133
- package/src/routes/ws/logs.ts +67 -5
- package/src/routes/ws/subscription-hub.ts +394 -0
- package/src/schemas/agents.ts +28 -3
- package/src/schemas/ai-accounting.ts +5 -0
- package/src/schemas/ai-usage.ts +3 -0
- package/src/schemas/auth.ts +5 -0
- package/src/schemas/common.ts +3 -0
- package/src/schemas/datasets.ts +23 -1
- package/src/schemas/event-payloads.ts +3 -1
- package/src/schemas/files.ts +7 -1
- package/src/schemas/models.ts +2 -0
- package/src/schemas/objects.ts +41 -2
- package/src/schemas/project.ts +4 -0
- package/src/schemas/status.ts +0 -6
- package/src/server.ts +7 -1
- package/dist/routes/ws/log-subscription-hub.d.ts +0 -50
- package/dist/routes/ws/log-subscription-hub.d.ts.map +0 -1
- package/src/routes/ws/log-subscription-hub.ts +0 -369
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import { BrokerCursorExpiredError } from "@sixb/core/broker"
|
|
2
|
+
|
|
3
|
+
const MAX_CLIENT_RECORDS = 1_000
|
|
4
|
+
const MAX_CLIENT_BYTES = 1_048_576
|
|
5
|
+
const MAX_SOCKET_BUFFERED_BYTES = 1_048_576
|
|
6
|
+
const MAX_BATCH_RECORDS = 100
|
|
7
|
+
const FLUSH_DELAY_MS = 10
|
|
8
|
+
|
|
9
|
+
interface HubSocket {
|
|
10
|
+
send(message: string): unknown
|
|
11
|
+
close(code?: number, reason?: string): unknown
|
|
12
|
+
readonly raw?: unknown
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface HubRecord {
|
|
16
|
+
readonly cursor: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** One retained broker stream, as the hub consumes and frames it. */
|
|
20
|
+
export interface HubSource<T extends HubRecord> {
|
|
21
|
+
/** Delivers records appended after the call. */
|
|
22
|
+
subscribe(deliver: (records: readonly T[]) => void): Promise<() => void>
|
|
23
|
+
/** Socket frames for one flushed batch, in order. */
|
|
24
|
+
frames(records: readonly T[]): readonly unknown[]
|
|
25
|
+
/** Frame for a client whose replay cursor left retention. Live delivery continues after it. */
|
|
26
|
+
expired(): Promise<unknown>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One socket's view of the stream. */
|
|
30
|
+
export interface HubSubscription<T extends HubRecord> {
|
|
31
|
+
matches(record: T): boolean
|
|
32
|
+
/**
|
|
33
|
+
* The matching record as this socket may read it, or `undefined` to withhold it. It keeps the
|
|
34
|
+
* record's cursor. Omit to deliver matching records unchanged.
|
|
35
|
+
*/
|
|
36
|
+
view?(record: T): T | undefined
|
|
37
|
+
/** Replays retained records after `afterCursor` (or from the oldest) before live ones. */
|
|
38
|
+
readonly replay?: {
|
|
39
|
+
readonly afterCursor: string | undefined
|
|
40
|
+
read(afterCursor: string | undefined): Promise<{
|
|
41
|
+
readonly records: readonly T[]
|
|
42
|
+
readonly cursor?: string
|
|
43
|
+
readonly hasMore: boolean
|
|
44
|
+
}>
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface ClientState<T extends HubRecord> {
|
|
49
|
+
readonly ws: HubSocket
|
|
50
|
+
readonly subscription: HubSubscription<T>
|
|
51
|
+
readonly queue: T[]
|
|
52
|
+
readonly queuedCursors: Set<string>
|
|
53
|
+
readonly pendingLive: T[]
|
|
54
|
+
readonly pendingCursors: Set<string>
|
|
55
|
+
readonly replayedPendingCursors: Set<string>
|
|
56
|
+
queuedBytes: number
|
|
57
|
+
pendingBytes: number
|
|
58
|
+
flushTimer: ReturnType<typeof setTimeout> | null
|
|
59
|
+
readonly queueProgressWaiters: Set<() => void>
|
|
60
|
+
catchingUp: boolean
|
|
61
|
+
closed: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* One broker subscription per server/project and stream, multiplexed to all connected clients
|
|
66
|
+
* and released when the last one leaves. Each client has a bounded queue so a slow socket cannot
|
|
67
|
+
* retain an unbounded portion of the process heap.
|
|
68
|
+
*/
|
|
69
|
+
export class SubscriptionHub<T extends HubRecord> {
|
|
70
|
+
private readonly clients = new Map<object, ClientState<T>>()
|
|
71
|
+
private readonly subscriptionGenerations = new WeakMap<object, number>()
|
|
72
|
+
private started: Promise<() => void> | null = null
|
|
73
|
+
private closed = false
|
|
74
|
+
|
|
75
|
+
constructor(private readonly source: HubSource<T>) {}
|
|
76
|
+
|
|
77
|
+
async subscribe(
|
|
78
|
+
key: object,
|
|
79
|
+
ws: HubSocket,
|
|
80
|
+
subscription: HubSubscription<T>,
|
|
81
|
+
onSubscribed: () => void
|
|
82
|
+
): Promise<void> {
|
|
83
|
+
if (this.closed) throw new Error("Subscription hub is closed")
|
|
84
|
+
const generation = this.nextSubscriptionGeneration(key)
|
|
85
|
+
this.removeClient(key)
|
|
86
|
+
|
|
87
|
+
// The last client leaving while this waits releases the subscription it waited for.
|
|
88
|
+
let started: Promise<() => void>
|
|
89
|
+
do {
|
|
90
|
+
started = this.start()
|
|
91
|
+
try {
|
|
92
|
+
await started
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (this.closed || !this.isCurrentSubscription(key, generation)) return
|
|
95
|
+
throw error
|
|
96
|
+
}
|
|
97
|
+
if (this.closed || !this.isCurrentSubscription(key, generation)) return
|
|
98
|
+
} while (started !== this.started)
|
|
99
|
+
|
|
100
|
+
const state: ClientState<T> = {
|
|
101
|
+
ws,
|
|
102
|
+
subscription,
|
|
103
|
+
queue: [],
|
|
104
|
+
queuedCursors: new Set(),
|
|
105
|
+
pendingLive: [],
|
|
106
|
+
pendingCursors: new Set(),
|
|
107
|
+
replayedPendingCursors: new Set(),
|
|
108
|
+
queuedBytes: 0,
|
|
109
|
+
pendingBytes: 0,
|
|
110
|
+
flushTimer: null,
|
|
111
|
+
queueProgressWaiters: new Set(),
|
|
112
|
+
catchingUp: subscription.replay !== undefined,
|
|
113
|
+
closed: false,
|
|
114
|
+
}
|
|
115
|
+
this.clients.set(key, state)
|
|
116
|
+
onSubscribed()
|
|
117
|
+
|
|
118
|
+
if (subscription.replay) {
|
|
119
|
+
void this.catchUp(key, state, subscription.replay)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
unsubscribe(key: object): void {
|
|
124
|
+
this.nextSubscriptionGeneration(key)
|
|
125
|
+
this.removeClient(key)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private removeClient(key: object): void {
|
|
129
|
+
const state = this.clients.get(key)
|
|
130
|
+
if (!state) return
|
|
131
|
+
state.closed = true
|
|
132
|
+
if (state.flushTimer) clearTimeout(state.flushTimer)
|
|
133
|
+
this.notifyQueueProgress(state)
|
|
134
|
+
this.deleteClient(key)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private deleteClient(key: object): void {
|
|
138
|
+
this.clients.delete(key)
|
|
139
|
+
if (this.clients.size === 0) this.release()
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private nextSubscriptionGeneration(key: object): number {
|
|
143
|
+
const generation = (this.subscriptionGenerations.get(key) ?? 0) + 1
|
|
144
|
+
this.subscriptionGenerations.set(key, generation)
|
|
145
|
+
return generation
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private isCurrentSubscription(key: object, generation: number): boolean {
|
|
149
|
+
return this.subscriptionGenerations.get(key) === generation
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async close(): Promise<void> {
|
|
153
|
+
this.closed = true
|
|
154
|
+
for (const key of this.clients.keys()) this.unsubscribe(key)
|
|
155
|
+
this.release()
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private start(): Promise<() => void> {
|
|
159
|
+
if (this.closed) return Promise.reject(new Error("Subscription hub is closed"))
|
|
160
|
+
if (!this.started) {
|
|
161
|
+
const started = this.source.subscribe((records) => this.deliverLive(records))
|
|
162
|
+
started.catch(() => {
|
|
163
|
+
if (this.started === started) this.started = null
|
|
164
|
+
})
|
|
165
|
+
this.started = started
|
|
166
|
+
}
|
|
167
|
+
return this.started
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private release(): void {
|
|
171
|
+
const started = this.started
|
|
172
|
+
this.started = null
|
|
173
|
+
started?.then(
|
|
174
|
+
(unsubscribe) => unsubscribe(),
|
|
175
|
+
() => undefined
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private deliverLive(records: readonly T[]): void {
|
|
180
|
+
for (const state of this.clients.values()) {
|
|
181
|
+
for (const record of records) {
|
|
182
|
+
const visible = visibleRecord(state.subscription, record)
|
|
183
|
+
if (!visible) continue
|
|
184
|
+
if (state.catchingUp) this.enqueuePendingLive(state, visible)
|
|
185
|
+
else this.enqueue(state, visible)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private async catchUp(
|
|
191
|
+
key: object,
|
|
192
|
+
state: ClientState<T>,
|
|
193
|
+
replay: NonNullable<HubSubscription<T>["replay"]>
|
|
194
|
+
): Promise<void> {
|
|
195
|
+
let afterCursor = replay.afterCursor
|
|
196
|
+
try {
|
|
197
|
+
let hasMore = true
|
|
198
|
+
while (hasMore) {
|
|
199
|
+
const page = await replay.read(afterCursor)
|
|
200
|
+
if (state.closed || this.clients.get(key) !== state) return
|
|
201
|
+
|
|
202
|
+
for (const record of page.records) {
|
|
203
|
+
if (state.pendingCursors.has(record.cursor)) {
|
|
204
|
+
state.replayedPendingCursors.add(record.cursor)
|
|
205
|
+
}
|
|
206
|
+
const visible = visibleRecord(state.subscription, record)
|
|
207
|
+
if (!visible) continue
|
|
208
|
+
if (!(await this.enqueueReplay(state, visible))) return
|
|
209
|
+
}
|
|
210
|
+
if (state.closed) return
|
|
211
|
+
afterCursor = page.cursor ?? afterCursor
|
|
212
|
+
hasMore = page.hasMore
|
|
213
|
+
if (hasMore && !page.cursor) {
|
|
214
|
+
throw new Error("Broker returned hasMore without a cursor")
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
state.catchingUp = false
|
|
219
|
+
const pendingLive = [...state.pendingLive]
|
|
220
|
+
const replayedPendingCursors = new Set(state.replayedPendingCursors)
|
|
221
|
+
state.pendingLive.length = 0
|
|
222
|
+
state.pendingCursors.clear()
|
|
223
|
+
state.replayedPendingCursors.clear()
|
|
224
|
+
state.pendingBytes = 0
|
|
225
|
+
for (const record of pendingLive) {
|
|
226
|
+
if (!replayedPendingCursors.has(record.cursor)) this.enqueue(state, record)
|
|
227
|
+
}
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (state.closed || this.clients.get(key) !== state) return
|
|
230
|
+
state.catchingUp = false
|
|
231
|
+
state.pendingLive.length = 0
|
|
232
|
+
state.pendingCursors.clear()
|
|
233
|
+
state.replayedPendingCursors.clear()
|
|
234
|
+
state.pendingBytes = 0
|
|
235
|
+
|
|
236
|
+
if (error instanceof BrokerCursorExpiredError) {
|
|
237
|
+
try {
|
|
238
|
+
this.send(state, await this.source.expired())
|
|
239
|
+
} catch (resetError) {
|
|
240
|
+
this.fail(
|
|
241
|
+
state,
|
|
242
|
+
resetError instanceof Error ? resetError.message : String(resetError),
|
|
243
|
+
1011
|
|
244
|
+
)
|
|
245
|
+
}
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
this.fail(state, error instanceof Error ? error.message : String(error), 1011)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private enqueue(state: ClientState<T>, record: T): void {
|
|
254
|
+
if (state.closed || state.queuedCursors.has(record.cursor)) return
|
|
255
|
+
const bytes = encodedBytes(record)
|
|
256
|
+
if (!hasQueueCapacity(state, bytes)) {
|
|
257
|
+
this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013)
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
this.pushQueuedRecord(state, record, bytes)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private async enqueueReplay(state: ClientState<T>, record: T): Promise<boolean> {
|
|
265
|
+
if (state.closed) return false
|
|
266
|
+
if (state.queuedCursors.has(record.cursor)) return true
|
|
267
|
+
const bytes = encodedBytes(record)
|
|
268
|
+
|
|
269
|
+
while (!hasQueueCapacity(state, bytes)) {
|
|
270
|
+
// Replay is an internal producer and can pause while already-queued replay
|
|
271
|
+
// batches drain. Pending live records cannot drain until replay finishes,
|
|
272
|
+
// so a queue containing only pending live records has no forward progress.
|
|
273
|
+
if (state.queue.length === 0 || socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
|
|
274
|
+
this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013)
|
|
275
|
+
return false
|
|
276
|
+
}
|
|
277
|
+
this.scheduleFlush(state)
|
|
278
|
+
await this.waitForQueueProgress(state)
|
|
279
|
+
if (state.closed) return false
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
this.pushQueuedRecord(state, record, bytes)
|
|
283
|
+
return !state.closed
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private pushQueuedRecord(state: ClientState<T>, record: T, bytes: number): void {
|
|
287
|
+
state.queue.push(record)
|
|
288
|
+
state.queuedCursors.add(record.cursor)
|
|
289
|
+
state.queuedBytes += bytes
|
|
290
|
+
this.scheduleFlush(state)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private enqueuePendingLive(state: ClientState<T>, record: T): void {
|
|
294
|
+
if (state.closed || state.pendingCursors.has(record.cursor)) return
|
|
295
|
+
const bytes = encodedBytes(record)
|
|
296
|
+
if (!hasQueueCapacity(state, bytes)) {
|
|
297
|
+
this.fail(state, "Stream client is too slow; reconnect from the last cursor.", 1013)
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
state.pendingLive.push(record)
|
|
301
|
+
state.pendingCursors.add(record.cursor)
|
|
302
|
+
state.pendingBytes += bytes
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private scheduleFlush(state: ClientState<T>): void {
|
|
306
|
+
if (state.closed || state.flushTimer) return
|
|
307
|
+
state.flushTimer = setTimeout(() => {
|
|
308
|
+
state.flushTimer = null
|
|
309
|
+
this.flush(state)
|
|
310
|
+
}, FLUSH_DELAY_MS)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private flush(state: ClientState<T>): void {
|
|
314
|
+
if (state.closed || state.queue.length === 0) return
|
|
315
|
+
if (socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
|
|
316
|
+
this.scheduleFlush(state)
|
|
317
|
+
return
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const records = state.queue.splice(0, MAX_BATCH_RECORDS)
|
|
321
|
+
for (const record of records) {
|
|
322
|
+
state.queuedCursors.delete(record.cursor)
|
|
323
|
+
state.queuedBytes -= encodedBytes(record)
|
|
324
|
+
}
|
|
325
|
+
this.notifyQueueProgress(state)
|
|
326
|
+
for (const frame of this.source.frames(records)) this.send(state, frame)
|
|
327
|
+
if (state.queue.length > 0) this.scheduleFlush(state)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private waitForQueueProgress(state: ClientState<T>): Promise<void> {
|
|
331
|
+
return new Promise((resolve) => state.queueProgressWaiters.add(resolve))
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private notifyQueueProgress(state: ClientState<T>): void {
|
|
335
|
+
const waiters = [...state.queueProgressWaiters]
|
|
336
|
+
state.queueProgressWaiters.clear()
|
|
337
|
+
for (const resolve of waiters) resolve()
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private send(state: ClientState<T>, payload: unknown): void {
|
|
341
|
+
if (state.closed) return
|
|
342
|
+
try {
|
|
343
|
+
state.ws.send(JSON.stringify(payload))
|
|
344
|
+
} catch (error) {
|
|
345
|
+
this.fail(state, error instanceof Error ? error.message : String(error), 1011)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private fail(state: ClientState<T>, message: string, closeCode: number): void {
|
|
350
|
+
if (state.closed) return
|
|
351
|
+
try {
|
|
352
|
+
state.ws.send(JSON.stringify({ type: "error", message }))
|
|
353
|
+
} catch {
|
|
354
|
+
// The close below is still required when the error frame cannot be sent.
|
|
355
|
+
}
|
|
356
|
+
state.closed = true
|
|
357
|
+
if (state.flushTimer) clearTimeout(state.flushTimer)
|
|
358
|
+
this.notifyQueueProgress(state)
|
|
359
|
+
for (const [key, candidate] of this.clients) {
|
|
360
|
+
if (candidate === state) this.deleteClient(key)
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
state.ws.close(closeCode, closeCode === 1013 ? "Stream backpressure" : "Stream failure")
|
|
364
|
+
} catch {
|
|
365
|
+
// Socket is already gone.
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function visibleRecord<T extends HubRecord>(
|
|
371
|
+
subscription: HubSubscription<T>,
|
|
372
|
+
record: T
|
|
373
|
+
): T | undefined {
|
|
374
|
+
if (!subscription.matches(record)) return undefined
|
|
375
|
+
return subscription.view ? subscription.view(record) : record
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function hasQueueCapacity(state: ClientState<HubRecord>, bytes: number): boolean {
|
|
379
|
+
return (
|
|
380
|
+
state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS &&
|
|
381
|
+
state.queuedBytes + state.pendingBytes + bytes <= MAX_CLIENT_BYTES
|
|
382
|
+
)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function encodedBytes(value: unknown): number {
|
|
386
|
+
return new TextEncoder().encode(JSON.stringify(value)).byteLength
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function socketBufferedAmount(ws: HubSocket): number {
|
|
390
|
+
const raw = ws.raw
|
|
391
|
+
if (!raw || typeof raw !== "object" || !("bufferedAmount" in raw)) return 0
|
|
392
|
+
const bufferedAmount = (raw as { bufferedAmount?: unknown }).bufferedAmount
|
|
393
|
+
return typeof bufferedAmount === "number" ? bufferedAmount : 0
|
|
394
|
+
}
|
package/src/schemas/agents.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MAX_AGENT_CONTEXT_ENTRIES } from "@sixb/core"
|
|
2
|
+
import { MAX_AGENT_CONTEXT_LABEL_LENGTH } from "@sixb/core/agents/context"
|
|
2
3
|
import {
|
|
3
4
|
AGENT_RUN_DIAGNOSTIC_CODES,
|
|
4
5
|
AGENT_RUN_FAILURE_CODES,
|
|
@@ -9,7 +10,7 @@ import {
|
|
|
9
10
|
import { z } from "zod"
|
|
10
11
|
import { AiCostSummarySchema } from "./ai-accounting"
|
|
11
12
|
import { AiUsageSummarySchema } from "./ai-usage"
|
|
12
|
-
import { JsonValueSchema, sixbFailureSchema } from "./common"
|
|
13
|
+
import { ErrorResponseSchema, JsonValueSchema, sixbFailureSchema } from "./common"
|
|
13
14
|
import { FileRefSchema } from "./files"
|
|
14
15
|
import { LanguageModelRefSchema, ModelReasoningSchema } from "./models"
|
|
15
16
|
|
|
@@ -44,6 +45,12 @@ export const AgentObjectContextSchema = z.object({
|
|
|
44
45
|
objectTypeId: z.string().min(1),
|
|
45
46
|
primaryId: z.string().min(1),
|
|
46
47
|
}),
|
|
48
|
+
label: z
|
|
49
|
+
.string()
|
|
50
|
+
.min(1)
|
|
51
|
+
.max(MAX_AGENT_CONTEXT_LABEL_LENGTH)
|
|
52
|
+
.optional()
|
|
53
|
+
.describe("Shown in the chat instead of the object's title. Never sent to the model."),
|
|
47
54
|
})
|
|
48
55
|
|
|
49
56
|
export const AgentAppStateContextSchema = z.object({
|
|
@@ -175,8 +182,14 @@ const AgentToolCallErrorSchema = AgentToolCallBaseSchema.extend({
|
|
|
175
182
|
errorText: z.string(),
|
|
176
183
|
})
|
|
177
184
|
|
|
185
|
+
/** The user asked to continue an answer cut short; Sixb writes what the model reads. */
|
|
186
|
+
const AgentContinuationPartSchema = z.object({
|
|
187
|
+
type: z.literal("continuation"),
|
|
188
|
+
})
|
|
189
|
+
|
|
178
190
|
export const AgentMessagePartSchema = z.union([
|
|
179
191
|
AgentTextPartSchema,
|
|
192
|
+
AgentContinuationPartSchema,
|
|
180
193
|
AgentReasoningPartSchema,
|
|
181
194
|
AgentStepStartPartSchema,
|
|
182
195
|
AgentFilePartSchema,
|
|
@@ -189,7 +202,7 @@ export const AgentMessagePartSchema = z.union([
|
|
|
189
202
|
export const AgentRunDiagnosticSchema = z.object({
|
|
190
203
|
code: z.enum(AGENT_RUN_DIAGNOSTIC_CODES),
|
|
191
204
|
severity: z.enum(["warning", "error"]),
|
|
192
|
-
scope: z.
|
|
205
|
+
scope: z.enum(["output", "run"]),
|
|
193
206
|
path: z.string().optional(),
|
|
194
207
|
message: z.string(),
|
|
195
208
|
})
|
|
@@ -234,15 +247,27 @@ export const AgentMessageListResponseSchema = z.object({
|
|
|
234
247
|
|
|
235
248
|
export const PostAgentMessageBodySchema = z
|
|
236
249
|
.object({
|
|
237
|
-
|
|
250
|
+
/** Required unless `continue` is set. */
|
|
251
|
+
text: z.string().trim().min(1).optional(),
|
|
252
|
+
/** Continue the previous answer after it reached the turn limit, without text of its own. */
|
|
253
|
+
continue: z.literal(true).optional(),
|
|
238
254
|
model: LanguageModelRefSchema.optional(),
|
|
239
255
|
reasoning: ModelReasoningSchema.optional(),
|
|
256
|
+
/** IANA time zone of the person asking. The Agent presents dates and times in it. */
|
|
257
|
+
timeZone: z.string().trim().min(1).max(100).optional(),
|
|
258
|
+
/** BCP 47 language of the person asking. */
|
|
259
|
+
locale: z.string().trim().min(1).max(100).optional(),
|
|
240
260
|
attachments: z.array(FileRefSchema).optional(),
|
|
241
261
|
context: z.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
|
|
242
262
|
messageId: z.string().trim().min(1).optional(),
|
|
243
263
|
})
|
|
244
264
|
.strict()
|
|
245
265
|
|
|
266
|
+
/** A refused message request, with the stable code of the reason, such as `invalid_locale`. */
|
|
267
|
+
export const AgentRequestErrorResponseSchema = ErrorResponseSchema.extend({
|
|
268
|
+
code: z.string().optional(),
|
|
269
|
+
})
|
|
270
|
+
|
|
246
271
|
export const CancelAgentRunBodySchema = z.object({
|
|
247
272
|
runId: z.string().trim().min(1),
|
|
248
273
|
})
|
|
@@ -58,6 +58,7 @@ const AiAccountingAggregateSchema = z.object({
|
|
|
58
58
|
cacheWriteInputTokens: z.number().int().nonnegative(),
|
|
59
59
|
textOutputTokens: z.number().int().nonnegative(),
|
|
60
60
|
reasoningOutputTokens: z.number().int().nonnegative(),
|
|
61
|
+
audioDurationMs: z.number().int().nonnegative(),
|
|
61
62
|
}),
|
|
62
63
|
}),
|
|
63
64
|
costs: AiCostSummarySchema,
|
|
@@ -120,6 +121,7 @@ const AiCostComponentSchema = z.object({
|
|
|
120
121
|
"tokens.output.total",
|
|
121
122
|
"tokens.output.text",
|
|
122
123
|
"tokens.output.reasoning",
|
|
124
|
+
"audio.input.milliseconds",
|
|
123
125
|
]),
|
|
124
126
|
quantity: IntegerStringSchema,
|
|
125
127
|
rateAmountNanosPerMillion: IntegerStringSchema,
|
|
@@ -192,6 +194,9 @@ const AiModelCallUsageRecordSchema = z.object({
|
|
|
192
194
|
callId: z.string(),
|
|
193
195
|
providerId: z.string(),
|
|
194
196
|
requestedModelId: z.string(),
|
|
197
|
+
modelKind: z
|
|
198
|
+
.enum(["language", "image", "video", "embedding", "decision", "transcription", "reranking"])
|
|
199
|
+
.optional(),
|
|
195
200
|
requestedReasoning: ModelReasoningSchema.optional(),
|
|
196
201
|
responseModelId: z.string().optional(),
|
|
197
202
|
responseId: z.string(),
|
package/src/schemas/ai-usage.ts
CHANGED
|
@@ -12,5 +12,8 @@ export const AiUsageSummarySchema = z.object({
|
|
|
12
12
|
cacheWriteInputTokens: TokenCountSchema.optional(),
|
|
13
13
|
textOutputTokens: TokenCountSchema.optional(),
|
|
14
14
|
reasoningOutputTokens: TokenCountSchema.optional(),
|
|
15
|
+
audioDurationMs: TokenCountSchema.optional().describe(
|
|
16
|
+
"Audio content duration in milliseconds; not billed duration."
|
|
17
|
+
),
|
|
15
18
|
reportingStatus: z.enum(["complete", "partial", "unavailable"]),
|
|
16
19
|
})
|
package/src/schemas/auth.ts
CHANGED
|
@@ -274,6 +274,11 @@ export const RevokeAuthInvitationResponseSchema = z.object({
|
|
|
274
274
|
export const AuthSessionResponseSchema = z.union([
|
|
275
275
|
z.object({
|
|
276
276
|
authenticated: z.literal(false),
|
|
277
|
+
/**
|
|
278
|
+
* False when the project runs without auth: every request is allowed and there is nothing to
|
|
279
|
+
* sign in to. Browser shells read it instead of being told by the server that serves them.
|
|
280
|
+
*/
|
|
281
|
+
authEnabled: z.boolean(),
|
|
277
282
|
}),
|
|
278
283
|
z.object({
|
|
279
284
|
authenticated: z.literal(true),
|
package/src/schemas/common.ts
CHANGED
|
@@ -13,6 +13,9 @@ export function codedErrorResponseSchema<
|
|
|
13
13
|
})
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
/** Values omitted because the caller lacks a clearance for their markings. */
|
|
17
|
+
export const RedactionsSchema = z.record(z.object({ reason: z.literal("missing_clearance") }))
|
|
18
|
+
|
|
16
19
|
export const SuccessResponseSchema = z.object({ success: z.boolean() })
|
|
17
20
|
|
|
18
21
|
/** The canonical `Principal` shape from `@sixb/core`. */
|
package/src/schemas/datasets.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod"
|
|
2
|
+
import { RedactionsSchema } from "./common"
|
|
2
3
|
|
|
3
4
|
export const DatasetParamsSchema = z.object({
|
|
4
5
|
datasetId: z.string().min(1),
|
|
@@ -12,9 +13,27 @@ export const DatasetVersionsQuerySchema = z.object({
|
|
|
12
13
|
limit: z.string().optional(),
|
|
13
14
|
})
|
|
14
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Elysia's query parser splits any comma-separated value into an array before validation, and
|
|
18
|
+
* pushes a repeated key's value into the existing array as-is. `?columns=id`, `?columns=id,title`,
|
|
19
|
+
* `?columns=id&columns=title` and `?columns=x&columns=id,title` therefore arrive as a string, a
|
|
20
|
+
* flat array, a flat array, and a nested array. All of them name the same thing: a column list.
|
|
21
|
+
*/
|
|
22
|
+
const QueryStringListSchema = z.preprocess(flattenQueryStringList, z.array(z.string()))
|
|
23
|
+
|
|
24
|
+
function flattenQueryStringList(value: unknown): unknown {
|
|
25
|
+
if (typeof value !== "string" && !Array.isArray(value)) return value
|
|
26
|
+
const items = [value].flat(Number.POSITIVE_INFINITY)
|
|
27
|
+
if (!items.every((item) => typeof item === "string")) return value
|
|
28
|
+
return items
|
|
29
|
+
.flatMap((item) => item.split(","))
|
|
30
|
+
.map((item) => item.trim())
|
|
31
|
+
.filter(Boolean)
|
|
32
|
+
}
|
|
33
|
+
|
|
15
34
|
export const DatasetRowsQuerySchema = z.object({
|
|
16
35
|
versionId: z.string().optional(),
|
|
17
|
-
columns:
|
|
36
|
+
columns: QueryStringListSchema.optional(),
|
|
18
37
|
limit: z.string().optional(),
|
|
19
38
|
offset: z.string().optional(),
|
|
20
39
|
})
|
|
@@ -99,7 +118,10 @@ export const DatasetRowsResponseSchema = z.object({
|
|
|
99
118
|
datasetId: z.string(),
|
|
100
119
|
versionId: z.string(),
|
|
101
120
|
version: DatasetVersionSchema,
|
|
121
|
+
/** Returned columns. Redacted columns are left out. */
|
|
102
122
|
columns: z.array(z.string()),
|
|
123
|
+
/** Columns omitted because the caller lacks a clearance for their markings. */
|
|
124
|
+
redactions: RedactionsSchema.optional(),
|
|
103
125
|
rows: z.array(z.record(z.unknown())),
|
|
104
126
|
count: z.number(),
|
|
105
127
|
limit: z.number(),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { DomainEvent } from "@sixb/core"
|
|
2
2
|
import { z } from "zod"
|
|
3
|
-
import { JsonNullSchema, JsonValueSchema } from "./common"
|
|
3
|
+
import { JsonNullSchema, JsonValueSchema, RedactionsSchema } from "./common"
|
|
4
4
|
|
|
5
5
|
const PropertyChangeSchema = z.discriminatedUnion("operation", [
|
|
6
6
|
z.object({ operation: z.literal("created"), after: JsonValueSchema }),
|
|
@@ -22,11 +22,13 @@ const ObjectMutationPayloadSchema = z.object({
|
|
|
22
22
|
primaryId: z.string(),
|
|
23
23
|
properties: z.record(JsonValueSchema),
|
|
24
24
|
propertyChanges: PropertyChangesSchema,
|
|
25
|
+
redactions: RedactionsSchema.optional(),
|
|
25
26
|
})
|
|
26
27
|
const ObjectDeletedPayloadSchema = z.object({
|
|
27
28
|
objectTypeId: z.string(),
|
|
28
29
|
primaryId: z.string(),
|
|
29
30
|
propertyChanges: PropertyChangesSchema,
|
|
31
|
+
redactions: RedactionsSchema.optional(),
|
|
30
32
|
})
|
|
31
33
|
const LinkSubjectSchema = z.object({
|
|
32
34
|
sourceTypeId: z.string(),
|
package/src/schemas/files.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { canonicalMediaType } from "@sixb/core/internal/blob-storage"
|
|
1
2
|
import { z } from "zod"
|
|
2
3
|
|
|
3
4
|
export const BlobDigestSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/)
|
|
@@ -13,7 +14,12 @@ export const FileRefSchema = z.object({
|
|
|
13
14
|
|
|
14
15
|
export const CreateFileUploadBodySchema = z.object({
|
|
15
16
|
fileName: z.string().optional(),
|
|
16
|
-
mediaType: z
|
|
17
|
+
mediaType: z
|
|
18
|
+
.string()
|
|
19
|
+
.refine((value) => canonicalMediaType(value) !== null, {
|
|
20
|
+
message: 'Expected a single media type, such as "application/pdf"',
|
|
21
|
+
})
|
|
22
|
+
.optional(),
|
|
17
23
|
sizeBytes: z.number().int().nonnegative().optional(),
|
|
18
24
|
digest: BlobDigestSchema.optional(),
|
|
19
25
|
logicalPath: z.string().optional(),
|
package/src/schemas/models.ts
CHANGED
|
@@ -29,6 +29,8 @@ export const LanguageModelSchema = LanguageModelRefSchema.extend({
|
|
|
29
29
|
contextWindowTokens: z.number().int().positive().optional(),
|
|
30
30
|
}),
|
|
31
31
|
reasoningLevels: z.array(z.enum(MODEL_REASONING_LEVELS)),
|
|
32
|
+
/** Reasoning the project applies when a request selects this model without choosing one. */
|
|
33
|
+
defaultReasoning: z.enum(MODEL_REASONING_LEVELS).optional(),
|
|
32
34
|
})
|
|
33
35
|
|
|
34
36
|
export const ModelCatalogSchema = z.object({
|